body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>Over at Stack Overflow I asked <a href="https://stackoverflow.com/questions/22923873/search-filesystem-via-perl-script-while-ignoring-remote-mounts">how to scan a local filesystem ignoring all remote mount points</a>. I only really wanted a push in the right direction and received it. After clacking away on my keyboard I think I might have what I what I need. I ask for an evaluation to determine if it fulfills the requirements:</p>
<ol>
<li>Scan every local directory for world-writable files ignoring "special" directories (/sys, /proc, /dev)</li>
<li>Ignore directories</li>
<li>Ignore files on any remote filesystems which may be mounted</li>
<li>Ignore any files in an "exclude" list</li>
</ol>
<p>I'm quite certain it could be drastically optimized and any suggestions are welcome as are any suggestions for a better algorithm. However, rewriting the script is secondary to performing the task properly.</p>
<p>I've tested it and I'm fairly confident that I've created what I want. I just need some extra eyes to confirm.</p>
<pre><code>#!/usr/bin/perl
# Directives which establish our execution environment
use warnings;
use strict;
use Fcntl ':mode';
use File::Find;
no warnings 'File::Find';
no warnings 'uninitialized';
# Variables used throughout the script
my $DIR = "/var/log/tivoli/";
my $MTAB = "/etc/mtab";
my $PERMFILE = "world_writable_w_files.txt";
my $TMPFILE = "world_writable_files.tmp";
my $EXCLUDE = "/usr/local/etc/world_writable_excludes.txt";
my $ROOT = "/";
my @devNum;
# Create an array of the file stats for "/"
my @rootStats = stat("${ROOT}");
# Compile a list of mountpoints that need to be scanned
my @mounts;
open MT, "<${MTAB}" or die "Cannot open ${MTAB}, $!";
# We only want the local mountpoints
while (<MT>) {
if ($_ =~ /ext[34]/) {
my @line = split;
push(@mounts, $line[1]);
}
}
close MT;
# Read in the list of excluded files and create a regex from them
my $regExcld = do {
open XCLD, "<${EXCLUDE}" or die "Cannot open ${EXCLUDE}, $!\n";
my @ignore = <XCLD>;
chomp @ignore;
local $" = '|';
qr/@ignore/;
};
# Create a regex containing mountpoint dev numbers to compare file device numbers to.
my $devRegex = do {
chomp @devNum;
local $" = '|';
qr/@devNum/;
};
# Create the output file path if it doesn't already exist.
mkdir("${DIR}" or die "Cannot execute mkdir on ${DIR}, $!") unless (-d "${DIR}");
# Create our filehandle for writing our findings
open WWFILE, ">${DIR}${TMPFILE}" or die "Cannot open ${DIR}${TMPFILE}, $!";
foreach (@mounts) {
# The anonymous subroutine which is executed by File::Find
find sub {
# Is it in a basic (non-special) directory, ...
return if $File::Find::dir =~ /sys|proc|dev/;
# ...a regular file, ...
return unless -f;
# ...local, ...
my @dirStats = stat($File::Find::name);
return unless $dirStats[0] =~ $devRegex;
# ...and world writable?
return unless (((stat)[2] & S_IWUSR) && ((stat)[2] & S_IWGRP) && ((stat)[2] & S_IWOTH));
# Add the file to the list of found world writable files unless it is
# in the list if exclusions
print(WWFILE, "$File::Find::name\n") unless ($File::Find::name =~ $regExcld);
}, $_;
}
close WWFILE;
# If no world-writable files have been found ${TMPFILE} should be zero-size;
# Delete it so Tivoli won't alert
if (-z "${DIR}${TMPFILE}") {
unlink "${DIR}${TMPFILE}";
} else {
rename("${DIR}${TMPFILE}","${DIR}${PERMFILE}") or die "Cannot rename file ${DIR}${TMPFILE}, $!";
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:38:32.367",
"Id": "81454",
"Score": "2",
"body": "Tips on optimization and general code-quality are things you'll get from this site. However, wether or not this code fulfills your requirements is, IMO, part of _your_ job (develop, debug, test, and develop some more). That's not entirely part of code-review. Anyway, welcome to the site"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:13:34.510",
"Id": "81594",
"Score": "0",
"body": "You are correct. The writing, debugging, etc is my responsibility and I have done this. I guess I'm looking for validation :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T21:46:45.737",
"Id": "83046",
"Score": "0",
"body": "A few comments off the top of my head: 1) Don't turn off warnings; fix the code that emits the warnings. 2) Don't comment things that are obvious, e.g. \"Directives which establish our execution environment\" and \"Variables used throughout the script.\" 3) Use lowercase for variables since built-in variables tend to use all-caps. 4) Use lexical filehandles and the 3-argument open, e.g. `open my $fh, '<', $file or die \"$file: $!\";` 5) Instead of generating complex regexes (which you haven't anchored, by the way, so they will probably match more than you want), use hashes: *(continue)*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T21:53:35.953",
"Id": "83049",
"Score": "0",
"body": "e.g. `my %ignore = map { $_ => 1 } @array;` 6) Don't call `find` in a loop, just call it once with `@mounts` as the second argument. 7) Write a separate `wanted` sub and pass it to `find` to improve readability. 8) Don't use `rename` as it's not portable. Instead use `move` from [File::Copy](http://perldoc.perl.org/File/Copy.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T22:33:20.163",
"Id": "84050",
"Score": "0",
"body": "I'm working through your suggestions. So far I've only modified variable names. I have a couple questions: When you say call `find` with `@mounts` as the second argument how do you mean? Would it be `}, $_, @mounts;`? For anchoring the regexes (If I stick with that rather than mapping to a hash) would this be correct: `qr/^@devNum$/;`? I'm not sure I know how to use a separate `wanted` sub."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T23:05:01.830",
"Id": "88901",
"Score": "0",
"body": "@ThisSuitIsBlackNot Can you please elaborate on your suggestions in an answer? I'm not following some of them. The comments I get, but such things as the find or hash I'd like some examples of, if you don't mind."
}
] | [
{
"body": "<h3>Processing mount points</h3>\n\n<p>This can be improved in many ways:</p>\n\n<blockquote>\n<pre><code># Compile a list of mountpoints that need to be scanned\nmy @mounts;\nopen MT, \"<${MTAB}\" or die \"Cannot open ${MTAB}, $!\";\n\n# We only want the local mountpoints\nwhile (<MT>) {\n if ($_ =~ /ext[34]/) {\n my @line = split;\n push(@mounts, $line[1]);\n }\n}\n\nclose MT;\n</code></pre>\n</blockquote>\n\n<p>Using bare names for file handles is not recommended: \nreplace <code>MT</code> with <code>my $MT</code>, and <code><MT></code> with <code><$MT></code>.</p>\n\n<p>The comment talks about local mount points.\nThat's too vague, when in fact you're looking specifically for <code>ext3</code> and <code>ext4</code> filesystems.</p>\n\n<p>You could simplify <code>if ($_ =~ /ext[34]/)</code> as <code>if (/ext[34]/)</code>.</p>\n\n<p>You could put the entire <code>while</code> loop inside a <code>map</code>, and it will be still readable.</p>\n\n<p>Putting it together, you can rewrite like this:</p>\n\n<pre><code>open my $MT, \"<${MTAB}\" or die \"Cannot open ${MTAB}, $!\";\n\n# Compile a list of mountpoints that need to be scanned\n# We only want the ext3 ext4 partitions\nmy @mounts = map((split)[1], grep(/ext[34]/, <$MT>));\n\nclose $MT;\n</code></pre>\n\n<p>Note that if you didn't find any mount points,\nthe script has nothing to process, so it should exit:</p>\n\n<pre><code>die 'no mount points to process' unless @mounts;\n</code></pre>\n\n<p>Try to apply these techniques everywhere in the script,\nespecially the bit about filehandlers.</p>\n\n<hr>\n\n<blockquote>\n<pre><code># Read in the list of excluded files and create a regex from them\nmy $regExcld = do {\n open XCLD, \"<${EXCLUDE}\" or die \"Cannot open ${EXCLUDE}, $!\\n\";\n my @ignore = <XCLD>;\n chomp @ignore;\n local $\" = '|';\n qr/@ignore/;\n};\n</code></pre>\n</blockquote>\n\n<p>As earlier, replace <code>XCLD</code> with <code>my $XCLD</code> or something.\nYou also forgot to <code>close</code> it.</p>\n\n<p>Btw, a common way to shorten <code>my @arr = <$fh>; chomp @arr</code> as <code>chomp(my @arr = <$fh>)</code>.</p>\n\n<p>Most importantly,\nshould it be really a fatal error if the file with excluded patterns doesn't exist?\nIt might make sense to make this optional.\nPerhaps issue a warning instead, something like this:</p>\n\n<pre><code>my $regExcld = do {\n if (open my $fh, \"<${EXCLUDE}\") {\n chomp(my @ignore = <$fh>);\n close($fh);\n local $\" = '|';\n qr/@ignore/;\n } else {\n warn \"Cannot open ${EXCLUDE}, $!\\n\";\n undef;\n }\n};\n</code></pre>\n\n<hr>\n\n<p>This bit seems pointless:</p>\n\n<blockquote>\n<pre><code># Create a regex containing mountpoint dev numbers to compare file device numbers to.\nmy $devRegex = do {\n chomp @devNum;\n local $\" = '|';\n qr/@devNum/;\n};\n</code></pre>\n</blockquote>\n\n<p>Because <code>@devNum</code> is an empty array in your script,\nyou never actually gave it any values.</p>\n\n<hr>\n\n<p>This is quite strange:</p>\n\n<blockquote>\n<pre><code># Create the output file path if it doesn't already exist.\nmkdir(\"${DIR}\" or die \"Cannot execute mkdir on ${DIR}, $!\") unless (-d \"${DIR}\");\n</code></pre>\n</blockquote>\n\n<p>You misplaced the <code>die</code>:\nit will run if <code>\"${DIR}\"</code> is empty,\nnot if <code>mkdir</code> fails.</p>\n\n<p>Also, there's no need whatsoever to double-quote <code>${DIR}</code>.</p>\n\n<p>Corrected and simplified:</p>\n\n<pre><code>mkdir($DIR) or die \"Cannot execute mkdir on ${DIR}, $!\" unless -d $DIR;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-17T15:12:24.977",
"Id": "60301",
"ParentId": "46611",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T05:22:01.460",
"Id": "46611",
"Score": "3",
"Tags": [
"perl",
"file-system",
"linux"
],
"Title": "Finding world-writable files in local directories only"
} | 46611 |
<p>I am formally a PHP/C# developer and I am new to C. I need you to help to correct my coding with C.</p>
<p>I have a kind of following pieces of HTTP user data string.</p>
<pre><code>char *userData = "=GET /ad26908aa2e811e3855e0a22f2d2d906_8.jpg HTTP/1.1..Host: distilleryimage10.ak.instagram.com..Connection: keep-alive..Accept-Encoding: gzip, deflate..User-Agent: Instagram 4.2.7 (iPhone6,2; iPhone OS 7_0_6; en_US; en) AppleWebKit/420+..Accept-Language: en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5..Accept: */*....";
</code></pre>
<p>I need to capture/slice <code>Host</code>, <code>Query String</code> and <code>httpmethod</code> from the above char string.</p>
<p>My function is below.</p>
<pre><code>int diggForUrl(char *userData, HttpData *httpData)
{
const char str_GET[] = "GET";
const char str_POST[] = "POST";
const char str_DELETE[] = "DELETE";
const char str_PUT[] = "PUT";
const char str_HTTP[] = "HTTP";
const char str_HOST[] = "Host:";
char httpMethod[10] = {'\0'};
char *qString = (void *) 0;
char *host = (void *) 0;
char *ptr_SRV_CMD = (void *) 0;
if (ptr_SRV_CMD = strstr (userData, str_GET)) {
strncpy(httpMethod, str_GET, strlen(str_GET));
}
else if (ptr_SRV_CMD = strstr (userData, str_POST)) {
strncpy(httpMethod, str_POST, strlen(str_POST));
}
else if (ptr_SRV_CMD = strstr (userData, str_DELETE)) {
strncpy(httpMethod, str_DELETE, strlen(str_DELETE));
}
else if (ptr_SRV_CMD = strstr (userData, str_PUT)) {
strncpy(httpMethod, str_PUT, strlen(str_PUT));
}
if (ptr_SRV_CMD == NULL)
return -1;
char *ptr_HTTP = strstr(userData, str_HTTP);
if (ptr_HTTP && ptr_SRV_CMD) {
char *ptr_qs_start = ptr_SRV_CMD + strlen(httpMethod) + 1;
// Compare the HTTP position and METHOD position
if (ptr_HTTP > ptr_qs_start) {
// Create query string size
int qsSize = ptr_HTTP - ptr_qs_start;
qString = malloc(qsSize + 1);
memset(qString, '\0', (qsSize + 1));
strncpy(qString, ptr_qs_start, qsSize);
}
}
char *ptr_HOST = strstr(userData, str_HOST);
if (ptr_HOST){
char *ptr_HOST_END = strstr(ptr_HOST, "..");
if (ptr_HOST_END) {
int hostSize = ptr_HOST_END - (ptr_HOST + (strlen(str_HOST) + 1));
host = malloc(hostSize + 1);
memset(host, '\0', hostSize + 1);
strncpy(host, (ptr_HOST + strlen(str_HOST) + 1), hostSize);
}
}
// copy final value of httpMethod char array to char string
httpData->httpMethod = malloc(sizeof(httpMethod) + 1);
memset(httpData->httpMethod, '\0', sizeof(httpMethod) + 1);
strncpy(httpData->httpMethod, httpMethod, sizeof(httpMethod) + 1);
httpData->host = host;
httpData->qString = qString;
return 0;
}
</code></pre>
<p>and struct which I am capturing the data into is</p>
<pre><code>typedef struct {
char *httpMethod;
char *host;
char *qString;
} HttpData;
</code></pre>
<p>This code runs and give me expected result. Still I feel the coding is not neat and it can be improved. Also, if I run this with <code>valgrind</code> I am getting the message that there are leaks.</p>
<pre><code>==16470== Memcheck, a memory error detector
==16470== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==16470== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==16470== Command: ./http_data_digg
==16470==
GET
distilleryimage10.ak.instagram.com
/ad26908aa2e811e3855e0a22f2d2d906_8.jpg
==16470==
==16470== HEAP SUMMARY:
==16470== in use at exit: 87 bytes in 3 blocks
==16470== total heap usage: 3 allocs, 0 frees, 87 bytes allocated
==16470==
==16470== LEAK SUMMARY:
==16470== definitely lost: 87 bytes in 3 blocks // <<======= LOST HERE
==16470== indirectly lost: 0 bytes in 0 blocks
==16470== possibly lost: 0 bytes in 0 blocks
==16470== still reachable: 0 bytes in 0 blocks
==16470== suppressed: 0 bytes in 0 blocks
==16470== Rerun with --leak-check=full to see details of leaked memory
==16470==
==16470== For counts of detected and suppressed errors, rerun with: -v
==16470== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 8)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:02:00.390",
"Id": "81450",
"Score": "0",
"body": "You (potentially, depending on which branches are taken) use `malloc` twice but never `free` anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:06:06.020",
"Id": "81451",
"Score": "0",
"body": "yea I could figure out that, I put freed them after using. now leak is gone. Please give me the feedback about the function. Can it be done simpler than this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:22:35.263",
"Id": "81458",
"Score": "0",
"body": "@BlueBird: You aren't freeing `host` and `qString` before the `return`, are you? because then you'd have undefined behaviour on your hands: the memory the struct members point to, then, would be freed..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:01:42.747",
"Id": "81477",
"Score": "0",
"body": "@Yuushi If you've spotted a bug, please write [an answer, not a comment.](http://meta.codereview.stackexchange.com/a/1479/9357)"
}
] | [
{
"body": "<p>Let's start by making this code just a lot easier to read (to my eye at least). I'd change:</p>\n\n<pre><code>const char str_GET[] = \"GET\";\n</code></pre>\n\n<p>This statement, without the <code>const</code> keyword would take a constant char array (string), and <em>copy</em> it to <code>str_GET</code>. But do we really need that copy? Of course not, instead, a constant pointer to an immutable string will do fine. Your compiler might even optimize your code to do just that, but still, instead, I'd assign the address of this string to a constant pointer, and write:</p>\n\n<pre><code>const char *str_GET = \"GET\";\n</code></pre>\n\n<p>However, this will create these pointers each time the function is called. You could make them static, especially given the fact that the strings themselves won't change in between function calls, too.<br>\nFor that very same reason, it would not be uncommon to see these string constants being defined as macro's, too.</p>\n\n<p>Next:</p>\n\n<pre><code>char httpMethod[10] = {'\\0'};\nchar *qString = (void *) 0;\nchar *host = (void *) 0;\n</code></pre>\n\n<p>Can be written as simple as this:</p>\n\n<pre><code>char httpMethod[10] = \"\",\n *qString = NULL,\n *host = NULL;\n//or on a separate line:\nchar *ptr_SRV_CMD = NULL;\n</code></pre>\n\n<p>I'd consider the latter easier to read, too. Casting <code>0</code> to a void pointer isn't <em>wrong</em>, but an uninitialized, safe pointer is called a NULL-pointer. Assign it <code>NULL</code>, then.<Br>\nIn C, <code>\"\"</code> is the same as writing <code>{'\\0'}</code>, only a lot shorter :).</p>\n\n<p>Moving on</p>\n\n<pre><code>if (ptr_SRV_CMD = strstr (userData, str_GET)) {\n strncpy(httpMethod, str_GET, strlen(str_GET));\n}\nelse if (ptr_SRV_CMD = strstr (userData, str_POST)) {\n strncpy(httpMethod, str_POST, strlen(str_POST));\n}\nelse if (ptr_SRV_CMD = strstr (userData, str_DELETE)) {\n strncpy(httpMethod, str_DELETE, strlen(str_DELETE));\n}\nelse if (ptr_SRV_CMD = strstr (userData, str_PUT)) {\n strncpy(httpMethod, str_PUT, strlen(str_PUT));\n}\n</code></pre>\n\n<p>Fine, though since <code>httpMethod</code> is already initialized to an empty string, you could use <code>strncat</code> here, too. However, using all those <code>strlen</code> calls really is adding quite pointless overhead. You <em>know</em> <code>httpMethod</code> is an empty string, and you know its size to be 10, so why not use a constant max length? optionally defined as macro:</p>\n\n<pre><code>#define HTTP_METHOD_LEN 10\n\nchar httpMethod[HTTP_METHOD_LEN] = \"\";\n//later on:\nstrncat(httpMethod, str_PUT, HTTP_METHOD_LEN-1);\n</code></pre>\n\n<p>In theory, you could even do away with that -1 at the end, simply because you <em>know</em> the source string (<code>str_POST</code>, <code>str_GET</code> and the like) will always fit in <code>httpMethod</code>.<br>\nWith that in mind, you could use:</p>\n\n<pre><code>strcpy(httpMethod, str_POST);\n</code></pre>\n\n<p>quite safely. It's bound to be faster, anyway.<br>\nAnyway, next:</p>\n\n<pre><code>if (ptr_SRV_CMD == NULL)\n return -1;\n</code></pre>\n\n<p>Why aren't you putting this in an <code>else</code> branch along with the previous <code>if-else if</code> blocks? I mean: <code>ptr_SRV_CMD</code> won't be <code>NULL</code> unless the substring in question wasn't found, right? then wouldn't this make more sense:</p>\n\n<pre><code>if (ptr_SRV_CMD = strstr (userData, str_GET)) {\n strncpy(httpMethod, str_GET, strlen(str_GET));\n}\nelse if (ptr_SRV_CMD = strstr (userData, str_POST)) {\n strncpy(httpMethod, str_POST, strlen(str_POST));\n}\nelse if (ptr_SRV_CMD = strstr (userData, str_DELETE)) {\n strncpy(httpMethod, str_DELETE, strlen(str_DELETE));\n}\nelse if (ptr_SRV_CMD = strstr (userData, str_PUT)) {\n strncpy(httpMethod, str_PUT, strlen(str_PUT));\n}\nelse//<-ptr_SRV_CMD is null here\n return -1;\n</code></pre>\n\n<p>Then you have 2 very similar blocks of code, perhaps consider writing a function for this bit, but change the code a little. I've put some remarks in comments</p>\n\n<pre><code>char *ptr_HTTP = strstr(userData, str_HTTP);\n//no need to check for ptr_SRV_CMD being a null pointer again here...\nif (ptr_HTTP && ptr_SRV_CMD) {\n char *ptr_qs_start = ptr_SRV_CMD + strlen(httpMethod) + 1;\n //This HAS to be true for this block to do anything\n //move it to the first if\n if (ptr_HTTP > ptr_qs_start) {\n //guaranteed to be positive at this point, perhaps use size_t?\n int qsSize = ptr_HTTP - ptr_qs_start;\n //malloc + memset == calloc\n qString = malloc(qsSize + 1);\n memset(qString, '\\0', (qsSize + 1));\n strncpy(qString, ptr_qs_start, qsSize);\n }\n}\n</code></pre>\n\n<p>So, what I'd write is this:</p>\n\n<pre><code>char *ptr_HTTP = NULL;//\nif ((ptr_HTTP = strstr(userData, str_HTTP)) != NULL\n && ptr_HTTP > (ptr_SRV_CMD + strlen(httpMethod) + 1))\n{\n int qsSize = ptr_HTTP - (ptr_SRV_CMD + strlen(httpMethod) + 1);\n qString = calloc(qsSize, sizeof *qString);\n strncpy(qString, ptr_qs_start, qsSize);\n}\n</code></pre>\n\n<p>A couple of remarks after a quick glance at your code, more to come shortly .</p>\n\n<p><em>Update - recommendation for future development</em><br>\nAs 200_success rightfully pointed out in his answer: you're implementing some form of rudimentary parsing functionality that will work +95% of the time in your case. As time progresses, however, and your project grows, it's not unlikely for you to find yourself having to constantly return to this code, add some functionality and fix new bugs all the time.</p>\n\n<p>For that reason, learning to use a parser lib could well be worth your while. In order for you to be able to keep using your structs, just write a simple wrapper around the lib you choose.<br>\nYou can then separate that code, compile and link it independently, which will make it easier to maintain, too.</p>\n\n<p>Here's a link to a <a href=\"http://sourceforge.net/p/uriparser/git/ci/master/tree/\" rel=\"nofollow\">decent lib for you to use</a>, but google around, there's many to choose from.</p>\n\n<p>Something else I'd like to say, even though this is <em>\"risky advice\"</em>: don't blindly rely on mem-leaks reported by valgrind. Valgrind is a mature tool, of course, and it's very valuable, but false positives aren't unheard of.<Br>\nBesides, unfreed pointers are, in many (if not most) cases <strong>not</strong> the cause of leaks. An unclosed file pointer, for example is far more likely to cause leaks.<br>\nIn fact, after a quick search <a href=\"http://www.c-faq.com/malloc/freeb4exit.html\" rel=\"nofollow\">this came up</a>, read the answer + links. It talks about what the job of <code>free</code> actually is, and how it rarely returns memory to the OS. It also explicitly states that you <em>shouldn't call <code>free</code> at the end of your program</em>. By That, they don't mean: it's bad of you to do so, but they're saying that: <em>it shouldn't be required of you, the OS should be able to reclaim the memory</em>.</p>\n\n<p>And indeed, most modern OS's will in fact reclaim un-freed pointers the moment a process terminates. When those pointers can in fact be <code>NULL</code> pointers, then it's also best to check before calling <code>free</code>.<Br>\nPerhaps you've heard this before, but calling <code>free</code> on an uninitialized pointer is dangerous, and outright wrong. Calling <code>free</code> on a <code>NULL</code> pointer is deemed safe (as in no undefined behaviour), but it's a pointless function call. Choosing to write something in C often implies writing time-critical applications, so any pointless function call is to be avoided.<br>\nCouple that to what I've said before: most OS's being able to reclaim unfreed memory and you will, I hope, understand that I would alter code like this:</p>\n\n<pre><code>int main ( void )\n{\n char * my_buffer = malloc(20000 * sizeof *my_buffer);\n //do stuff\n if (request_clear_buffer())\n free(my_buffer);\n //do more stuff\n free(my_buffer);//<== DANGER\n return 0;\n}\n</code></pre>\n\n<p>To look like this, when I get my hands on it:</p>\n\n<pre><code>int main ( void )\n{\n char * my_buffer = malloc(20000 * sizeof *my_buffer);\n //do stuff\n if (my_buffer && request_clear_buffer() == true)\n {\n free(my_buffer);\n my_buffer = NULL;//<-- safety first\n }\n //do more stuff\n /**\n * Uncomment if you want, but free before return on our system\n * is pointless, system will reclaim memory just fine\n *\n * if (my_buffer) free(my_buffer);\n */\n return 0;\n}\n</code></pre>\n\n<p>Of course, if this code is ever to be used in other projects, and I don't know what system it'll be running under, I will uncomment the code. But on most OS's, there really is no need to do so.</p>\n\n<p>You may be wondering why I said this to be <em>risky</em> advice, and why people keep saying how <em>\"every malloc/calloc/realloc call must be accompanied by a free call\"</em>. That's simple: it's not because, at some point you need to allocate memory that that chunk of memory will be required for as long as your program runs.<Br>\nThe reason why <code>free</code> is an important function is because it allows you, as programmer, to use heap memory, and release it as soon as you're done playing with it. If you never do so, the program's memory usage will just grow and grow, right up to the point where either the heap is depleted or the program exits. Only at that point, all of the memory you claimed will be freed again.<br>\nThat's why <code>malloc</code> without <code>free</code> is deemed <em>bad practice</em>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:21:06.750",
"Id": "46622",
"ParentId": "46616",
"Score": "3"
}
},
{
"body": "<p><em>Ad hoc</em> string searching is a poor substitute for parsing the headers according to <a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-4\" rel=\"nofollow noreferrer\">RFC 2616</a>. That is, you should split the request by <kbd>CR</kbd><kbd>NL</kbd> line breaks. For the first line, look for three space-separated words. On subsequent lines, look for a field name, followed by a <code>:</code>, followed by the field value.</p>\n<p>As currently written, your code could get fooled by a request that looks like:</p>\n<pre><code>POST /KFC/CHICKEN_NUGGETS.jpg HTTP/1.0\nHost: example.com\n</code></pre>\n<p>or by</p>\n<pre><code>GET /wiki/List_of_HTTP_status_codes HTTP/1.0\nHost: en.wikipedia.org\n</code></pre>\n<hr />\n<p>What you call the "Query String", the RFC calls the "URI". <a href=\"https://www.rfc-editor.org/rfc/rfc3986#section-3.4\" rel=\"nofollow noreferrer\">RFC 3986</a> defines the Query String to be the part of the URI that follows a <code>?</code> and precedes a <code>#</code> (if it exists). To avoid confusion, you should use the commonly accepted vocabulary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:16:55.740",
"Id": "81470",
"Score": "0",
"body": "Good point on the parsing according to RFC recommendations. Hope you don't mind my adding that to my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:44:32.670",
"Id": "81473",
"Score": "0",
"body": "@EliasVanOotegem Answers don't need to be all-encompassing; [short answers are perfectly fine, and encouraged](http://meta.codereview.stackexchange.com/q/1008/9357)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:56:31.033",
"Id": "81475",
"Score": "0",
"body": "Nips, I didn't get that memo. My answers tend to be quite verbose, I know. However your point was too important not to mention in my answer, too. hence the +1, but I'll stop editing my answer meanwhile before it's long enough to be published as a booklet"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:06:19.603",
"Id": "46627",
"ParentId": "46616",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T06:34:35.607",
"Id": "46616",
"Score": "1",
"Tags": [
"c",
"memory-management"
],
"Title": "Capture and assign portions of char array to a struct"
} | 46616 |
<p>Please review the following code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *some_text = "THIS IS SOME ARBITRARY TEXT FOR TESTING THE STRLEN AND COPY FUNCTIONS";
char *test = malloc(strlen(some_text) + 1);
strncpy(test, some_text, strlen(some_text));
strcat(test, "\0");
printf("%s\n", test);
if (test != NULL) free (test);
}
</code></pre>
<ol>
<li><p>create a <code>char* some_text</code> with constant string;</p></li>
<li><p>create a <code>char*test</code> with and allocate memory the size of <code>some_text</code></p></li>
<li><p>copy the content of <code>some_text</code> to <code>test</code></p></li>
<li><p>concatenate the termination character to <code>test</code></p></li>
<li><p>print out the <code>test</code></p></li>
<li><p>free the <code>test</code> pointer</p></li>
</ol>
<p>If I run this with <code>valgrind</code>, it says:</p>
<pre><code>==31176== Conditional jump or move depends on uninitialised value(s)
==31176== at 0x4008667: __GI_strlen (mc_replace_strmem.c:404)
==31176== by 0x861DD4: puts (in /lib/libc-2.12.so)
==31176== by 0x80484DF: main (strlen_and_copy.c:13)
</code></pre>
<p>The line mentioned in <code>valgrind</code> output strlen_and_copy.c:13 is below:</p>
<pre><code>printf("%s\n", test);
</code></pre>
<p>Is it avoidable or should it be ignored? What is wrong with my code above? Someone please explain.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:15:34.850",
"Id": "81457",
"Score": "0",
"body": "Is that Valgrind's cryptic way of complaining that you didn't check whether `malloc()` returned `NULL`?"
}
] | [
{
"body": "<p>Some general remarks to your code:</p>\n\n<ol>\n<li>You should store the string length as a variable rather than calling it multiple times.</li>\n<li>If you do <code>strncpy(test, some_text, strlen(some_text) + 1)</code> you can get rid of the <code>strcat</code> as <code>strncpy</code> will padd the remainder with <code>\\0</code> if <code>src</code> is less than <code>n</code> characters.</li>\n<li>You don't need to test for <code>NULL</code> before <code>free</code>\n<ul>\n<li>a) because you'd get a segfault anyway before that line of code if it were <code>NULL</code></li>\n<li>b) because the standard guarantees that it is safe to call <code>free(NULL)</code></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:32:57.947",
"Id": "81459",
"Score": "0",
"body": "Thaks @chrisWue, Actually why this output is coming in valgrind `==31176== at 0x4008667: __GI_strlen (mc_replace_strmem.c:404)` ? Still it is availeble"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:38:47.647",
"Id": "81461",
"Score": "0",
"body": "Thaks @chrisWue, Ok. your 2nd point made it success."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:48:12.187",
"Id": "46621",
"ParentId": "46619",
"Score": "8"
}
},
{
"body": "<p>First string you pass to <a href=\"http://en.cppreference.com/w/c/string/byte/strcat\" rel=\"noreferrer\">strcat</a> is not null-terminated, which is incorrect (it takes two null-terminated byte strings). Actually it is null-terminated, but only because malloc returns pointer to zeroed memory on your system. Anyway, after call to strncpy you have a string with last byte uninitialized.</p>\n\n<p>This code</p>\n\n<pre><code>strcat(test, \"\\0\");\n</code></pre>\n\n<p>does nothing (\"\\0\" and \"\" are equal).</p>\n\n<p>To make it correct you can write</p>\n\n<pre><code>strcpy(test, some_text);\n// without strcat\n</code></pre>\n\n<p>or</p>\n\n<pre><code>strncpy(test, some_text, strlen(some_text) + 1)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>strncpy(test, some_text, strlen(some_text));\ntest[strlen(some_text)] = 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T09:12:26.800",
"Id": "81463",
"Score": "5",
"body": "Good observation that `strcat()` cannot be used to add a NUL terminator to a string that doesn't already have one. Also a good observation that `test` is NUL terminated more by luck than by design. However, @ChrisWue's `strncpy(test, some_text, strlen(some_text) + 1)` is a better solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T08:21:36.110",
"Id": "46623",
"ParentId": "46619",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46621",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:21:07.090",
"Id": "46619",
"Score": "7",
"Tags": [
"c",
"strings",
"memory-management"
],
"Title": "Conditional jump or move depends on uninitialised value"
} | 46619 |
<p>I need to seed a database with user data.</p>
<p>When trying to write records to a file using sqlite3 with node, I tried writing the logic in a naive manner, without any error checks - but it was failing with numerous SQLITE_BUSY database locked errors.</p>
<p>Then I added code to retry in case of an error, but was insufficient - ended up with corrupt tables, and so I added transactions as suggested on freenode.</p>
<p>Now, it works. However the problem is that it is pathetically slow - takes up to 5 minutes for around 50 records. Also, I need to pass in a retries parameter of roughly <code>number_of_users * 2</code> in order for the process to complete successfully or else it bails out. Something is not correct, but I cannot pin it down. </p>
<p>What is wrong?</p>
<pre><code>//in the constructor ...
function TestController (api_url_root,number_of_users,number_of_devices) {
...
this.user_write_q = async.queue(function (task,callback) {
that.registerUserWithAPI(task.username, task.email, task.password, task.runAfterAllUsersAdded, callback);
}, 1);
this.user_write_q.drain = function() {
console.log("Finished adding all users - queue drained");
}
...
}
TestController.prototype.addUsers = function (callback_after_all_users_have_been_added) {
this.pending_db_writes_for_user = this.number_of_users;
fs.appendFileSync(this.user_list_file_path,"user email, password, api_key, api_secret\n");
for(var i=0;i < this.number_of_users;i++) {
var username = Faker.Name.findName();
var useremail = Faker.Internet.email();
var password = Faker.Lorem.words(1)[0];
this.user_write_q.push({username: username, email: useremail, password: password, runAfterAllUsersAdded: callback_after_all_users_have_been_added});
console.log("Remaining requests: " + that.user_write_q.length());
}
};
TestController.prototype.registerUserWithAPI = function (username, useremail, password, callback_after_all_users_have_been_added, queueCallback) {
var controller = this;
var post_options = {
host: this.api_url_root,
path: '/users/'+ useremail,
method: 'POST',
headers: {
'Content-type': 'application/json'
}
}
var post_req = http.request(post_options, function (res) {
var data = "";
res.setEncoding('utf8');
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
var dat = JSON.parse(data);
controller.writeUserToLocalDatabase(controller.number_of_users*2,username,useremail,password,dat.api_key,dat.api_secret, queueCallback, callback_after_all_users_have_been_added);
});
});
var post_data = '{"name":"'+username+'","password":"'+ password + '"}';
post_req.write(post_data);
post_req.end();
}
TestController.prototype.writeUserToLocalDatabase = function (retries,username,useremail,password,api_key,api_secret, queueCallback, callback_after_all_users_have_been_added) {
var dbase = this.connectToDb();
var controller = this;
if (retries < 0) {
console.log("Bailing out of writeUserToLocalDatabase after max retry attempts");
return;
}
dbase.run("BEGIN TRANSACTION");
var stmt = dbase.prepare("insert into user_table values(?,?,?,?,?)", function(err) {
if(err !== null) {
console.log("Error when trying to write user to database in prepare! "+err);
dbase.run("ROLLBACK");
dbase.close(function(err){if(err !== null) {console.log("Close failed in in prepare "+err);}});
controller.writeUserToLocalDatabase(--retries,username,useremail,password,api_key,api_secret, queueCallback, callback_after_all_users_have_been_added);
}
});
stmt.run(username,useremail,password,api_key,api_secret, function(err) {
if(err !== null) {
//console.log("Error when trying to write user to database in run! "+err);
stmt.finalize();
dbase.run("ROLLBACK");
dbase.close(function(err){if(err !== null) {console.log("Close failed in in run "+err);}});
controller.writeUserToLocalDatabase(--retries,username,useremail,password,api_key,api_secret,queueCallback, callback_after_all_users_have_been_added);
}
else {
stmt.finalize(function(err) {
if(err !== null && err !== undefined) {
console.log("Error when trying to write user to database in finalize ! "+err);
dbase.run("ROLLBACK");
dbase.close(function(err){if(err !== null) {console.log("Close failed in in finalize "+err);}});
controller.writeUserToLocalDatabase(--retries,username,useremail,password,api_key,api_secret, queueCallback, callback_after_all_users_have_been_added);
}
else {
dbase.run("COMMIT");
controller.appendToUserFile(useremail,password,api_key,api_secret);
controller.pending_db_writes_for_user--;
if (controller.pending_db_writes_for_user <= 0) {
console.log("Finished writing all users, now invoking db.close with callback");
queueCallback();
dbase.close(callback_after_all_users_have_been_added);
}
else {
console.log("Remaining users to add: "+controller.pending_db_writes_for_user);
dbase.close(function(err){if(err !== null) {console.log("Close failed in after adding user "+err);}});
queueCallback();
}
}
});
}
});
}
</code></pre>
<p>EDIT ---
The code works acceptably.
I managed to improve the performance by orders of magnitude by using async.queue with a queue length of 1 - now about 5 records per second as compared to 20 seconds per record. However this remains an open question about the best way to do concurrent writes to an sqlite3 database from node.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:36:44.820",
"Id": "81503",
"Score": "2",
"body": "I would simply generate a file with `INSERT` statements in Node. Then upload that file straight into your SQLITE database. I do not believe that your approach is meant for ETL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:04:50.283",
"Id": "81529",
"Score": "1",
"body": "What @konijn said. 5 minutes for 50 records sounds utterly insane. In this case you're (presumably) inserting valid, trusted data, so you don't need to muck around with prepared statements, transactions and all the other things you usually have to deal with. You can just truncate (or drop) the table and load all the rows wholesale from a file. Or just point `this.dbpath` to a pre-seeded .sqlite file for that matter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T00:09:54.780",
"Id": "81642",
"Score": "0",
"body": "Okay ... but a part of this fake data comes from a web api server, this function gets called after the api key and secret is received from the server. The simple way out would be to just append to a simple text file, however, using the sqlite3 module is a good opportunity to try working with the async nature of node, and say 50 writes would not seem to be a far fetched scenario even for a non ETL scenario"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T23:31:12.190",
"Id": "82019",
"Score": "0",
"body": "@BenVlodgi yes, thanks, I looked at the help center section. As I mentioned in the edit, the code now does what I want. The question is about performance - and looking at the help center, it lists performance in the very top of http://codereview.stackexchange.com/help/on-topic"
}
] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>The constructor could use some rework:</p>\n\n<ul>\n<li>You are not using any of the parameters, you might as well not declare them</li>\n<li>It would be cleaner to just send <code>task</code> to <code>registerUserWithAPI</code> since it has almost all the info</li>\n<li>lowerCamelCase is the standard</li>\n<li>The magical constant 1 should be documented<br></li>\n</ul>\n\n<p>so you could have something like this instead:</p>\n\n<pre><code>function TestController () {\n\n var concurrency = 1; //Only allow one task at a time\n\n this.userCreationQueue = async.queue(function (task,callback) {\n that.registerUserWithAPI(task, callback);\n }, concurrency );\n\n this.userCreationQueue.drain = function() {\n console.log(\"Finished adding all users - queue drained\");\n }\n}\n</code></pre>\n\n<p>A minor side note, perhaps your test is super slow because of that concurrency setting ?</p></li>\n<li><p>You are writing a lot of code, with really length names to a) determine when the last record is written b) what to do in that case. In my mind, that is what <code>drain</code> was designed for. The database connection should have been managed in <code>function TestController</code> and should have been closed in <code>drain</code>. This would make your code leaner..</p></li>\n<li>Also, please fix indentation, <code>var post_req</code> is a bit of a mess</li>\n</ul>\n\n<p>In the end, it seems like you have been troubleshooting this code a lot, and you have left a number of things in there because you were debugging with <code>console.log</code> statements. You should fix that. Also, you should try to loosen up the <code>concurrency</code> value; 1 at a time, is not a good test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:46:26.943",
"Id": "82277",
"Score": "0",
"body": "Thanks, setting concurrency to anything more than 1 *slows* up the operation, causing multiple errors during the writes, almost as if the sqlite3 library was not designed for concurrency. I had to use the async module just to throttle the writes. The correct way of using sqlite3 is a part of the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:51:21.783",
"Id": "82278",
"Score": "0",
"body": "Also, this is just for setting up the test instance data - registering users and devices with a cloud api and recording the seed data to a local database. A Test Runner will then use this seed data to do the actual testing. This class should be named TestConfigurator or something similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:55:07.343",
"Id": "82279",
"Score": "0",
"body": "The large volume of code is because when doing concurrent writes, SQLITE_BUSY database locked errors would occur at random points and hence wrapping the operation in a transaction and rolling back any time the error occurs was necessary."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T16:28:33.423",
"Id": "46939",
"ParentId": "46620",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T07:28:44.817",
"Id": "46620",
"Score": "3",
"Tags": [
"javascript",
"performance",
"node.js",
"error-handling",
"sqlite"
],
"Title": "Seeding a file with fake records - doing concurrent updates"
} | 46620 |
<p>Please let me know a better approach to solve below problem:</p>
<p><strong>Problem:</strong> Vertically arrange the words in a string and print on console.</p>
<p><strong>Sample Input:</strong></p>
<blockquote>
<pre><code>Hello Jack
</code></pre>
</blockquote>
<p><strong>Output:</strong></p>
<blockquote>
<pre><code>H J
e a
L c
L k
o
</code></pre>
</blockquote>
<p><strong>My solution:</strong></p>
<pre><code>public static void toVerticalWords(String str){
//split the words by whitespace
String[] strArr = str.split("\\s");
int maxWordLen = 0;
//get the longest word length
for(String strTemp : strArr) {
if(strTemp.length() > maxWordLen)
maxWordLen = strTemp.length();
}
//make a matrix of the words with each character in an array block
char[][] charArr = new char[strArr.length][maxWordLen];
for(int i=0; i<strArr.length; i++) {
int j=0;
for(char ch : strArr[i].toCharArray()){
charArr[i][j] = ch;
j++;
}
}
//print the vertical word pattern, or transpose of above matrix (2D array)
for(int j=0; j<maxWordLen; j++) {
for(int i=0; i<strArr.length; i++) {
if (i!=0)
System.out.print(" ");
System.out.print(charArr[i][j]);
}
System.out.println();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:36:27.270",
"Id": "81471",
"Score": "0",
"body": "Not an answer, but an idea: In the end you are requesting the \"zip\" function, which exist in several functional programming languages. Java also got functional elements with the Version SE 8.\nUnfortunately the zip-function is not implemented by the standard libraries. But it is doing exactly, what you implemented - only in a more generic way. Here is an example implementation with no functional syntax: http://stackoverflow.com/questions/3833814/java-how-to-write-a-zip-function-what-should-be-the-return-type"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:24:18.663",
"Id": "81498",
"Score": "0",
"body": "@Wintermute Think its an overkill in the context of this question. But a good share. I will see."
}
] | [
{
"body": "<ol>\n<li><p>Looking at this code:</p>\n\n<pre><code>if(strTemp.length() > maxWordLen)\n maxWordLen = strTemp.length();\n</code></pre>\n\n<p>This could be reduced to: </p>\n\n<pre><code>maxWordLen = Math.max(maxWordLen,strTemp.length());\n</code></pre></li>\n<li><p>Inline the incrementation: </p>\n\n<pre><code>charArr[i][j++] = ch;\n</code></pre>\n\n<p>Or just use System.arraycopy:</p>\n\n<pre><code>char[][] charArr = new char[strArr.length][maxWordLen];\nfor (int i = 0; i < strArr.length; i++) {\n System.arraycopy(strArr[i].toCharArray(), 0, charArr[i], 0, strArr[i].length());\n}\n</code></pre></li>\n<li><p>Either inline the output:</p>\n\n<pre><code>System.out.print((i != 0 ? \" \" : \"\") + charArr[i][j]);\n</code></pre>\n\n<p>or at least place braces:</p>\n\n<pre><code>if (i!=0){\n System.out.print(\" \");\n}\n</code></pre>\n\n<p>4 . If you wonder about other solutions, check this one:</p>\n\n<pre><code>int i = 0;\n\nboolean hasMoreChars = true;\n\nwhile (hasMoreChars) {\n\n hasMoreChars = false;\n\n for (String str : strArr) {\n\n if (i < str.length()) {\n\n hasMoreChars = true;\n\n System.out.print(str.charAt(i) + \" \");\n }\n else {\n //two spaces, added by xploreraj in Edit\n //in case a shorter word comes before longer word\n //we must compensate the absence of character with space\n System.out.print(\" \");\n }\n }\n System.out.println();\n i++;\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:18:14.320",
"Id": "81496",
"Score": "0",
"body": "Thanks, noted. But I am expecting a better logic which is reader friendly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:44:41.650",
"Id": "81525",
"Score": "0",
"body": "This 4th point code is neat and nice. But it misses out on the whitespace in case a smaller word comes in front of a bigger word. And the bigger word letters will come below previous smaller word."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:21:12.883",
"Id": "81565",
"Score": "1",
"body": "I would explicitly recommend *against* in-lining an increment (number 2). Errors involving whether the increment returns the original or the new value are well known. (I personally can never keep it straight.) Also, embedding side effects in a line that is doing something else makes your logic dense enough that interpreting the code becomes more difficult; it is easier to understand that side effects are occurring when explicitly separate calls are made. (I would argue that for readability and simplicity, increment shouldn't even have a return value, personally.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:33:29.303",
"Id": "81678",
"Score": "0",
"body": "The point 4 is concise and easily understandable. Accepting as answer (alternate easy logic)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T09:58:03.067",
"Id": "46626",
"ParentId": "46624",
"Score": "10"
}
},
{
"body": "<p>I assume you are only trying to work with ASCII characters, but I would like to point out a few Unicode-related failure modes, which can be exhibited by the following code:</p>\n\n<pre><code>String[] funkyStrings = {\n \"foo bar\",\n \"foo ba\\u0308r\",\n \"\\ud835\\udcbb\\u2134\\u2134 \\ud835\\udcb7\\ud835\\udcb6\\ud835\\udcc7\"\n};\nfor (String str : funkyStrings) {\n System.out.println(str);\n toVerticalWords(str);\n}\n</code></pre>\n\n<p>The first string produces ordinary output:</p>\n\n<pre><code>foo bar\nf b\no a\no r\n</code></pre>\n\n<p>The second string contains a grapheme cluster that is made up from multiple code points – the <code>a</code> and an accent <code>̈</code> which together create the glyph <code>ä</code> (← that's the precomposed form showing how it should look, as not all fonts handle combined characters correctly)</p>\n\n<pre><code>foo bär\nf b\no a\no ̈\n r\n</code></pre>\n\n<p>The third string uses mathematical glyphs which have code points beyond <code>U+FFFF</code>. Because Java is slightly Unicode-retarded and can't deal with such high code points properly, its <code>char</code>s are actually UTF-16 code units (16 bit wide, far to small for what we are dealing with here). Therefore, higher code points have to be specified as a pair of surrogate halves. The encoding for <code>U+1D4BB</code> is <code>d835 dcbb</code> in UTF-16BE. This now produces the following output:</p>\n\n<pre><code>ℴℴ \n? ?\n? ?\nℴ ?\nℴ ?\n ?\n ?\n</code></pre>\n\n<p>Only the <code>ℴ</code> is displayed correctly, because it has a lower code point of <code>U+2134</code>. For the other characters, the surrogate halves are separated from each other, leading to invalid characters.</p>\n\n<p>Not shown here: how fullwidth and halfwidth charaters can mess up your vertical layout.</p>\n\n<hr>\n\n<p>The moral of the story: code points, UTF-16 code units, characters and glyphs are different things. Dealing with them correctly is excessively difficult, and I don't know about any suitable tools. If you are not prepared to deal correctly with any input you may encounter, then check that the input conforms to a subset you are comfortable with.</p>\n\n<pre><code>for (char c : str) {\n if (c > 0x7F) {\n throw new IllegalArgumentException(\"The input string may only contain ASCII code points\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:16:40.247",
"Id": "81495",
"Score": "1",
"body": "At this moment I am not concerned by non-ASCII things or exceptions, just betterment of a simple logic. Thank you for sharing the risk, it is a new learning although over the head knowledge slightly. Noted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:31:24.713",
"Id": "46628",
"ParentId": "46624",
"Score": "11"
}
},
{
"body": "<p>At the moment, your current code does not handle properly the fact that a short word can be followed by a long word. The input <code>\"Hello Jack the Magnificient\"</code> can show you what happens.</p>\n\n<p>Two solutions to this problem :</p>\n\n<ol>\n<li><p>you can add a loop to add the missing whitespaces.</p>\n\n<pre><code> for ( ; j <maxWordLen ; j++)\n {\n charArr[i][j] = ' ';\n }\n</code></pre></li>\n<li><p>You change the whole structure of the loop :</p>\n\n<pre><code> char[] charArray = strArr[i].toCharArray();\n for (int j=0 ; j <maxWordLen ; j++)\n {\n charArr[i][j] = (j < charArray.length) ? charArray[j] : ' ';\n }\n</code></pre></li>\n</ol>\n\n<p>The second solution is likely to be slower but I find it more elegant.</p>\n\n<hr>\n\n<p>Tiny detail, you can write :</p>\n\n<pre><code> if (i!=0)\n System.out.print(\" \");\n System.out.print(charArr[i][j]);\n</code></pre>\n\n<p>in a more concise way :</p>\n\n<pre><code> System.out.print(charArr[i][j] + \" \");\n</code></pre>\n\n<p>(this will add trailing whitespaces but who cares really?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:10:42.627",
"Id": "81492",
"Score": "0",
"body": "It works for \"Hello Jack the Magnificient\" because the character array will have length of 'Magnificient' as its the longest word and for other words, the remaining char array block will have default '\\0' character which is not printed anyway. Please check.\nFor second part, yes I agree, but just I'm able to leave trailing whitespace, I did that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:27:00.013",
"Id": "81500",
"Score": "0",
"body": "I have retried and I confirm it looks wrong : http://ideone.com/xYstrt"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:32:43.487",
"Id": "81501",
"Score": "0",
"body": "Ideone may be is having problems with the '\\0' character, and this can really vary across different consoles, but in Eclipse Juno, and CMD, its proper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:36:21.597",
"Id": "81502",
"Score": "0",
"body": "It doesn't work on my computer neither so there is an actual issue even if you cannot see it in your setup. The point is that the array should be filled with whitespaces and not '\\0'. I've raised the issue, now I'll let you decide if you want to consider this as a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:10:36.970",
"Id": "81523",
"Score": "0",
"body": "OK. I am into it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:31:30.323",
"Id": "81567",
"Score": "0",
"body": "@xploreraj Relying on `(char)0` to be printed is generally a bad idea. I believe it's the null character, which is not printable according to ASCII. (See http://en.wikipedia.org/wiki/Null_character: \"it does nothing (some terminals, however, incorrectly display it as space)\".)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:51:36.760",
"Id": "46629",
"ParentId": "46624",
"Score": "10"
}
},
{
"body": "<h1>Variable Names</h1>\n<p>Your variables names are unnecessarily abbreviated and genetic. Also suffixes such as <code>Arr</code> are usually unnecessary. Here some examples I'd use:</p>\n<ul>\n<li><code>str</code> => <code>sentence</code></li>\n<li><code>strArr</code> => <code>words</code></li>\n<li><code>strTemp</code> => <code>word</code></li>\n</ul>\n<h1>Algorithm</h1>\n<p>You could drop copying the strings into the character array, by using <code>strArr</code> directly and simply checking if <code>j</code> exceeds the length of the word and printing a space if it does.</p>\n<p>Also getting the maximal word length could also be avoided, if you check during output, if all strings are shorter than <code>j</code>.</p>\n<h1>My version</h1>\n<pre><code>public static void toVerticalWords(String sentence){\n String[] words = sentence.split("\\\\s");\n \n boolean allWordsEnded;\n int row = 0;\n \n do {\n allWordsEnded = true;\n\n char[] output = new char[words.length * 2];\n int column = 0;\n for (String word : words) {\n char c;\n if (row < word.length()) {\n c = word.charAt(row);\n allWordsEnded = false;\n } else {\n c = ' ';\n }\n output[column++] = c;\n output[column++] = ' ';\n }\n if (!allWordsEnded) {\n System.out.println(output);\n }\n row++;\n }\n while (!allWordsEnded);\n}\n</code></pre>\n<p>The main loop is a bit more complicated, because I cache the line to be written, so when all words have ended, it won't output a line of spaces.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:25:45.260",
"Id": "81681",
"Score": "0",
"body": "Agree with your conventions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T10:55:26.807",
"Id": "46630",
"ParentId": "46624",
"Score": "10"
}
},
{
"body": "<p>You don't really need to compute the <code>maxWordLen</code> or the matrix. Once there is nothing else to print, stop!</p>\n\n<p>Here is my solution:</p>\n\n<pre><code>public static void toVerticalWords(String str) {\n String[] words = str.split(\"\\\\s+\");\n boolean remained = true;\n\n for (int j = 0; remained; j++) {\n remained = false;\n for (int i = 0; i < words.length; i++) {\n remained = remained || (words[i].length() > j);\n System.out.print(words[i].length() > j ? words[i].charAt(j) : \" \");\n }\n System.out.println();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:44:06.553",
"Id": "81911",
"Score": "0",
"body": "Yes, you are right. But in the initial code, I held on to the maximum word which I could use for printing blank or whitespace in case of shorter words. However optimal versions of the code have come along since then."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:42:55.660",
"Id": "46792",
"ParentId": "46624",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46626",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T09:23:47.027",
"Id": "46624",
"Score": "10",
"Tags": [
"java",
"strings",
"console",
"formatting"
],
"Title": "Vertically placing the words in a string"
} | 46624 |
<pre><code>int kth_smallest_number(int A[], int n, int k){
/*kth smallest number is smaller than pr equal to n-k numbers in A*/
int smaller_than_count;
int i,j;
for(i=0; i<n; i++){
/*Check whether the number A[i] satisfies
the condition*/
smaller_than_count = 0;
for(j=0; j<n; j++){
if(A[i]<=A[j]){
smaller_than_count++;
}
}
if(smaller_than_count == n-k){
return A[i];
}
}
}
</code></pre>
<p>I just wanted to know if this solution is right, I am not worried about efficiency right now just correctness. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:26:45.073",
"Id": "81480",
"Score": "0",
"body": "i have the feeling that your code didn't come out the way you wrote it, is that correct? For more help see [markdown help](http://codereview.stackexchange.com/help/formatting#code)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:27:08.160",
"Id": "81481",
"Score": "1",
"body": "Before I go any futher, this is known as http://en.wikipedia.org/wiki/Selection_algorithm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:04:20.827",
"Id": "81578",
"Score": "0",
"body": "The code in the question had leading tabs, instead of the four spaces required by Markdown. I've taken the liberty of reindenting the code in the question (which we normally don't do)."
}
] | [
{
"body": "<p><strong>The compiler is your friend</strong></p>\n\n<p>Activate all warnings and you'll get pretty good hints :</p>\n\n<pre><code>selection.c: In function ‘kth_smallest_number’:\nselection.c:17:1: warning: control reaches end of non-void function [-Wreturn-type]\n }\n ^\n</code></pre>\n\n<p><strong>Test your code</strong></p>\n\n<p>Here's what I have written to test your code :</p>\n\n<pre><code>int A[] = {4,4,56,78,54,6512,21,8,7,2,321,87,78,54,2,21,5,4,321,456,5,4,35,5,4,1,67,8,1,54,4,654,7,6,54,321,7,32,4,21,54,7};\nint n = sizeof(A)/sizeof(A[0]);\nfor (int k=0; k<n; k++)\n{\n printf(\"%d %d\\n\",k,kth_smallest_number(A,n,k));\n}\n</code></pre>\n\n<p>I'd expect the returned value to be sorted and it's clearly not the case here. Thus, I expect something to be wrong.</p>\n\n<p>Playing with other inputs : <code>int A[] = {10,9,8,7,6,5,4,3,2,1,0};</code> , <code>int A[] = {10,9,8,7,6,5,5,4,3,2,1,0};</code>, it seems like your solution does not handle properly duplicated value.</p>\n\n<p><strong>A matter of style</strong></p>\n\n<p>The indentation looks weird on your question.</p>\n\n<p>You should try to declare your local variable in the smallest possible scope. Among other things, you can define your loop indices in the loop syntax in you use the C99 mode (<code>-std=c99</code>).</p>\n\n<p>Once rewritten (but still wrong), your code looks like :</p>\n\n<pre><code>int kth_smallest_number(int A[], int n, int k){\n for(int i=0; i<n; i++){\n /*Check whether the number A[i] satisfies\n the condition*/\n int smaller_than_count = 0;\n for(int j=0; j<n; j++){\n if(A[i]<=A[j]){\n smaller_than_count++;\n }\n }\n if(smaller_than_count == n-k){\n return A[i];\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Edit : </p>\n\n<p><strong>An attempt to correctness</strong></p>\n\n<p>Here what I have written , it seems to work fine but I won't promise anything.</p>\n\n<pre><code>int kth_smallest_number(int A[], int n, int k){\n for(int i=0; i<n; i++){\n /*Check whether the number A[i] satisfies the condition*/\n int ai = A[i];\n int smaller_than_count = 0;\n int bigger_than_count = 0;\n for(int j=0; j<n; j++){\n int aj = A[j];\n if (ai < aj) {\n smaller_than_count++;\n if (smaller_than_count >= n-k) break; // Optimisation\n } else if (ai > aj) {\n bigger_than_count++;\n if (bigger_than_count > k) break; // Optimisation\n }\n }\n if(smaller_than_count < n-k && bigger_than_count <= k){\n return ai;\n }\n }\n return -1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:02:05.583",
"Id": "81489",
"Score": "0",
"body": "Is there any way I can handle the element duplicates without altering the array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:37:02.483",
"Id": "81684",
"Score": "0",
"body": "I've edited my answer to add a potential solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:40:51.043",
"Id": "46633",
"ParentId": "46632",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:21:33.563",
"Id": "46632",
"Score": "4",
"Tags": [
"c",
"algorithm"
],
"Title": "A function that finds the kth smallest integer in array A (unsorted), of size n"
} | 46632 |
<p>I have code which I need to refactor in order to use in many places. So I tried some solutions but always ending with repeated and messy code. So, I decided to ask what possible best solutions are.</p>
<p>This code is used for calculating sale price in e-commerce project. My goal is to put some code in method which will not change over time, or better to say, which will be managed only from one place. This part is considering of setting sale price based on some comparison. And problem occurs in this comparison. I want also to do some formatting of controls like Label based on this result, like setting currency code. The currency code will be sometimes in $, sometimes in USD. So, this means I should somehow isolate this currency code also.</p>
<p>In short, I want to refactor this currency code and formatting controls based on calculated sale price.</p>
<p>So, I created <code>BasketHelper</code> class with <code>Product</code> and <code>Account</code> properties and method <code>SetBasketPayment</code> that return properties I set in this method. Basically, I use this approach to group properties of <code>Product</code> and <code>Account</code> classes and then return values.</p>
<p>Here is my code. Any further explanation, I will provide upon your request.</p>
<pre><code>public class BasketHelper
{
public Product _product { get; set; }
public Account _account { get; set; }
public BasketHelper SetBasketPayment(Product product, Account account,
HyperLink lblIconOnSale, Label lblSalePrice, Label lblListPrice,
HyperLink lblIconCampaign)
{
decimal _brandAccountDiscountRate = default(decimal);
decimal _accountDiscount = default(decimal);
if (HttpContext.Current.Request.IsAuthenticated) {
MembershipUser mUser = Membership.GetUser();
if (mUser != null) {
account = Account.GetAccountByUserId(
(Guid)Membership.GetUser().ProviderUserKey);
try {
_accountDiscount = account.DiscountRate;
} catch (Exception ex) { }
BrandAccountDiscount brandAccountDiscount =
BrandAccountDiscount
.GetBrandAccountDiscountByUserAndBrandId(
product.BrandId, mUser.ProviderUserKey.ToString());
if (brandAccountDiscount != null) {
_brandAccountDiscountRate = brandAccountDiscount.DiscountRate;
}
}
}
decimal currencyMultiplier = Currency.GetCurrencyValue(product.CurrencyCode);
decimal _listPriceTL = product.ListPrice * currencyMultiplier;
decimal _productCampaignPrice = _listPriceTL * (1 - product.DiscountRate / 100);
decimal _accountPrice = _listPriceTL * (1 - _accountDiscount / 100);
decimal _brandPrice = _accountPrice * (1 - _brandAccountDiscountRate / 100);
lblListPrice.Text = product.ListPrice.ToString("N2") + " " + product.CurrencyCode;
if (product.DiscountRate > 0) {
product.SalePrice = _productCampaignPrice;
lblSalePrice.Text = _productCampaignPrice.ToString("C2") + " + KDV";
lblListPrice.CssClass += " strike";
lblIconCampaign.Text = "+%" + product.DiscountRate.ToString("N0");
lblIconCampaign.Visible = true;
} else {
if (_accountPrice < _listPriceTL) {
product.SalePrice = _accountPrice;
lblIconOnSale.Text = "%" + _accountDiscount.ToString();
lblIconOnSale.Visible = true;
}
if (_brandAccountDiscountRate > 0) {
product.SalePrice = _brandPrice;
lblSalePrice.Text = _brandPrice.ToString("C2") + " +KDV";
}
}
return new BasketHelper {
_product = product,
_account = account
};
}
}
</code></pre>
| [] | [
{
"body": "<p>you have no comments in your code - you need some with any code, but especially something like this. Start by extracting the individual functions (you may find this easier once you've added comments); for example:</p>\n\n<pre><code>private void DiscountNotZero()\n{\n product.SalePrice = _productCampaignPrice;\n\n lblSalePrice.Text = _productCampaignPrice.ToString(\"C2\") + \" + KDV\";\n lblListPrice.CssClass += \" strike\";\n lblIconCampaign.Text = \"+%\" + product.DiscountRate.ToString(\"N0\");\n lblIconCampaign.Visible = true;\n}\n</code></pre>\n\n<p>That should give you a much smaller function.</p>\n\n<p>Secondly, I would take all your instance variables: <code>_brandPrice</code>, <code>_listPrice</code>, etc. and extract them into a separate model.</p>\n\n<p>The third point is that you are mixing your UI and business layers. Once you have a small function that returns a model, you should then be able to call it, and then subsequently read it into (or better, bind it to) the UI layer.</p>\n\n<p>Just to add slightly to this, and to address your \"time constraints\". The Visual Studio IDE has a Refactor menu. Just highlight the code you wish to refactor, and select Refactor -> Extract Method. If you then give the extracted function a descriptive name, this should go at least some way to breaking up your function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:50:43.020",
"Id": "81508",
"Score": "0",
"body": "The thing about comments is that this code was developed by another dev and he didn't comment anything, so commenting it will take at least 2 weeks, since there is a lot of code and I don't have that time. Anyway, I will try to do something with this mess"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:00:23.423",
"Id": "81511",
"Score": "2",
"body": "If you start splitting the code into smaller functions, you may find that does some of the commenting for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:05:16.477",
"Id": "81512",
"Score": "2",
"body": "Be careful with comments. Comments that try to explain bad code are better replaced by self-explaining code. Comments providing background information are good. They can help to answer questions like: \"Why was this algorithm used?\", \"What value ranges are allowed\", \"Are `null` arguments allowed\", \"What kind of result will be returned if the user cannot be authenticated? Will `null` be returned, will an exception be thrown?\" and so on. Doc-comments (XML-comments) are a good place to start with commenting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:09:18.147",
"Id": "81513",
"Score": "0",
"body": "I almost agree. As I said, splitting into smaller functions would massively help with this, and the comments, ideally should be function comments, because the functions are so small. However, even a couple of comments in his original function to say what was being done next would be better than it currently is. Certainly not ideal, I agree."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:39:59.640",
"Id": "46636",
"ParentId": "46634",
"Score": "5"
}
},
{
"body": "<p><code>BasketHelper</code> mixes the different aspects of identifying and authenticating users, calculating prices and displaying information. These aspects should be separated. Especially manipulating the view (setting label texts, choosing CSS-formatting etc.) should not be mixed with business logic. The view logic shouldn't need to calculate prices and discounts. It should only work on results calculated somewhere else. </p>\n\n<p>You have a <code>Product</code> class. Why do you not move product related calculations to <code>Product</code>? For instance add a method <code>GetProductCampaignPrice</code> to <code>Product</code>. You could make it a property as well, but since it is not returning a \"static\" value but depends on other properties, a method seems more appropriate.</p>\n\n<pre><code>public decimal GetProductCampaignPrice()\n{\n decimal currencyMultiplier = Currency.GetCurrencyValue(CurrencyCode);\n decimal listPriceTL = ListPrice * currencyMultiplier;\n return listPriceTL * (1 - DiscountRate / 100);\n}\n</code></pre>\n\n<p>Except for the currency calculator the calculation only needs properties of the product itself (<code>CurrencyCode</code>, <code>ListPrice</code> and <code>DiscountRate</code>). An even better design would be to inject a currency calculator into this method in order to remove the dependency on a specific currency calculator.</p>\n\n<pre><code>public decimal GetProductCampaignPrice(ICurrencyCalculator currencyCalculator)\n{\n decimal listPriceNormalized = currencyCalculator.ToStandardCurrency(ListPrice, CurrencyCode);\n return listPriceNormalized * (1 - DiscountRate / 100);\n}\n</code></pre>\n\n<p>Also note that I have removed the leading underscore (<code>_</code>) from the local variable. Underscores are used for fields, i.e. \"variables\" at class or struct level only.</p>\n\n<p>The stuff in helper classes should be kept to a strict minimum and should really on hold things that don’t fit in anywhere else.</p>\n\n<p>Look at your code and try to identify things that you can move to more specific classes.</p>\n\n<p>A possible class integrating product and account related calculations could be called <code>PriceCalculator</code>; this is a much better name than <code>FooHelper</code> and it leads to a better design. Naming is crucial and goes hand in hand with good designs.</p>\n\n<hr>\n\n<p>Note: If you don't want to or cannot change the <code>Product</code> class (e.g. because it is generated automatically), you could split the class into two partial classes, one holding the data and one with additional methods. You could also create a <code>ProductExtensions</code> class and make the method an extension method</p>\n\n<pre><code>public static class ProductExtensions\n{\n public static decimal GetProductCampaignPrice(this Product product,\n ICurrencyCalculator currencyCalculator)\n {\n decimal listPriceNormalized =\n currencyCalculator.ToStandardCurrency(ListPrice, CurrencyCode);\n return listPriceNormalized * (1 - DiscountRate / 100);\n }\n}\n</code></pre>\n\n<p>You can call this method as if it was a member of <code>Product</code></p>\n\n<pre><code>decimal result = product.GetProductCampaignPrice(currencyCalculator);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:55:19.200",
"Id": "81509",
"Score": "0",
"body": "I agree with all above you said. The thing is that I couldn't find way to refactor it effectivelly inspite of fact that I have some theoretic knowledge of code design and principles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:21:37.917",
"Id": "81519",
"Score": "0",
"body": "I really didn't know where to put this code, because currently code design is like one class is responsible for one table in database. Classes are designed to be strongly typed with constructor involve all classes properties. So, moving some properties in BasketHelper to for example Product class will lead to more bad design, IMO. I do not like this code design too. But thing is I have to use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:28:05.850",
"Id": "81520",
"Score": "0",
"body": "I am not suggesting to move properties, but the product campaign price calculation only requires properties of the product itself (`CurrencyCode`, `ListPrice`, `DiscountRate`), so why not creating a method in `Product` to do the calculation in place, instead of extracting those informations from the product and do the calculation somewhere else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:43:17.247",
"Id": "81524",
"Score": "0",
"body": "upvoted. But seems like I will stay with this solutions. Anyway thank for recommendations. I will look for some refactoring book, maybe Refactoring: Improving the Design of Existing Code and than try to do it better next time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:06:17.950",
"Id": "81550",
"Score": "0",
"body": "Added a note with two options for the `GetProductCampaignPrice` placement."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:45:21.003",
"Id": "46638",
"ParentId": "46634",
"Score": "7"
}
},
{
"body": "<p>First of all, <code>BasketHelper</code> is a good name for static class, but not for your case.</p>\n\n<pre><code>public Product _product { get; set; }\npublic Account _account { get; set; }\n</code></pre>\n\n<p>should be renamed:</p>\n\n<pre><code>public Product Product { get; set; }\npublic Account Account { get; set; }\n</code></pre>\n\n<p>because <code>Product</code> and <code>Account</code> are public properties.</p>\n\n<pre><code>public BasketHelper SetBasketPayment(Product product, Account account, HyperLink lblIconOnSale, Label lblSalePrice, Label lblListPrice, HyperLink lblIconCampaign)\n</code></pre>\n\n<p>I'm not sure that is a good idea to put labels and hyperlinks as parameters of method. It looks like mix of view and business logic.</p>\n\n<pre><code>decimal _brandAccountDiscountRate = default(decimal);\ndecimal _accountDiscount = default(decimal);\n</code></pre>\n\n<p>Use names without _ for local variables. By convention _ uses for private fields. Use <code>var</code> for local variables, I didn't get using default values for those variables.</p>\n\n<p>Just put: </p>\n\n<pre><code>var brandAccountDiscountRate = 0;\nvar accountDiscount = 0;\n</code></pre>\n\n<p>There is no handling exceptions. Put errors into log, display for user etc.:</p>\n\n<pre><code>catch (Exception ex) { }\n</code></pre>\n\n<p>Method <code>SetBasketPayment</code> should only set paymant, but a lot of logic that should be in view:</p>\n\n<pre><code> lblSalePrice.Text = _productCampaignPrice.ToString(\"C2\") + \" + KDV\";\n lblListPrice.CssClass += \" strike\";\n lblIconCampaign.Text = \"+%\" + product.DiscountRate.ToString(\"N0\");\n lblIconCampaign.Visible = true;\n</code></pre>\n\n<p>It looks like this class can be static with method <code>SetBasketPayment</code>.\nI hope it helps :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:41:58.793",
"Id": "81521",
"Score": "0",
"body": "Thank you for good points. I know that everything is mixed. Thaht's why I posted this question here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:27:43.613",
"Id": "46642",
"ParentId": "46634",
"Score": "4"
}
},
{
"body": "<p>I see Helpers as utility classes that just perform simple quick repetitive operations, I would never put business logic on a Helper class.</p>\n\n<p>BasketHelper is therefore for me a bad name: I would call it for instance BasketService.</p>\n\n<p>You need interfaces: without interfaces it is very hard to refactor nor test anything.</p>\n\n<p>Yo need one interface for your BasketService class, one for Product and one for Account (so your input parameters would not be of type Product but say of type IProduct). By creating interfaces you can create classes that do just one thing each (as opposed to one class doing everything), this is the famous Single responsibility principle</p>\n\n<p>If you look at the code, you are basically updating the SalePrice and the 4 associated labels/hyperlinks. Return a new Basket class with these, and try not to modify any input objects (ie the product).</p>\n\n<p>I don't quite understand the logic of the discounts: if a product has a discount then both the account and brand discounts are ignored (even if they are bigger discounts), this does not make sense to me.</p>\n\n<p>I have put together a skeleton of a partial possible structure -it does not cover everything-, it looks rather big, but it helps segregate the functionality into separate classes (see <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">http://en.wikipedia.org/wiki/Single_responsibility_principle</a>) and by using interfaces, it hides the actual implementation details.</p>\n\n<pre><code>using System;\nusing System.Web;\n\npublic partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n IAccount account = null;//your product here\n IProduct product = null;//your account here\n\n IDiscountService discountService = new DiscountService();\n ICurrencyService currencyService = new CurrencyService();\n\n IBasketService basketService = new BasketService(discountService, currencyService);\n\n BasketPayment basketPayment = basketService.CalculateBasketPayment(product, account, HttpContext.Current.Request);\n\n //now populate the ui elements\n //with the basketPayment information\n }\n}\n\n\npublic interface IProduct\n{\n double ListPrice { get; set; }\n string CurrencyCode { get; set; }\n}\n\npublic interface IAccount\n{\n double DiscountRate { get; set; }\n}\n\n\n\npublic interface IDiscountService\n{\n //ideally this interface should not have to know about the HttpRequest, but about the MembershipUser\n double CalculateBrandDiscount(IProduct product, HttpRequest request);\n double CalculateAccountDiscount(IAccount account, HttpRequest request);\n}\n\n\npublic interface IBasketService\n{\n BasketPayment CalculateBasketPayment(IProduct product, IAccount account, HttpRequest request);\n}\n\npublic interface ICurrencyService\n{\n double GetCurrencyMultiplier(string currencyCode);\n}\n\n//This class only knows about Currencies\npublic class CurrencyService : ICurrencyService\n{\n\n public double GetCurrencyMultiplier(string currencyCode)\n {\n switch (currencyCode.ToUpper())\n {\n case \"EUR\" : return 1.0;\n default: return 1.0;\n }\n }\n}\n\n/// <summary>\n/// This class only calculates Discounts\n/// </summary>\npublic class DiscountService : IDiscountService\n{\n\n public double CalculateBrandDiscount(IProduct product, HttpRequest request)\n {\n //to be implemented\n return 0.0;\n }\n\n public double CalculateAccountDiscount(IAccount account, HttpRequest request)\n {\n //to be implemented\n return 0.0;\n }\n}\n\n\npublic class BasketPayment\n{\n public double SalePrice { get; set; }\n\n //etc\n}\n\n\npublic class BasketService : IBasketService\n{\n IDiscountService DiscountService;\n ICurrencyService CurrencyService;\n\n public BasketService(IDiscountService discountService, ICurrencyService currencyService)\n {\n // Consider Using Dependency Injection to provide this parameters automagically\n DiscountService = discountService;\n CurrencyService = currencyService;\n }\n\n /// <summary>\n /// Interface method. All the data it needs should be in its parameters, in the constructor of the class or as result of previous operations,\n /// avoid using environment data such as HttpContext.Current.Request, this way the code can be mocked and tested in a controlled environment.\n /// </summary>\n /// <param name=\"product\"></param>\n /// <param name=\"account\"></param>\n /// <param name=\"request\"></param>\n /// <returns></returns>\n public BasketPayment CalculateBasketPayment(IProduct product, IAccount account, HttpRequest request)\n {\n var brandDiscount = DiscountService.CalculateBrandDiscount(product, request);\n var accountDiscount = DiscountService.CalculateAccountDiscount(account, request);\n\n BasketPayment result = new BasketPayment();\n result.SalePrice = _CalculatePrice(product, brandDiscount, accountDiscount);\n\n return result;\n }\n\n /// <summary>\n /// The actual implementation is private to the class\n /// </summary>\n /// <param name=\"product\"></param>\n /// <param name=\"brandDiscount\"></param>\n /// <param name=\"accountDiscount\"></param>\n /// <returns></returns>\n private double _CalculatePrice(IProduct product, double brandDiscount, double accountDiscount)\n {\n var currencyMultipler = CurrencyService.GetCurrencyMultiplier(product.CurrencyCode);\n\n var effectiveDiscount = brandDiscount < accountDiscount ? brandDiscount : accountDiscount;\n\n return product.ListPrice * currencyMultipler * (1 - effectiveDiscount / 100);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:45:23.383",
"Id": "81588",
"Score": "0",
"body": "I just read your answer and now I am gonna play with it. I was looking for answer like you provided. As of discount parts, our customer wanted it in that way, so if there is a product discount the other two discounts are ignored. So this logic is a requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:13:08.633",
"Id": "81593",
"Score": "0",
"body": "Hope it works for you. The customer is king!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:27:54.230",
"Id": "46654",
"ParentId": "46634",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:49:15.137",
"Id": "46634",
"Score": "8",
"Tags": [
"c#"
],
"Title": "E-Commerce 'sale price' calculator"
} | 46634 |
<p>I just finished writing a flat-file DB class for PHP which supports selecting, updating, inserting and deleting. </p>
<p>I was wondering if there are any ways to make it faster or if I'm doing anything the wrong way.</p>
<pre><code><?php
class FlatDB {
private static $field_deliemeter = "\t";
private static $linebreak = "\n";
private static $table_extension = '.tsv';
public $table_name;
public $table_contents = array("FIELDS" => NULL, "RECORDS" => NULL);
/*
** This method creates a table
**
** @param string $table_name
**
** @example
** $db = new FlatDB;
** $db->createTable('Administrators');
**/
public function createTable($table_name, $table_fields) {
// Create the file
$tbl_name = $table_name.self::$table_extension;
$header = '';
foreach($table_fields as $field) {
$header .= $field.self::$field_deliemeter;
}
file_put_contents($tbl_name, $header);
}
/*
** This method opens a table for querying, editing, etc
**
** @param string $table_name
**
** @example
** $db = new FlatDB;
** $db->openTable('Test.csv');
**/
public function openTable($table_name) {
// Check if this table is found
$table_name = $table_name.self::$table_extension;
if(file_exists($table_name) === FALSE) throw new Exception('Table not found.');
// Set the table in a property
$this->table_name = $table_name;
// Get the fields
$table = file($this->table_name, FILE_IGNORE_NEW_LINES);
$table_fields = explode(self::$field_deliemeter, $table[0]);
unset($table[0]);
// Put all records in an array
$records = array();
$num = 0;
foreach($table as $record) {
$records_temp = explode(self::$field_deliemeter, $record);
$count = count($records_temp);
for($i = 0; $i < $count; $i++)
$records[$num][$table_fields[$i]] = $records_temp[$i];
$num++;
}
$this->table_contents['FIELDS'] = $table_fields;
$this->table_contents['RECORDS'] = $records;
}
/*
** This method returns fields selected by the user based on a where criteria
**
** @param array $select an array containing the fields the user wants to select, if he wants all fields he should use a *
** @param array $where an array which has field => value combinations
** @return array it returns an array containing the records
**
** @example
** $db = new FlatDB;
** $db->openTable('Test.csv');
** $select = array("id", "name", "group_id");
** $where = array("group_id" => 2);
** $db->getRecords($select, $where);
**/
public function getRecords($select, $where = array()) {
// Do some checks
if(is_array($select) === FALSE) throw new Exception('First argument must be an array');
if(is_array($where) === FALSE && isset($where)) throw new Exception('Second arguement must be an array');
if(empty($this->table_name) === TRUE) throw new Exception('There is no connection to a table opened.');
// If the array contains only one key which is a *, then select all fields
if($select[0] == '*') $select = $this->table_contents['FIELDS'];
// Check if the fieldnames in select are all found
foreach($select as $field_name)
if(in_array($field_name, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field_name." is not found in the table.");
// Check if the fieldnames in where are all found
foreach($where as $field_name => $value)
if(in_array($field_name, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field['name']." is not found in the table.");
// Find the record that the user queried in where
$user_records = $this->table_contents['RECORDS'];
if(isset($where)) {
foreach($where as $field => $value) {
foreach($this->table_contents['RECORDS'] as $key => $record) {
if($record[$field] != $value) {
unset($user_records[$key]);
}
}
}
}
// Preserve only the keys that the user asked for
$final_array = array();
$temp_fields = array_flip($select);
foreach($user_records as &$record) {
$final_array[] = array_intersect_key($record, $temp_fields);
}
return $final_array;
}
/*
** This method updates fields based on a criteria
**
** @param array $update an array containing the fields the user wants to update
** @param array $where an array which has field => value combinations which is the criteria
**
** @example
** $db = new FlatDB;
** $db->openTable('Test.csv');
** $update = array("group_id" => 1);
** $where = array("group_id" => 2);
** $db->updateRecords($update, $where);
**/
public function updateRecords($update, $where) {
// Check if the connection is opened
if(empty($this->table_name) === TRUE) throw new Exception('There is no connection to a table opened.');
// Check if each field in update and where are found
foreach($update as $field => $value)
if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field." is not found.");
foreach($where as $field => $value)
if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field." is not found.");
// Find the record that the user queried in where
$user_records = $this->table_contents['RECORDS'];
$preserved_records = array();
foreach($where as $field => $value) {
foreach($this->table_contents['RECORDS'] as $key => $record) {
if($record[$field] != $value) {
unset($user_records[$key]);
$preserved_records[$key] = $record;
}
}
}
// Update whatever needs updating
$user_records_temp = $user_records;
foreach($user_records_temp as $key => $record) {
foreach($update as $field => $value) {
$user_records[$key][$field] = $value;
}
}
// Merge the preserved records and the records that were updated, then sort them by their record number
$user_records += $preserved_records;
ksort($user_records, SORT_NUMERIC);
// Modify the property of the records and insert the new table
$this->table_contents['RECORDS'] = $user_records;
// Implode it so we can save it in a file
$final_array[] = implode(self::$field_deliemeter, $this->table_contents['FIELDS']);
foreach($user_records as $record)
$final_array[] = implode(self::$field_deliemeter, $record);
// Implode by linebreaks
$data = implode(self::$linebreak, $final_array);
// Save the file
file_put_contents($this->table_name, $data);
}
/*
** This method inserts a new record to the table
**
** @param array $insert an array containing field => value combinations
** @param array $where an array which has field => value combinations which is the criteria
**
** @example
** $db = new FlatDB;
** $db->openTable('Test.csv');
** $array = array("id" => 7, "name" => "Jack", "password" => "1234567", "group_id" => 2);
** $db->insertRecord($array);
**/
public function insertRecord($insert) {
if(is_array($insert) === FALSE) throw new Exception('The values need to be in an array');
if(empty($this->table_name) === TRUE) throw new Exception('You need to open a connection to a table first.');
// Check if each field in insert is found
foreach($insert as $field => $value)
if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field." is not found.");
// Build the new record
$newRecord = array();
foreach($this->table_contents['FIELDS'] as $field) {
if(isset($insert[$field])) $newRecord[$field] = $insert[$field];
else $newRecord[$field] = NULL;
}
// Add the new record to the pre-existing table and save it in the records
$records = $this->table_contents['RECORDS'];
$records[] = $newRecord;
$this->table_contents['RECORDS'] = $records;
// Format it for saving
$data = array();
$data[] = implode(self::$field_deliemeter, $this->table_contents['FIELDS']);
foreach($records as $record)
$data[] = implode(self::$field_deliemeter, $record);
// Implode by linebreaks
$data = implode(self::$linebreak, $data);
// Save in file
file_put_contents($this->table_name, $data);
}
/*
** This method deletes records from a table
**
** @param array $where an array which has field => value combinations which is the criteria
**
** @example
** $db = new FlatDB;
** $db->openTable('Test.csv');
** $where = array("group_id" => 3);
** $db->deleteRecords($where);
**/
public function deleteRecords($where) {
if(is_array($where) === FALSE) throw new Exception('The argument must be an array');
if(empty($this->table_name) === TRUE) throw new Exception('You need to open a connection to a database first.');
// Check if each field in insert is found
foreach($where as $field => $value)
if(in_array($field, $this->table_contents['FIELDS']) === FALSE) throw new Exception($field." is not found.");
// Find the records that match and delete them
$records = $this->table_contents['RECORDS'];
foreach($records as $key => $record) {
foreach($where as $field => $value) {
if($record[$field] == $value) unset($records[$key]);
}
}
// Save the records in the property
$this->table_contents['RECORDS'] = $records;
// Format it for saving
$data = array();
$data[] = implode(self::$field_deliemeter, $this->table_contents['FIELDS']);
foreach($records as $record)
$data[] = implode(self::$field_deliemeter, $record);
// Implode by linebreaks
$data = implode(self::$linebreak, $data);
// Save the file
file_put_contents($this->table_name, $data);
}
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:17:53.310",
"Id": "81518",
"Score": "0",
"body": "Please explain as to the purpose of this class seeing that there are MANY db wrappers that are already efficient and optimized such as Eloquent and other framework's packagegist"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:58:03.160",
"Id": "81527",
"Score": "0",
"body": "@azngunit81 *waves* It seems that Chosen Wann is building a flat file database 9http://en.wikipedia.org/wiki/Flat_file_database), not a wrapper around PDO or an ORM like Eloquent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:17:19.723",
"Id": "81535",
"Score": "0",
"body": "@jsanc623 so sqlite?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:21:09.347",
"Id": "81538",
"Score": "0",
"body": "@azngunit81 SQLite is not a flat-file database, its a single database system which stores data in structured files with indexes (similar to how MySQL does). A flat-file database would use \"flat\" text files, e.g. CSV."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:29:53.853",
"Id": "81566",
"Score": "1",
"body": "@azngunit81 The purpose is re-inventing the wheel, I just thought it was a good project and I worked on it."
}
] | [
{
"body": "<p>So, let's say you build a website that uses this class for storing data.</p>\n\n<p>Then, one evening, you and I both visit the website at the same time. We both hit the button that opens the table and reads the data into memory. Now there are two copies of the data in memory -- one in the page you're looking at, one in the page I'm looking at.</p>\n\n<p>You add a record. The \"insert\" function adds your new record and writes the file to disk.</p>\n\n<p>Now I update a record. But the copy of the data in my window doesn't include the record you just added. So when my instance of the code hits the statement file_put_contents(...), what happens to the record you just inserted?</p>\n\n<p>This is the sort of reason it's recommended to use real database engines like sqlite or mysql. They're designed to serialize calls and protect users from each other so they can't overwrite or corrupt each other's data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T05:47:57.647",
"Id": "83356",
"Score": "0",
"body": "Nice rebuttal! Not quite a review, but definitely a good point."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T04:19:21.703",
"Id": "47537",
"ParentId": "46635",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:15:50.007",
"Id": "46635",
"Score": "4",
"Tags": [
"php",
"classes",
"database",
"crud"
],
"Title": "Flat-file DB with CRUD"
} | 46635 |
<p>I have a <code>DataService</code>, which should talk to the server and store vars (for complicated calls, for example).</p>
<p>Last time, I ended up with this approach (for the example, I'm working with a list): </p>
<ul>
<li><code>GetList()</code> - returns cached data (just a property) </li>
<li><p><code>SetList()</code> - sets a property</p></li>
<li><p><code>ReadList()</code> - read data from file from <code>IsoStorage</code></p></li>
<li><p><code>WriteList()</code> - write data to file</p></li>
<li><p><code>PullList()</code> - pull data from the server</p></li>
<li><code>PushList()</code> - push data to the server</li>
</ul>
<p>NB: I'm using my old <code>IsoStorage</code> approach (<a href="https://codereview.stackexchange.com/questions/33074/isosettingsmanager">IsoSettingsManager</a>).</p>
<p>Now, after some time, I understood that I can merge first two stages: caching and writing to <code>IsoStorage</code>. Now I'm thinking of something like</p>
<pre><code> private int? deliveryId = null;
public int DeliveryId
{
get { return deliveryId ?? IsoSettingsManager.GetProperty<int>("DeliveryId"); }
set { deliveryId = value; IsoSettingsManager.SetProperty("DeliveryId", value); }
}
</code></pre>
<p>Where setting property is </p>
<pre><code>public static void SetProperty(string propertyName, object content)
{
if (System.ComponentModel.DesignerProperties.IsInDesignTool)
return;
if (content == null)
RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);
isoSettings[propertyName] = content;
isoSettings.Save();
}
</code></pre>
<p>What do you think about it?</p>
<p>First thing that comes to my mind is to make <code>SetProperty</code> to return the setted value so I'd be able to use it like</p>
<pre><code>public int DeliveryId
{
set { deliveryId = IsoSettingsManager.SetProperty("DeliveryId", value); }
***
</code></pre>
<p>unsetting <code>DeliveryId = null;</code> is not working for <code>int</code>s (fair enough), and I couldn't yet find how to push/pull them effectively.</p>
| [] | [
{
"body": "<p><strong>Style</strong> </p>\n\n<p>It won't hurt you and makes your code less error prone, if you would use braces <code>{}</code> also for single <code>if</code> statements. </p>\n\n<p>Commented code (<code>// if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);</code>) should be removed completely. You should instead use a code versioning system like svn or git. </p>\n\n<p><strong>Update based on the comments below</strong><br>\nIt is not about a comment but about commented out code which is just <strong>dead code</strong>. What value has dead code ? Does it make your live code more readable or does it make your live code easier to understand ? No, it is quite the opposite. </p>\n\n<p>Asume the following </p>\n\n<pre><code>public static void SetProperty(string propertyName, object content)\n{\n //if (System.ComponentModel.DesignerProperties.IsInDesignTool)\n // return;\n\n //if (content == null)\n RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);\n\n isoSettings[propertyName] = content;\n isoSettings.Save();\n} \n</code></pre>\n\n<p>this is quite hard to read and understatnd by <strong>Mr.Maintainer</strong>. </p>\n\n<p>This instead </p>\n\n<pre><code>public static void SetProperty(string propertyName, object content)\n{\n RemoveProperty(propertyName);\n\n isoSettings[propertyName] = content;\n isoSettings.Save();\n}\n</code></pre>\n\n<p>is much better to understand. </p>\n\n<p>If you check something into svn/git you always should add a descriptive message to the commit. </p>\n\n<p><strong><code>SetProperty()</code> method</strong> </p>\n\n<blockquote>\n<pre><code>if (content == null)\n RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);\n\n isoSettings[propertyName] = content;\n isoSettings.Save(); \n</code></pre>\n</blockquote>\n\n<p>this does not make sense to me. If <code>content==null</code> you first remove the property, and then you add it. Next time passing <code>null</code> you just do the same. </p>\n\n<p>You should consider returning after you have removed the property. There is no need to save the setting. </p>\n\n<p><strong>SetProperty() returning setted value</strong> </p>\n\n<p>This is in my opinion a bad idea for a method which seems to be like a property setter. A property setter should only <strong>set</strong> a properties value. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T09:24:31.503",
"Id": "125610",
"Score": "0",
"body": "First of all, thanks for an answer. I thought it would stay unanswered for ages. Style - i think, the most important part of the style is : it should be the same everywhere. I prefer to skip {} for a single 'if' and i think its fine while i'm using it everywhere.\n\nI also read some articles about using svn instead of comments, but i real life, i never user that. Its much faster to read a comment than to search svn for a old version of file. Can you please share more experience on this field, if it works fine for you?\n\nAnd your notes about SetProperty() makes total sense, thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-03T15:47:09.833",
"Id": "68761",
"ParentId": "46637",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T12:42:33.977",
"Id": "46637",
"Score": "1",
"Tags": [
"c#",
"windows",
"windows-phone",
"windows-phone-7"
],
"Title": "DataService data storage"
} | 46637 |
<p>I'm new to this pattern and I see arguments online about different implementations. I have the following code and it seems fine to me, <strong>but I'm wondering if having to pass the DBContext into the constructor would cause any issues down the line?</strong> I'm using this with EntityFramework (RECORD_TYPE is a table brought in from EF).</p>
<p>I'm a little newer to unit testing as well, so I'm thinking I would have to make a mock context in my unit tests that basically return a list of RECORD_TYPE objects that I create in the mock DBContext I make.</p>
<p><strong>Am I missing any ideas with this?</strong></p>
<pre><code>public interface IRepository<T> where T : class
{
IQueryable<T> All { get; }
T Find(int id);
void Save();
}
public class Repository<T> : IRepository<T> where T : class
{
private DbContext context;
public Repository(DbContext c)
{
context = c;
}
public IQueryable<T> All { get { return context.Set<T>(); } }
public T Find(int id)
{
return context.Set<T>().Find(id);
}
public void Save()
{
context.SaveChanges();
}
}
public class RecordTypeRepository : Repository<RECORD_TYPE>
{
public RecordTypeRepository(DbContext context)
: base(context)
{
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:53:56.607",
"Id": "81506",
"Score": "0",
"body": "you might want to read this: http://www.wekeroad.com/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T22:02:16.057",
"Id": "81507",
"Score": "0",
"body": "@Zdeslav this is exactly the reason I made this post. When you search this online you get a million different ways and views on it. It's enough to drive a person insane. However, the reason I was looking into it was because of doing unit tests. I don't want to hit my database (and everything I do uses a database) because I don't want to have my database be in the right state (it's a pain). So I want an easy way to mock the db context so I can manually fill it with data to use for testing. This then opens up a big wormhole in all the possibilities."
}
] | [
{
"body": "<p>In my opinion using the repository pattern is absolutely fine, for a number of reasons, not limited to:</p>\n\n<ol>\n<li>It enables unit testing</li>\n<li>Allows you to change EF for a another DB technology</li>\n</ol>\n\n<p>The detail that you have to be careful of using the base class is that you make sure that you declare properties/variables via the interface and not via the base class. So consider this:</p>\n\n<p><strong>Good</strong></p>\n\n<pre><code>public class Test{\n private IRepository<MyClass> _repo;\n}\n</code></pre>\n\n<p><strong>Bad</strong></p>\n\n<pre><code>public class Test{\n private BaseRepository<MyClass> _repo;\n}\n</code></pre>\n\n<hr>\n\n<p>With the actual code, I would suggest a number of changes:</p>\n\n<ol>\n<li>The interface should have full CRUD operations</li>\n<li>Try and use the same name for fetching a record (Consider <code>Get()</code> and <code>Get(id)</code> vs <code>All()</code> and <code>Get(1)</code>. It makes it more natural to consumers)</li>\n<li>The class <code>Repository</code> should be marked as abstract to stop you using it directly</li>\n<li>The class <code>Repository</code> should probably be named <code>EFBaseRepository</code></li>\n</ol>\n\n<p>Typically, when I implement the pattern I create the interface followed by a class called <code>BaseRepository</code> that implements all the methods. The methods no nothing more than throw a <code>NotSupportedException</code>/<code>NotImplementedException</code>. This is because I might only want consumers to have read/update but not create. It does depend on the context of the application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T18:41:58.113",
"Id": "47996",
"ParentId": "46639",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47996",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:45:16.460",
"Id": "46639",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Implementing the Repository Pattern"
} | 46639 |
<p>I've been working on a Sudoku solver as an introduction to the Java programming language. I know there's a bunch of ways to program a Sudoku solver, including a brute force/recursive approach and a logical approach. I've chosen the logical approach to start out to keep things simple.</p>
<p>This program solves Sudokus the exact same way I do when I'm using pen and paper. It picks a number, and then it picks a 3x3 region (I call these regions "squares" in my comments), and then it analyzes that region and the rows and columns that intersect it to see what boxes it can eliminate. Once all but one box has been eliminated, then that leaves us with our solved square.</p>
<p>I have big plans for the program, including adding a GUI, adding more logical techniques (Sudoku is surprisingly elaborate, check out all the techniques they have <a href="http://www.sudokuwiki.org/Strategy_Families">here</a> for example), and adding that recursive/brute force technique in another method. Before I go further however, I'd like to run my code by you guys for review. That way if I have any bad habits we can catch them now.</p>
<p>My background is mainly PHP programming.</p>
<p>SudokuSolver class:</p>
<pre><code>public class SudokuSolver
{
public static void main(String[] args)
{
// score 51 - websudoku.com - medium difficulty - solved in 14 iterations using LAST CANDIDATE
Sudoku easyToSolve = new Sudoku("036000820009500000800400007600100039003000500920006008500004002000002700071000450");
// score 57 - websudoku.com - hard difficulty - my solver can't solve this yet - has some HIDDEN SINGLES
Sudoku hardToSolve = new Sudoku("000007018094150700005600000106000000080070020000000904000003800008029140370400000");
// Here are the methods you can use here:
// printPuzzle() - prints the puzzle in a more readable form
// solvePuzzle() - solves the puzzle
// solvePuzzle(true) - shows you in detail how it solves the puzzle
easyToSolve.solvePuzzle(true);
hardToSolve.solvePuzzle(true);
}
}
</code></pre>
<p>Sudoku class:</p>
<pre><code>import java.util.Arrays;
public class Sudoku
{
private byte[][] myPuzzle = new byte[][]
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
public Sudoku(String incomingPuzzle)
{
if ( incomingPuzzle.length() != 81 )
{
System.out.println("Invalid Sudoku puzzle syntax. Should be 81 numbers.");
System.exit(1);
}
for ( int row = 0; row <= 8; row++ )
{
for ( int column = 0; column <= 8; column++ )
{
myPuzzle[row][column] = convertCharToByte(incomingPuzzle.charAt(row*9+column));
}
}
if ( puzzleIsValid() == false )
{
System.out.println("Illegal puzzle.");
System.exit(1);
}
}
public void printPuzzle()
{
for ( byte y = 0; y <=8; y++ )
{
for ( byte x = 0; x <=8; x++ )
{
System.out.print(myPuzzle[y][x] + " ");
if ( x == 2 || x == 5 )
{
System.out.print(" ");
}
}
System.out.println();
if ( y == 2 || y == 5 || y == 8 )
{
System.out.println();
}
}
}
public void solvePuzzle()
{
solvePuzzle(false);
}
public void solvePuzzle(boolean showDetails)
{
// print puzzle in the console
System.out.println("Unsolved puzzle:");
printPuzzle();
byte cyclesElapsed = 1;
// iterate through each square in a 9x9 sudoku puzzle and try to solve the square
while ( true )
{
byte squaresSolved = 0;
// We need some way to pause execution if the puzzle either becomes solved or is discovered to be unsolvable.
boolean somethingChanged = false;
// check each square
for ( byte square = 1; square <= 9; square++ )
{
// when we do our x-ray checks later we will need to know what row numbers and what column numbers to check
byte[] coordinates = getSquareCoordinates(square, (byte) 1);
byte checkThisRowFirst = coordinates[1];
byte checkThisColumnFirst = coordinates[0];
// make a boolean array to keep track of whether or not a coordinate in the square can be a solution for that numToCheck
// true = possibly a solution, false = not a solution
// once we are down to 1 true and 8 falses, we have solved that numToCheck and can update the box in myPuzzle
boolean[] possiblyContainsNum = new boolean[] {true, true, true, true, true, true, true, true, true};
// eliminate all occupied cells in the square
// iterate through the 9 boxes in the square and plug it into the getSquareCoordinates method
for ( byte i = 1; i <=9; i++ )
{
byte[] coordinates2 = getSquareCoordinates(square, i);
if ( myPuzzle[coordinates2[1]][coordinates2[0]] != 0 )
{
possiblyContainsNum[i-1] = false;
}
}
// check each number 1 through 9
// don't go box by box, go number by number
for ( byte numToCheck = 1; numToCheck <= 9; numToCheck++ )
{
// does the square contain this number already?
// if yes, skip. if no, try to solve
if ( squareContainsNumber(square, numToCheck) == false )
{
// I had possiblyContainsNum inside this loop for awhile, but then I realized it is
// more efficient to just compute it once and store it in memory. We'll make a new
// possiblyContainsNum for this numToCheck, copying the values of the original calculation
// (occupied squares) to start us off
boolean[] possiblyContainsNum2 = Arrays.copyOf(possiblyContainsNum, possiblyContainsNum.length);
// eliminate x-rays from rows and columns
// check the entire row or column (all 9 boxes), easier to code than 6 boxes
// row 1
if ( rowContainsNumber(checkThisRowFirst, numToCheck) == true )
{
possiblyContainsNum2[0] = false;
possiblyContainsNum2[1] = false;
possiblyContainsNum2[2] = false;
}
// row 2
if ( rowContainsNumber((byte) (checkThisRowFirst+1), numToCheck) == true )
{
possiblyContainsNum2[3] = false;
possiblyContainsNum2[4] = false;
possiblyContainsNum2[5] = false;
}
// row 3
if ( rowContainsNumber((byte) (checkThisRowFirst+2), numToCheck) == true )
{
possiblyContainsNum2[6] = false;
possiblyContainsNum2[7] = false;
possiblyContainsNum2[8] = false;
}
// column 1
if ( columnContainsNumber(checkThisColumnFirst, numToCheck) == true )
{
possiblyContainsNum2[0] = false;
possiblyContainsNum2[3] = false;
possiblyContainsNum2[6] = false;
}
// column 2
if ( columnContainsNumber((byte) (checkThisColumnFirst+1), numToCheck) == true )
{
possiblyContainsNum2[1] = false;
possiblyContainsNum2[4] = false;
possiblyContainsNum2[7] = false;
}
// column 3
if ( columnContainsNumber((byte) (checkThisColumnFirst+2), numToCheck) == true )
{
possiblyContainsNum2[2] = false;
possiblyContainsNum2[5] = false;
possiblyContainsNum2[8] = false;
}
// check possiblyContainsNum and see how many "true" cells there are
// if "true" cells == 1 then we have solved that numToCheck in that square
// go ahead and update myPuzzle[][]
byte counter = 0;
byte k = 0; // this will store the last value of j that was true
for ( byte j = 0; j <= 8; j++ )
{
if ( possiblyContainsNum2[j] == true )
{
counter++;
k = j;
}
}
if ( counter == 1 )
{
byte[] coordinates3 = getSquareCoordinates(square, (byte) (k+1));
myPuzzle[coordinates3[1]][coordinates3[0]] = numToCheck;
somethingChanged = true;
squaresSolved++;
}
}
}
}
if ( showDetails == true )
{
System.out.println("Iteration " + cyclesElapsed + " complete. Solved " + squaresSolved + " squares.");
printPuzzle();
}
cyclesElapsed++;
// If no cells were solved during this iteration, that means that the puzzle is completely solved, is completely
// unsolvable, or is unsolvable using just this technique. Time to exit the loop.
if ( somethingChanged == false )
{
break;
}
}
// do a quick check and make sure the puzzle is solved
// if it isn't, throw an unsolvable puzzle error
if ( puzzleIsSolved() == false )
{
System.out.println("Unsolvable using just the LAST CANDIDATE technique. More advacned techniques are needed.");
System.out.println("Try plugging the 81 digit number into the sudoku solver at http://www.sudokuwiki.org/sudoku.htm");
System.out.println();
return;
}
// print puzzle in the console
System.out.println("Solved puzzle:");
printPuzzle();
}
private byte convertCharToByte(char f)
{
switch ( f )
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
System.out.println("Invalid Sudoku puzzle syntax. Should be 81 numbers.");
System.exit(1);
}
return 0; // the compiler made me put this, logically it should be unreachable
}
private boolean puzzleIsValid()
{
// 1) check each row and make sure there is only 1 number per row
for ( byte y = 0; y <=8; y++ )
{
// we need a new oneThroughNine for each row, so we'll put this inside the "y" loop
boolean[] oneThroughNine = new boolean[] {false, false, false, false, false, false, false, false, false};
for ( byte x = 0; x <=8; x++ )
{
if ( myPuzzle[y][x] != 0 )
{
if ( oneThroughNine[myPuzzle[y][x] - 1] == false )
{
oneThroughNine[myPuzzle[y][x] - 1] = true;
}
else
{
return(false);
}
}
}
}
// 2) check each column and make sure there is only 1 number per column
for ( byte x = 0; x <=8; x++ )
{
// we need a new oneThroughNine for each column, so we'll put this inside the "y" loop
boolean[] oneThroughNine = new boolean[] {false, false, false, false, false, false, false, false, false};
for ( byte y = 0; y <=8; y++ )
{
if ( myPuzzle[y][x] != 0 )
{
if ( oneThroughNine[myPuzzle[y][x] - 1] == false )
{
oneThroughNine[myPuzzle[y][x] - 1] = true;
}
else
{
return(false);
}
}
}
}
// 3) check each square and make sure there is only 1 number per square
for ( byte square = 1; square <=9; square++ )
{
// we need a new oneThroughNine for each square, so we'll put this inside the "y" loop
boolean[] oneThroughNine = new boolean[] {false, false, false, false, false, false, false, false, false};
for ( byte i = 1; i <=9; i++ )
{
byte[] coordinates = getSquareCoordinates(square, i);
if ( myPuzzle[coordinates[0]][coordinates[1]] != 0 )
{
if ( oneThroughNine[myPuzzle[coordinates[0]][coordinates[1]] - 1] == false )
{
oneThroughNine[myPuzzle[coordinates[0]][coordinates[1]] - 1] = true;
}
else
{
return(false);
}
}
}
}
return(true);
}
private boolean puzzleIsSolved()
{
for ( byte y = 0; y <= 8; y++ )
{
for ( byte x = 0; x <= 8; x++ )
{
if ( myPuzzle[y][x] == 0 )
{
return(false);
}
}
}
return(true);
}
private byte[] getSquareCoordinates(byte squareNumber, byte i)
{
byte[] startCoordinates = null;
switch ( squareNumber )
{
case 1:
startCoordinates = new byte[]{0,0};
break;
case 2:
startCoordinates = new byte[]{3,0};
break;
case 3:
startCoordinates = new byte[]{6,0};
break;
case 4:
startCoordinates = new byte[]{0,3};
break;
case 5:
startCoordinates = new byte[]{3,3};
break;
case 6:
startCoordinates = new byte[]{6,3};
break;
case 7:
startCoordinates = new byte[]{0,6};
break;
case 8:
startCoordinates = new byte[]{3,6};
break;
case 9:
startCoordinates = new byte[]{6,6};
break;
}
byte[] finalCoordinates = null;
// let's check the square in this order:
// 1 2 3
// 4 5 6
// 7 8 9
switch ( i )
{
case 1:
finalCoordinates = new byte[] {startCoordinates[0], startCoordinates[1]};
break;
case 2:
finalCoordinates = new byte[] {(byte) (startCoordinates[0]+1), startCoordinates[1]};
break;
case 3:
finalCoordinates = new byte[] {(byte) (startCoordinates[0]+2), startCoordinates[1]};
break;
case 4:
finalCoordinates = new byte[] {startCoordinates[0], (byte) (startCoordinates[1]+1)};
break;
case 5:
finalCoordinates = new byte[] {(byte) (startCoordinates[0]+1), (byte) (startCoordinates[1]+1)};
break;
case 6:
finalCoordinates = new byte[] {(byte) (startCoordinates[0]+2), (byte) (startCoordinates[1]+1)};
break;
case 7:
finalCoordinates = new byte[] {startCoordinates[0], (byte) (startCoordinates[1]+2)};
break;
case 8:
finalCoordinates = new byte[] {(byte) (startCoordinates[0]+1), (byte) (startCoordinates[1]+2)};
break;
case 9:
finalCoordinates = new byte[] {(byte) (startCoordinates[0]+2), (byte) (startCoordinates[1]+2)};
break;
}
return finalCoordinates;
}
private boolean squareContainsNumber(byte square, byte numToCheck)
{
for ( byte i = 1; i <= 9; i++ )
{
byte[] coordinates = getSquareCoordinates(square, i);
if ( myPuzzle[coordinates[1]][coordinates[0]] == numToCheck )
{
return(true);
}
}
return(false);
}
private boolean rowContainsNumber(byte rowToCheck, byte numToCheck)
{
for ( byte column = 0; column <= 8; column++)
{
if ( myPuzzle[rowToCheck][column] == numToCheck )
{
return(true);
}
}
return(false);
}
private boolean columnContainsNumber(byte columnToCheck, byte numToCheck)
{
for ( byte row = 0; row <= 8; row++)
{
if ( myPuzzle[row][columnToCheck] == numToCheck )
{
return(true);
}
}
return(false);
}
}
</code></pre>
| [] | [
{
"body": "<p><strong>Quitting an application</strong></p>\n\n<blockquote>\n<pre><code>if ( incomingPuzzle.length() != 81 )\n{\n System.out.println(\"Invalid Sudoku puzzle syntax. Should be 81 numbers.\");\n System.exit(1);\n}\n</code></pre>\n</blockquote>\n\n<p>This is not a good way to quit an application where you use it. When you're in a class and you encounter an invalid state for your application, throw an exception. It's not the responsibility of the class to decide if you should terminate the application or not. If you throw an exception, you can control the flow of your application. </p>\n\n<p>In a small program, you won't see the drawback of using this, but in more complex application you will likely want to close your application in a graceful manner. Even for your application you could want someday to save the state of the Sudoku you're working with maybe. </p>\n\n<p>In your case, you could probably throw <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html\"><code>IllegalArgumentException</code></a>, this is a <code>RuntimeException</code> taht unless explicitly catch somewhere, will terminate the application. The advantage of using an exception vs <code>System.exit</code> is that you could decide to catch the exception and terminate the application with what you need to do.</p>\n\n<p><strong>Boolean if</strong></p>\n\n<blockquote>\n<pre><code>if ( showDetails == true )\n</code></pre>\n</blockquote>\n\n<p>This is the same as this :</p>\n\n<pre><code>if (showDetails)\n</code></pre>\n\n<p>I suggest you check directly with the boolean, it will remove \"noise\" form your code.</p>\n\n<p><strong>Method with boolean argument</strong></p>\n\n<p>The first time I read your main, I find it hard to understand what <code>solvePuzzle(true)</code> was suppose to mean. I needed to read a comment and look at the method to know that this turn on a more detailed output. I'm not a fan of this approach. I could suggest that you create a another method which would look like this : </p>\n\n<pre><code>public void solvePuzzleWithDetails()\n{\n solvePuzzle(true);\n}\n</code></pre>\n\n<p>You can now know simply by reading the method name that you will have more details in your output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:47:59.747",
"Id": "81558",
"Score": "0",
"body": "Great suggestions! I'll refactor my code right now. If you think of anything else, feel free to edit your post. I appreciate all the detail you put into it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:25:05.777",
"Id": "46641",
"ParentId": "46640",
"Score": "16"
}
},
{
"body": "<p>It looks good overall, but I have some comments:</p>\n\n<ol>\n<li><p>Small detail: the starting curly brace in Java goes at the end of the line instead of on a new line. It's a small detail, but you never see Java code with the indentation you used (PHP).</p></li>\n<li><p>Another small detail: the parentheses in <code>return (false);</code> look odd.</p></li>\n<li><p><code>byte[][] myPuzzle = new byte[9][9];</code> sets everything to 0 by default. Java guarantees this; probably PHP does not.</p></li>\n<li><p>As pointed out by Marc-Andre, it's better to throw exceptions when you fail rather then printing a sentence and then calling System.exit(1). It's really the same thing.</p></li>\n<li><p>I would make this more OO by creating an interface SudokuSolver with a method solve(Sudoku). Your current algorithm would be one implementation (subclass) of this interface. If you code different solver algorithms, you just have to make them different implementations of SudokuSolver. The class Sudoku would then only represent the board and maybe you should rename such a class to SudokuBoard.</p></li>\n<li><p>Some of your methods are too long. You should break long methods into shorter methods. </p></li>\n<li><p>You don't need convertCharToByte: you can use Byte.parseByte(String.valueOf(someChar)).</p></li>\n<li><p>getSquareCoordinates() has two series of swich-case statements. You can probably simplify that with a simple math formula. (I have not tried to do so).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:50:06.500",
"Id": "81560",
"Score": "0",
"body": "Thanks for the Java style tips. It would seem I have a bit of a PHP \"accent\". Hahaha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:02:13.690",
"Id": "81576",
"Score": "4",
"body": "I never heard that curly braces on the next line is \"not Java\". It's a matter of style and I personally prefer it because of improved readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:19:19.930",
"Id": "81595",
"Score": "1",
"body": "@popovitsj I would say that it is a Java requirement: for any Java developer position, you would be required to use that indentation style. But I agree with you that the code is more readable with the opening braces on their own line."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:05:33.137",
"Id": "46643",
"ParentId": "46640",
"Score": "14"
}
},
{
"body": "<p>If I were writing this program, I would try to simplify the solver by moving some of the complexity into the board's storage itself, hopefully removing some of it altogether in the process.</p>\n\n<p>Note that I am using some Java 8 features in my code, so if you are using an earlier version you may need to substitute equivalent code for the <code>Optional<Byte></code> (which is easy enough to just implement yourself) and the stream statements in the last two functions (which could be replaced with some loops and conditionals).</p>\n\n<p>First off, I would use one of these to represent the marks on the grid:</p>\n\n<pre><code>Optional<Byte>\n</code></pre>\n\n<p>Unfortunately, that class is declared as <code>final</code>, so I can't declare a no-elements subclass to change the name to be clearer what I am using it for.</p>\n\n<p>You also need cells to hold marks in the grid:</p>\n\n<pre><code>class Cell {\n Optional<Byte> value = Optional.empty();\n boolean editable = false;\n\n public Cell(Optional<Byte> value){\n this.value = value;\n if(!value.isPresent()) editable = true;\n }\n\n public Optional<Byte> getMark(){\n return value;\n }\n\n public boolean setMark(Optional<Byte> mark){\n if(!editable) return false;\n this.value = mark;\n return true;\n }\n public boolean isEditable(){\n return editable;\n }\n}\n</code></pre>\n\n<p>The purpose of this is so we can mutate the contents of the board without having to redistribute a new copy to everyone. This will need additional parts (such as extending <code>ReentrantLock</code>) if concurrent access is desired, but most likely YAGNI.</p>\n\n<p>Now, for the game logic itself, instead of hardcoding the restrictions on the cells into the big conditional mess, we can add objects to represent restrictions:</p>\n\n<pre><code>class Constraint {\n Set<Cell> cells = new HashSet<>();\n public Constraint(){}\n public Constraint(Cell ... cells){\n add(cells);\n }\n public Constraint add(Cell ... cells){\n this.cells.addAll(cells);\n }\n\n Set<Optional<Byte>> allMarks() {\n Set<Optional<Byte>> all = new HashSet<>();\n for(int idx = 0; idx < cells.size(); idx++)\n all.add(Optional.of(idx));\n return all;\n }\n\n public boolean isViolated(){\n Set<Optional<Byte>> marks = allMarks();\n for(Cell cell: cells)\n if(cell.contents.isPresent() && !marks.remove(cell.contents)) return false;\n return true;\n }\n public boolean isSatisfied(){\n Set<Optional<Byte>> marks = allMarks();\n marks.remove(Optional.empty());\n for(Cell cell: cells)\n if(!cell.contents.isPresent() || !marks.remove(cell.contents)) return false;\n return true;\n }\n}\n</code></pre>\n\n<p>Just have one of these for every row, column, and block.</p>\n\n<p>You then need a class for the board as a whole:</p>\n\n<pre><code>class Board {\n final int DEFAULT_SIZE = 9;\n\n public Cell [][] cells;\n Set<Constraint> constraints;\n\n public Board(String contents){\n this(DEFAULT_SIZE, contents);\n }\n\n public Board(int size, String contents){\n\n cells = new Cell[size][size];\n constraints = new HashSet<>(3*size);\n\n List<Constraint> rows = new ArrayList<>(size),\n columns = new ArrayList<>(size),\n blocks = new ArrayList<>(size);\n\n for(int idx = 0; idx < size; idx++){\n rows.add(new Constraint());\n columns.add(new Constraint());\n blocks.add(new Constraint());\n }\n\n int sqsize = (int)Math.sqrt(size);\n\n for(int idx = 0; idx < contents.size(); idx++){\n Cell cell = new Cell(markFor(contents.charAt(idx)));\n\n cells[idx/size][idx%size] = cell;\n rows.get(idx/size).add(cell);\n columns.get(idx%size).add(cell);\n blocks.get(idx/sqsize+sqsize*idx%sqsize).add(cell);\n }\n\n constraints.addAll(rows);\n constraints.addAll(columns);\n constraints.addAll(blocks);\n }\n\n Optional<Byte> markFor(char ch, int range){\n if(ch == ' ') return Optional.empty();\n else return Optional.of(Byte.valueOf(ch.toString(), range)));\n }\n\n\n public Set<Constraint> constraintsViolated(){\n return constraints.stream()\n .filter(c->c.isViolated())\n .collect(Collectors.toCollection(HashSet::new));\n }\n\n public Set<Constraint> constraintsNotSatisfied(){\n return constraints.stream()\n .filter(c->!c.isSatisfied())\n .collect(Collectors.toCollection(HashSet::new));\n }\n}\n</code></pre>\n\n<p>The solver code can be far simplified if you use structures like this to store your data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:07:07.647",
"Id": "81531",
"Score": "2",
"body": "I call overengineering!! I also do that quite often, but it's really overkill to have numeric values represented by an enum-structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:21:22.447",
"Id": "81539",
"Score": "0",
"body": "A compromise to having enums for nothing and 1 to 9 would be to use Optional<Byte>, but that's only available in Java 8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:23:17.903",
"Id": "81540",
"Score": "0",
"body": "@toto2 that might actually be better anyway, though.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:51:08.933",
"Id": "81562",
"Score": "0",
"body": "This code makes me want to go learn advanced data structures now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:52:07.173",
"Id": "81563",
"Score": "0",
"body": "If you want to support sudoku with more than 9 digits for larger boards (up to 99), you can create an enum whose values comprise of two `Mark` instances, then, you can create an enum with 3 mark instances for up to 1000. Inventing numbers is so much fun."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:19:35.570",
"Id": "81610",
"Score": "0",
"body": "@toto2 I have implemented the change you suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:20:42.170",
"Id": "81611",
"Score": "1",
"body": "@BenjaminGruenbaum I see your point, and I agree it is foolish."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:31:36.687",
"Id": "81613",
"Score": "0",
"body": "`Optional<Byte>` seems like a much better choice here anyway :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:54:35.337",
"Id": "46645",
"ParentId": "46640",
"Score": "8"
}
},
{
"body": "<p>A style thing: most of the methods in your class <code>Sudoku</code> are called things like <code>printPuzzle</code>, <code>showPuzzle</code>, etc. If these were instance methods of a class called <code>Puzzle</code>, it would be unnecessary to call them all this. They would be better named <code>print</code>, <code>show</code>, etc. </p>\n\n<p>In your case the class is actually called <code>Sudoku</code>. Perhaps it would be better named <code>Puzzle</code>? Or perhaps <code>Puzzle</code> should actually be a different class, and the methods <code>somethingPuzzle</code> should be in that class?</p>\n\n<p>In any case, there shouldn't be a discrepancy between what you call the class, and the word you use in your head to think about the object concerned, and the names of methods shouldn't be redundant.</p>\n\n<p>I know this might seem trivial, but naming things correctly does make a difference, to how you document and how you are able to maintain your code. If object-oriented code involves objects, each of which we can point at and explain simply what it does, it can be very clean and straightforward. When we lose this, it can get very confusing quite fast. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:30:54.560",
"Id": "81657",
"Score": "0",
"body": "Don't worry, I agree with you! I don't like redundancy either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T23:42:33.647",
"Id": "81834",
"Score": "1",
"body": "I refactored the code so that everything is in a package called \"sudoku\". The two classes were renamed to \"solver\" and \"puzzle\", and the methods were renamed to \"print\", \"solveLogically\", and \"solveLogicallyWithDetails\". I'll add \"solveRecursively\" later. Thanks for the tip."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:02:49.397",
"Id": "46681",
"ParentId": "46640",
"Score": "5"
}
},
{
"body": "<p>A thing to consider may be all the <code>System.out.println(\"\")</code> statements. In a later stage of your application, when an other GUI than the console is used, this statement will (maybe) not be helpful anymore, because the application will run without console.</p>\n\n<p>Splitting your application a bit more into a core part (solving the Sudoku) and a GUI part (with Interface) can help. So the interface could have a <code>printMessage</code> method and the GUI (the console at the moment) can display it in any suitable form.</p>\n\n<p>Once I used <a href=\"http://logging.apache.org/log4j/1.2/\" rel=\"nofollow\">Apache Log4J</a> and used different appender for different GUI.</p>\n\n<p>I'm out of Java for some time now, maybe better solutions are available</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T23:44:59.443",
"Id": "81835",
"Score": "0",
"body": "I'll work on this. I guess the end goal is for the Sudoku class to only return objects. That way it doesn't matter whether I'm using a console or a GUI. Whatever the receiving class is can worry about displaying it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:23:59.077",
"Id": "81985",
"Score": "0",
"body": "[Logback](http://logback.qos.ch/) and [SLF4J](http://www.slf4j.org/) are the latest Java logging hotness. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:47:47.033",
"Id": "46706",
"ParentId": "46640",
"Score": "6"
}
},
{
"body": "<p>You have already got lot's of good suggestions. I just want to add one more thing, you can simplify your if conditions. for example Condition <code>if (puzzleIsValid() == false)</code> which can be simplified as <code>if (!puzzleIsValid())</code>. Condition <code>if (rowContainsNumber(checkThisRowFirst, numToCheck) == true)</code> can be simplified as <code>if (rowContainsNumber(checkThisRowFirst, numToCheck)</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T19:56:35.043",
"Id": "73855",
"ParentId": "46640",
"Score": "2"
}
},
{
"body": "<p>A few add-ons to what others have mentioned:</p>\n\n<ul>\n<li><p>If its possible to avoid multiple switch statements with a simple <code>if-else</code>, do it.</p>\n\n<pre><code>private byte convertCharToByte(char f)\n{\n int cellVal = f - '0';\n if( cellVal>=0 && cellVal<=9){\n return cellVal;\n }else{\n // throw an exception.\n }\n}\n</code></pre></li>\n<li><p>The other one is the <code>switch(squareNumber)</code> with</p>\n\n<pre><code>int rowNum = 3*((squareNumber-1)%3);\nint colNum = 3*((squareNumber-1)/3);\nstartCoordinates = new byte[]{rowNum, colNum};\n</code></pre></li>\n<li><p>Similarly for finalCoordinate</p>\n\n<pre><code>int rowOffset = ((squareNumber-1)%3);\nint colOffset = ((squareNumber-1)/3);\nfinalCoordinates = new byte[] {(byte) (startCoordinates[0]+rowOffset ), (byte) (startCoordinates[1]+colOffset )};\n</code></pre></li>\n<li><p>Try your solver for the <a href=\"http://i.telegraph.co.uk/multimedia/archive/02260/Untitled-1_2260717b.jpg\" rel=\"nofollow\">world's hardest sudoku</a>.</p></li>\n</ul>\n\n<p>A suggestion:</p>\n\n<ul>\n<li>Aim for a generic implementation. Why 9x9 only, why not 3x3, 4x4 ,etc.</li>\n<li>Have the rowNum and colNum as the class members and calculate based on it.</li>\n</ul>\n\n<p>You will savour your implementation :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T16:27:48.743",
"Id": "135295",
"Score": "0",
"body": "Thanks for your feedback ! My program only uses 1 technique. To solve difficult Sudokus using logic you need to apply multiple techniques. The following is my go-to Sudoku solver because it applies most of the known techniques: http://www.sudokuwiki.org/sudoku.htm I plugged your world's hardest Sudoku into this one and you stumped it, which is pretty rare. I've seen it eat other hard Sudokus for breakfast. I think the one you gave is only solvable by recursion. If you click \"Solution Count\" that will calculate the solution recursively."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T20:36:33.710",
"Id": "73863",
"ParentId": "46640",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46645",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T13:00:33.893",
"Id": "46640",
"Score": "14",
"Tags": [
"java",
"beginner",
"sudoku"
],
"Title": "Logical Sudoku Solver in Java"
} | 46640 |
<p>I have an array of length <em>n</em> that contains numbers from 0 to <em>n</em>-1 in random order.
I now want to "inverse" this array to one that where index <em>i</em> corresponds to the location of <em>i</em> in the source array.</p>
<p><strong>Example</strong></p>
<pre><code>Source_Array = {2,0,1}
</code></pre>
<p>Transform to:</p>
<pre><code>Result_Array = {1,2,0}
</code></pre>
<p>This means I find the index 0 at position 1 in my source, 1 is at location 2 and so on.</p>
<p>I did this with the following function:</p>
<pre><code>Dim Sourcelist As List(Of Integer) = Source.ToList
Dim Result(Source.Count - 1) As Integer
For i = 0 To Source.Count - 1
Result(i) = Sourcelist.IndexOf(i)
Next
</code></pre>
<p>Casting the array to List and then slowly using <code>IndexOf</code> to select the indices is not really great. Is there a better method maybe using LINQ?</p>
<p>Both VB.NET and C# answers are very much appreciated.</p>
| [] | [
{
"body": "<p>Unfortunately I don't really know visual basic but I think that you will find it easy to grasp the idea (and implement it in any language) of the following java code:</p>\n\n<pre><code>int[] source = new int[]{2,0,1};\nint[] dest = new int[source.length];\nfor (int i = 0; i < source.length; i += 1) {\n dest[source[i]] = i;\n}\n</code></pre>\n\n<p>The code runs at \\$O(n)\\$ time whereas if you search for every element you get \\$O(n^2)\\$ time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:32:06.340",
"Id": "81544",
"Score": "0",
"body": "Perfect, that's an elegant solution to this problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:27:46.307",
"Id": "46649",
"ParentId": "46647",
"Score": "6"
}
},
{
"body": "<p>I'm not very good with LINQ but here's my take at it.</p>\n\n<pre><code>Dim Result_Array = From v In Source_Array Select Source_Array(v)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:27:11.793",
"Id": "46663",
"ParentId": "46647",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:08:26.230",
"Id": "46647",
"Score": "6",
"Tags": [
"optimization",
"performance",
"array",
"linq",
"vb.net"
],
"Title": "Inversion of an array that contains indices"
} | 46647 |
<p>I am applying to a university to study Computational Linguistics, and as I read, it would be recommended to have a background in Artificial Intelligence.</p>
<p>The Admission board asked me to prepare a portfolio of my works, and I am considering to add this solution to the portfolio.</p>
<p>I have been lazy to develop an AI to bypass the default obstacles, so I added mine to ease the movement of the robot.</p>
<pre><code> /*
* robotNav.js
*
* The green key is located in a slightly more
* complicated room. You'll need to get the robot
* past these obstacles.
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function startLevel(map) {
map.placePlayer(0, map.getHeight() - 1);
var player = map.getPlayer();
map.defineObject('robot', {
'type': 'dynamic',
'symbol': 'R',
'color': 'gray',
'onCollision': function (player, me) {
me.giveItemTo(player, 'greenKey');
},
'behavior': function (me) {
for(i = 2; i<9; i++){
map.placeObject(map.getWidth() - 20, i, 'block');
}
for(i = 2; i<9; i++){
map.placeObject(map.getWidth() - 3, i, 'block');
}
if(me.canMove('down') && !me.canMove('left')){
me.move('down');
}else{
if(me.canMove('right') && !me.canMove('down')){
me.move('right');
}
if(me.canMove('up') && !me.canMove('right')){
if(me.canMove('left')){
me.move('up');
}else{
me.move('down');
}
}
if(!me.canMove('up') && me.canMove('right')){
me.move('right');
}
if(!me.canMove('up') && !me.canMove('right')){
me.move('down');
}
}
}
});
map.defineObject('barrier', {
'symbol': '░',
'color': 'purple',
'impassable': true,
'passableFor': ['robot']
});
map.placeObject(map.getWidth() - 1, map.getHeight() - 1, 'exit');
map.placeObject(1, 1, 'robot');
map.placeObject(map.getWidth() - 2, 8, 'greenKey');
map.placeObject(map.getWidth() - 2, 9, 'barrier');
for (var x = 0; x < map.getWidth(); x++) {
map.placeObject(x, 0, 'block');
if (x != map.getWidth() - 2) {
map.placeObject(x, 9, 'block');
}
}
for (var y = 1; y < 9; y++) {
map.placeObject(0, y, 'block');
map.placeObject(map.getWidth() - 1, y, 'block');
}
for (var i = 0; i < 4; i++) {
map.placeObject(20 - i, i + 1, 'block');
map.placeObject(35 - i, 8 - i, 'block');
}
}
function validateLevel(map) {
map.validateExactlyXManyObjects(1, 'exit');
map.validateExactlyXManyObjects(1, 'robot');
map.validateAtMostXObjects(1, 'greenKey');
}
function onExit(map) {
if (!map.getPlayer().hasItem('greenKey')) {
map.writeStatus("We need to get that key!");
return false;
} else {
return true;
}
}
</code></pre>
<p>This Solution is to the quiz #12 in Chapter 2 of <a href="http://alexnisnevich.github.io/untrusted/" rel="nofollow noreferrer">Untrusted Game</a>.</p>
<p>What I mean by <em>ethical</em> is that am I allowed to cheat my way out in the AI world, or am I required to solve the problem as it is without additions (the additions here are the two added walls).</p>
<p><strong>EDIT:</strong></p>
<p>Here is the default setup of the scene:</p>
<p><img src="https://i.stack.imgur.com/XTB7A.png" alt="default scene"></p>
<p>And here are my changes:</p>
<p><img src="https://i.stack.imgur.com/szIsd.png" alt="my solution"></p>
<p>The '@' is the player, the small blue rectangle in the bottom-right corner is the goal, 'R' is the robot that must be programmed (it moves once the player moves), 'K' is the goal for the robot it also is the key that allows the player to open his goal, the robot must reach the key and move through the portal under it (no human is allowed to pass it) and provide the key to the player so he can win the quiz.</p>
<p>Another thing is that I am only allowed to edit the behaviour of the 'robot' object (at line 24). </p>
<pre><code>'behavior': function (me) {....}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:38:39.470",
"Id": "81569",
"Score": "3",
"body": "Re ethics: this game encourages cheating. I very much like the idea of placing additional barriers to guide the robot. This game requires creative thinking, but it's not good material for a resume: you didn't solve the problem with any kind of AI."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:43:33.143",
"Id": "81572",
"Score": "0",
"body": "@amon would you please guide me to an article/resource that would help me create the AI with only two variables from the environment ?\npossible directions are : up down left right, and I am only allowed to use canMove(direction) and move(direction), also for each step the player moves, the AI moves one step also (can't use move(left) and move(up) in the same step)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:02:47.187",
"Id": "81577",
"Score": "0",
"body": "No, you can figure out the pathfinding yourself – this is Code Review, not a place for implementation help. Tips: You can use the `player` variable to store arbitrary state, e.g. via an object. The robot can erect barriers to seal off dead ends."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:22:02.770",
"Id": "81597",
"Score": "0",
"body": "You are forgetting how js works... all you need to do is create a closure and you can have all the variables you want, you just need one place to store it and you have that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:27:41.867",
"Id": "81599",
"Score": "1",
"body": "Heh, I just set the robot to duplicate my movements keeping a bit of `y` distance. No AI of any kind, just I :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:30:30.480",
"Id": "81600",
"Score": "0",
"body": "As one of the creators of Untrusted, I think it's a great solution, and absolutely in keeping with the spirit of the game :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:57:25.993",
"Id": "81603",
"Score": "0",
"body": "Thank you @BadgerPriest, If you would like to take a look at my solutions for the previous problems, I would be happy to provide them privately, as most (if not all) are cheating, and took less than 30 seconds to create (remove all blocks, place the exit near player when no validation etc...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T23:59:17.830",
"Id": "82021",
"Score": "0",
"body": "@Flambino my solution was a weighted random walk (biased so it would eventually get to the bottom right). Didn't take that long to run, either, actually. (The maze was even easier - just a simple `if(me.canMove('down')) me.move('down'); else me.move('right');` is enough - you just need to regenerate the map until you get one that it can solve.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:48:34.153",
"Id": "82023",
"Score": "0",
"body": "@AJMansfield Sure, but I could the same ~6 line solution for 3 levels, _and_ I got a neat robot buddy :) But seriously, I'm not saying my solution was brilliant or anything, just that it was the opposite of AI :)"
}
] | [
{
"body": "<p>From a quick review:</p>\n\n<ul>\n<li>As @Amon said, I would not use this for your portfolio, especially if you are cheating</li>\n<li>You have 0 comments in your code, even for a fake AI that is not good enough</li>\n<li>Instead of all the <code>if</code>s and <code>else</code> I would build a rules table, the logic would go through each entry, see if a condition evaluates to true, and then perform the action.</li>\n<li>I don't see any style problems, so that's good</li>\n</ul>\n\n<p>I got out with this:</p>\n\n<pre><code> this.direction = this.direction || 'down';\n\n var moves = {\n 'down' : [ 'left' , 'down' , 'right' , 'up' ],\n 'right': [ 'down' , 'right' , 'up' , 'left' ],\n 'left' : [ 'up' , 'left' , 'down' , 'right' ],\n 'up' : [ 'right' , 'up' , 'left' , 'down' ]\n\n }, \n move = moves[this.direction];\n\n if( me.canMove( move[0] ) )\n this.direction = move[0];\n else if ( me.canMove( move[1] ) )\n this.direction = move[1]; \n else if ( me.canMove( move[2] ) )\n this.direction = move[2]; \n else \n this.direction = move[3];\n\n\n me.move( this.direction )\n</code></pre>\n\n<p>Obviously the access to each movement option could have been handled with a loop, but you get the gist.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:58:21.143",
"Id": "81604",
"Score": "0",
"body": "I mostly use arrays to store the logic for bigger programs, but as these took less than a minute to solve, I just stick to if else :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:07:12.280",
"Id": "81718",
"Score": "0",
"body": "Sure, but I think your portfolio deserves better ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:22:12.693",
"Id": "46662",
"ParentId": "46650",
"Score": "5"
}
},
{
"body": "<p>I'm one of the developers of Untrusted (neunenak). Your solution is completely ethical/fair/okay. The whole idea behind the game was that the player could write whatever code they needed to be able to progress to the next level. We do have a lot of code in the game's framework designed to make really easy and uncreative solutions impossible, but that's just to try to force the player to think creatively - if the code you wrote lets you get Dr. Eval to the next level, it's all good. After all, in the real world you don't get more points for writing a complicated AI when a shell script solves your actual problem just as well!</p>\n\n<p>Thanks for playing the game by the way! We're glad you're enjoying it :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T20:52:39.007",
"Id": "81609",
"Score": "10",
"body": "I have played many javascript games like this (Javascript RPG anyone?), but I was never attached and emotionally involved to any of them like this one, I have spent hours reading the code and solving my way out. Sir, you deserve a beer, and a high five :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T20:43:26.357",
"Id": "46673",
"ParentId": "46650",
"Score": "23"
}
},
{
"body": "<p>Yeah, for this level it's up to you.</p>\n\n<p>For instance, you made an AI for your robot. I did a remote control for mine.</p>\n\n<pre><code> if (player.getX() == 0) {\n me.move('left');\n } else if (player.getX() == 1) {\n me.move('right');\n } else if (player.getX() == 2) {\n me.move('down');\n } else if (player.getX() == 3) {\n me.move('up');\n }\n</code></pre>\n\n<p>Choose your robot direction with player's X position. Move your robot by walking player along Y axis.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:06:01.663",
"Id": "46814",
"ParentId": "46650",
"Score": "1"
}
},
{
"body": "<p>My solution for robots is control them by player position like this:</p>\n\n<pre><code> if( player.atLocation(3, map.getHeight() - 2))\n me.move('left');\n if( player.atLocation(5, map.getHeight() - 2))\n me.move('right');\n if( player.atLocation(4, map.getHeight() - 3))\n me.move('up');\n if( player.atLocation(4, map.getHeight() - 1))\n me.move('down');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T11:26:44.247",
"Id": "46900",
"ParentId": "46650",
"Score": "1"
}
},
{
"body": "<p>Right hand wall walk is not that hard to code (kept it simple so my son could understand it): </p>\n\n<pre><code> if(me.vars === undefined)\n {\n me.vars = 1;\n me.facing = 0; \n me.direction = Array ('up','right','down','left','up'); \n }\n\n if(me.canMove(me.direction[me.facing+1]))\n {\n me.facing++;\n }\n else if(me.canMove(me.direction[me.facing]))\n {\n\n }\n else\n {\n me.facing--;\n }\n\n\n if(me.facing < 0)\n {\n me.facing = 0;\n }\n if(me.facing > 3)\n {\n me.facing = 0;\n }\n\n me.move(me.direction[me.facing]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T00:03:57.183",
"Id": "46978",
"ParentId": "46650",
"Score": "4"
}
},
{
"body": "<p>There is better 'unethical' solution - works for 12th and 13th level</p>\n\n<pre><code> map.defineObject('xxx', \n {\n 'type': 'static',\n 'symbol': 'X',\n 'color': '#0f0',\n 'onCollision': function (player, game) {\n game.addToInventory('greenKey');\n }\n });\n if(!me.xx){\n map.placeObject(20, map.getHeight() - 1, 'xxx');\n me.xx=true;\n } \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:49:12.813",
"Id": "47242",
"ParentId": "46650",
"Score": "2"
}
},
{
"body": "<p>I knew my solution was not the expected one, but it worked for several stages before this one, so the code was written and just had to change the directions. The solution was to trigger set directions with the phone, using player color swaps.</p>\n\n<pre><code>var player = map.getPlayer();\nplayer.setPhoneCallback( function(){\n if(player.getColor()=='#0f0'){\n player.setColor('#f0f');\n }else if(player.getColor()=='#f0f'){\n player.setColor('#00f');\n }else if(player.getColor()=='#00f'){\n player.setColor('#0ff');\n }else{\n player.setColor('#f00');\n }\n});\nif(player.getColor()=='#0f0'){ me.move('down'); }\nif(player.getColor()=='#f0f'){ me.move('right'); }\nif(player.getColor()=='#00f'){ me.move('up'); }\nif(player.getColor()=='#0ff'){ me.move('right'); }\nif(player.getColor()=='#f00'){ me.move('down'); }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T00:02:22.037",
"Id": "48090",
"ParentId": "46650",
"Score": "1"
}
},
{
"body": "<p>I can't reply to the answer itself, but <a href=\"https://codereview.stackexchange.com/a/46978/41528\">https://codereview.stackexchange.com/a/46978/41528</a> doesn't actually solve the problem; it moves the Robot in a square (right, down, left, up) because:</p>\n\n<p>1) 'up' and 'down' were reversed.</p>\n\n<p>2) The direction was improperly reset when it went past the array bounds.</p>\n\n<p>A working wall-walk for lefties AND it delivers the key to the player (for this particular puzzle):</p>\n\n<pre><code>if(me.vars === undefined)\n{\n me.vars = 1;\n me.facing = 0; \n me.direction = Array ('down','right','up','left','down'); \n}\n\nif(me.canMove(me.direction[me.facing+1]))\n{\n me.facing++;\n}\nelse if(me.canMove(me.direction[me.facing]))\n{\n\n}\nelse\n{\n me.facing--;\n}\n\n\nif(me.facing < 0)\n{\n me.facing = 3;\n}\nif(me.facing > 3)\n{\n me.facing = 0;\n}\n\nme.move(me.direction[me.facing]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:36:15.687",
"Id": "48487",
"ParentId": "46650",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "46673",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:42:14.547",
"Id": "46650",
"Score": "15",
"Tags": [
"javascript",
"game",
"interview-questions",
"pathfinding",
"ai"
],
"Title": "Is my AI solution to Untrusted Game considered logical or \"ethical\"?"
} | 46650 |
<p>I am trying to implement a custom ApiClient in Python, using requests.
The way it does authentication is by:</p>
<ol>
<li><p>login(username, password) -> get back a token if valid, http error code if not</p></li>
<li><p>set the token in <code>{'Authorization': token}</code> header and use that header for all endpoints which need authentication</p></li>
</ol>
<p>Can you check if the code looks OK, and if not what kind of changes would you recommend?</p>
<pre><code>#!/usr/bin/env python
import requests
import json
import os
import sys
def read_file_contents(path):
if os.path.exists(path):
with open(path) as infile:
return infile.read().strip()
class ApiClient():
token = None
api_url = 'http://10.0.1.194:1234'
session = requests.Session()
def __init__(self):
self.token = self.load_token()
if self.token:
self.session.headers.update({'Authorization': self.token})
else:
# if no token, do login
if not self.token:
try:
self.login()
except requests.HTTPError:
sys.exit('Username-password invalid')
def load_token(self):
return read_file_contents('token')
def save_token(self, str):
with open('token', 'w') as outfile:
outfile.write(str)
def login(self):
email = '1@1.hu'
password = 'passwd'
headers = {'content-type': 'application/json'}
payload = {
'email': email,
'password': password
}
r = requests.post(self.api_url + '/auth',
data=json.dumps(payload),
headers=headers)
# raise exception if cannot login
r.raise_for_status()
# save token and update session
self.token = r.json()['session']['token']
self.save_token(self.token)
self.session.headers.update({'Authorization': self.token})
def test_auth(self):
r = self.session.get(self.api_url + '/auth/is-authenticated')
return r.ok
if __name__ == '__main__':
api = ApiClient()
print api.test_auth()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:39:25.993",
"Id": "81557",
"Score": "0",
"body": "the email-password will obviously not be hard coded"
}
] | [
{
"body": "<p>I don't have time to do a thorough review, but here are some comments based on a casual reading.</p>\n\n<ul>\n<li><p>In <code>read_file_contents</code>, the function returns <code>None</code> if the file doesn’t exist. I’d suggest modifying this to print or return an explicit message to that effect, to make debugging easier later. For example, something like:</p>\n\n\n\n<pre><code>def read_file_contents(path):\n try:\n with open(path) as infile:\n return infile.read().strip()\n except FileNotFoundError:\n print \"Couldn't find the token file!\"\n return None\n</code></pre>\n\n<p>will make your life easier later.</p>\n\n<p>Also, is this meant to be <code>open(path, 'r')</code>?</p></li>\n<li><p>New-style classes should inherit from object: that is, use</p>\n\n\n\n<pre><code>class ApiClient(object):\n</code></pre>\n\n<p>instead of </p>\n\n\n\n<pre><code>class ApiClient():\n</code></pre></li>\n<li><p>Don't copy and paste the API URL throughout your code. Make it a variable, and then pass <code>api_url</code> as an input to <code>ApiClient()</code>. That way, you can reuse this code for other APIs, or make changes to the URL in a single place. (If, for example, the API changes.)</p></li>\n<li><p><strong>Don't hard code username, email and password in the <code>login</code> function.</strong> It makes it harder to change them later, and it's a security risk. Consider using something like the <a href=\"https://pypi.python.org/pypi/keyring\" rel=\"nofollow\"><code>keyring</code></a> module for storing sensitive information. (Should the token be stored securely as well?)</p></li>\n<li><p>The <code>__init__</code> function uses the token, and also retrieves it from the file. This can cause problems if you later get the token from somewhere else. (For example, if you used <code>keyring</code>.) Instead, consider passing <code>token</code> as an argument to <code>__init__</code>, and having the code to obtain the token somewhere else. Something like:</p>\n\n\n\n<pre><code>def __init__(self, api_url, token=None):\n self.api_url = api_url\n self.token = token\n\n if self.token is not None:\n # if you get a token\n else:\n # if you don't\n</code></pre>\n\n<p>and then later:</p>\n\n\n\n<pre><code>if __name__ == '__main__':\n api_token = read_file_contents('token')\n api_url = 'http://10.0.1.194:1234'\n api = ApiClient(api_token, api_url)\n print api.test_auth()\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:49:53.553",
"Id": "81559",
"Score": "1",
"body": "Even better than returning `None` if the file is unreadable, just let the exception propagate, and catch it in `__init__()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:50:57.630",
"Id": "81561",
"Score": "1",
"body": "`open()` mode is `'r'` by default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:51:53.007",
"Id": "81620",
"Score": "1",
"body": "@200_success While that is true, it could be argued that this qualifies as \"explicit is better than implicit\"."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:43:21.353",
"Id": "46653",
"ParentId": "46652",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46653",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:20:45.363",
"Id": "46652",
"Score": "7",
"Tags": [
"python",
"http",
"authentication"
],
"Title": "Python auth using requests"
} | 46652 |
<p>This query produces the results I want. </p>
<p>Is there a less wordy or more effective way to write <a href="http://sqlfiddle.com/#!4/9d4bb/50" rel="nofollow">this query</a>?</p>
<pre><code>Criteria:
1. Vendor in detail record must have a record in TRANSEFFECTIVE
2. Get the most recent (begin_frame) record from TRANSDETAIL
3. Tells me if the vendor has any other categories in the TRANSMODAL table.
</code></pre>
<p>In this case, </p>
<p>Since DDAN has a detail record and has record in TRANSEFFECTIVE, report that DDAN has an AIR,GROUND,and SEA modal record.</p>
<p>Since POKE has a detail record and has record in TRANSEFFECTIVE, report that POKE has only AIR and GROUND modal records.</p>
<pre><code>select vend_code,
vend_numb,
description,
freight_mode
from (
select vend_code,
vend_numb,
begin_frame,
freight_mode,
freight_count,
description,
row_number() over (partition by vend_code,
vend_numb,
(case modal_class_code
when 'A1' then 1
when 'A2' then 1
when 'G1' then 2
when 'S1' then 3
end)
order by vend_code,
vend_numb) as modal_class_count
from
(
select td.modal_vend_code as vend_code,
td.modal_vend_numb as vend_numb,
td.modal_begin_frame as begin_frame,
td.modal_description as description,
te.modal_vend_begin_frame as te_begin,
te.modal_vend_close_frame as te_close,
tm.modal_class_code as modal_class_code,
case tm.modal_class_code
when 'A1' then 'AIRFREIGHT'
when 'A2' then 'AIRFREIGHT'
when 'G1' then 'GROUND'
when 'S1' then 'SEABOUND'
else 'UNKNOWN'
end as freight_mode,
rank() over (partition by td.modal_vend_code,
td.modal_vend_numb
order by td.modal_begin_frame desc) as freight_choice,
count(*) over (partition by td.modal_vend_code,
td.modal_vend_numb) freight_count
from transdetail td
inner join transeffective te on td.modal_vend_code = te.modal_vend_code
and td.modal_vend_numb = te.modal_vend_numb
inner join transmodal tm on td.modal_vend_code = tm.modal_vend_code
and td.modal_vend_numb = tm.modal_vend_numb
)
where freight_choice=1
)
where modal_class_count=1
;
</code></pre>
| [] | [
{
"body": "<p>Well, I think I broke SQLFiddle... Just for clarity's sake, I'd refactor the subqueries... that's the best way I know to do step-wise development and refinement. I know my subquery names suck - they should be descriptive. I would also strip out un-necessary column names -- or in my case, comment them out.</p>\n\n<pre><code>with qry1 as\n (\n select td.modal_vend_code as vend_code,\n td.modal_vend_numb as vend_numb,\n td.modal_begin_frame as begin_frame,\n td.modal_description as description,\n te.modal_vend_begin_frame as te_begin,\n te.modal_vend_close_frame as te_close,\n tm.modal_class_code as modal_class_code,\n case tm.modal_class_code\n when 'A1' then 'AIRFREIGHT'\n when 'A2' then 'AIRFREIGHT'\n when 'G1' then 'GROUND'\n when 'S1' then 'SEABOUND'\n else 'UNKNOWN'\n end as freight_mode,\n case tm.modal_class_code\n when 'A1' then 1\n when 'A2' then 1\n when 'G1' then 2\n when 'S1' then 3\n else NULL\n end as modal_class,\n rank() over (partition by td.modal_vend_code,\n td.modal_vend_numb\n order by td.modal_begin_frame desc) as freight_choice,\n count(*) over (partition by td.modal_vend_code,\n td.modal_vend_numb) freight_count\n from transdetail td\n inner join transeffective te on td.modal_vend_code = te.modal_vend_code\n and td.modal_vend_numb = te.modal_vend_numb\n inner join transmodal tm on td.modal_vend_code = tm.modal_vend_code\n and td.modal_vend_numb = tm.modal_vend_numb\n )\n ,\n qry2 as\n (\n select vend_code,\n vend_numb,\n -- begin_frame,\n freight_mode,\n -- freight_count,\n description,\n row_number() over (partition by vend_code,\n vend_numb,\n modal_class\n order by vend_code, \n vend_numb) as modal_class_count\n from \n qry1\n where freight_choice=1\n )\n\n select vend_code,\n vend_numb,\n description,\n freight_mode\n from qry2\n where modal_class_count=1\n ;\n</code></pre>\n\n<p>Then again, seeing as when I tried to run this in SQLFiddle, it didn't return for over a minute, and when I tried to refresh, I got a 404 -- my attempt may be a problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T03:12:23.773",
"Id": "47430",
"ParentId": "46657",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:44:03.127",
"Id": "46657",
"Score": "1",
"Tags": [
"sql",
"oracle"
],
"Title": "SQL double nested query"
} | 46657 |
<p>I am looking for a review on the following code which is for this <a href="http://www.codechef.com/APRIL14/problems/ADIGIT/" rel="nofollow">question</a>. I am looking for a general review of the code. I am specifically also looking for advice on how to make this code run more efficiently.</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.*;
public class Main
{
public static void main(String args[]) throws IOException
{
int S[] = new int[100000];
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String s[] = in.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
String St = in.readLine();
char num[] = St.toCharArray();
for (int j = 0; j < m; j++)
{
String r1 = in.readLine();
int r = Integer.parseInt(r1);
int sum1 = 0, sum2 = 0;
for (int p = 0, len = num[r - 1]; p < r - 1; p++)
{
int diff = len - num[p];
if (diff < 0)
sum1 = sum1 + diff;
else
sum2 = sum2 + diff;
}
out.println((sum2 - sum1));
}
out.flush();
out.close();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:37:46.033",
"Id": "81601",
"Score": "2",
"body": "This looks like it is a C program. It's not bad in itself, but you probably don't want to write something like this for a Java job interview."
}
] | [
{
"body": "<p><strong>Naming Conventions</strong><br>\nVariables in java should be <code>camelCase</code>, meaning they should start with a small letter.</p>\n\n<p><strong>Meaningful names</strong><br>\nSomeone reading your code doesn't stand a chance in hell to understand what you are trying to do without actually running this code in his head...<br>\nYour class is called <code>Main</code>, your only method is <code>main</code>... at least try to tell your reader some story on what you are trying to do, especially when you post it for review!<br>\nVariable names like <code>n</code>, <code>m</code>, <code>num</code>, and <code>sum</code> add nothing to explain your code. Names like <code>s</code> and <code>S</code> are even worse.</p>\n\n<p><strong>Efficiency</strong><br>\nIt is very hard to give efficiency advice, if I can't say what exactly you are trying to achieve, but some obvious observations:</p>\n\n<pre><code>int S[] = new int[100000];\n</code></pre>\n\n<p>This doesn't look very efficient - you allocate all this memory up front, and I couldn't really see where you are using it...</p>\n\n<p>Your is also not very defensive - <strike>you don't close your stream in case of an exception (you should use <code>try(PrintWriter out = new PrintWriter(System.out))</code> block to make sure of that), and </strike>you never validate that <code>num[r - 1]</code> is valid, so there is a decent chance that your code will not run as expected.</p>\n\n<p><strong>Idioms</strong><br>\nYou should use the idioms relevant for the language you use, for example - <code>sum1 += diff;</code> instead of <code>sum1 = sum1 + diff;</code><br>\nAnother example - don't wrap <code>System.out</code> with <code>PrintWriter</code> simply use <code>System.out.println(sum2 - sum1)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:21:52.577",
"Id": "81581",
"Score": "0",
"body": "@ Uri Aggasi the code is giving output on expected lines,But I keep getting Time Limit Exceeded issue,that array declaration in needless,iam fine with that,is der any way to avoid the iterative loops and get to the answer in a single expression,any specific algorithm I mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:24:53.870",
"Id": "81583",
"Score": "2",
"body": "I can't tell you, because I can't understand what your code does. I suggest that you edit your post, add some description on what you are trying to do, with example input and output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:53:04.437",
"Id": "81590",
"Score": "0",
"body": "http://www.codechef.com/APRIL14/problems/ADIGIT Refer this link for Problem Statement and Sample input output"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:09:09.423",
"Id": "81591",
"Score": "2",
"body": "@arunkrishnamurthy01 Uri isn't asking what the problem statement is, Uri is telling you that it is too much effort to try to understand what your code does. Without understanding what your code does it is not possible to offer suggestions on how to improve it. Make your existing code easier to understand and people will be more willing to help you improve it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:15:20.280",
"Id": "46661",
"ParentId": "46658",
"Score": "6"
}
},
{
"body": "<p>First of all, it's important to decompose the problem to its elementary steps, for example:</p>\n\n<ul>\n<li>Read the input</li>\n<li>Parse the input</li>\n<li>Do the calculation</li>\n</ul>\n\n<p>In your program everything is in a single method: the problem is not decomposed well. You should decompose at least to these items, and possibly further decompose the calculation.</p>\n\n<p>In a quiz like this, if performance is the problem, it's usually all because of the calculation. So I'll focus on that part only. After you decomposed the problem, you should end up with a method like this:</p>\n\n<pre><code>private int doCalculation(int[] digits, int index) {\n int sum = 0;\n // TODO\n return sum;\n}\n</code></pre>\n\n<p>That is, a method that takes the digits you parsed, and the index you parsed, and the method should calculate the answer. As a next step, it's good to create unit tests based on the given examples to check your solution, for example:</p>\n\n<pre><code>@Test\npublic void testExamples() {\n int[] digits = new int[] {0, 3, 2, 4, 1, 5, 2, 3, 9, 7};\n Assert.assertEquals(0, doCalculation(digits, 1));\n Assert.assertEquals(7, doCalculation(digits, 4));\n Assert.assertEquals(9, doCalculation(digits, 7));\n}\n</code></pre>\n\n<p>I simply added the tests from the problem description. If you can think of corner cases not covered by these examples, you should add them too.</p>\n\n<p>Next, you can implement the calculation using a naive logic that might be inefficient, but serve as a good proof of concept, especially for corner cases. For example, a simplified version of yours, but probably still inefficient:</p>\n\n<pre><code>private int doCalculation(int[] digits, int index) {\n int sum = 0;\n for (int i = 0; i < index - 1; ++i) {\n sum += Math.abs(digits[index - 1] - digits[i]);\n }\n return sum;\n}\n</code></pre>\n\n<p>Once that's done you can move on to refactoring the calculation logic, try to make it more efficient without breaking the unit tests.</p>\n\n<p>As for making it more efficient... Off the top of my head: the current naive implementation might recalculate sums too many times unnecessarily. Consider the case when <code>digits[X-1] == digits[Y-1]</code> for <code>X < Y</code>. If we already called <code>doCalculation(digits, X)</code>, then <code>doCalculation(digits, Y)</code> will unnecessary calculate sums for <code>digits[0] ... digits[X-1]</code>. It would be better to reuse the result of the previously calculated <code>doCalculation(digits, X)</code>, and add to that the sums for <code>digits[X] ... digits[Y-1]</code>.</p>\n\n<p>I hope this helps, and good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:20:44.350",
"Id": "46675",
"ParentId": "46658",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:51:03.900",
"Id": "46658",
"Score": "6",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "\"Chef and Digits\" Java solution"
} | 46658 |
<p>I decided to write a program to test music theory, and, while it would've been much easier for me to make it elegant and perfect in Java, I thought I'd take the opportunity to get more familiar with Python.</p>
<p>Below is the full script. It simply prints a staff in treble of bass clef with a note somewhere and asks the user to identify it.</p>
<p>Things I'm particularly interested in getting feedback about:</p>
<ol>
<li>The <code>@staticmethod</code> in the <code>Staff</code> class. I tried this both as an instance function (is it even appropriate to call it this in Python?) and as the static version below, but both seemed kind of clunky to me. It doesn't make much sense to me that I have to refer to the class's fields with the class name when I'm already <em>in</em> the class (e.g., <code>Staff.lines</code> instead of just <code>lines</code>, or <code>self.lines</code> if it's an instance function). It makes me think I'm doing something wrong.</li>
<li>I've heard multiple times that having constants isn't very Pythonic. Is there a better way for me to handle the <code>TREBLE_CLEF</code>, <code>BASS_CLEF</code>, <code>TREBLE_CLEF_NOTES</code>, and <code>BASS_CLEF_NOTES</code> fields?</li>
<li>I'm interested in a solution which allows the user to input a command like <code>exit</code> into the prompt in order to leave the program. I know I could've put this in the <code>test_note</code> function, but that would break the principle that each function should do only one thing and do it well (i.e., the <code>test_note</code> function test's the user's knowledge of the staff -- it shouldn't be responsible at all for controlling the application or its state). I couldn't think of an elegant way to do this and still preserve that principle, so I just bypassed the issue for now, haha.</li>
<li>Am I using classes appropriately? Any way I can use them better?</li>
</ol>
<p>Of course, any and all feedback is welcome, especially including anything which breaks from conventional Python style. I'd like to be as Pythonic as possible.</p>
<hr>
<pre><code>import random
import time
class Clef:
def __init__(self, name, notes):
self.name = name
self.notes = notes
def random_note(self):
return random.choice(list(self.notes.keys()))
def get_note(self, index):
return self.notes[index]
class Staff:
lines = 9
line_length = 9
line_text = '-' * line_length
space_text = ' ' * line_length
note_text = 'O'
@staticmethod
def display(note_index):
for i in range(Staff.lines):
add_note = i == note_index
print_line = Staff.line_text if i % 2 == 0 else Staff.space_text
if i == note_index:
print_line = print_line[:4] + Staff.note_text + print_line[5:]
print(print_line)
TREBLE_CLEF_NOTES = { 0 : 'F',
1 : 'E',
2 : 'D',
3 : 'C',
4 : 'B',
5 : 'A',
6 : 'G',
7 : 'F',
8 : 'E' }
BASS_CLEF_NOTES = { 0 : 'A',
1 : 'G',
2 : 'F',
3 : 'E',
4 : 'D',
5 : 'C',
6 : 'B',
7 : 'A',
8 : 'G' }
TREBLE_CLEF = Clef('Treble', TREBLE_CLEF_NOTES)
BASS_CLEF = Clef('Bass', BASS_CLEF_NOTES)
def test_note(clef, note_index):
print(clef.name)
Staff.display(note_index)
answer = clef.get_note(note_index)
user_choice = input('Enter the note: ').strip().upper()
if user_choice == answer:
print('Correct!')
else:
print('Wrong. This is ' + answer)
def main():
print('To exit, type CTRL + C')
while True:
print('\n')
clef = random.choice([TREBLE_CLEF, BASS_CLEF])
test_note(clef, clef.random_note())
time.sleep(2)
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p><em>Warning for other reviewers : <a href=\"https://docs.python.org/2/library/functions.html#input\">input</a> and <a href=\"https://docs.python.org/3.4/library/functions.html#input\">input</a> are different depending on the version of Python you are using. This is about Python 3.</em></p>\n\n<hr>\n\n<p>Instead of defining the notes of a clef as a dictionnary mapping consecutive integers from 0 to n to names, you could use a list.</p>\n\n<p>You'll have the much more natural :</p>\n\n<pre><code>TREBLE_CLEF_NOTES = [ 'F', 'E', 'D', 'C', 'B', 'A', 'G', 'F', 'E' ]\nBASS_CLEF_NOTES = [ 'A', 'G', 'F', 'E', 'D', 'C', 'B', 'A', 'G' ]\n</code></pre>\n\n<p>and you just need to change :</p>\n\n<pre><code>def random_note(self):\n return random.choice(range(len(self.notes)))\n</code></pre>\n\n<hr>\n\n<p><code>add_note = i == note_index</code> does not seem useful : get rid of it.</p>\n\n<hr>\n\n<p>The way you are playing with string slicing to display a note or a line doesn't need to be that complicated. Also, defining values as class members was a nice touch but the fact that you hardcode indices in the logic with the string slicing kind of removes the all point. As for me, I'll keep things simple and not so well organised for the time being as these values are unlikely to be useful for anything else than displaying.</p>\n\n<p>Here's my suggestion :</p>\n\n<pre><code>def display(note_index):\n for i in range(9):\n line_element = '-' if i%2 else ' '\n print(line_element * 4 + ('O' if i == note_index else line_element) + line_element*5)\n</code></pre>\n\n<hr>\n\n<p><em>I have to go, I'll try to add more details later. In the meantime, if you are interested in Python and music theory, you might be interested by <a href=\"https://github.com/falziots/musthe\">this github project</a>.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:21:30.167",
"Id": "81596",
"Score": "0",
"body": "Ah, yeah, the `add_note` variable was supposed to be removed. Whoops. And as for the string slicing, you're right, that should be more dynamic based on the `line_length` variable. Whoops again! Haha. Thanks for your comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:23:06.940",
"Id": "81598",
"Score": "0",
"body": "I think changing the dictionaries to lists would require a lot more changes to the code than just the random thing, though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:19:53.500",
"Id": "46667",
"ParentId": "46665",
"Score": "8"
}
},
{
"body": "<p>To address your numbered questions:</p>\n\n<ol>\n<li>A class with one static method has no reason to be a class at all. You could write a function instead. If you need multiple functions to share some data, the normal approach is to use instance methods and instance attributes of a class. Only when you need multiple instances of a class to share some data, use class attributes. </li>\n<li><p>There is a naming convention for constants in Python and it is exactly what you use: all caps with underscores between words. I don't there would be a convention for something that is strongly discouraged.</p>\n\n<p>When I see constants in a module, I understand that if I want to change them I have two options: either edit them to change them for good, or look up their use in the code and implement another approach. In both cases the constant is a good starting point.</p></li>\n<li><blockquote>\n <p>each function should do only one thing and do it well (i.e., the <code>test_note</code> function tests the user's knowledge of the staff -- it shouldn't be responsible at all for controlling the application or its state)</p>\n</blockquote>\n\n<p>I don't think testing user's knowledge is only one thing from the programmer's perspective. The <code>test_note</code> function presents the problem to the user, reads input, decides if the answer is correct and outputs the result. Perhaps you could create a class to handle some of that:</p>\n\n<pre><code>class NoteTest(object):\n def __init__(self):\n self.clef = random.choice([TREBLE_CLEF, BASS_CLEF]) \n self.note = self.clef.random_note()\n\n def print_test(self):\n print(self.clef.name)\n Staff.display(self.note)\n\n def print_result(self, user_choice):\n answer = self.clef.get_note(self.note) \n if user_choice == answer:\n print('Correct!')\n else:\n print('Wrong. This is ' + answer) \n\ndef main():\n while True:\n note_test = NoteTest()\n print('\\n')\n note_test.print_test()\n user_choice = input('Enter the note or exit to exit: ').strip().upper()\n if user_choice == 'EXIT':\n return\n note_test.print_result(user_choice)\n time.sleep(2)\n</code></pre></li>\n<li><p>See the answers to 1 and 3.</p></li>\n</ol>\n\n<p><hr>\nTo replace the <code>Staff</code> class I propose this function. Note the use of <a href=\"https://docs.python.org/3/library/stdtypes.html#str.center\" rel=\"nofollow\"><code>str.center</code></a> instead of the less convenient <code>print_line[:4] + Staff.note_text + print_line[5:]</code></p>\n\n<pre><code>def print_staff(note_index, \n lines=9, \n line_length=9, \n line_text='-',\n space_text=' ',\n note_text='O'):\n for i in range(lines):\n fill_char = (line_text, space_text)[i % 2]\n symbol = note_text if i == note_index else ''\n print(symbol.center(line_length, fill_char))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:15:27.873",
"Id": "81793",
"Score": "0",
"body": "Thanks for your comments! Re: `A class with one static method has no reason to be a class at all`, the reason I thought a class made sense is because it encapsulated all of the fields/settings for the `Staff` object (lines, text, etc.). Originally, I had them all as constants, but it seemed dirtier. Do you disagree?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T19:04:10.797",
"Id": "81803",
"Score": "0",
"body": "@JeffGohlke Added a few words about constants, and a concrete replacement for `Staff`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:57:46.950",
"Id": "46741",
"ParentId": "46665",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46741",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T18:46:30.267",
"Id": "46665",
"Score": "8",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"quiz",
"music"
],
"Title": "Python script to test music sight reading"
} | 46665 |
<p>Can someone help me refactor this to be more optimized? Performance seems to be very optimal, but I think more can be squeezed from it.</p>
<pre><code><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class o7th_Model extends CI_Model {
private $msg = '';
private $custom_msg = null;
private $last_id;
private $full_qry_count;
// construct our class, including the parent, database, form_validation, and pagination
public function __construct(){
parent::__construct();
$this->load->database();
$this->load->library('form_validation');
$this->load->library('pagination');
}
// Setup a list assoc array to return
/*
* USAGE - the only array parameter required is the 'table_name'
self::qlist(array('select'=>'FIELDS', --- should be a comma seperate string of field names
'where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'like'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'group_by'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'distinct'=>'TRUE/FALSE/NULL', --- TRUE enables SELECT DISTINCT, FALSE/NULL doesnt bother adding it
'having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'order_by'=>array(array('field'=>'FIELD_NAME', 'direction'=>'ASC/DESC'),), --- can have as many of these field/direction arrays as you need, direction is optional
'limit'=>array(array('limit'=>'NUMBER_TO_LIMIT_RESULTS', 'offset'=>'NUMBER_TO_LIMIT_RESULTS')),
'join'=>array(array('table'=>'TABLE_NAME_TO_JOIN', 'on'=>'EX: a.field1 = b.field2', 'direction'=>'left/right/outer/inner/left outer/right outer'),), --- can have as many of these table/on/direction arrays as you need
'validations'=>array(array('field'=>'FORM_FIELD', 'label'=>'FORM_FIELD_LABEL', 'validation'=>'VALIDATION - See CI Docs'),), --- can have as many of these field/value/validation arrays as you need
'pagination'=>array('page_num'=>'CURRENT_PAGE_WE_ARE_ON', 'per_page'=>'HOW_MANY_RECORD_PER_PAGE'), --- page_num = the page number we are currently on, per_page is how many should be displayed per page: to display the links echo the self::paginator($base_url, $per_page, $total_rows, $num_links, $uri_segment, $aclass = null); method
'custom_message'=>'TO OVERRIDE THE INTERNAL ERROR MESSAGE RETURN',
'table_name'=>'TABLE_NAME')); --- REQUIRED!!!
*/
public function qlist(){
try{
$tArgs = func_get_args();
$tbl = self::prepArgs(1, $tArgs);
if($tbl != null){
$qry = $this->db->get($tbl);
if($qry->num_rows() > 0){
$rs = $qry->result_array();
$this->full_qry_count = count($rs);
if(array_key_exists('pagination', $tArgs[0])){
$rs = array_slice($rs, $tArgs[0]['pagination']['page_num'], $tArgs[0]['pagination']['per_page']);
}
}else{
$rs = null;
$this->msg .= 'There were no records found, for the query performed<br />' . $this->db->_error_message();
}
}else{
$rs = null;
$this->msg .= 'There were no records found, for the query performed<br />' . $this->msg;
}
return $rs;
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return null;
}
}
// setup a return assoc array details record, only returns 1 record
/*
* USAGE - the only array parameter required is the 'table_name'
self::qdetails(array('select'=>'FIELDS', --- should be a comma seperate string of field names
'where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'like'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'group_by'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'distinct'=>'TRUE/FALSE/NULL', --- TRUE enables SELECT DISTINCT, FALSE/NULL doesnt bother adding it
'having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'order_by'=>array(array('field'=>'FIELD_NAME', 'direction'=>'ASC/DESC'),), --- can have as many of these field/direction arrays as you need, direction is optional
'limit'=>array(array('limit'=>'NUMBER_TO_LIMIT_RESULTS', 'offset'=>'NUMBER_TO_LIMIT_RESULTS')),
'join'=>array(array('table'=>'TABLE_NAME_TO_JOIN', 'on'=>'EX: a.field1 = b.field2', 'direction'=>'left/right/outer/inner/left outer/right outer'),), --- can have as many of these table/on/direction arrays as you need
'validations'=>array(array('field'=>'FORM_FIELD', 'label'=>'FORM_FIELD_LABEL', 'validation'=>'VALIDATION - See CI Docs'),), --- can have as many of these field/value/validation arrays as you need
'custom_message'=>'TO OVERRIDE THE INTERNAL ERROR MESSAGE RETURN',
'table_name'=>'TABLE_NAME')); --- REQUIRED!!!
*/
public function qdetails(){
try{
$tbl = self::prepArgs(1, func_get_args());
if($tbl != null){
$qry = $this->db->get($tbl);
if($qry->num_rows() > 0){
return $qry->row_array();
}else{
$this->msg .= 'There were no records found, for the query performed<br />' . $this->db->_error_message();
return null;
}
}else{
$this->msg .= 'There were no records found, for the query performed<br />' . $this->msg;
return null;
}
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return null;
}
}
// setup db insertion, return BOOLEAN
/*
* USAGE - the only array parameter required is the 'table_name', and 'insert'
self::qinsert(array('insert'=>array('DB_FIELD_NAME'=>'VALUE',), --- can have as many of these field/value items as you need
'validations'=>array(array('field'=>'FORM_FIELD', 'label'=>'FORM_FIELD_LABEL', 'validation'=>'VALIDATION - See CI Docs'),), --- can have as many of these field/value/validation arrays as you need
'custom_message'=>'TO OVERRIDE THE INTERNAL ERROR MESSAGE RETURN',
'table_name'=>'TABLE_NAME')); --- REQUIRED!!!
*/
public function qinsert(){
try{
return self::prepArgs(2, func_get_args());
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return FALSE;
}
}
// setup db edit, return BOOLEAN
/*
* USAGE - the only array parameter required is the 'table_name', and a where or like clause
self::qedit(array('update'=>array('DB_FIELD_NAME'=>'VALUE',), --- can have as many of these field/value items as you need
'where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'like'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'group_by'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'join'=>array(array('table'=>'TABLE_NAME_TO_JOIN', 'on'=>'EX: a.field1 = b.field2', 'direction'=>'left/right/outer/inner/left outer/right outer'),), --- can have as many of these table/on/direction arrays as you need
'validations'=>array(array('field'=>'FORM_FIELD', 'label'=>'FORM_FIELD_LABEL', 'validation'=>'VALIDATION - See CI Docs'),), --- can have as many of these field/value/validation arrays as you need
'custom_message'=>'TO OVERRIDE THE INTERNAL ERROR MESSAGE RETURN',
'table_name'=>'TABLE_NAME')); --- REQUIRED!!!
*/
public function qupdate(){
try{
return self::prepArgs(3, func_get_args());
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return FALSE;
}
}
// setup db delete, return BOOLEAN
/*
* USAGE - the only array parameter required is the 'table_name', and a where or like clause
self::qdelete(array('where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_where'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'or_where_not_in'=>array(array('field'=>'FIELD_NAME', 'value'=>array('VAL1', 'VAL2', etc...)),), --- can have as many of these field/value arrays as you need, value needs to be an array
'like'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'or_not_like'array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE', 'wildcard'=>'before/after/both/none'),), --- can have as many of these field/value arrays as you need, wildcard is optional
'group_by'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'or_having'=>array(array('field'=>'FIELD_NAME', 'value'=>'FIELD_VALUE'),), --- can have as many of these field/value arrays as you need
'join'=>array(array('table'=>'TABLE_NAME_TO_JOIN', 'on'=>'EX: a.field1 = b.field2', 'direction'=>'left/right/outer/inner/left outer/right outer'),), --- can have as many of these table/on/direction arrays as you need
'custom_message'=>'TO OVERRIDE THE INTERNAL ERROR MESSAGE RETURN',
'table_name'=>'TABLE_NAME')); --- REQUIRED!!!
*/
public function qdelete(){
try{
return self::prepArgs(4, func_get_args());
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return FALSE;
}
}
// get the last inserted id - only valid on inserts
public function last_insert_id(){
try{
return $this->last_id;
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return null;
}
}
// return a message if any of the returns above are invalid/false/errored out -- a specififed custom_message will override this
public function message(){
return ($this->custom_msg != null) ? $this->custom_msg : $this->msg;
}
// return a number of records based on the query run only valid on the selects
public function fullrecordcount(){
try{
return $this->full_qry_count;
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return null;
}
}
// return the pagination links -- only valid for qlist
public function paginator($base_url, $per_page, $total_rows, $num_links, $uri_segment, $aclass = null){
try{
$config['base_url'] = $base_url;
$config['per_page'] = $per_page;
$config['total_rows'] = $total_rows;
$config['num_links'] = $num_links;
$config['first_link'] = '<span class="fa fa-angle-double-left page_num"></span>';
$config['last_link'] = '<span class="fa fa-angle-double-right page_num"></span>';
$config['cur_tag_open'] = '<span class="page_num bold">';
$config['cur_tag_close'] = '</span>';
$config['next_link'] = '<span class="fa fa-angle-right page_num"></span>';
$config['prev_link'] = '<span class="fa fa-angle-left page_num"></span>';
$config['uri_segment'] = $uri_segment;
$config['num_tag_open'] = '<span class="page_num">';
$config['num_tag_close'] = '</span>';
if($aclass != null){
$config['anchor_class'] = 'class="' . $aclass . '" ';
}
$this->pagination->initialize($config);
return $this->pagination->create_links();
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return null;
}
}
// setup all possible arguments for all of the above, return name of the table from the arguments
private function prepArgs($which, $args){
if($args){
try{
if(array_key_exists('custom_message', $args[0])){
$this->custom_msg = $args[0]['custom_message'];
}
switch($which){
case 1: // select
return self::setupSelect($args);
break;
case 2: // insert
return self::setupInsert($args);
break;
case 3: // update
return self::setupUpdate($args);
break;
case 4: // delete
return self::setupDelete($args);
break;
}
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
}
}else{
$this->msg .= 'You have not passed in any arguments to your query, please have a look over your code.';
}
}
// setup our edit
private function setupUpdate($args){
try{
// setup our arguments
$this->setupArgs($args);
$data = array();
$tname = '';
$valid = TRUE;
// needs to include at least some kind of filter
if(!$this->validateFilters($args)){
$valid = FALSE;
$this->msg .= 'You need to have at least one filter, in order to update your record.';
}
// array of data to insert: required
if(array_key_exists('update', $args[0])){
$data = $args[0]['update'];
}else{
$valid = FALSE;
$this->msg .= 'You need to specify field/value pairs of data to update.';
}
// table name: required
if(array_key_exists('table_name', $args[0])){
$tname = $args[0]['table_name'];
}else{
$valid = FALSE;
$this->msg .= 'You need to specify a table name to update.';
}
// setup our validations
$valid = $this->setupValidations($args);
if($valid){
$this->db->update($tname, $data);
if(!($this->db->affected_rows() > 0)){
$this->msg .= $this->db->_error_message();
return FALSE;
}else{
return TRUE;
}
}else{
return $valid;
}
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return FALSE;
}
}
// setup our delete
private function setupDelete($args){
try{
// setup our arguments
$this->setupArgs($args);
// needs to include at least some kind of filter
if(!$this->validateFilters($args)){
$this->msg .= 'You need to have at least one filter, in order to delete your record.';
return null;
}
// table name: required
if(array_key_exists('table_name', $args[0])){
if($args[0]['table_name'] != null){
$this->db->delete($args[0]['table_name']);
if($this->db->affected_rows() <= 0){
$this->msg = 'There was an issue removing that record.<br />' . $this->db->_error_message();
return FALSE;
}
}else{
$this->msg = 'There was an issue removing that record.<br />' . $this->msg;
return FALSE;
}
}else{
$this->msg .= 'A table name is required in order to delete a record from it';
return FALSE;
}
return TRUE;
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return FALSE;
}
}
// setup(and run) our insert
private function setupInsert($args){
try{
$data = array();
$tname = '';
$valid = TRUE;
// array of data to insert: required
if(array_key_exists('insert', $args[0])){
$data = $args[0]['insert'];
}else{
$valid = FALSE;
$this->msg .= 'You need to specify field/value pairs of data to insert.';
}
// table name: required
if(array_key_exists('table_name', $args[0])){
$tname = $args[0]['table_name'];
}else{
$valid = FALSE;
$this->msg .= 'You need to specify a table name to insert data into.';
}
// setup our validations
$valid = $this->setupValidations($args);
if($valid){
$this->db->insert($tname, $data);
if(!($this->db->affected_rows() > 0)){
$this->msg .= $this->db->_error_message();
return FALSE;
}else{
$this->last_id = $this->db->insert_id();
return TRUE;
}
}else{
return $valid;
}
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return FALSE;
}
}
// setup our select
private function setupSelect($args){
try{
$tname = null;
// select field names
if(array_key_exists('select', $args[0])){
$this->db->select($args[0]['select']);
}
// setup our arguments
$this->setupArgs($args);
// setup our validations
$valid = $this->setupValidations($args);
// table name: required
if($valid){
if(array_key_exists('table_name', $args[0])){
$tname = $args[0]['table_name'];
}else{
$this->msg .= 'A table name is required to select any records from.';
}
}
return $tname;
}catch(Exception $ex){
$this->msg .= $ex->getMessage();
return null;
}
}
// setup validations
private function setupValidations($args){
if(array_key_exists('validations', $args[0])){
$v = $args[0]['validations'];
$vCt = count($v);
for($vv = 0; $vv < $vCt; ++$vv){
$this->form_validation->set_rules($v[$vv]['field'], $v[$vv]['label'], $v[$vv]['validation']);
}
if ($this->form_validation->run() === FALSE){
$this->msg .= validation_errors();
return FALSE;
}
return TRUE;
}
return TRUE;
}
// setup the arguments
private function setupArgs($args){
// where clause(s)
if(array_key_exists('where', $args[0])){
$w = $args[0]['where'];
$wCt = count($w);
for($ww = 0; $ww < $wCt; ++$ww){
if($w[$ww]['value']){
$this->db->where($w[$ww]['field'], $w[$ww]['value']);
}
}
}
// or_where clause(s)
if(array_key_exists('or_where', $args[0])){
$w = $args[0]['or_where'];
$wCt = count($w);
for($ww = 0; $ww < $wCt; ++$ww){
if($w[$ww]['value']){
$this->db->or_where($w[$ww]['field'], $w[$ww]['value']);
}
}
}
// where_in clause(s)
if(array_key_exists('where_in', $args[0])){
$w = $args[0]['where_in'];
$wCt = count($w);
for($ww = 0; $ww < $wCt; ++$ww){
if($w[$ww]['value']){
$this->db->where_in($w[$ww]['field'], $w[$ww]['value']);
}
}
}
// or_where_in clause(s)
if(array_key_exists('or_where_in', $args[0])){
$w = $args[0]['or_where_in'];
$wCt = count($w);
for($ww = 0; $ww < $wCt; ++$ww){
if($w[$ww]['value']){
$this->db->or_where_in($w[$ww]['field'], $w[$ww]['value']);
}
}
}
// where_not_in clause(s)
if(array_key_exists('where_not_in', $args[0])){
$w = $args[0]['where_not_in'];
$wCt = count($w);
for($ww = 0; $ww < $wCt; ++$ww){
if($w[$ww]['value']){
$this->db->where_not_in($w[$ww]['field'], $w[$ww]['value']);
}
}
}
// or_where_not_in clause(s)
if(array_key_exists('or_where_not_in', $args[0])){
$w = $args[0]['or_where_not_in'];
$wCt = count($w);
for($ww = 0; $ww < $wCt; ++$ww){
if($w[$ww]['value']){
$this->db->or_where_not_in($w[$ww]['field'], $w[$ww]['value']);
}
}
}
// like clause(s)
if(array_key_exists('like', $args[0])){
$l = $args[0]['like'];
$lCt = count($l);
for($ll = 0; $ll < $lCt; ++$ll){
if($l[$ll]['value']){
$this->db->like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null);
}
}
}
// or_like clause(s)
if(array_key_exists('or_like', $args[0])){
$l = $args[0]['or_like'];
$lCt = count($l);
for($ll = 0; $ll < $lCt; ++$ll){
if($l[$ll]['value']){
$this->db->or_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null);
}
}
}
// not_like clause(s)
if(array_key_exists('not_like', $args[0])){
$l = $args[0]['not_like'];
$lCt = count($l);
for($ll = 0; $ll < $lCt; ++$ll){
if($l[$ll]['value']){
$this->db->not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null);
}
}
}
// or_not_like clause(s)
if(array_key_exists('or_not_like', $args[0])){
$l = $args[0]['or_not_like'];
$lCt = count($l);
for($ll = 0; $ll < $lCt; ++$ll){
if($l[$ll]['value']){
$this->db->or_not_like($l[$ll]['field'], $l[$ll]['value'], (isset($l[$ll]['wildcard'])) ? $l[$ll]['wildcard'] : null);
}
}
}
// group_by clause(s)
if(array_key_exists('group_by', $args[0])){
$g = $args[0]['group_by'];
$gCt = count($g);
for($gg = 0; $gg < $gCt; ++$gg){
if($g[$gg]['value']){
$this->db->group_by($g[$gg]['field'], $g[$gg]['value']);
}
}
}
// distinct flag
if(array_key_exists('distinct', $args[0])){
if($args[0]['distinct'] == TRUE){
$this->db->distinct();
}
}
// having clause(s)
if(array_key_exists('having', $args[0])){
$h = $args[0]['having'];
$hCt = count($h);
for($hh = 0; $hh < $hCt; ++$hh){
if($h[$hh]['value']){
$this->db->having($h[$hh]['field'], $h[$hh]['value']);
}
}
}
// or_having clause(s)
if(array_key_exists('or_having', $args[0])){
$h = $args[0]['or_having'];
$hCt = count($h);
for($hh = 0; $hh < $hCt; ++$hh){
if($h[$hh]['value']){
$this->db->or_having($h[$hh]['field'], $h[$hh]['value']);
}
}
}
// order_by clause(s)
if(array_key_exists('order_by', $args[0])){
$o = $args[0]['order_by'];
$oCt = count($o);
for($oo = 0; $oo < $oCt; ++$oo){
$this->db->order_by($o[$oo]['field'], ($o[$oo]['direction']) ? $o[$oo]['direction'] : null);
}
}
// join clause(s)
if(array_key_exists('join', $args[0])){
$j = $args[0]['join'];
$jCt = count($j);
for($jj = 0; $jj < $jCt; ++$jj){
$this->db->join($j[$jj]['table'], $j[$jj]['on'], $j[$jj]['direction']);
}
}
// limit
if(array_key_exists('limit', $args[0])){
$this->db->limit($args[0]['limit']['limit'], $args[0]['limit']['offset']);
}
}
// validate our filters
private function validateFilters($args){
return (!array_key_exists('where', $args[0]) ||
!array_key_exists('or_where', $args[0]) ||
!array_key_exists('where_in', $args[0]) ||
!array_key_exists('or_where_in', $args[0]) ||
!array_key_exists('where_not_in', $args[0]) ||
!array_key_exists('or_where_not_in', $args[0]) ||
!array_key_exists('like', $args[0]) ||
!array_key_exists('or_like', $args[0]) ||
!array_key_exists('not_like', $args[0]) ||
!array_key_exists('or_not_like', $args[0]));
}
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:46:19.640",
"Id": "82206",
"Score": "0",
"body": "I guess no comments or answers is a good thing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T18:04:58.390",
"Id": "86044",
"Score": "0",
"body": "pick out a portion of the code that you think could use some improvement and post that as a question. where is too much code here to be reviewed in whole."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T18:09:10.420",
"Id": "86045",
"Score": "0",
"body": "Looking for the comments in this class as a whole. To break it out into seperate chunked out questions is not conducive to the class..."
}
] | [
{
"body": "<p>The only thing that I can see at a quick glance is that you need to give your variables more meaningful names so that when you come back on these later you will know exactly what their purpose in life is. </p>\n\n<p>I will take another look later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T18:24:51.260",
"Id": "86051",
"Score": "0",
"body": "appreciate it. I know it's long, and I apologize for that, but it's got a big job... ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T12:34:57.087",
"Id": "86158",
"Score": "0",
"body": "@o7thWebDesign, sorry I didn't get a chance last night."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T18:15:03.570",
"Id": "49001",
"ParentId": "46669",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T20:10:45.817",
"Id": "46669",
"Score": "1",
"Tags": [
"php",
"optimization",
"performance",
"php5",
"codeigniter"
],
"Title": "Codeigniter ActiveRecord Wrapper Model"
} | 46669 |
<p>I've been studying PHP for a while now and decided to dive into OOP. Most of my code was a mess and I've begun to refactor much of the website to OOP; however, I'm having an issue with redundancy in my class functions. Below is a my Tracking.class.php file, which is responsible for returning arrays based on the function and the instance. This is my first time using OOP so I'm unsure if I'm being overly redundant in my child classes, and not entirely sure if there is a way I could clean up my code even more. Any help would be great! </p>
<p>
<pre><code>class Tracking {
protected $type;
protected $user_id;
protected $response_array;
protected $result;
protected $typeToTable = array('weight' => 'wp_weight', 'calories' => 'wp_calories', 'move' => 'wp_move', 'sleep' => 'wp_sleep');
protected $arrayValue = array('weight' => 'value', 'calories' => 'totalcal', 'move' => 'length', 'sleep' => 'value');
function __construct($user_id, $type){
$this->type = $type;
$this->user_id = $user_id;
}
public static function getInstance($user_id, $type){
switch($type) {
case "weight" : $obj = new weightTracking($user_id, $type); break;
case "calories" : $obj = new caloriesTracking($user_id, $type); break;
case "move" : $obj = new moveTracking($user_id, $type); break;
case "sleep" : $obj = new sleepTracking($user_id, $type); break;
case "mood" : $obj = new feelTracking($user_id, $type); break;
}
return $obj;
}
function stats( Database $pdo ) {
$table_value = $this->arrayValue[$this->type];
$table = $this->typeToTable[$this->type];
$query = "SELECT AVG($table_value) as avg, MAX($table_value) as max, MIN($table_value) as min from $table WHERE user_id = :user_id";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->single();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
$avg = round($row['avg'], 2);
$min = round($row['min'], 2);
$max = round($row['max'], 2);
$this->response_array['avg'] = $avg;
$this->response_array['min'] = $min;
$this->response_array['max'] = $max;
return $this->response_array;
}
function returnGoalData( Database $pdo ) {
$query = 'SELECT * FROM wp_goals WHERE goal_type = :goal_type AND user_id = :user_id AND completed = :completed';
$pdo->query($query);
$pdo->bind(':goal_type', $this->type);
$pdo->bind(':user_id', $this->user_id);
$pdo->bind(':completed', 'N');
$pdo->execute();
$row = $pdo->single();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
if ($this->type == 'weight'){
$this->response_array['status'] = 'success';
$this->response_array['value'] = $row['value'];
$this->response_array['diff'] = days_diff($row['end']);
}
else {
$this->response_array['status'] = 'success';
$this->response_array['value'] = $row['value'];
}
return $this->response_array;
}
function lastResult( Database $pdo ){
$table_value = $this->arrayValue[$this->type];
$table = $this->typeToTable[$this->type];
date_default_timezone_set('America/Indiana/Indianapolis');
$date = new DateTime('now');
$date = date('Y-m-d', strtotime($date));
$query = "SELECT $table_value FROM $table WHERE user_id = :user_id AND time = :time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->bind(':time' , $date);
$pdo->execute();
$row = $pdo->single();
if ( empty( $row ) ) {
$this->response_array['status'] = 'success';
$this->response_array['last'] = '0';
} else {
$this->response_array['status'] = 'success';
$this->response_array['last'] = $row['value'];
}
return $this->response_array;
}
}
class caloriesTracking extends Tracking {
function prepareGraph( $pdo ){
$query = "SELECT time, SUM(totalcal) as cal FROM wp_calories WHERE user_id = :user_id GROUP BY time ORDER BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
// Initialize Array
$data = array('cols' => array(array('label' => 'time', 'type' => 'date'), array('label' => 'value', 'type' => 'number')),'rows' => array());
// Build Array
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => datecleanse($rows['time'])), array('v' => $rows['cal'])));
}
return $data;
}
function enumerateGraph( Database $pdo ){
$query = "SELECT wp_calories.time as time, food_db.desc as `desc`, wp_calories.totalcal as totalcal, wp_calories.food_id as food_id, wp_calories.servenum as servenum, food_weight.desc as weight_desc, wp_calories.meal as meal FROM wp_calories INNER JOIN food_db ON food_db.food_id = wp_calories.food_id INNER JOIN food_weight on food_weight.food_id = wp_calories.food_id AND food_weight.unit_id = wp_calories.unit_id WHERE user_id = :user_id ORDER BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
// Build Array
foreach($row as $rows){
$data['rows'][] = array('time' => datecleanse($rows['time']), 'desc' => $rows['desc'], 'totalcal' => $rows['totalcal'], 'food_id' => $rows['food_id'], 'servenum' => $rows['servenum'], 'weight_desc' => $rows['weight_desc'], 'meal' => $rows['meal']);
}
return $data;
}
}
class moveTracking extends Tracking {
function prepareGraph( Database $pdo ){
$query = "SELECT time, length FROM wp_move WHERE user_id = :user_id GROUP BY time ORDER BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
// Initialize Array
$data = array('cols' => array(array('label' => 'time', 'type' => 'date'), array('label' => 'value', 'type' => 'number')),'rows' => array());
// Build Array
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => datecleanse($rows['time'])), array('v' => $rows['length'])));
}
return $data;
}
function enumerateGraph( Database $pdo ){
$query = "SELECT time, value, length, calburn FROM wp_move WHERE user_id = :user_id GROUP BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
// Initialize Array
$data = array('cols' => array(array('label' => 'time', 'type' => 'date'), array('label' => 'value', 'type' => 'string'), array('label' => 'value', 'type' => 'number'), array('label' => 'value', 'type' => 'number')), 'rows' => array());
// Build Array
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => datecleanse($rows['time'])), array('v' => $rows['value']), array('v' => $rows['length']), array('v' => $rows['calburn'])));
}
return $data;
}
}
class sleepTracking extends Tracking {
function prepareGraph( Database $pdo ){
$query = "SELECT time, value FROM wp_sleep WHERE user_id = :user_id ORDER BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
$data = array('cols' => array(array('label' => 'time', 'type' => 'date'), array('label' => 'value', 'type' => 'number')),'rows' => array());
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => datecleanse($rows['time'])), array('v' => $rows['value'])));
}
return $data;
}
}
class feelTracking extends Tracking {
function prepareGraph( Database $pdo ){
$query = "SELECT time, value FROM wp_mood WHERE user_id = :user_id ORDER BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
// Initialize Array
$data = array('cols' => array(array('label' => 'time', 'type' => 'string'),array('label' => 'value', 'type' => 'number')));
// Build Array
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => datecleanse($rows['time'])), array('v' => $rows['value'])));
}
return $data;
}
function enumerateGraph( Database $pdo ){
$query = "SELECT value, count(*) as count FROM wp_mood WHERE user_id = :user_id GROUP BY value";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
// Initialize Array
$data = array('cols' => array(array('label' => 'time', 'type' => 'string'),array('label' => 'Frequency', 'type' => 'number')));
// Build Array
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => $rows['value']), array('v' => $rows['count'])));
}
return $data;
}
}
class weightTracking extends Tracking {
function lastResult( Database $pdo ){
$query = "SELECT value from wp_weight WHERE user_id = :user_id ORDER BY time DESC Limit 1";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->single();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
$this->response_array['status'] = 'success';
$this->response_array['last'] = $row['value'];
return $this->response_array;
}
function prepareGraph( Database $pdo ){
$query = "SELECT time, value FROM wp_weight WHERE user_id = :user_id ORDER BY time";
$pdo->query($query);
$pdo->bind(':user_id', $this->user_id);
$pdo->execute();
$row = $pdo->resultset();
if ( empty( $row ) ) {
throw new Exception('No Results');
}
$data = array('cols' => array(array('label' => 'time', 'type' => 'date'), array('label' => 'value', 'type' => 'number')),'rows' => array());
foreach($row as $rows){
$data['rows'][] = array('c' => array(array('v' => datecleanse($rows['time'])), array('v' => $rows['value'])));
}
return $data;
}
}
function days_diff($date){
date_default_timezone_set('America/Indiana/Indianapolis');
$today = new DateTime('now');
$date = new DateTime($date);
$diff = date_diff($date, $today);
return $diff->d . " days";
}
function datecleanse($date){
$year = substr($date, 0, 4);
$month = intval(substr($date, 5, -3)) - 1;
$day = substr($date, -2);
$newd = 'Date('.$year.', '.$month.', '.$day.')';
return $newd;
}
</code></pre>
<p><strong>Edit</strong>: For reference is here my Database Class.</p>
<pre><code>class Database {
protected $host = DB_HOST;
protected $user = DB_USER;
protected $pass = DB_PASS;
protected $dbname = DB_NAME;
protected $dbh;
protected $error;
protected $stmt;
public function __construct() {
// SET DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value) :
$type = PDO::PARAM_INT;
break;
case is_bool($value) :
$type = PDO::PARAM_BOOL;
break;
case is_null($value) :
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:32:52.313",
"Id": "81614",
"Score": "1",
"body": "Going from Precedural to OOP is an interesting journey which I took also - so my eyes are burning - but then again once upon a time I did the exact same quote you did. If none of the pros here that will give you a run through - my first two take is that you break SOLID design pattern and your code is too tightly coupled. If no one takes a crack at it - I will reply soon (its just lengthy to drill it down)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T22:27:16.990",
"Id": "81628",
"Score": "0",
"body": "I'd appreciate all the help you can give me. Honestly feel like this code is a big step forward from my earlier procedural work; however, I want to make sure Im moving forward."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:00:53.900",
"Id": "81692",
"Score": "0",
"body": "When moving to OO code, you're moving in the direction of re-usable, and generic code. An important part of this is code that conforms to standards, both in style and autoloading. [check the PHP coding standards](http://www.php-fig.org) and stick to them as much as possible: file-names, indentation... all of these things _matter_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:02:47.023",
"Id": "81694",
"Score": "0",
"body": "Oh, and extending, or wrapping `PDO` is not the greatest of ideas, as I have [explained before](http://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394). Just pass around `PDO` instances instead"
}
] | [
{
"body": "<p>I will apologize for the lack of formatting and using your code segments as straight example - but as I re-read your code I see my old self a whole lot and I don't consider myself any level near some of the coders here.</p>\n\n<p>However one important aspect to improvement is obviously trial and error and a lot of refactoring. So you asked about OOP going from procedural php within a single require I would assume your going into one right way which is using classes - however there is a lot of pitfalls in your code.</p>\n\n<p>The first would be that to effectively do OOP you should use <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\"><strong>SOLID</strong></a> design pattern. </p>\n\n<p>First there are plenty of ORM out there that does your PDO wrapper. One thing starters would like to do is to wrap a low level class (the PDO object) into a higher wrapper functional object - its not wrong to do so - but its been done over. In reality what you should do is not offer the user (ie you in this case) a simpler form of accessing data that you need while using the database. The database of your APP can change...what will you then? You will need to write a wrapper class again because your class is tightly coupled with PDO.</p>\n\n<p>Lets take a look at the database class</p>\n\n<pre><code>protected $host = DB_HOST;\nprotected $user = DB_USER;\nprotected $pass = DB_PASS;\nprotected $dbname = DB_NAME;\n\nprotected $dbh;\nprotected $error;\nprotected $stmt;\n</code></pre>\n\n<p>Too many variables - the majority of the time the need to hold onto the DB's credential inside the object is not necessary - it should be part of your configuration of the APP and invoked as such then passed inside to the DB object to initialize the connection - once that is done you don't need this info. </p>\n\n<p>If you change information then a new object should be created. Why? because image you do need to connect to two different DB (one for user, one for tracking as an example) - if you store your credential your stuck to this. Also as I can see from your constructor - your not even passing your credentials to it - its fixed from a global stand point.</p>\n\n<p>The majority of your class is just a smaller typing of what is already presented ie: query, then bind, then execute. Its a rehash of the system's PDO.</p>\n\n<p>Another flaw is your Single() function - it has the <code>execute()</code> command - what happens if your query returns more than one result and you want to iterate it one at a time - you can't re-execute the query to grab the second row. fetch()'s purpose is to go fetch and iterate through the rows one by one. You can argue that you can use resultSet() to grab all then foreach but if you are returning 10K rows you will be in a heap of trouble.</p>\n\n<p>Next - lets touch a bit of the tracking class.</p>\n\n<p>One flaw is the getInstance. Singleton are bad for maintainability because you can't make more than one object of it and its hard to test it.</p>\n\n<p>Ideally - since all your functions are relying on the database - you should have passed it (aka injected) is part of your constructor and then call your functions which uses the DB. Its not like you will instantly use a different DB within the function because you are tightly coupled from it.</p>\n\n<p>Basically: your Track class is your repository, and your PDO is redundant because its just shorthanding the coding.</p>\n\n<p>thats my first pass through of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:06:40.110",
"Id": "81695",
"Score": "0",
"body": "_\"you will never need to hold onto the DB's credential inside the object\"_ - I'd have to respectfully disagree with you on that one. Of course, you don't hold on to the password, but the user/host/selected db _can_ be valuable in scenario's where different DB users have different rights to different dbs. adding a `whoami`-like method can sometimes be a useful thing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:50:27.227",
"Id": "81705",
"Score": "0",
"body": "@EliasVanOotegem I was waiting for you to comment. I'll edit it from \"never\" to most likely. Right there are very particular chances that you would be doing different switching but as I explained - make yourself two DB connections - pass it through the constructoor"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:32:05.897",
"Id": "81713",
"Score": "0",
"body": "Waiting for me to comment? Why? Pointing out SOLID, existing ORM's, injection (and the inherent problems of Singletons) require no comments, only up-votes. My initial comment was a bit of a nit-pick anyways. +1 anyways"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:41:35.547",
"Id": "81731",
"Score": "0",
"body": "@EliasVanOotegem you are more thorough than I am. - and tks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:45:05.030",
"Id": "81776",
"Score": "0",
"body": "Thanks for detailed response to my question. Seems there is still quite a bit I need to learn. Completely understand your analysis of my database class, and to be honest, built it based on a tutorial as I was trying to learn PDO. As far as the tracking class, I believe I'm still trying to get a grasp on the differences between OOP and Procedural code. It feels like my class functions are tightly coupled to their respective queries, which may make my code harder to work with. Any further suggestions on how to clean up the functions in my Tracking class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:48:55.523",
"Id": "81778",
"Score": "0",
"body": "To add to my last comment, I guess something doesn't feel right in my need to extend my Tracking class for each different tracking variable I'm using and seems extremely redundant. Wish there was a way I could elaborate on this further, but with my lack of OOP knowledge I can't quite express it the way I'd like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:49:45.420",
"Id": "81779",
"Score": "0",
"body": "@paleclimber go the sister site \"programmers\" on stackexchange - there has been MANY debates over the SOLID concept and there are many examples and analogy for each of the letters. Take it one letter at a time - I tried to do it one shot and well it just boggle down. My second recommendation is to read up on INTERFACE / INHERITANCE / SINGLE RESPONSIBLITY (ie the first letter) they are intertwined so thats a good starting point. Remember \"a class should only be responsible for one thing\" it might look long but your aim is portability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:56:09.063",
"Id": "81780",
"Score": "0",
"body": "Thanks for the quick response once again. You've definitely helped me realize that OOP is much deeper than I imagined. This has been my first question on this site so thanks again for being as helpful as you have been."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:39:22.077",
"Id": "46684",
"ParentId": "46670",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46684",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T20:26:45.490",
"Id": "46670",
"Score": "4",
"Tags": [
"php",
"optimization",
"object-oriented",
"design-patterns",
"pdo"
],
"Title": "Redunancy Issues in PHP Class"
} | 46670 |
<p>How could this template class <code>ThreadPool</code> be improved?</p>
<p>I use Boost queue to keep <code>std::function</code>'s numbers from <code>std::array</code>(simple hashing) from which I can later retrieve the <code>std::function</code>'s objects to execute them with <code>operator()</code>.
It's not possible to store them directly in <code>boost::lockfree::queue</code> (Stored Object Type must have non-trivial destructor).</p>
<p>That's why I emulate primitive lockfree container with <code>std::array<std::pair<int , ...></code>.
The <code>GuarderArray</code> template class lacks garbage collector. </p>
<pre><code>#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
#include <atomic>
#include <functional>
#include <boost/lockfree/queue.hpp>
#include <array>
using std::cout ; using std::cin; using std::endl;
using std::mutex; using std::atomic;
using std::array; using std::function;
template <int NN> using guardedArray = std::array<std::pair<std::atomic<bool>,std::function<void()>>, NN> ;
template <typename T> using lockfreequeue = boost::lockfree::queue<T,boost::lockfree::capacity<1000>>;
class Functor{
int myNN;
public:
Functor(int nn):myNN(nn){};
Functor(std::function<void()> ff) : myff(ff){};
std::function<void()> myff;
Functor(const Functor&) = default;
Functor operator=(const Functor&) ;
~Functor() = default;
void operator()(){
myff();
}
};
template <int NN > class GuardedArray{
guardedArray<NN> myGuardedArray;
public:
int insertObject(std::function<void()> ff){
int kk ;
bool empty;
do{
kk = rand () % NN;
empty = myGuardedArray[kk].first;
cout << "spining ... " << endl;
}while(!(std::atomic_compare_exchange_weak(&myGuardedArray[kk].first,&empty,true)));
myGuardedArray[kk].second = ff;
return kk;
};
std::function<void()> getIndex(int ii){return myGuardedArray[ii].second ; };
std::thread garbageCollectorThread;
};
template <int NN > class ThreadPool{
private:
std::thread tt[NN];
GuardedArray<1000> myGA;
bool endFlag;
public:
ThreadPool():endFlag(false){
for(int ii = 0 ; ii < NN ; ++ii){
std::thread localThread(&ThreadPool<NN>:: threadLoop, this);
tt[ii].swap(localThread);
}
};
void bookTask(std::function<void()> ff){
int ii = myGA.insertObject(ff);
mySync.push(ii);
};
bool demandedAccess[NN];
int waitingProcess;
~ThreadPool() {endFlag = true; for (int ii = 0 ; ii < 10 ; ii++ ){ tt[ii].join();} };
int myWrapper();
void threadLoop();
lockfreequeue<int> mySync;
};
template <int NN> void ThreadPool<NN>::threadLoop(){
std::thread::id kk = std::this_thread::get_id();
std::function<void()> fun ;
int ff;
while(!endFlag){
if(!mySync.empty()){
bool result = mySync.pop(ff);
if(result){
fun = myGA.getIndex(ff);
fun();
}
}
}
}
int main(int argc, char** argv){
ThreadPool<10> tp;
Functor ff(( [](){ cout <<"a kuku "<<endl; }));
tp.bookTask(ff);
std::this_thread::sleep_for(std::chrono::seconds(20));
return 0 ;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T02:11:21.983",
"Id": "81651",
"Score": "0",
"body": "Can you please at least add good indentation. Currently its nearly impossible to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T09:18:41.200",
"Id": "81689",
"Score": "0",
"body": "Seems everyone has his own >>good<< indentation language..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T09:19:59.887",
"Id": "81690",
"Score": "1",
"body": "@user40334 On Code Review, you should not modify your code once posted. Otherwise, it invalidates the answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:46:55.533",
"Id": "81765",
"Score": "0",
"body": "@user40334: There are a couple of acceptable indention patterns. Yours matches none of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T19:49:02.237",
"Id": "81807",
"Score": "1",
"body": "There were still some changes that invalidated my answer. You may still add the additional functionality that was *not* addressed, otherwise please keep everything else intact."
}
] | [
{
"body": "<p>Just some stylistic things that stick out to me:</p>\n\n<ul>\n<li><p>I think it's a bit cumbersome to have all of this:</p>\n\n<pre><code>using std::cout ; using std::cin; using std::endl;\nusing std::mutex; using std::atomic;\nusing std::array; using std::function;\n</code></pre>\n\n<p>You're also still prefixing <code>std::</code> in places, which defeats the purpose of having this. Since you could always end up using something not already in this list, you might as well keep prefixing <code>std::</code> as you're doing already, and remove all of that above.</p></li>\n<li><p>Some of your indentation and semicolon placing are inconsistent. In some places you indent or not, and in some places you have a space before the ending semicolon. Keep the indentation consistent (you <em>should</em> utilize it) and choose what to do with all of your semicolons.</p></li>\n<li><p>It would be more readable and maintainable to place the <code>template</code> statements on separate lines from the class or function, especially if either statement is lengthy:</p>\n\n<pre><code>template <typename T>\nclass Class\n{\n};\n</code></pre>\n\n<p></p>\n\n<pre><code>template <typename T>\nvoid function()\n{\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T22:55:43.310",
"Id": "81635",
"Score": "0",
"body": "yeah code paste was little messy , I better auto-format this in editor. My initial bet was to use the std::move casting to prevent spourious cp ctors."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T22:22:31.557",
"Id": "46680",
"ParentId": "46672",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T20:41:41.520",
"Id": "46672",
"Score": "5",
"Tags": [
"c++",
"multithreading",
"c++11",
"lock-free"
],
"Title": "Lockfree ThreadPool implementation"
} | 46672 |
<p>Suppose the following example unit test for an ASP.NET MVC controller:</p>
<pre><code>[Test]
public void Delete_Will_Redirect_To_Index_1()
{
bookRepository.Add(someBook);
var result = booksController.Delete(someBook.Id) as RedirectToRouteResult;
Assert.That(result, Is.Not.Null);
Assert.That(result.RouteValues["Action"], Is.EqualTo("Index"));
}
</code></pre>
<p>Resharper unwittingly complains on the fourth line of code that <code>result.RouteValues</code> may cause a possible <code>NullReferenceException</code>. I hate those squiggly lines, so I figured I could just as easily write it as follows:</p>
<pre><code>[Test]
public void Delete_Will_Redirect_To_Index_2()
{
bookRepository.Add(someBook);
var result = (RedirectToRouteResult)booksController.Delete(someBook.Id);
Assert.That(result.RouteValues["Action"], Is.EqualTo("Index"));
}
</code></pre>
<p>This has some advantages:</p>
<ul>
<li>One LoC less;</li>
<li>More to the point;</li>
</ul>
<p>It also has one main disadvantage:</p>
<ul>
<li>Code will fail with a cast exception if the result is of unexpected type. This seems(?) less clear than a failed assert.</li>
</ul>
<p>Some other alternatives I've considered include :</p>
<pre><code>[Test]
public void Delete_Will_Redirect_To_Index_3()
{
bookRepository.Add(someBook);
var result = booksController.Delete(someBook.Id);
Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
var redirectResult = (RedirectToRouteResult)result;
Assert.That(redirectResult.RouteValues["Action"], Is.EqualTo("Index"));
}
</code></pre>
<p>This is five lines of code, but has two very clear asserts. </p>
<p>I've even considered this version:</p>
<pre><code>[Test]
public void Delete_Will_Redirect()
{
bookRepository.Add(someBook);
var result = booksController.Delete(someBook.Id);
Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
}
[Test]
public void Delete_Will_Redirect_To_Index_4()
{
bookRepository.Add(someBook);
var redirectResult = (RedirectToRouteResult)booksController.Delete(someBook.Id);
Assert.That(redirectResult.RouteValues["Action"], Is.EqualTo("Index"));
}
</code></pre>
<p>All in all I see the following points in play to judge the various forms:</p>
<ul>
<li>number of lines of code;</li>
<li>readability of the code;</li>
<li>clarity of failing-unit-test feedback;</li>
<li>how pragmatic and painless it is to write a test;</li>
</ul>
<p>Did I miss any important points? Did I miss a scenario that has the best of all points? What can I do to get the best of all scenarios?</p>
<p>PS. I'd prefer a framework-agnostic answer, but if it matters, I'm using C# NUnit tests for an ASP.NET MVC5 controller.</p>
| [] | [
{
"body": "<p>You could make a strong argument that you need 2 tests.</p>\n\n<p>General theory has a unit test (as opposed to an integration test) containing only one assert, see e.g. <a href=\"https://softwareengineering.stackexchange.com/questions/7823/is-it-ok-to-have-multiple-asserts-in-a-single-unit-test\">Programmers.StackExchange</a></p>\n\n<p>So you probably want:</p>\n\n<pre><code>[Test]\npublic void Delete_WithValidBook_ReturnsRedirectToRouteResult()\n{\n bookRepository.Add(someBook);\n var result = booksController.Delete(someBook.Id);\n Assert.That(result.Type, Is.EqualTo(typeof(RedirectToRouteResult)));\n}\n\n[Test]\npublic void Delete_WithValidBook_RedirectsToValidIndex()\n{\n bookRepository.Add(someBook);\n var result = (RedirectToRouteResult)booksController.Delete(someBook.Id);\n Assert.That(result.RouteValues[\"Action\"], Is.EqualTo(\"Index\"));\n}\n</code></pre>\n\n<p>This has the added advantage that it is <em>much</em> easier to find the bug later based on the name of the failed test alone.</p>\n\n<p>For example, if your type test fails, presumably your redirect test will also fail, but I know which I'd look at first during debugging!</p>\n\n<p>If, on the other hand, the <code>Delete</code> method is guaranteed (by the framework) to return a <code>RedirectToRouteResult</code>, then you only want one test:</p>\n\n<pre><code>[Test]\npublic void Delete_WithValidBook_RedirectsToValidIndex()\n{\n bookRepository.Add(someBook);\n var result = (RedirectToRouteResult)booksController.Delete(someBook.Id);\n Assert.That(result.RouteValues[\"Action\"], Is.EqualTo(\"Index\"));\n}\n</code></pre>\n\n<p>If you have multiple tests, or a guard assertion, the reader (i.e. you at some point in the future) will assume that it must be possible to get, say, a <code>null</code> result, which will mean you may feel the need to add null checks, etc, to other parts of the code that may not be required.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:58:36.923",
"Id": "81668",
"Score": "0",
"body": "Thanks for your answer, I was leaning towards this as well, even though it is the most work (and: is the tradeoff worth it?). One question though: the linked Programmers.SE topic has a second comment on [Guard Assertions](http://xunitpatterns.com/Guard%20Assertion.html), isn't my case very similar (though probably not the *same*), thus being an exception to the rule?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:47:39.810",
"Id": "81702",
"Score": "0",
"body": "@Jeroen It depends, I'm not super familiar with asp, but you certainly shouldn't be unit testing the compiler. I.e. if the compiler/framework guarantees the result type, the heuristic I apply is not to test it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:57:25.870",
"Id": "81707",
"Score": "0",
"body": "Hmm? I fail to see how this relates to \"testing the compiler\" (which indeed would be unnecessary). What I meant was, my version `Delete_Will_Redirect_To_Index_3` has two asserts, but the first assert is very much like a Guard Assertion from mentioned article, in which case the article you linked to would condone having it as a second assert in a single test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:55:32.647",
"Id": "81826",
"Score": "1",
"body": "@Jeroen updated the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:17:37.073",
"Id": "46683",
"ParentId": "46676",
"Score": "8"
}
},
{
"body": "<p>I totally agree with @ByronRoss' answer, you need 2 tests here.</p>\n<p>I'll address another aspect here: naming.</p>\n<blockquote>\n<pre><code>public void Delete_Will_Redirect()\npublic void Delete_Will_Redirect_To_Index()\n</code></pre>\n</blockquote>\n<p>Test methods are methods, test classes are classes. I'm surprised ReSharper isn't complaining about all these underscores, it normally enforces PascalCase naming for public methods (I run it with default settings - indeed, no complain with the underscores).</p>\n<p>I would expect the method names in the rest of your code to look like this:</p>\n<pre><code>public void DeleteWillRedirect()\npublic void DeleteWillRedirectToIndex()\n</code></pre>\n<p>I don't see a reason for test methods to follow their own naming convention<sup>1</sup>.</p>\n<hr />\n<h3>Edit</h3>\n<p>I think a compromise could be a standard pattern like <em><code>[TestedMethod_DescriptiveOutcome]</code></em>, which would make the method names look like this:</p>\n<pre><code>public void Delete_WillRedirect()\npublic void Delete_WillRedirectToIndex()\n</code></pre>\n<p>I find it gives the underscore a stronger meaning (delimiting between the <em>tested method</em> and the actual <em>expected outcome</em>) than just having it everywhere - that's just my opinion though.</p>\n<hr />\n<p><sup>1</sup> of course that doesn't hold if that naming convention is consistent across the entire code base.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T05:39:25.050",
"Id": "81878",
"Score": "1",
"body": "Hey Mat, thanks for your review! Resharper was indeed complaining, and after some pondering I've purposely added an exception for my unit test method names. I prefer having rather verbose test method names that read like a (business) requirement, and so my method names can become rather long (longer than mentioned example). I find that the underscores here are worth it, improving readability and giving me instant clarity about the problem when looking at test reports / test runners."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:19:19.533",
"Id": "81917",
"Score": "1",
"body": "The use of underscores in naming test classes and methods is the standard way of doing it. It is more readable with longer more descriptive names usually associated with tests. Because tests should be describing behavior, rather than simply \"being a thing\". I see no reason not to differentiate betwen your tests and code in a visual way like this either, as can help with the context switching."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:17:17.177",
"Id": "85098",
"Score": "0",
"body": "see also http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-20T21:08:59.430",
"Id": "128799",
"Score": "0",
"body": "It looks like newer versions of ReSharper no longer complain about test names. I don't actually recall it ever behaving like that :/"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:02:44.263",
"Id": "46776",
"ParentId": "46676",
"Score": "6"
}
},
{
"body": "<p>Honestly, I would say there is nothing wrong with your original answer. It's very descriptive, and easy to read. I don't see any business value for creating two tests just to check \"instanceOf\". The cast method also works as a null reference in a 3 line test method with only one cast is pretty obvious what's failing (even if the error message isn't \"should not be null\")</p>\n\n<p>Resharper is a great tool for many things, but it's not always right. You should never blindly refactor code to appease your tools unless you understand why you are doing so. In this case resharper is trying to warn you that you are doing a cast, and using a value without checking for null in the \"traditional\" sense. You are however, checking for null with an assertion, and as such resharpers concern is not applicable in this situation.</p>\n\n<p>If you want the squiggly to go away, you can surpress the message in resharper for this particular case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:28:46.737",
"Id": "81919",
"Score": "0",
"body": "+1, this was one of my thoughts too. On a side note, of course I realize Resharper is just a tool, not The Law. My hate for squiggly lines was meant to come across with a ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:00:51.767",
"Id": "81936",
"Score": "1",
"body": "Thank you for backing your downvote with an additional answer (on top of a comment), this (having more than just 1 answer on that question and encouraging more point of views [points of view?] to be brought up) is exactly why I posted mine in the first place. I'm currently [out of ammo](http://meta.codereview.stackexchange.com/a/1515/23788), but I'll make sure to come back here when votes reload, and upvote this answer - I completely agree with ReSharper *suggestions* being nothing more than *suggestions*."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:26:01.997",
"Id": "46805",
"ParentId": "46676",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46683",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T21:30:28.987",
"Id": "46676",
"Score": "8",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Unit tests: to cast or not to cast?"
} | 46676 |
<p>I am writing a stochastic simulation for a <a href="http://www.stat.berkeley.edu/~aldous/Networks/lec4.pdf" rel="nofollow">Yule process</a>:</p>
<p>If you start with a certain number of bins each containing a random number of balls, you add another ball to an existing bin with a probability that is proportional to the number of balls within that bin, as well as create another bin with a single ball each time step.</p>
<p>Because I am trying to basically weed out any stochastic noise, I am using very large number of iterations, on the order of 1e6. This code was originally developed in MATLAB, making much less complicated, but is far too slow for large simulations.</p>
<p>Is there a better way of doing this?</p>
<pre><code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
void init_KISS();
unsigned int JKISS();
double uni_dblflt();
double array_sum();
int main()
{
int t,count,i,j,k,ii,jj,kk;
int desval;
desval=1000000;
unsigned int r;
double v,u,bsum;
init_KISS();
for(i=0; i<100000;i++)
{
r = JKISS(); /* waste the first 100000 random numbers */
uni_dblflt();
}
/*allocate memory for all params*/
double *bins=malloc((desval+1)*sizeof(double));/*Urns, keeps track of actual "balls" in each bin*/
if(bins==NULL)
{
printf("out of memory\n");
exit(1);
}
double *p=malloc((desval+1)*sizeof(double));/* Urns/(sum of all "balls) i.e. the probability
that a new ball get placed in the ith urn. */
if(p==NULL)
{
printf("out of memory\n");
exit(1);
}
double *ptot=malloc((desval+1)*sizeof(double));/*Sum of all probabilities for the 1st to the ith
bin*/
if(ptot==NULL)
{
printf("out of memory\n");
exit(1);
}
for(i=0;i<(desval+1);i++)
{
bins[i]=0;
ptot[i]=0;
p[i]=0;
}
for(i=0;i<10;i++)/*seed 10 initial bins with 1 "ball"*/
{
v=1;
bins[i]=v;
}
for(j=10;j<desval;j++)
{
bsum=array_sum(bins,desval);/*sum the balls in each bin*/
for(k=0;k<j;k++) /* calculate the probability that with which a ball might be placed in
each urn*/
{
p[k]=bins[k]/bsum;
}
for(ii=0;ii<desval;ii++)/*Evaluate the probability total cutoffs*/
{
ptot[ii]=array_sum(p,ii);
}
u=uni_dblflt();
count=0;
while(u<=ptot[count])/*choose bin to place new ball. The numerical value of ptot(count)
is directly related to the probability space with which u can be
picked*/
{
count++;
}
bins[count]++;
bins[j]=1;
}
for(jj=0;jj<desval;jj++)
{
printf("%.8f\n",bins[jj]);
}
free(bins);
free(p);
free(ptot);
bins=NULL;
p=NULL;
ptot=NULL;
return 0;
}
double array_sum(double *arr, int maxval)
{
/* this function sums a large array*/
int i;
double sum;
sum=0;
for(i=0; i<maxval;i++)
{
sum +=arr[i];
}
return sum;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:52:55.903",
"Id": "81622",
"Score": "2",
"body": "Questions directly about implementation of algorithms in specific languages generally belong on StackOverflow. I've flagged this for migration, so hopefully it will be moved to the appropriate site by a the system, or a user with moderator privileges."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T19:22:49.457",
"Id": "81623",
"Score": "3",
"body": "however optimizing/improving working code is better on codereview.SE"
}
] | [
{
"body": "<p>This is really an algorithms question. For example, consider this loop:</p>\n\n<pre><code>for(ii=0;ii<desval;ii++)/*Evaluate the probability total cutoffs*/\n{\n ptot[ii]=array_sum(p,ii);\n}\n</code></pre>\n\n<p>why are you calling array_sum() every time through this loop when the only thing that changes is the addition of one more element?\nWhy can't this loop be: </p>\n\n<pre><code>sum= 0;\nptot[0]= 0;\nfor(ii=1;ii<desval;ii++)/*Evaluate the probability total cutoffs*/\n{\n ptot[ii]=(sum+= p[ii - 1]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:35:46.000",
"Id": "46678",
"ParentId": "46677",
"Score": "3"
}
},
{
"body": "<p>Let's get some preliminary problems out of the way before we discuss efficiency — and there is much efficiency to be gained.</p>\n\n<h3>Random number generator</h3>\n\n<p>You appear to be using the <a href=\"http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf\" rel=\"nofollow noreferrer\">advice and public-domain code from David Jones</a> for your pseudo-random number generator. Basically,</p>\n\n<ul>\n<li><code>init_KISS()</code> seeds the pseudorandom number generator</li>\n<li><code>JKISS()</code> generates a random <code>unsigned int</code></li>\n<li><code>uni_dblflt()</code> generates a random <code>double</code> between 0 and 1 using a uniform distribution.</li>\n</ul>\n\n<p>It would have been nice to note that information in the question.</p>\n\n<p><strong>Declutter your <code>main()</code></strong> by moving this code out into a function with a self-documenting name.</p>\n\n<pre><code>void initialize_prng()\n{\n init_KISS();\n for (int discard = 0; discard < 100000; discard++)\n {\n JKISS(); /* waste the first 100000 random numbers */\n uni_dblflt();\n }\n}\n</code></pre>\n\n<h3>Proliferation of variables</h3>\n\n<p>First, let the compiler alert you to problems. Compiling with warnings turned on, we see problems about how variables are being used.</p>\n\n<pre><code>$ gcc -Wall -c yule.c\nyule.c:13:9: warning: unused variable 't' [-Wunused-variable]\n int t,count,i,j,k,ii,jj,kk;\n ^\nyule.c:13:29: warning: unused variable 'kk' [-Wunused-variable]\n int t,count,i,j,k,ii,jj,kk;\n ^\n2 warnings generated.\n</code></pre>\n\n<p>For that matter, <code>r</code> is assigned but never used, so it could also be eliminated. <code>v</code> is just a constant 1, and can also be eliminated.</p>\n\n<p>The overall problem here is that you have a proliferation of variables that makes the code hard to follow. Ever since C99, you can declare variables anywhere inside a function, not just at the top. (It's now 2014 — surely it's OK to use C99?) Best practice is to <strong>declare your variables as close to the point of use as possible,</strong> as it improves readability, decreases mental workload, and puts variables in a tighter scope to avoid silly mistakes.</p>\n\n<h3>Other matters of style</h3>\n\n<p>An <a href=\"https://stackoverflow.com/a/589684/1157100\"><code>int</code> is only guaranteed to hold 16 bits, or numbers up to 32767</a>. In practice, your code will work because an <code>int</code> will be 32 bits on any modern machine. However, if you want to be certain that you can store 10<sup>6</sup>, strictly speaking, you should use a <code>long</code>.</p>\n\n<p>Think about readability when using loop-counting variables. For example, <code>for(j=10;j<desval;j++)</code> is notionally a continuation of <code>for(i=0;i<10;i++)</code>, just with a different loop body. Therefore, I would use <code>i</code> as the counter for the second loop as well.</p>\n\n<p>I don't see any need here for <code>#include <math.h></code> and <code>#include <time.h></code>.</p>\n\n<p>Instead of zeroing the arrays manually, <strong>use <code>calloc()</code>,</strong> which zeroes out the memory it allocates.</p>\n\n<p>You allocate one more element than you need for each array, as if making a zero-terminator element at the end. That's something that one would do with NUL-terminated strings and some arrays of pointers. For this problem, a zero-terminator is useless, since 0.0 is a legal value that can't act as a sentinel. Therefore, the code would be less puzzling if you dropped the pretense of having a zero-terminator.</p>\n\n<p>Declutter your <code>main()</code> function further by extracting the printing loop into its own function.</p>\n\n<h3>Efficiency</h3>\n\n<p>As @llewelly noted, you are doing unnecessary work to sum the arrays repeatedly. How bad is it?</p>\n\n<pre><code>for(j=10;j<desval;j++)\n{\n …\n\n for(ii=0;ii<desval;ii++)/*Evaluate the probability total cutoffs*/\n {\n ptot[ii]=array_sum(p,ii);\n }\n …\n}\n</code></pre>\n\n<p>Three nested loops makes it O(<em>n</em><sup>3</sup>). When <em>n</em> = 10<sup>6</sup>, that's significant!</p>\n\n<p>@llewelly suggests removing the innermost <code>array_sum()</code>, to make it O(<em>n</em><sup>2</sup>). We can actually do much, much better than that.</p>\n\n<p>First, note that <strong>the <code>p</code> array is a useless intermediary</strong> between <code>bins</code> and <code>ptot</code>.</p>\n\n<p>Next, consider <strong>combining <code>bins</code> and <code>ptot</code> into a single array.</strong> Suppose that instead of using <code>bins</code> to store the number of balls in each element, we had a <code>cumulative_bins</code> that stored the <em>cumulative</em> number of balls from bin 0 to bin <em>i</em>. Reconstructing what <code>bins</code> would have held is trivial: just subtract the predecessor from <code>cumulative_bins[i]</code>. Reconstructing what <code>ptot</code> would have held is also easy: divide <code>cumulative_bins[i]</code> by <code>cumulative_bins[desval - 1]</code>, where <code>cumulative_bins[desval - 1]</code> is the total number of balls in the system. (Note that this <code>cumulative_bins[]</code> should be discrete, not floating-point.)</p>\n\n<p>If you try to implement that idea, you'll find that reading the cumulative number of balls in bins 0 to <em>i</em> is an O(1) operation, adding one ball to a bin is an O(<em>n</em>) operation, and finding the index of a cumulative count is O(<em>n</em>). Fortunately, there is a nice data structure that can improve on that: a <strong><a href=\"http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees\" rel=\"nofollow noreferrer\">binary indexed tree</a>, also known as a <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.14.8917&rep=rep1&type=pdf\" rel=\"nofollow noreferrer\">Fenwick Tree</a></strong>, which can do all three operations in O(log <em>n</em>) time.</p>\n\n<hr>\n\n<h3>Solution</h3>\n\n<p>This program performs the job in O(<em>n</em> log <em>n</em>) time, in contrast to your original O(<em>n</em><sup>3</sup>). Excluding the time it takes to print the output, it completes a simulation of <em>n</em> = 10<sup>6</sup> bins in about half a second.</p>\n\n<pre><code>long array_get_cumulative(const long fenwick_tree[], long idx)\n{\n long sum = 0;\n for (; idx >= 0; idx = (idx & (idx + 1)) - 1)\n {\n sum += fenwick_tree[idx];\n }\n return sum;\n}\n\nvoid array_incr(long fenwick_tree[], long idx, size_t size, long incr)\n{\n for (; idx < size; idx |= (idx + 1))\n {\n fenwick_tree[idx] += incr;\n }\n}\n\nlong array_find_cumulative(long fenwick_tree[], long cumFre, size_t size)\n{\n long idx = 0, tIdx, bitMask;\n for (bitMask = 1; size & ~((bitMask << 1) - 1); bitMask <<= 1) {}\n for (; bitMask && ((tIdx = idx + bitMask) < size); bitMask >>= 1)\n {\n if (cumFre >= fenwick_tree[tIdx - 1])\n { \n // if current cumulative frequency is equal to cumFre, \n // we are still looking for higher index (if exists)\n idx = tIdx;\n cumFre -= fenwick_tree[tIdx - 1];\n }\n }\n return idx - (cumFre == 0);\n}\n\nvoid array_print(long fenwick_tree[], size_t size)\n{\n for (long i = 0, preceding_cumulative = 0; i < size; i++)\n {\n long cumulative = array_get_cumulative(fenwick_tree, i);\n printf(\"%ld\\n\", cumulative - preceding_cumulative);\n preceding_cumulative = cumulative;\n }\n}\n\nint main()\n{\n long n = 1000000L;\n\n initialize_prng();\n\n /* Urns, keeps track of cumulative \"balls\" in each bin (including all preceding bins) */\n long *bins = calloc(n, sizeof(long));\n if (bins == NULL)\n {\n fprintf(stderr, \"Out of memory\\n\");\n exit(1);\n }\n\n for (long i = 0; i < 10; i++) /* seed 10 initial bins with 1 \"ball\" each */\n {\n array_incr(bins, i, n, 1);\n }\n\n for (long i = 10; i < n; i++)\n {\n long ball_count = array_get_cumulative(bins, n - 1);\n double u = uni_dblflt();\n\n long j = array_find_cumulative(bins, u * ball_count, n);\n\n array_incr(bins, j, n, 1);\n array_incr(bins, i, n, 1);\n }\n\n array_print(bins, n);\n free(bins);\n return 0;\n}\n</code></pre>\n\n<p>There may be off-by-one errors in <code>array_find_cumulative()</code> — I'll leave it to you to work them out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:57:07.483",
"Id": "81706",
"Score": "0",
"body": "The Fenwick Tree also appeared in [this Code Review question](http://codereview.stackexchange.com/q/37825/9357)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:55:57.437",
"Id": "46715",
"ParentId": "46677",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T16:33:55.493",
"Id": "46677",
"Score": "1",
"Tags": [
"c",
"array",
"simulation"
],
"Title": "Adding very large arrays"
} | 46677 |
<p>If I need to obfuscate an iPhone password that is hardcode (Oauth Client Identifier and Client Secret), would this be a way to do it?</p>
<pre><code>NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";
NSString *d = @"d";
NSString *e = @"e";
NSString *f = @"f";
NSString *g = @"g";
NSString *h = @"h";
NSString *i = @"i";
/* hidden */
NSString *w = @"w";
NSString *x = @"x";
NSString *y = @"y";
NSString *z = @"z";
NSString *pwd = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@", p,a,s,s,w,o,r,d];
</code></pre>
<p>I know obfuscate isn't recommended but after reading this <a href="https://stackoverflow.com/questions/1934187/oauth-secrets-in-mobile-apps" title="Oauth secrets in mobile apps">Oauth secrets in mobile apps</a> it seems like the only way.</p>
| [] | [
{
"body": "<p>A slightly better option that takes a little more effort up front but saves a lot of time in the long run, and makes the code more readable (and the obfuscated word harder to crack) would be to follow this pattern...</p>\n\n<p>First, create an <code>NSString</code> class category and fill that category with a readonly property for every character.</p>\n\n<pre><code>@interface NSString (Obfuscater)\n\n@property (readonly) NSString *a;\n@property (readonly) NSString *b;\n@property (readonly) NSString *c;\n// etc...\n\n@end\n</code></pre>\n\n<p>Now, we write the accessor method, which will follow this pattern:</p>\n\n<pre><code>- (NSString *)a {\n return [self stringByAppendingString:@\"a\"];\n}\n</code></pre>\n\n<p>And how does this work?</p>\n\n<pre><code>NSString *password = @\"\".p.a.s.s.w.o.r.d;\n</code></pre>\n\n<p>This is about the same as nesting <code>stringByAppendingString:</code> several times, with the inner most call being:</p>\n\n<pre><code>[@\"\" stringByAppendingString:@\"p\"];\n</code></pre>\n\n<p>We start with an empty string and append the first character, etc.</p>\n\n<p>Now, this version, compared to the one proposed in the question, is slower, and becomes noticeably more slower with exceptionally long strings, but the obfuscation is better and the working code is more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T00:21:25.227",
"Id": "46689",
"ParentId": "46685",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46689",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:40:59.670",
"Id": "46685",
"Score": "6",
"Tags": [
"security",
"objective-c",
"ios"
],
"Title": "Obfuscating iPhone Password"
} | 46685 |
<p>This was a question asked to me before setting up an interview.<br>
You are given a game board that contains a four by four (4x4) array of pieces. The pieces can be one of six shapes and can be one of six colors. </p>
<p>If the board contains 4 pieces of the same shape and same color, the board contains a winning pattern. </p>
<pre><code>public enum Color
{
Red,
Blue,
Green,
Yellow,
Black,
Purple
}
public enum Shape
{
Square,
Triangle,
Circle,
Star,
Pentagon,
Octagon
}
public class Piece
{
public Color color;
public Shape shape;
public bool Equals(Piece compareTo) {};
}
public class Board
{
public Piece[,] position = new Piece[4,4];
public void Board(){ /*completely builds the board*/};
public void MakeRandomBoard(){};
public piece GetPiece(int x) {};
public bool IsWinner() {};
}
</code></pre>
<p>Write the code to detect when a winning pattern is present in a board.</p>
<p>Answer :</p>
<pre><code>bool isWinner() {
HashMap <Pair<Color, Enum>, int> pieceCount;
for(int row = 0; row < 4; row++) {
for(int col =0; col < 4; col++) {
Piece p = GetPiece(row, col); // Note: Sig is different than Given.
Pair <Color, Enum> pair(p.Color, p.Enum);
if (pieceCount.Contains(pair)) {
pieceCount[pair]++;
if (pieceCount[pair] >= 4) return true;
} else {
pieceCount[pair] = 1;
}
}
}
return false;
}
</code></pre>
<p>The question was to come up with 3 different ways to solve this and list the pros and cons for each solution. This is one of the solution that I was able to do.<br>
Please give your inputs on the code.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T01:05:53.400",
"Id": "81644",
"Score": "0",
"body": "This question appears to be off-topic because it isn't asking for anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T01:17:12.770",
"Id": "81645",
"Score": "2",
"body": "@JesseC.Slicer then just assume its for a Code Review?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:46:41.023",
"Id": "81672",
"Score": "2",
"body": "This is not valid C# code. `Pair<T1,T2>` should be `Tuple<T1,T2>`, `HashMap` (which is Java) should be `Dictionary`. This is C++ syntax:`Pair <Color, Enum> pair(p.Color, p.Enum);`. Semicolons after curly braces. `pieceCount.Contains` should be `ContainsKey`. So on, so forth..."
}
] | [
{
"body": "<p>Another method would be to check the board as each piece is added. This has an advantage of real time checking, but requires looping through the whole board. Also you could use a <code>Dictionary<Piece, int></code> to keep track of which pieces are added and check that instead of the board array. Using the <code>ContainsKey</code> eliminates extra looping but requires an extra collection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T01:17:57.647",
"Id": "81646",
"Score": "0",
"body": "Could you explain why this would be a better approach? Or why you would suggest doing it this way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T01:19:09.947",
"Id": "81647",
"Score": "0",
"body": "The OP only asked for alternatives. Since each method has its own pros and cons `better` is very subjective."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T01:19:53.817",
"Id": "81648",
"Score": "1",
"body": "Then It would be helpful for future users to see the Pros and Cons. That's what Code Review is about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T02:29:18.857",
"Id": "81652",
"Score": "0",
"body": "This is similar to the approach i followed. I used to a hashmap instead of a dictionary."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T01:16:31.567",
"Id": "46691",
"ParentId": "46686",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T23:55:13.210",
"Id": "46686",
"Score": "3",
"Tags": [
"c#",
"interview-questions"
],
"Title": "Winning Pattern Detection"
} | 46686 |
<p>So, I have the boundaries of every states in the US, from the google map KML file.</p>
<p>This KML file is actually a XML file.</p>
<p>I'm converting this file to a JS file compatible with google map in order to draw polygons on my map.</p>
<p>Here is an excerpt from <a href="https://gist.github.com/anonymous/698af53e77c56ce3439b" rel="nofollow">the file with all the coordinates</a>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<Placemark>
<name>WA</name>
<description><![CDATA[]]></description>
<styleUrl>#style37</styleUrl>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<tessellate>1</tessellate>
<coordinates>
-122.402015585862,48.2252165511906
-122.368333031748,48.1281417374007
-122.216991980112,48.0074395523983
-122.230120864997,47.9691133009971
-122.302922293019,47.9502148146411
-122.394492319816,47.7741760704507
-122.414815251142,47.6641799154458
-122.382220450337,47.5954090424224
-122.392633724016,47.510242430349
-122.319738644767,47.3901148739843
-122.325376306437,47.3443234291417
-122.420837154063,47.3188444009071
<!-- etc., 243 points altogether for WA state -->
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</code></pre>
<p>Here is my code to convert the KML file to the JS file.</p>
<pre><code>require 'rubygems'
require 'xmlsimple'
def read_xmlfile(file_name)
file = File.open(file_name, "r")
data = file.read
file.close
return data
end
target = "states.js"
xml_data = read_xmlfile('Stateborders.xml')
data = XmlSimple.xml_in(xml_data, 'KeyToSymbol' => true)
content = "var stateBorders = {\n"
data[:document][0].each_with_index do |item, index|
states = item[1]
states.each_with_index do |state, index|
name = state[:name][0]
coord = state[:polygon][0][:outerboundaryis][0][:linearring][0][:coordinates][0].tr("\t", "").strip.gsub(/[\n]/,") ,new google.maps.LatLng(").gsub(" ) ,", "), ");
coord = state[:polygon][0][:outerboundaryis][0][:linearring][0][:coordinates][0].tr("\t", "").strip
coord2 = ""
coord.split("\n").each do |ll|
ll = ll.split(",")
lat = ll[1].to_s.strip
lat = lat.to_f.round(6).to_s
lon = ll[0].to_s.strip
lon = lon.to_f.round(6).to_s
coord2 << "new google.maps.LatLng("+lat+", "+lon+"), "
end
statecoord = "'#{name}' : [#{coord2}],".gsub(", ],","],")
content << statecoord+"\n"
end
end
content << "};"
File.open(target, "w+") do |f|
f.write(content)
end
</code></pre>
<p>The code itself is fast enough but i'm sure can be much simpler/cleaner. Also for the last state I have <code>],</code> instead of <code>]</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:04:32.567",
"Id": "81653",
"Score": "1",
"body": "I've created the [tag:geospatial] tag instead, as it has broader applicability. The combination of [tag:xml] and [tag:geospatial] should turn up some KML-related questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:14:53.120",
"Id": "81655",
"Score": "0",
"body": "@200_success Neat. Although maybe \"gis\" would be an even broader tag?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:17:49.870",
"Id": "81656",
"Score": "0",
"body": "@Flambino Stack Overflow has both tags, both equally popular. I think \"geospatial\" is clearer to those who aren't familiar with the \"gis\" abbreviation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:54:57.893",
"Id": "81687",
"Score": "0",
"body": "@200_success Good point"
}
] | [
{
"body": "<p>I'd suggest <a href=\"http://nokogiri.org/\" rel=\"nofollow\">Nokogiri</a> for parsing the KML/XML. It's a more full-featured library, which makes things easier. For instance, you can get rid of all those long lines of <code>[:symbol][0][:another_symbol][0]...</code> (or maybe xmlsimple is brilliant, but, frankly, the docs are a rambling mess, so I'd steer clear)</p>\n\n<p>I'd also suggest skipping the <code>new google.maps.LatLng(...)</code>. All it does is guarantee a bunch of processing the moment the JS file is loaded. Possibly a lot of errors, too, in case GMaps hasn't loaded or isn't involved - perhaps you just want the actual coordinates, not <code>LatLng</code> objects. Or perhaps you just want one state, and don't want to bother instantiating <code>LatLng</code> objects for every state in the Union. And so on - much simpler to just write out the data</p>\n\n<p>I'd also skip a lot of the \"manual\" string construction in the output, and use a JSON library to do the heavy lifting. In fact, I'd consider simply producing a JSON file - not a JS file. As with avoiding the <code>new google.maps.LatLng</code> stuff above, the point would be to keep data and logic separate. Although the different between JSON and JS is a matter of adding <code>var ... =</code> at the start and <code>;</code> at the end, it still changes the file from a pure data format to code.</p>\n\n<p>But you know your needs better than I do, so I've mimicked your code's output in my code.</p>\n\n<p>I've split everything up into methods to keep things clean. It also lets you use the parsed data for something other than JS/JSON output, if need be. </p>\n\n<pre><code>require 'rubygems'\nrequire 'nokogiri'\nrequire 'json/ext'\n\n# Parse the file at the given path\n# See #parse_kml_doc for return value\ndef parse_kml_file(file)\n doc = File.open(file, 'r') { |io| Nokogiri::XML.parse(io) }\n parse_kml_doc(doc)\nend\n\n# Parse the given Nokogiri doc\n# Returns an array of 2-element arrays containing\n# the name and coordinates of the states\ndef parse_kml_doc(kml_doc)\n kml_doc.css(\"Placemark\").map do |node| # CSS-type selectors\n state = node.css(\"name\").first.content.strip # get state abbreviation\n coords = node.css(\"coordinates\").first.content # get coords string\n coords = coords.strip.each_line.map do |line| # parse the string\n line.strip.split(/,/).map(&:to_f) # I've skipped the rounding\n end\n [ state, coords ] # return a tuple\n end\nend\n\n# Write out a JavaScript file with the data\ndef write_js_file(data, file)\n json = Hash[data].to_json\n File.open(file, 'w+') do |io|\n io << \"var stateBorders = \"\n io << json\n io << \";\"\n end\nend\n\n# Read a KML file and write a JS file\ndef kml_to_js(kml_file, js_file)\n data = parse_kml_file(kml_file)\n write_js_file(data, js_file)\nend\n\n# Do everything!\nkml_to_js(\"stateborders.kml\", \"stateborders.js\")\n</code></pre>\n\n<p>It runs about 1.25x faster than the original; nothing spectacular there, but the code really only needs to run once anyway (at least until a state secedes)</p>\n\n<hr>\n\n<p>Update: Ok, so if you truely want <code>LatLng</code> objects, I'd suggest doing this: Include a small snippet of JS in the file, which'll do the <code>LatLng</code> instantion when the file's loaded. I.e. something like</p>\n\n<pre><code>var stateBorders = (function () {\n var state, i, l, json = { .. plain json data .. };\n for(state in json) {\n if(json.hasOwnProperty(state)) {\n for(i = 0, l = json[state].length ; i++) {\n json[state][i] = new google.maps.LatLng(json[state][i][0], json[state][i][1]);\n }\n }\n }\n return json;\n}());\n</code></pre>\n\n<p>It will cut the file size in half, to about 280kb (if you include the <code>round(6)</code>).</p>\n\n<p>Or, if you want a file with <code>new google.map.LatLng(...)</code> repeating thousands of times, you can define a simple class:</p>\n\n<pre><code> LatLng = Struct.new(:lat, :lng) do\n def to_json(*a)\n \"new google.maps.LatLng(#{lat.round(6)},#{lng.round(6)})\"\n end\n end\n</code></pre>\n\n<p>Use it to model coordinates (changing a line in the <code>parse_kml_doc</code> method):</p>\n\n<pre><code># ...\ncoords = coords.strip.each_line.map do |line|\n LatLng.new(*line.strip.split(/,/).map(&:to_f))\nend\n# ...\n</code></pre>\n\n<p>And done. Leave the rest as-is, and it'll write out a file like you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:50:04.067",
"Id": "81658",
"Score": "0",
"body": "This is great! Thanks a lot! You're awesome! \nI'm going to keep the `new google.maps.LatLng(...)`. The main idea is to export the kml file downloadable from https://mapsengine.google.com/map/u/0/?hl=en&pli=1 (create custom maps) and to convert it to polygons on the google maps js api v3.\nI'm also going to keep the rounding, it saves +-250kb on the size of my file :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:13:53.560",
"Id": "81791",
"Score": "0",
"body": "@bl0b Updated my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T23:24:08.183",
"Id": "81831",
"Score": "0",
"body": "I like the idea of the JS snippet. This is smart. Thanks a lot!!! If I would chose a more complete file like this one: http://code.google.com/apis/kml/documentation/us_states.kml where a state have multiple polygons(typically islands), I guess I would need an array with 3 dimensions right [AllStates][All polygons in state][All coordinates in polygons]. How would you do it in the code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:42:23.043",
"Id": "81892",
"Score": "0",
"body": "@bl0b We're wandering off of the original question here, so I can't really answer. I'd just say try something, and see if it works. If it gives you trouble, put a question up on StackOverflow; if you got it working, but think it can be better, put it up for review here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:44:57.850",
"Id": "81969",
"Score": "0",
"body": "Thanks for your help! IT's is awesome, I have something, I will put it on codereview later, I have to move on with my work :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:04:02.960",
"Id": "46692",
"ParentId": "46688",
"Score": "3"
}
},
{
"body": "<p>@Flambino has already explained the main problems in your code. I'd only add: 1) why do you use <code>each_with_index</code> if you don't actually use the indexes? 2) Ruby would have a terrible standard library if you needed 4 lines just to read the contents of a file: <code>contents = File.read(path)</code>. </p>\n\n<p>That's how I'd write it:</p>\n\n<pre><code>require 'nokogiri'\nrequire 'json'\n\nkml = Nokogiri::XML(open(\"Stateborders.xml\"))\ncoordinates_by_state = kml.css(\"Placemark\").map do |placemark|\n state = placemark.at_css(\"name\").text.strip\n coordinates = placemark.at_css(\"coordinates\").text.strip.lines.map do |line|\n line.split(\",\").map { |coord| coord.to_f.round(6).to_s }\n end\n [state, coordinates]\nend.to_h\n\njscode = \"var stateBorders = #{coordinates_by_state.to_json};\"\nFile.write(\"stateborders.js\", jscode)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:40:05.150",
"Id": "46707",
"ParentId": "46688",
"Score": "4"
}
},
{
"body": "<p>@Flambino and @tokland have both suggested good strategies on how your task should be done.</p>\n\n<p>I want to talk about your code:</p>\n\n<p><strong>Naming conventions</strong><br>\nXML file is two words - name the method accordingly - <code>read_xml_file</code></p>\n\n<p><strong>Useful names</strong><br>\nNames like <code>coord</code> and <code>coord2</code> are bad because they don't convey the true role of them, and might confuse the reader - <code>raw_coordinates</code> and <code>formatted_coordinates</code> would be better.<br>\nAny two letter variable which is used for anything less trivial than running index is not advisable, and variables named <code>l</code> and <code>ll</code> are even worse, since the letter <code>l</code> might be indistinguishable from the digit <code>1</code> in some fonts, which might be very confusing...</p>\n\n<p><strong>Don't shadow variables</strong><br>\nYes, you should not use <code>each_with_index</code>, you should use <code>each</code>. But if we assume that that is the required API - don't name the inner and out arguments with the same name (<code>index</code>).<br>\nIf you know you are not going to use the argument in the body of the block, ruby conventions suggest you use the special variable name <code>_</code>:</p>\n\n<pre><code>data[:document][0].each_with_index do |item, _|\n states = item[1]\n states.each_with_index do |state, _|\n # ... snip ...\n end\nend\n</code></pre>\n\n<p><strong>Redundant operations</strong><br>\n<code>split</code> returns a list of strings. There is no point in calling <code>to_s</code> on its children.<br>\nString concatenation implicitly calls <code>to_s</code> on all non-string elements you concat, so calling <code>to_s</code> after the rounding is also redundant.<br>\nYou assign <code>coord</code> twice, totally ignoring the first assignment - that line is totally redundant.</p>\n\n<p><strong>Don't re-use variables by changing their meaning</strong><br>\nOne side-effect of meaningless variable names is that you might be tempted to re-use them</p>\n\n<blockquote>\n<pre><code>coord.split(\"\\n\").each do |ll|\n ll = ll.split(\",\")\n</code></pre>\n</blockquote>\n\n<p>when <code>ll</code> is first assigned it is a string, but then you re-assign it as an array. You do the same with <code>lat</code> and <code>lon</code>. A reader who misses such a re-assignment will be confused about what you do with the variables after it.</p>\n\n<p><strong>When you know what elements you have in an array</strong><br>\nWhen you have an array, and all you do with it is assign the first element to variable <code>a</code>, the second element to variable <code>b</code>, etc. you can use ruby's <a href=\"http://nathanhoad.net/ruby-multiple-assignment\" rel=\"nofollow\">multiple assignment</a> instead:</p>\n\n<pre><code>lat, lon = ll.split(',')\n</code></pre>\n\n<p><strong>Ruby's <code>map</code> chaining and keeping it DRY</strong><br>\nTo elaborate on the multiple assignment above, it is idiomatic in ruby to use <code>map</code> to transform all elements in an array:</p>\n\n<pre><code>lat, lon = ll.split(',').map { |number| number.to_f.round(6) }\n</code></pre>\n\n<p>This removes the code duplication you have for <code>lat</code> and <code>lon</code>.</p>\n\n<p><strong>What <code>join</code> does better</strong></p>\n\n<blockquote>\n<pre><code>statecoord = \"'#{name}' : [#{coord2}],\".gsub(\", ],\",\"],\")\n</code></pre>\n</blockquote>\n\n<p>This ugly code is needed, because inside the loop you don't know when the last element is reached. Ruby already solved this problem with <code>join</code>:</p>\n\n<pre><code>coord2 = coord.split(\"\\n\").map do |ll|\n # ...\n \"new google.maps.LatLng(\"+lat+\", \"+lon+\")\"\nend\n\nstatecoord = \"'#{name}' : [#{coord2.join(\", \")}]\"\n</code></pre>\n\n<p>Same is true for <code>content</code>...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:16:56.893",
"Id": "46743",
"ParentId": "46688",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46692",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T00:10:53.633",
"Id": "46688",
"Score": "5",
"Tags": [
"javascript",
"ruby",
"parsing",
"xml",
"geospatial"
],
"Title": "Converting KML/XML to Javascript"
} | 46688 |
<p>I wrote the following <code>split</code> function. It takes a <code>list</code>, an <code>element</code> and an <code>Ordering (LT, GT, EQ)</code>. For <code>LT</code>, the list will filter out all items that are >= the element argument.</p>
<pre><code>split' :: (Ord a) => [a] -> a -> Ordering -> [a]
split' [] _ _ = []
split' (x:xs) a LT
| x < a = x : split' xs a LT
| otherwise = split' xs a LT
split' (x:xs) a GT
| x > a = x : split' xs a GT
| otherwise = split' xs a GT
-- non-exhaustive, unacceptable
</code></pre>
<p>Example:</p>
<pre><code>*Main> split' [1,2,3] 2 LT
[1]
</code></pre>
<p>Note that this function can result in an exception if the <code>Ordering</code> argument is <code>EQ</code>. Of course this is terrible.</p>
<p>However, please review the above code, offering suggestions on how to improve it.</p>
| [] | [
{
"body": "<p>Your <code>split'</code> could be simplified using <code>filter</code>.</p>\n\n<pre><code>split' :: (Ord a) => [a] -> a -> Ordering -> [a]\nsplit' list value cmp = filter (\\x -> compare x value == cmp) list\n</code></pre>\n\n<p>I think that the order of arguments to <code>split'</code> is awkward. I would suggest that the reverse order is more natural.</p>\n\n<pre><code>split :: (Ord a) => Ordering -> a -> [a] -> [a]\nsplit cmp value list = filter (\\x -> compare x value == cmp) list\n\n*Main> split LT 2 [1, 2, 3]\n[1]\n</code></pre>\n\n<p>Then you could also define <code>split</code> in a curried form:</p>\n\n<pre><code>split :: (Ord a) => Ordering -> a -> ([a] -> [a])\nsplit cmp value = filter (\\x -> compare x value == cmp)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:56:38.580",
"Id": "46696",
"ParentId": "46693",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:13:07.030",
"Id": "46693",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Splitting a List"
} | 46693 |
<p>This is a piece of code I am working on to reuse in a few places on various websites. It is used to capture name and email addresses for people interesting in registering for something, we want to add them a newsletter...So here is the scripts/CSS/HTML and it feels clunky. And maybe others might have some input on how I can do this better.</p>
<p>The Javascript (jQuery):</p>
<pre><code>$(document).ready(function () {
$("img").each(function (i) {
var imgUrla = $(this).closest("a").attr('href');
$("a img").attr('data-link', imgUrla).attr('id', 'target');
$(this).closest("a").contents().unwrap();
});
$('img#target').click(function (e) {
var imgUrl = $(this).attr('data-link');
$('#noThanks').attr('onclick', 'opentab("' + imgUrl + '");');
$('#thanks').attr('value', imgUrl);
var posTop = 200;
$('body').append('<div id="overlay"></div>');
$('#achi').wrap('<div id="lightbox">').removeClass('newHidden');
$('#lightbox').css('top', posTop + 'px');
$('#overlay').fadeTo(500, 0.75, function () {
$('#lightbox').fadeTo(250, 1);
});
});
$('#overlay, #lightbox_close').live('click', function (e) {
$('#achi').unwrap('<div id="lightbox">').addClass('newHidden');
$('#overlay').remove();
$('#lightbox_close').remove();
});
$("#submit").click(function () {
$('form').submit(function () {
var faults = $('input').filter(function () {
return $(this).data('required') && $(this).val() === "";
}).css("background-color", "pink");
if (faults.length) return false;
});
});
});
</code></pre>
<p>The code above does a few things. It looks for any image with hyperlinks and strips the tag then moves the <code>href</code> portions (the URL) into the image as a parameter called <code>data-link</code>. The next thing it does is when the image is clicked, it presents a floating div/form to capture the name and email of the user with cancel and submit. If they hit submit and the fields are not filled then it errors (it is a simple validation), if the user hits cancel then it shoots them to the redirect url in the data-link img parameter.</p>
<p>Here is the CSS:</p>
<pre><code>#overlay {
position: fixed;
top: 0;
left: 0;
background-color: #000000;
width: 100%;
height: 100%;
z-index: 998;
display: none;
}
#lightbox {
position: fixed;
z-index: 999;
width: 590px;
text-align: center;
display: none;
background-color: #fff;
left: 50%;
margin-left: -285px;
}
.newHidden {
display: none;
}
img {
width:100px;
height:auto;
}
</code></pre>
<p>The CSS above was very specific and somewhat difficult. I had to get help with it because the overlay and form were not behaving right. Everything in there may be necessary with the exception of the img width and height (which I added to scale the images.</p>
<p>The HTML:</p>
<pre><code><!--hidden div/form-->
<div id="achi" class="newHidden">
<h2>Be notified!</h2>
<form id="" action="" name="hiddenForm" method="post">
<label>Name</label>
<br />
<input type="text" value="" name="name" data-required="true">
<br />
<label>Email Address</label>
<br>
<input type="text" value="" name="emailAddress" data-required="true"> <b class="clear">
<div style="width:485px;margin:0 auto;margin-bottom:60px;">
<button type="button" class="left noThanksButton" id="noThanks" name="noThanks">No Thanks</button>
<button type="submit" class="right" id="submit" name="submit">Submit</button>
</div>
</b>
<input id="thanks" type="hidden" value="" name="URLAddress">
</form>
</div>
<!--hidden div/form-->
<h3>Links</h3>
<p>Come explore!</p>
<p><a href="http://google.com/">
<img class="colorboxd" src="https://www.google.com/images/srpr/logo11w.png"/>
</a>
</p>
<h3>August Wild Night!</h3>
<p>Come discover the animals and birds!.</p>
<p><a href="http://google.com/">
<img class="colorboxd" src="https://www.google.com/images/srpr/logo11w.png"/>
</a>
</p>
<h3>September 19 We're Grounded Again!</h3>
<p>This month we'll explore creatures that love to creep and crawl...</p>
<p><a href="http://google.com/">
<img class="colorboxd" src="https://www.google.com/images/srpr/logo11w.png"/>
</a>
</p>
</code></pre>
<p>The HTML above has the div with the form to capture user data. It is set to hidden from the get go. The link stuff above is there to model against and is just for testing.</p>
<p>So what I am looking for is code enhancement suggestions. Maybe shorthanding some of that jQuery. It would really be nice to push the CSS stuff into the jQuery (or have it write it so I can eleminate the CSS, I want to eleminate the HTML to and have the script build it.</p>
<p>But first I want to refine the jQuery and anything else that could be improved. So please, make suggestions. And if you have any questions please let me know.</p>
<p>Here is the <a href="http://jsfiddle.net/franktudor/jZj7S/" rel="nofollow">jsfiddle</a></p>
<p>Here is my revised code using suggestings by the two guys that helped me out below:</p>
<p>The Javascript:</p>
<pre><code>$(document).ready(function () {
function minMod_subscriber(){
var minMod_subscriber = '';
minMod_subscriber +='<div id="minMod_achi" class="minMod_newHidden">';
minMod_subscriber +='<h2>Be notified!</h2>';
minMod_subscriber +='<form id="" action="" name="hiddenForm" method="post">';
minMod_subscriber +='<label>Name</label>';
minMod_subscriber +='<br />';
minMod_subscriber +='<input type="text" value="" name="name" data-required="true">';
minMod_subscriber +='<br />';
minMod_subscriber +='<label>Email Address</label>';
minMod_subscriber +='<br>';
minMod_subscriber +='<input type="text" value="" name="emailAddress" data-required="true">';
minMod_subscriber +='<b class="minMod_clear">';
minMod_subscriber +='<div style="width:485px;margin:0 auto;margin-bottom:60px;">';
minMod_subscriber +='<button type="button" id="minMod_noThanks" name="noThanks">No Thanks</button>';
minMod_subscriber +='<button type="submit" id="minMod_thanks" name="submit">Submit</button>';
minMod_subscriber +='</div>';
minMod_subscriber +='</b>';
minMod_subscriber +='</form>';
minMod_subscriber +='</div>';
return minMod_subscriber;
}
$('body').append(minMod_subscriber());
function minMod_stripper(){
$("p a img").each(function (i) {
var imgUrla = $(this).closest("a").attr('href');
$("p a img").attr('data-link', imgUrla).attr('id', 'minMod_target');
$(this).closest("a").contents().unwrap();
});
}
minMod_stripper();
function unwrapOverlays() {
var imgUrl = $(this).attr('data-link');
window.open(imgUrl, '_blank');
$('#minMod_achi').unwrap('<div id="minMod_lightbox">').addClass('minMod_newHidden');
$('#minMod_overlay').remove();
$('#minMod_lightbox_close').remove();
}
function checkinputs() {
var checkinputs = true;
$("input").each(function () {
var val = $(this).val();
if ($(this).attr('data-required') && val === "") {
$(this).css("background-color", "pink");
event.preventDefault(); // Stop the submit here!
checkinputs = false;
}
});
return checkinputs;
}
$('#minMod_noThanks').on('click', function () {
unwrapOverlays();
});
$('#minMod_thanks').on('click', function () {
if (checkinputs()) {
unwrapOverlays();
}
});
$('img#minMod_target').click(function (e) {
var posTop = 200;
$('body').append('<div id="minMod_overlay"></div>');
$('#minMod_achi').wrap('<div id="minMod_lightbox">').removeClass('minMod_newHidden');
$('#minMod_lightbox').css('top', posTop + 'px');
$('#minMod_overlay').fadeTo(500, 0.75, function () {
$('#minMod_lightbox').fadeTo(250, 1);
});
});
});
</code></pre>
<p>The CSS:</p>
<pre><code>#minMod_overlay {
position: fixed;
top: 0;
left: 0;
background-color: #000000;
width: 100%;
height: 100%;
z-index: 998;
display: none;
}
#minMod_lightbox {
position: fixed;
z-index: 999;
width: 590px;
text-align: center;
display: none;
background-color: #fff;
left: 50%;
margin-left: -285px;
}
.minMod_newHidden {
display: none;
}
.minMod_clear {
clear:both;
}
</code></pre>
<p>The HTML:</p>
<pre><code><!--test code-->
<h3>Links</h3>
<p>Come explore!</p>
<p>
<a href="http://google.com/">
<img src="https://www.google.com/images/srpr/logo11w.png"/>
</a>
</p>
<!--test code-->
</code></pre>
<p>A few notes: I made more unique CSS IDs and Classes. I also created more functionality in the JS. I moved the form build into JS. I also improved the a href targets. So links have to be in p tags, then a tags, and have img tags in that order (to prevent a bunch of unforeseen targeting).</p>
<p>Here is the <a href="http://jsfiddle.net/franktudor/asfnU/" rel="nofollow">jsfiddle!</a></p>
<p>Last thoughts. In my next iteration I will make things more customizable for example. Coloring of the background to the modal, and several other things, like text overrides, etc.</p>
| [] | [
{
"body": "<blockquote>\n <p>This is a piece of code I am working on to reuse in a few places on various websites</p>\n</blockquote>\n\n<p>This line alone tells me that it's a drop-in script. And that alone makes me tell you to <em>skip jQuery altogether</em>. Never assume a website uses jQuery. Also, not all systems can run jQuery. It could be due to compatibility with another library, an older version of jQuery or license restrictions. Who knows?</p>\n\n<p>If you want to keep this script versatile (and sneaky):</p>\n\n<ul>\n<li>Skip jQuery, create your own abstractions. This keeps your script flexible yet light.</li>\n<li><a href=\"http://projects.jga.me/jquery-builder/\" rel=\"nofollow\">Ship a custom build of jQuery</a>, with only the things you need. Not the entire library.</li>\n<li>Drop-in scripts should be as simple as adding a <code><script></code> for the user. Use a \"trojan-style\" resource loading script instead. Basically it's a single script that loads all other stuff required. This is how Google scripts (API, Analytics) work. Resources include JS, CSS, and even HTML.</li>\n</ul>\n\n<blockquote>\n <p>The CSS above was very specific and somewhat difficult. I had to get help with it because the overlay and form were not behaving right.</p>\n</blockquote>\n\n<p>It's what you call <em>defensive programming</em>. What prevents the user from clobbering your styles if you have selectors such as <code>#overlay</code>, <code>img</code>, <code>#lightbox</code>. These names are too simple, and the user's stylesheets might contain similarly named selectors. Their styles will clobber your styles, even override them.</p>\n\n<p>Keep your selectors specific, and namespaced. for instance:</p>\n\n<pre><code><div id=\"MyModalDialog\">\n <span>text</span>\n</div>\n</code></pre>\n\n<p>If you styled span like <code>span{color:red}</code> and the user's style has <code>span{color:green}</code> after yours, then your styles are overridden. What you do is add more selectors to keep it specific, like <code>#MyModalDialog span{color:red}</code>.</p>\n\n<p>Also, by namespacing your style to <code>#MyModalDialog</code>, it keeps your styles focused on what's inside the <code>#MyModalDialog</code> and avoid clobbering the user's styles as well.</p>\n\n<hr>\n\n<p>As for other stuff:</p>\n\n<h2>You don't declare handlers like this</h2>\n\n<pre><code>$('#noThanks').attr('onclick', 'opentab(\"' + imgUrl + '\");');\n</code></pre>\n\n<p>Do this instead:</p>\n\n<pre><code>$('#noThanks').on('click',function(){\n opentab(imgUrl);\n});\n</code></pre>\n\n<h2>Avoid applying CSS using JS</h2>\n\n<pre><code>.css(\"background-color\", \"pink\");\n</code></pre>\n\n<p>Instead, add a class that contains that style. Saves you debugging time looking for where pink is from.</p>\n\n<pre><code>.addClass('bg-pink');\n\nbg-pink{\n background-color:pink;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:29:26.727",
"Id": "81726",
"Score": "0",
"body": "Very good feedback and this gets me thinking beyond my simple drop it. I don't have many websites that use this code but more now than before and no other modal example was simple that met my needs hence this project. I never thought about making it trojan-style but that is exactly what I will aim for. Thank you for the response!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:56:05.617",
"Id": "46708",
"ParentId": "46695",
"Score": "4"
}
},
{
"body": "<p>Extending on what Joseph wrote abotu namespacing: Your script currently breaks basically any webpage you add it to.</p>\n\n<pre><code> $(\"img\").each(function (i) {\n</code></pre>\n\n<p>Why are you apply this to all images on the page? There are probably plenty of linked images, that shouldn't be using your script.</p>\n\n<pre><code> $(\"a img\").attr('data-link', imgUrla).attr('id', 'target');\n</code></pre>\n\n<p>With <code>$(\"a img\")</code> applying this again to all (linked) images on the page. However you probably just want to work with the image of the current <code>.each()</code> loop. Why don't you just use <code>$(this)</code> again? </p>\n\n<p>Also this set the same id to all images. Ids <strong>must</strong> be unique per page. And why do you need this ID in the first place? Later you only use it to assign a click handler. Why don't you assign the click handler right here?</p>\n\n<pre><code>$(this).closest(\"a\").contents().unwrap();\n</code></pre>\n\n<p>You repeat <code>$(this).closest(\"a\")</code> here. Generally (not only here): If you need a reference to an element multiple times, then store that reference in a variable, instead of searching for it multiple times.</p>\n\n<p>Also you remove the link (again: all links around all images). What if the author needs this link, for example, for styling or he has his own event handler on it?</p>\n\n<pre><code>$('#overlay, #lightbox_close').live('click', function (e) {\n</code></pre>\n\n<p>What jQuery version are you using here? Are you seriously using an old version to develop a \"new\" script? <code>.live()</code> has been removed since jQuery 1.9. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:30:46.513",
"Id": "81728",
"Score": "0",
"body": "on your first comment I actually have what you describe in production I removed it here to simplify what I was doing and it looks like it bit me :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:35:47.720",
"Id": "81729",
"Score": "0",
"body": "On the second point. I was under deadline to get something and I was a frenzied mess. When I first started this I didn't even know what modal was so my searches were fruitless and like I mentioned to the first poster, when I did find a few examples, I tried to adapt then to my code and none worked for me. So I coded this up in about three hours to get business folks off my back :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:39:38.817",
"Id": "81730",
"Score": "0",
"body": "I am trying to make this content specific, so as you said anything could be a target. I don't want to affect the site logo that links back to the home page that would be stupid, so thanks for pointing that out. It will have to have an id or class attachment. I am using this with 1.11 jQuery. It worked in jsfiddle. Maybe not removed? maybe depreciated? I'll need to figure out how to do this a different way. Thanks for pointing that out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T14:12:43.480",
"Id": "81740",
"Score": "0",
"body": "I'm talking about that .live() function..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:28:00.537",
"Id": "46710",
"ParentId": "46695",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:39:36.967",
"Id": "46695",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Interupt redirect to catch potential newsletter signup"
} | 46695 |
<p>I created this small Python calculator after abstaining from writing code for a while now. I would love seasoned programmers input.</p>
<pre><code>#!/usr/bin/env python
" A Simple calculator "
class Calculator(object):
""" Example input:
expression: (12+4)*2^4-(10-3*(15/5))
steps:
1) compile it to a list of ops and numbers: [ [12,+,4],*,2,^,4,-,[10,-,3,*,[15,/,5]] ]
2) calculate starting with the highest operators first:
[ [12, +, 5], *, 16, -, [10,-,3,*,[15,/,5]] ]
[ 17, *, 16, -, [10,-,3,*,3] ]
[ 17, *, 16, -, [10-9] ]
[ 17, *, 16, -, 1]
[ 272, -, 1 ]
[ 271 ]
TODO:
* add floating point support
"""
_stack = []
" Flag that signfies if it's the first character in the expression "
INITIAL = True
" exit perenthesis "
EXIT_PE = False
" in number "
IN_NU = False
" in operator "
IN_OP = False
OPERATORS = ('+', '-', '*', '/', '^')
OP_ORDER = (('^',), ('*', '/'), ('+', '-'))
def compile(self, input_eq):
for c in input_eq:
try:
" check if its a number "
current = int(c)
self.IN_OP = False
" if it's a new digit to a previous number "
if self.IN_NU:
" add it to the previous number "
self._add_new_num(current)
else:
" it's a new number add it to stack "
self._add_new_num(current)
self.IN_NU = True
except ValueError:
self.IN_NU = False
" if it's an operator "
if c in self.OPERATORS:
if not self._stack:
raise Exception("You can't start an expression with an operator")
if self.IN_OP:
raise Exception("illegal expression")
else:
self._append_element(c)
self.IN_OP = True
elif c == '(':
self._add_new_perentheses()
self.IN_OP = True
elif c == ')':
self.EXIT_PE = True
self.IN_OP = False
else:
raise Exception("Bad input")
if self.INITIAL:
self.INITIAL = False
def _get_last_position(self):
" Returns the last inner most list in the stack "
list_ref = list_prev = self._stack
try:
" While there's a list "
while list_ref[-1] or list_ref[-1] == []:
if isinstance(list_ref[-1], list):
" make a reference to the list "
list_prev = list_ref
list_ref = list_ref[-1]
else:
break
if self.EXIT_PE == True:
self.EXIT_PE = False
return list_prev
else:
self.EXIT_PE = False
return list_ref
except IndexError:
if self.EXIT_PE == True:
self.EXIT_PE = False
return list_prev
else:
self.EXIT_PE = False
return list_ref
def _append_element(self, el):
last_pos = self._get_last_position()
last_pos.append(el)
def _add_new_num(self, num):
" if its the first character in an expression "
if not self._stack or self._get_last_position() == []:
self._append_element(num)
else:
prev_c = self._get_last_position()[-1]
" check if previous char is a number "
is_int = isinstance(prev_c, int)
if is_int:
self._add_to_previous_num(num, self._stack)
elif prev_c in self.OPERATORS:
self._append_element(num)
else:
is_list = isinstance(self._stack[-1], list)
" if it's a list search the last element in the list's children "
if is_list:
list_ref = self._get_last_position()
self._add_to_previous_num(num, list_ref)
else:
raise Exception("something is broken")
def _add_to_previous_num(self, num, stack):
try:
last_pos = self._get_last_position()
last_pos[-1] = last_pos[-1]*10+num
except IndexError:
last_pos.append(num)
def _add_new_perentheses(self):
last_pos = self._get_last_position()
last_pos.append([])
def calculate(self, expr):
self.compile(''.join(expr.split()))
result = self._rec_calc(self._stack)
" initialize the stack "
self._stack = []
return result
def _rec_calc(self, stack):
while len(stack) > 1:
for op in xrange(len(self.OP_ORDER)):
for el in xrange(len(stack)):
try:
if isinstance(stack[el], list):
result = self._rec_calc(stack[el])
del stack[el]
stack.insert(el, result)
elif stack[el] in self.OP_ORDER[op]:
result = self._calc_binary(stack, el, stack[el])
" delete all three elements that were used in the binary operation "
del stack[el-1]
del stack[el-1]
del stack[el-1]
stack.insert(el-1, result)
except IndexError:
break
else:
continue
break
return stack[0]
def _calc_binary(self, stack, index, op):
out = stack[index-1]
next = stack[index+1]
if op == '+':
out += next
elif op == '-':
out -= next
elif op == '*':
out *= next
elif op == '/':
out /= next
elif op == '^':
out **= next
return out
if __name__ == '__main__':
calc = Calculator()
print calc.calculate("12^2-(5*(2+2)))")
print calc.calculate("2*32-4+456+(1+2)+3+(1/2*3+3+(1+2))")
print calc.calculate("2 * (7+1) / (2 + 5 + (10-9)) ")
</code></pre>
<p><strong>Edit:</strong> This is the modified version using Sean Perry's comments. </p>
<pre><code>#!/usr/bin/env python
" A Simple calculator "
class Calculator(object):
""" Example input:
expression: (12+4)*2^4-(10-3**(15/5))
steps:
1) compile it to a list of ops and numbers: [ [12,+,4],*,2,^,4,-,[10,-,3,*,[15,/,5]] ]
2) calculate starting with the highest operators first:
[ [12, +, 5], *, 16, -, [10,-,3,*,[15,/,5]] ]
[ 17, *, 16, -, [10,-,3,*,3] ]
[ 17, *, 16, -, [10-9] ]
[ 17, *, 16, -, 1]
[ 272, -, 1 ]
[ 271 ]
TODO:
* add floating point support
"""
_stack = []
# Flag that signfies if it's the first character in the expression
INITIAL = True
# exit perenthesis
EXIST_PARENS = False
# in number
IN_NUM = False
# in operator
IN_OPERATOR = False
OPERATORS = {
'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'*': lambda x,y: x*y,
'/': lambda x,y: x/y,
'^': lambda x,y: x**y
}
OPS_ORDER = (('^',), ('*', '/'), ('+', '-'))
class ErrorInvalidExpression(Exception):
pass
def compile(self, input_eq):
"""
Compile the expression to a python representation
of a list of numbers, operators and lists (parentheses)
"""
for c in input_eq:
try:
# check if its a number
current = int(c)
except ValueError:
# its not a number
self.IN_NUM = False
# if it's an operator
if c in self.OPERATORS.keys():
if not self._stack:
raise ErrorInvalidExpression("You can't start an expression with an operator")
if self.IN_OPERATOR:
raise ErrorInValidExpression("More than one operator in a sequance")
else:
self._append_element(c)
self.IN_OPERATOR = True
elif c == '(':
self._add_new_parentheses()
self.EXITS_PARENS = False
elif c == ')':
self.EXIST_PARENS = True
else:
raise ErrorInvalidExpression("Syntax Error")
continue
# runs when its a number
self.IN_OPERATOR = False
# add the number to the stack
self._add_new_num(current)
# if its a new number
if not self.IN_NUM:
self.IN_NUM = True
if self.INITIAL:
self.INITIAL = False
def _get_last_position(self):
""" Returns the last inner most list in the stack """
list_ref = list_prev = self._stack
try:
# While there's a list
while list_ref[-1] or list_ref[-1] == []:
if isinstance(list_ref[-1], list):
# make a reference to the list
list_prev = list_ref
list_ref = list_ref[-1]
else:
break
except IndexError:
pass
if self.EXIST_PARENS == True:
self.EXIST_PARENS = False
return list_prev
else:
return list_ref
def _append_element(self, el):
last_pos = self._get_last_position()
last_pos.append(el)
def _add_new_num(self, num):
# if its the first character in an expression
if not self._stack or self._get_last_position() == []:
self._append_element(num)
else:
prev_c = self._get_last_position()[-1]
# check if previous char is a number
is_int = isinstance(prev_c, int)
if is_int:
self._add_to_previous_num(num, self._stack)
elif prev_c in self.OPERATORS.keys():
self._append_element(num)
else:
is_list = isinstance(self._stack[-1], list)
# if it's a list search the last element in the list's children
if is_list:
list_ref = self._get_last_position()
self._add_to_previous_num(num, list_ref)
else:
# this should never happen
raise Exception("A fatal error has occured")
def _add_to_previous_num(self, num, stack):
try:
last_pos = self._get_last_position()
last_pos[-1] = last_pos[-1]*10+num
except IndexError:
last_pos.append(num)
def _add_new_parentheses(self):
last_pos = self._get_last_position()
last_pos.append([])
def calculate(self, expr):
self.compile(''.join(expr.split()))
# do the actual calculation
result = self._rec_calc(self._stack)
# initialize the stack
self._stack = []
return result
def _rec_calc(self, stack):
while len(stack) > 1:
for ops in self.OPS_ORDER:
for el in xrange(len(stack)):
try:
if isinstance(stack[el], list):
result = self._rec_calc(stack[el])
del stack[el]
stack.insert(el, result)
elif stack[el] in ops:
result = self._calc_binary(stack, el)
# delete all three elements that were used in the binary operation
del stack[el-1]
del stack[el-1]
del stack[el-1]
stack.insert(el-1, result)
except IndexError:
break
else:
continue
break
return stack[0]
def _calc_binary(self, stack, index):
op = stack[index]
prev = stack[index-1]
next = stack[index+1]
for symbol, action in self.OPERATORS.items():
if symbol == op:
return action(prev, next)
if __name__ == '__main__':
calc = Calculator()
print calc.calculate("12^2-(5*(2+2)))") # 124
print calc.calculate("2*32-4+456+(1+2)+3+(1/2*3+3+(1+2))") # 528
print calc.calculate("2 * (7+1) / (2 + 5 + (10-9)) ") # 2
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:51:52.940",
"Id": "81674",
"Score": "2",
"body": "I also once wrote a Python calculator: `calculate = lambda x:eval(x)`. Works like a charm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:02:13.713",
"Id": "81680",
"Score": "2",
"body": "@ebarr calc(\"__import__('os').system('run evil command')\"); Besides I didn't do it to get the functionality (writing a calculator is a pretty futile tasks considering the alternatives) I just wanted to brush up on my python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:35:02.610",
"Id": "81700",
"Score": "0",
"body": "Don’t use `==` with booleans; use `if self.EXIST_PARENS is True:` or even just `if self.EXIST_PARENS:`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:47:20.260",
"Id": "81715",
"Score": "0",
"body": "@user1179901 I merely jest. This is actually a pretty good exercise to get dug into a language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T16:59:41.070",
"Id": "81963",
"Score": "0",
"body": "The modified version has indentation error on line 76."
}
] | [
{
"body": "<p>Use actual comments for comments. All of those strings are kept by the interpreter. If you have to use a string as a documentation item then you should use the triple quote variety.</p>\n\n<p>Use full words or at least standard abbreviations. 'EXIT_PE' <-- no one else knows what this is. The proper spelling is 'parenthesis' singular or 'parentheses' plural. 'EXITS_PARENS' would be a good name. Same goes for 'IN_NU'. 'IN_NUM' would be acceptable.</p>\n\n<p>Limit the scope of your try/except blocks. In <code>compile</code> you are catching <code>ValueError</code> but is it from the call to <code>int()</code> or the internal methods?</p>\n\n<p>Make your own exceptions. Use these instead of just throwing <code>Exception</code>. It helps your reader (or debugger) know where to look.</p>\n\n<p>You repeat yourself in <code>_get_last_position</code>.</p>\n\n<p>In general, simplify your code and don't be afraid to use a few extra characters.</p>\n\n<p>Here is a more pythonic approach. I am not 100% happy with it because I repeat myself a little. There is always room for improvement :-)</p>\n\n<pre><code>import operator\nimport string\n\nclass EvaluationError(Exception):\n pass\n\n\nclass InvalidNumber(Exception):\n pass\n\n\nclass InvalidOperator(Exception):\n pass\n\n\nclass UnbalancedParens(Exception):\n pass\n\n\ndef cast(value):\n \"\"\"Attempt to turn a value into a number.\"\"\"\n if isinstance(value, (int, float)):\n return value\n\n try:\n return int(value)\n except ValueError:\n pass\n try:\n return float(value)\n except ValueError:\n pass\n\n raise InvalidNumber(value)\n\n\nclass Operator(object):\n def __init__(self, op, precedence):\n self._op = op\n self._prec = precedence\n\n def __call__(self, *args):\n return self._op(*args)\n\n def __lt__(self, op):\n return self._prec < op._prec\n\n def __gt__(self, op):\n return self._prec > op._prec\n\n def __eq__(self, op):\n return self._prec == op._prec\n\n def __repr__(self):\n return repr(self._op)\n\n def __str__(self):\n return str(self._op)\n\n\nclass Calculator(object):\n operators = {\n '+' : Operator(operator.add, 1),\n '-' : Operator(operator.sub, 1),\n '*' : Operator(operator.mul, 2),\n '/' : Operator(operator.div, 2),\n '^' : Operator(operator.pow, 3),\n }\n\n def __init__(self):\n pass\n\n def calculate(self, expr):\n \"\"\"Parse and evaluate the expression.\"\"\"\n tokens = self.parse(expr)\n result = self.evaluate(tokens)\n return result\n\n def evaluate(self, tokens, trace=False):\n \"\"\"Walk the list of tokens and evaluate the result.\"\"\"\n stack = []\n for item in tokens:\n if isinstance(item, Operator):\n if trace:\n print stack\n\n b, a = cast(stack.pop()), cast(stack.pop())\n result = item(a, b)\n stack.append(result)\n\n if trace:\n print stack\n else: # anything else just goes on the stack\n if item.endswith('.'):\n raise InvalidNumber(item)\n stack.append(item)\n\n if len(stack) > 1:\n raise EvaluationError(str(stack))\n\n return stack[0]\n\n def parse(self, expr, trace=False):\n \"\"\"Take an infix arithmetic expression and return the expression parsed into postfix notation.\n Note the numbers are left as strings to be evaluated later.\n \"\"\"\n tokens = []\n op_stack = []\n\n last = None\n\n for c in expr:\n if c in string.whitespace:\n last = c\n elif c in string.digits:\n value = str(c)\n if last and last in string.digits: # number continues, just append it\n value = tokens.pop() + value\n\n last = c\n tokens.append(value)\n elif c == '.':\n if last and last in string.digits: # looks like a decimal\n tokens.append(tokens.pop() + \".\")\n else:\n raise InvalidParse(\"misplaced decimal\")\n elif c == '(':\n op_stack.append('(')\n elif c == ')':\n if not op_stack:\n raise UnbalancedParens(c)\n\n # closing parens found, unwind back to the matching open\n while op_stack:\n curr = op_stack.pop()\n if curr is '(':\n break\n else:\n tokens.append(curr)\n else: # not a number or a parens, must be an operator\n op = self.operators.get(c, None)\n if op is None:\n raise InvalidOperator(c)\n\n while op_stack:\n curr = op_stack[-1]\n # the 'is' check prevents comparing an Operator to a string\n if curr is '(': # don't leave the current scope\n break\n elif curr < op:\n break\n tokens.append(op_stack.pop())\n\n op_stack.append(op)\n last = c\n\n if trace:\n print \"----\"\n print tokens\n print op_stack\n print \"----\"\n\n while op_stack:\n op = op_stack.pop()\n if op is '(':\n raise UnbalancedParens()\n tokens.append(op)\n\n if trace:\n print \"----\"\n print tokens\n print op_stack\n print \"----\"\n\n return tokens\n\nif __name__ == '__main__':\n import sys\n\n calc = Calculator()\n\n if len(sys.argv) == 2:\n print calc.calculate(sys.argv[1])\n raise SystemExit(0)\n\n try:\n calc.calculate(\"(2 * 4 + 5\")\n except UnbalancedParens:\n pass\n try:\n calc.calculate(\"2.\")\n except InvalidNumber:\n pass\n try:\n calc.calculate(\"5 % 2\")\n except InvalidOperator:\n pass\n\n print calc.calculate(\"2 * 3.14 * 5\") # 31.4\n print calc.calculate(\"12^2-(5*(2+2)))\") # 124\n print calc.calculate(\"2*32-4+456+(1+2)+3+(1/2*3+3+(1+2))\") # 528\n print calc.calculate(\"2 * (7+1) / (2 + 5 + (10-9)) \") # 2\n</code></pre>\n\n<p>(code fixed, sorry for that. Joys of cut and paste.)</p>\n\n<p>By transforming the input the state munging goes away and the stacks become part of the solution. The <code>Operator</code> class makes the operator handling simpler and clear. You can debug the pieces of this or use them independently.</p>\n\n<p>Note the calculator class has no internal state. This also makes debugging easier. All of the state is in the stacks within the methods.</p>\n\n<p>Enjoy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:30:51.940",
"Id": "81677",
"Score": "0",
"body": "Thanks for the tips, though I was aware of those issues except for the spelling part :). I was looking more for algorithm tips and code structure advice. And about the strings, my vim theme uses italic text in comments which isn't comfortable that's why I used those types of strings, but I will fix in the next version. Thanks again for your input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:26:04.660",
"Id": "81682",
"Score": "0",
"body": "Change OPERATORS to be a dict containing the symbol and the actions. Apply the input operator using the dict. This makes it easy to update the calculator and even add operators on the fly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:29:05.740",
"Id": "81683",
"Score": "0",
"body": "Python's list has a `pop` method. No need to use the magic -1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:53:36.980",
"Id": "81686",
"Score": "0",
"body": "I don't see where pop would be helpful since I don't want to modify the list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T09:02:44.657",
"Id": "81688",
"Score": "0",
"body": "I implemented the dictionary in OPERATORS though I think it only makes the code more complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:11:52.300",
"Id": "82079",
"Score": "0",
"body": "Your revised code is pretty awesome I'm learning a lot from it. I'll be studying it to, it doesn't really work even for simple input but I'll debug it. But the style is pretty neat so thanks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:51:10.297",
"Id": "82150",
"Score": "0",
"body": "Sorry about that. My cut and paste went all mixed up. Fixed. Although you probably learned more :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:52:48.360",
"Id": "82151",
"Score": "0",
"body": "BTW, the \"trick\" in the code is to transform from infix notation (2 + 2) to postfix notation (2 2 +). Postfix is easy to parse by simply pushing/popping the stack. This is what `parse` is doing basically."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:44:14.490",
"Id": "46702",
"ParentId": "46698",
"Score": "5"
}
},
{
"body": "<p>I generally have issues reading your code. As Sean suggests, you should simplify it. This could partly be due to the fact you're doing something unnecessarily low-level. In python, the way to go is import the modules you need and let them do the work. That decreases the amount of code you write yourself and makes it overall easier. That's one of the major reasons why I love python. But of course, this is an exercise. </p>\n\n<p>I personally avoid using <code>continue</code> or <code>break</code>. I prefer refactoring the loop. It generally simplifies the logic and makes your methods more readable.</p>\n\n<p>In the same readability spirit, I also never used the <code>for: ... else: ...</code> construct. I know it's technically fine, but I don't like it. I would prefer:</p>\n\n<pre><code>if len(arr) == 0:\n print 'no elements'\nelse:\n for item in arr:\n do_stuff_with(item)\n</code></pre>\n\n<p>It's more code, but it's simpler. And it's only the latter that counts.</p>\n\n<p>I would also reconsider the order of your methods. The main method is <code>calculate</code> and it's kind of hidden between other methods. That makes searching for the logic hard.</p>\n\n<p>I don't like the method name <code>compile</code>. It's too vague. I would go for something like <code>split_in_chunks</code>.</p>\n\n<p>I find it personally very hard to judge your algorithm. But I would suggest you use a regular expression to find the innermost brackets. All you need then is one method to resolve expressions that don't contain brackets:</p>\n\n<pre><code>import re\nexpression = '(3 * (1 + 4) - 9) * (5 + (3 * (2 - 1)))'\n\ndef resolve_expr_without_brackets(expr):\n \"\"\" Replace this method by something that actually resolves the expression \"\"\"\n return 'Hi!'\n\ninner_brackets_found = True\n\nwhile inner_brackets_found:\n m = re.search('\\([^\\(\\)]+\\)', expression)\n if m != None:\n # fetch a resolvable expression, and immediately drop its outer brackets\n expr_with_brackets = expression[m.start():m.end()]\n expr = expr_with_brackets[1:-2]\n result = resolve_expr_without_brackets(expr)\n expression = expression.replace(expr_with_brackets, result)\n # print expression for demonstrative purposes\n print expression\n else:\n inner_brackets_found = False\n total_result = resolve_expr_without_brackets(expression)\n\nprint total_result\n</code></pre>\n\n<p>Note how running the above script resolves expressions iteratively. It produces the following output:</p>\n\n<pre><code>(3 * Hi! - 9) * (5 + (3 * (2 - 1)))\nHi! * (5 + (3 * (2 - 1)))\nHi! * (5 + (3 * Hi!))\nHi! * (5 + Hi!)\nHi! * Hi!\nHi!\n</code></pre>\n\n<p>It should be noted though that regular expressions are often hard to debug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:22:36.023",
"Id": "46803",
"ParentId": "46698",
"Score": "5"
}
},
{
"body": "<p>This is a <code>while</code> loop that can exit three ways: by <code>IndexError</code>, by <code>break</code> or normally by the <code>while</code> condition.</p>\n\n<pre><code> try:\n # While there's a list\n while list_ref[-1] or list_ref[-1] == []:\n if isinstance(list_ref[-1], list):\n # make a reference to the list\n list_prev = list_ref\n list_ref = list_ref[-1]\n else:\n break\n except IndexError:\n pass\n</code></pre>\n\n<p>Much simpler would be just to make the <code>while</code> condition check what you are really after. This loop does exactly the same as above. Note how the short-circuiting behavior of <code>and</code> avoids the <code>IndexError</code>:</p>\n\n<pre><code> while list_ref and isinstance(list_ref[-1], list):\n list_prev = list_ref\n list_ref = list_ref[-1]\n</code></pre>\n\n<hr>\n\n<p>Variables defined directly under the <code>class</code> declaration are attributes of the class and shared between instances. When you assign eg. <code>self.IN_NUM = False</code> inside a method, you create an instance attribute that shadows the class attribute. This can a source of subtle bugs. Only use class attributes for data that is to be shared between instances, and initialize instance attributes in <code>__init__</code>. Also, only use ALL_CAPS naming convention for constants. In your case <code>OPERATORS</code> and <code>OPS_ORDER</code> seem to be constants, so I propose this:</p>\n\n<pre><code>class Calculator(object):\n OPERATORS = {\n '+': lambda x,y: x+y,\n '-': lambda x,y: x-y,\n '*': lambda x,y: x*y,\n '/': lambda x,y: x/y,\n '^': lambda x,y: x**y\n }\n\n OPS_ORDER = (('^',), ('*', '/'), ('+', '-'))\n\n def __init__(self):\n self._stack = []\n # Flag that signfies if it's the first character in the expression\n self.initial = True\n # exit parenthesis\n self.exist_parens = False\n # in number\n self.in_num = False\n # in operator\n self.in_operator = False\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:14:43.583",
"Id": "82080",
"Score": "0",
"body": "I used your first method in the beginning but it didn't catch cases where list_ref was an empty list, that's why I choose the method I choose. I'm not sure about your second point, what do you mean by class attributes as data to be shared between instances?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:25:59.583",
"Id": "82083",
"Score": "0",
"body": "`while list_ref` will certainly stop looping when `list_ref` is an empty list. The second point relates to the fact that in Python classes themselves are objects too, but the objects one normally works with *instances of classes*."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:13:09.760",
"Id": "46829",
"ParentId": "46698",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46702",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:12:29.980",
"Id": "46698",
"Score": "8",
"Tags": [
"python",
"calculator"
],
"Title": "Small Python calculator"
} | 46698 |
<p>Here is a question I tried from the Codility train website:</p>
<blockquote>
<p>A small frog wants to get to the other side of the road. The frog is
currently located at position X and wants to get to a position greater
than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to
reach its target.</p>
<p>Write a function:</p>
<pre><code>class Solution { public int solution(int X, int Y, int D); }
</code></pre>
<p>that, given three integers X, Y and D, returns the minimal number of
jumps from position X to a position equal to or greater than Y.</p>
<p>For example, given:</p>
<p>X = 10 Y = 85 D = 30</p>
<p>the function should return 3, because the frog will be positioned as
follows: after the first jump, at position 10 + 30 = 40 after the
second jump, at position 10 + 30 + 30 = 70 after the third jump, at
position 10 + 30 + 30 + 30 = 100</p>
<pre><code>Assume that:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
Complexity:
expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).
</code></pre>
</blockquote>
<p>This is the solution I gave which fetched me 50% and time complexity of O(Y-X). Can anyone please suggest a better solution?</p>
<pre><code>class Solution {
//X=start, Y=end, D=distance for code clarity
public int solution(int start, int end, int distance) {
// write your code in Java SE 7
int progress = start;
int count=0;
while(progress<end) {
progress=progress+distance;
count++;
}
return count;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:15:24.977",
"Id": "81669",
"Score": "5",
"body": "One word hint: \"division\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-03T15:15:45.013",
"Id": "250015",
"Score": "0",
"body": "This ansver get score of 100:\n\n public int solution(int X, int Y, int D) {\n if(X == Y) return 0;\n int dist = Y - X;\n return dist%D == 0? dist/D: dist/D + 1;\n }"
}
] | [
{
"body": "<p>Maybe you should try something like:</p>\n\n<pre><code>public class Frog {\n public static int solution(int x, int y, int d) {\n return (int) Math.ceil((y - x) / (float)d);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T06:51:29.167",
"Id": "81881",
"Score": "2",
"body": "or just `return (y - x + d - 1) / d;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-14T20:04:48.953",
"Id": "170250",
"Score": "1",
"body": "I'm seeing this a bit late, but could you add explanation why your solution is better? In it's current state it's nothing more than a code dump."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T13:29:32.160",
"Id": "456680",
"Score": "0",
"body": "I just came here from that test, and your solution is the first one I tried, but it gives me 44%."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:09:19.047",
"Id": "46705",
"ParentId": "46699",
"Score": "5"
}
},
{
"body": "<p>You don't need a loop for this, there is a mathematical solution:</p>\n\n<ul>\n<li>If <code>y - x</code> is divisible by <code>d</code>, then it takes <code>(y - x) / d</code> jumps</li>\n<li>If <code>y - x</code> is not divisible by <code>d</code>, then it takes <code>(y - x) / d + 1</code> jumps</li>\n</ul>\n\n<p>In other words:</p>\n\n<pre><code>if ((y - x) % d == 0) {\n return (y - x) / d;\n}\nreturn (y - x) / d + 1;\n</code></pre>\n\n<p>Or the somewhat less readable but more compact:</p>\n\n<pre><code>return (y - x) / d + ((y - x) % d == 0 ? 0 : 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-23T15:00:21.090",
"Id": "241566",
"Score": "0",
"body": "Brilliant, going by your first approach its best to check if the distance is zero so as to return x to prevent division by zero exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T13:34:34.363",
"Id": "456681",
"Score": "0",
"body": "best solution!!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:16:43.723",
"Id": "46716",
"ParentId": "46699",
"Score": "20"
}
},
{
"body": "<p><strong>Indentation</strong></p>\n\n<p>Indentation is the <strong>first</strong> step to have code that is readable. Your code should look like this :</p>\n\n<pre><code>class Solution {\n // X=start, Y=end, D=distance for code clarity\n public int solution(int start, int end, int distance) {\n\n // write your code in Java SE 7\n int progress = start;\n int count = 0;\n while (progress < end) {\n progress = progress + distance;\n count++;\n }\n return count;\n }\n}\n</code></pre>\n\n<p><strong>Addition</strong></p>\n\n<p>Do know that </p>\n\n<blockquote>\n<pre><code>progress = progress + distance;\n</code></pre>\n</blockquote>\n\n<p>is the same as </p>\n\n<pre><code>progress += distance;\n</code></pre>\n\n<p><strong>Visibility</strong></p>\n\n<p>Currently, your class <code>Solution</code> don't have an access modifier. Normally you should specify one, unless you really need the default one. Here is a little <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html\">tutorial</a>. In your case your class should probably be declare like this : </p>\n\n<pre><code>public class Solution {\n</code></pre>\n\n<p><strong>Comments</strong></p>\n\n<p>Your first comments is what I would consider a good comments. It explains why the name are not what the problem specified, which is a good thing to note. The problem is, if you change the variable name again, you need to remember to change the comment.</p>\n\n<p>The second comments is just noise. You should remove it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-16T13:55:45.957",
"Id": "151512",
"Score": "1",
"body": "@Ranjan Kumar I saw your edit, if you have an improvement to suggest about the code, do this in another answer. I was approaching the style of the code not the content."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:45:10.763",
"Id": "46724",
"ParentId": "46699",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:40:17.123",
"Id": "46699",
"Score": "15",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Codility Frog Jump - Count minimal number of jumps from position X to Y"
} | 46699 |
<p>As I understand, the constructor chaining can be applied to cases when we have some common data to initialize. I have 3 constructors that accept 3 different types of arguments and have some common data. I'm not sure if I can do constructor chaining.</p>
<pre><code>public class RStandart
{
private readonly SqlConnection _objConn;
private readonly RequestData _requestData = new RequestData();
public string CardNo { get; set; }
public string PaymentType { get; set; }
public double Total { get; set; }
public DateTime TransactionDate { get; set; }
public string TransactionId { get; set; }
public class RequestData
{
// Request data (just a properties}
}
public RequestData GetRequestData
{
get { return _requestData; }
}
public RStandart(Int64 orderID, string total)
{
_requestData.VpcVirtualPaymentClientURL = string.Format("https://{0}/vpcpay", ConfigurationManager.AppSettings["vpc_VirtualPaymentClientURL"]);
_requestData.VpcVersion = ConfigurationManager.AppSettings["vpc_Version"];
_requestData.VpcCommand = ConfigurationManager.AppSettings["vpc_Command"];
_requestData.VpcAccessCode = ConfigurationManager.AppSettings["vpc_AccessCode"];
_requestData.VpcOrderInfo = orderID;
_requestData.VpcMerchant = ConfigurationManager.AppSettings["vpc_Merchant"];
_requestData.VpcAmount = int.Parse(total.Replace(".", string.Empty).Replace(",", string.Empty));
_requestData.VpcLocale = ConfigurationManager.AppSettings["vpc_Locale"];
_requestData.VpcReturnURL = ConfigurationManager.AppSettings["vpc_ReturnURL"];
_requestData.RequestParams = string.Format(
"vpc_Version-{0}|vpc_Command-{1}|vpc_AccessCode-{2}|vpc_MerchTxnRef-{3}|vpc_Merchant-{4}|vpc_Amount-{5}|vpc_Locale-{6}|vpc_ReturnURL-{7}|vpc_OrderInfo-{8}",
_requestData.VpcVersion, _requestData.VpcCommand, _requestData.VpcAccessCode, _requestData.VpcMerchTxnRef, _requestData.VpcMerchant,
_requestData.VpcAmount.ToString(), _requestData.VpcLocale, _requestData.VpcReturnURL, _requestData.VpcOrderInfo);
_requestData.VpcSecureHash = GetMD5(SortParamStr(_requestData.RequestParams), ConfigurationManager.AppSettings["vpc_SecureHash"]);
}
public RStandart(SqlConnection conn)
{
_objConn = conn;
SetDefaultValues();
_requestData.VpcVirtualPaymentClientURL = string.Format("https://{0}/vpcdps", ConfigurationManager.AppSettings["vpc_VirtualPaymentClientURL"]);
_requestData.VpcVersion = ConfigurationManager.AppSettings["vpc_Version"];
_requestData.VpcCommand = ConfigurationManager.AppSettings["vpc_CommandDR"];
_requestData.VpcAccessCode = ConfigurationManager.AppSettings["vpc_AccessCode"];
_requestData.VpcMerchant = ConfigurationManager.AppSettings["vpc_Merchant"];
_requestData.VpcUser = ConfigurationManager.AppSettings["vpc_User"];
_requestData.VpcPassword = ConfigurationManager.AppSettings["vpc_Password"];
_requestData.RequestParams = string.Format(
"vpc_Version={0}&vpc_Command={1}&vpc_AccessCode={2}&vpc_MerchTxnRef={3}&vpc_Merchant={4}&vpc_User={5}&vpc_Password={6}",
_requestData.VpcVersion, _requestData.VpcCommand, _requestData.VpcAccessCode, _requestData.VpcMerchTxnRef,
_requestData.VpcMerchant, _requestData.VpcUser, _requestData.VpcPassword);
}
public RStandart(HttpRequest request)
{
string vpc_SH = Query.GetStrQueryParam(request, "vpc_SecureHash");
var query = new StringBuilder();
foreach (string key in request.QueryString.Keys)
{
if ((key != "rsCheck") && (key != "vpc_SecureHash"))
{
query.AppendFormat("{0}-{1}|", key, Query.GetStrQueryParam(request, key));
}
}
_requestData.VpcSecureHash = GetMD5(SortParamStr(query.ToString().Substring(0, query.ToString().Length - 1)), ConfigurationManager.AppSettings["vpc_SecureHash"]);
if (_requestData.VpcSecureHash.ToUpper() == vpc_SH)
{
int respCode = Query.GetIntQueryParam(request, "vpc_TxnResponseCode");
_requestData.VpcMessage = Query.GetStrQueryParam(request, "vpc_Message");
if ((respCode == 0) && (_requestData.VpcMessage.IndexOf("Approved") > -1))
{
_requestData.VpcOrderInfo = Query.GetIntQueryParam(request, "vpc_OrderInfo");
Total = double.Parse(Query.GetStrQueryParam(request, "vpc_Amount").Length > 2
? Query.GetStrQueryParam(request, "vpc_Amount")
.Insert(Query.GetStrQueryParam(request, "vpc_Amount").Length - 2, ",")
: "0," + Query.GetStrQueryParam(request, "vpc_Amount"));
TransactionDate = string.IsNullOrEmpty(Query.GetStrQueryParam(request, "vpc_BatchNo"))
? DateTime.Now
: DateTime.Parse(
Query.GetStrQueryParam(request, "vpc_BatchNo")
.Insert(6, "-")
.Insert(4, "-"));
TransactionId = Query.GetStrQueryParam(request, "vpc_TransactionNo");
CardNo = Query.GetStrQueryParam(request, "vpc_CardNum");
}
}
}
}
</code></pre>
<p>I'm also not sure if I should have <code>RequestData</code> class as nested class or it should be out of <code>RStandard</code> class, but in the same namespace.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:23:14.617",
"Id": "81670",
"Score": "0",
"body": "What are you doing with `_requestData` after forging it in the constructor? And with `_objConn`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T06:51:16.090",
"Id": "81673",
"Score": "0",
"body": "I use it in public GetRequestData property. I've updated the original vode. Please, check it."
}
] | [
{
"body": "<p>You can use constructor chaining on the first two constructors but the last one differs a lot.</p>\n\n<p>What i think is more important is that you give the RStandart class a lot of knowledge and responsibility to setup the RequestData class. Are you sure this class needs to know how to initialize a RequestData class?</p>\n\n<p>I would move all the code that depends on the ConfigurationManager to the RequestData class and it in turn would make your constructors simpler and you would remove that duplicate code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:13:29.387",
"Id": "81675",
"Score": "0",
"body": "It's interesting suggestion about configuration data. Do you think I should leave RequestData class as nested or to be out of RStandard class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T09:47:25.497",
"Id": "81691",
"Score": "0",
"body": "You can still keep your RequestData class as I'm sure it has more then what you are showing here :), but i would move it into a separate file as i always do that. At least in my mind that makes it easier to use and find later"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:01:59.323",
"Id": "81693",
"Score": "0",
"body": "But, DataRequest class uses some private methods from outside RStandard class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:10:17.057",
"Id": "81696",
"Score": "0",
"body": "I'm not entierly sure on what you mean by that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:15:31.467",
"Id": "81697",
"Score": "0",
"body": "I mean RStandard and RequestData classes use the same private methods. If RequestData class is nested into RStandard class it's ok. But, if RequestData class would be out of RStandard class as you suggest, I would double these methods."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:03:05.917",
"Id": "46703",
"ParentId": "46701",
"Score": "3"
}
},
{
"body": "<p>In my experience, constructor chaining is useful in cases where you want to initialize your object to some default value and set specific value of properties/ members as the number of parameters increases.\nIn your class you can create a private default constructor to place some of the common code, however in this creating a method makes more sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T07:04:55.887",
"Id": "46704",
"ParentId": "46701",
"Score": "0"
}
},
{
"body": "<h2>Information</h2>\n\n<p>You can do constructor chaining in C#. However what you are doing here does not require such techniques. Here in your case you have 3 constructors taking all different types of data, and mostly doing separate things. </p>\n\n<p>You will be best off grouping repeated code into a method and calling that method from each constructor that needs it. </p>\n\n<p>However, for future reference if you do want to do real constructor chaining, you can do it as such...</p>\n\n<pre><code>public RStandart(string something, string anotherThing)\n{\n // I do something!\n}\n\npublic RStandart(object somethingElse)\n :this(\"none\", somethingElse.ToString())\n{\n //This code runs after the first constructor is called.\n}\n</code></pre>\n\n<h2>Review</h2>\n\n<p>I don't know if this is something you should implement, because I don't know how you intend to use this class. In C# you can place access modifiers on the individual parts of the getters and setters. A way you can use this (again, not sure if you need to, but this is isncase you do):</p>\n\n<pre><code>public string CardNo { get; private set; }\n</code></pre>\n\n<p>Now your CardNo cannot be changed outside the scope of this class. This should be done any time you don't want something to be changed from an outside source. This doesn't work well with objects, because.. while the reference cannot be changed, the object its self can be, so you'll have to be careful there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:32:01.023",
"Id": "81965",
"Score": "0",
"body": "*This doesn't work well with objects* ...except `System.String` which is immutable, of course ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:37:00.173",
"Id": "81966",
"Score": "0",
"body": "@Mat'sMug I almost said `except immutable objects`, but I took the lazy road, and didn't bother to mention it, because there are other niche cases... and yah I was just being silly. I should have just said `\"The object its self can be, if it has public modifiable members\"`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:50:35.753",
"Id": "46752",
"ParentId": "46701",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T05:57:15.537",
"Id": "46701",
"Score": "3",
"Tags": [
"c#"
],
"Title": "3 constructors that accept 3 different types of arguments"
} | 46701 |
<p>I have this method in my service layer </p>
<pre><code> public ModuleResponse GetModules(ModuleRequest request)
{
var response = new ModuleResponse(request.RequestId);
try
{
response.Modules = Mapper.ToDataTransferObjects(ModuleDao.GetModules());
return response;
}
catch (Exception ex)
{
Log.Error(ex);
response.Acknowledge = AcknowledgeType.Failure;
response.Message = "An error occured.";
return response;
}
}
</code></pre>
<p>I've written a unit test like this</p>
<pre><code> [Fact]
public void GetModulesTest()
{
//Arrange
var mockModuleDao = Mock.Create<IModuleDao>();
var mockLog = Mock.Create<ILog>();
var mockAuditDao = Mock.Create<IAuditDao>();
var moduleList = new List<ModuleItem>
{
new ModuleItem {Id = 100, Category = "User Accounts", Feature = "Users"},
new ModuleItem {Id = 101, Category = "User Accounts", Feature = "Roles Permissions"}
};
mockModuleDao.Arrange(dao => dao.GetModules()).Returns(moduleList);
IUserManagementService userService = new UserManagementService(mockModuleDao, mockLog, mockAuditDao);
var request = new ModuleRequest().Prepare();
//Act
var actualResponse = userService.GetModules(request);
//Assert
Assert.Equal(AcknowledgeType.Success, actualResponse.Acknowledge);
Assert.Equal(2, actualResponse.Modules.Count);
}
</code></pre>
<p>My question is... are such methods worth testing? I have a whole other bunch of retrieve methods that just return me lists of data. </p>
<p>Are there any other ways to improve the unit test in this particular example?</p>
<p>The first assert basically checks if the method has been executed without any error.</p>
<p>Is the 2nd Assert of my test redundant?</p>
| [] | [
{
"body": "<p>In my opinion No. There is hardly any behaviour at all. As soon you say \"I have this method in my service layer\" it make it much more obvious. Service layer provide communication and pretty much should orchestrate things. That's it. </p>\n\n<p>Note that Unit tests are good but have it unnecessary written they become a maintenance issue. </p>\n\n<p>Test your code which has behaviour from the customer's requirements point of view.</p>\n\n<p>Typically you would have an acceptance type test or an integration test to cover service layer and other layers as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:28:41.327",
"Id": "81725",
"Score": "0",
"body": "Ah I see, oh well, my organization has a fixation over 100% code coverage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T14:42:39.713",
"Id": "81746",
"Score": "1",
"body": "As I tend to agree with 100% code coverage, for most teams, you might then be able to refactor the unit test to have a generic base test that covers all of those service layer calls. perhaps this can also help in refactoring the TryCatch logic http://codereview.stackexchange.com/questions/11999/encapsulating-common-try-catch-code-is-this-a-known-pattern-is-it-good-or-bad"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T23:31:52.120",
"Id": "81832",
"Score": "0",
"body": "@the8thbit unfortunately that's no good. It might actually work against you. IN reality \"sometimes\" 20% coverage is better than 80% coverage."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:15:31.957",
"Id": "46712",
"ParentId": "46709",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46712",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:01:34.930",
"Id": "46709",
"Score": "2",
"Tags": [
"c#",
".net",
"unit-testing"
],
"Title": "Unnecessary unit test?"
} | 46709 |
<p>This is piece of code is using to download images. Can somebody tell me how to optimize this code to decrease download time for each image?</p>
<pre><code> URL url;
HttpURLConnection connection = null;
InputStream input = null;
System.setProperty("http.keepAlive", "true");
try {
url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT);
connection.setRequestProperty("Connection", "Keep-Alive");
input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
currentRequestInProgress.remove(urlString);
if (connection != null)
connection.disconnect();
if(input != null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
| [] | [
{
"body": "<h3>Resources:</h3>\n<p>You should really use try-with-resources:</p>\n<pre><code>URL url = new URL(urlstring);\nSystem.setProperty("http.keepAlive","true");\ntry(HTTPUrlConnection connection = (HTTPUrlConnection) url.openConnection()){\n connection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT);\n connection.setRequestProperty("Connection", "Keep-Alive");\n try(InputStream input = connection.getInputStream()){\n return BitmapFactory.decodeStream(input);\n }\n catch(IOException e){\n e.printStackTrace();\n return null;\n }\n}\ncatch(MalformedURLException e){\n e.printStackTrace();\n return null;\n}\n</code></pre>\n<p>This code should do exactly the same. The finally becomes useless, as try-with-resources does the job for you. Keep in mind, your resources should implement <code>java.lang.AutoCloseable</code>, this is required to use try-with-resources.</p>\n<p>As mentioned in some comments:</p>\n<p>Try-with-resources works <strong>only</strong> as of Android 4.4.</p>\n<p>furthermore, if <code>HTTPUrlConnection</code> does not implement <code>AutoCloseable</code> you will have to restructure the code like this:</p>\n<pre><code>HTTPUrlConnection connection\ntry{\n connection = (HTTPUrlConnection) url.openConnection();\n //[...]\n} \ncatch(MalformedURLException e){\n e.printStackTrace();\n return null;\n}\nfinally {\n if(connection != null)\n connection.disconnect();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:58:41.253",
"Id": "81708",
"Score": "0",
"body": "resource means ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:59:39.317",
"Id": "81710",
"Score": "0",
"body": "@MohitSharma about everything you `.open();` and `.close();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:03:38.990",
"Id": "81716",
"Score": "3",
"body": "This is a good advice in general but I don't think `HTTPUrlConnection` implements `Autocloseable`. There is a `connection.disconnect()` in the Op code, which is not in this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:20:43.057",
"Id": "81720",
"Score": "1",
"body": "@MohitSharma - Android is based on Java6 - no try-with-resources."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:23:04.110",
"Id": "81721",
"Score": "1",
"body": "@MohitSharma - actually, I [may be wrong](http://stackoverflow.com/a/22303654/1305253) - but it is complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:29:36.690",
"Id": "81727",
"Score": "0",
"body": "@Marc-Andre that's why I mentioned it... I actually also doubt, it implements `AutoCloseable`, even though it probably really should..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:23:21.120",
"Id": "81757",
"Score": "0",
"body": "Android till now support Java 1.5 only"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:34:42.633",
"Id": "81762",
"Score": "0",
"body": "Try with resources only works as of Android 4.4"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:28:55.123",
"Id": "46713",
"ParentId": "46711",
"Score": "3"
}
},
{
"body": "<p><strong>Buffered streams</strong> usually result in greatly improved performance:</p>\n\n<pre><code>input = new BufferedInputStream(connection.getInputStream());\n</code></pre>\n\n<p>The buffer size is 8kb per default, tuning it may be an option (but not without measuring).</p>\n\n<p>And, if you download multiple images: <strong>parallelize it with multiple threads</strong> (most of the time is consumed by I/O waits anyway), this usually improves performance by <em>factors</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:01:25.520",
"Id": "81711",
"Score": "0",
"body": "Keep in mind, this is tagged android. I thus suspect you have a **very** limited bandwidth. Your CPU waiting times don't really decrease when you try to squeeze more through the bandwith..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:04:28.450",
"Id": "81717",
"Score": "2",
"body": "Good catch, from http://developer.android.com/reference/java/net/HttpURLConnection.html : `The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams with BufferedInputStream or BufferedOutputStream. Callers that do only bulk reads or writes may omit buffering.`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T11:32:05.520",
"Id": "46714",
"ParentId": "46711",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:39:09.673",
"Id": "46711",
"Score": "5",
"Tags": [
"java",
"android",
"http"
],
"Title": "Decrease Image downloading time with HttpURLConnection"
} | 46711 |
<p>I need to extract some metrics from ManagedBeans and store the collected metrics in an object bean.</p>
<p>The object bean is defined with member variables to hold the metrics. In this case, is it right to extend the ObjectBean and write the extractor class?</p>
<p>For example:</p>
<pre><code>class ThreadMetricsBean {
private long liveCount, daemonCount;
public void record(long liveCount, long daemonCount) {
this.liveCount = liveCount;
this.daemonCount = daemonCount;
}
}
// Here to avoid code redundancy I feel it's correct to extend the ThreadMetricsBean class
// Am I wrong ??
class ThreadMetricsExtractor {
private long liveCount, daemonCount;
private ThreadMetricsBean bean = new ThreadMetricsBean();
public void run() throws Exception{
extractMetrics();
recordToBean();
}
private void extractMetrics() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
this.liveCount = threadMXBean.getThreadCount();
this.daemonCount = threadMXBean.getDaemonThreadCount();
}
private void recordToBean() {
bean.record(liveCount, daemonCount);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:42:03.207",
"Id": "81876",
"Score": "1",
"body": "@palacsint that was a typo mistake. Now I have corrected."
}
] | [
{
"body": "<ol>\n<li><p>I would declare variables on separate lines.</p>\n\n<blockquote>\n<pre><code>private long liveCount, daemonCount;\n</code></pre>\n</blockquote>\n\n<p>From <em>Code Complete, 2nd Edition</em>, p761:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...] </p>\n \n <p>It’s easier to modify declarations because each declaration is self-contained.</p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single\n column rather than reading each line. It’s easier to find and fix\n syntax errors because the line number the compiler gives you has \n only one declaration on it.</p>\n</blockquote></li>\n<li><p>The code has a temporal coupling here:</p>\n\n<blockquote>\n<pre><code>public void run() throws Exception{\n extractMetrics();\n recordToBean();\n}\n</code></pre>\n</blockquote>\n\n<p>A maintainer easily can change the order of the called methods which brokes it. See: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G31: Hidden Temporal Couplings</em>, p302</p></li>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>// Here to avoid code redundancy I feel it's correct to extend \n// the ThreadMetricsBean class\n// Am I wrong ?? \n</code></pre>\n</blockquote>\n\n<p>It's hard to say that which would be better without knowledge about clients and typical/possible usages of these classes. You might be able to remove redundancy in the following way too:</p>\n\n<pre><code>class ThreadMetricsExtractor {\n private final ThreadMetricsBean bean = new ThreadMetricsBean();\n\n public void run() throws Exception {\n storeMetrics();\n }\n\n private void storeMetrics() {\n final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();\n final int liveCount = threadMXBean.getThreadCount();\n final int daemonCount = threadMXBean.getDaemonThreadCount();\n bean.record(liveCount, daemonCount);\n }\n}\n</code></pre>\n\n<p>I've found that composition usually leads better design, cleaner and testable code than inheritance. A reference: <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em>.</p></li>\n<li><p>The <code>throws Exception</code> is unnecessary here, as far I see nothing throws any checked exception inside the <code>run</code> method:</p>\n\n<blockquote>\n<pre><code>public void run() throws Exception{\n extractMetrics();\n recordToBean();\n}\n</code></pre>\n</blockquote></li>\n<li><p>You could use integers here:</p>\n\n<blockquote>\n<pre><code>this.liveCount = threadMXBean.getThreadCount();\nthis.daemonCount = threadMXBean.getDaemonThreadCount();\n</code></pre>\n</blockquote>\n\n<p>Both called methods returns <code>int</code>, so <code>liveCount</code> and <code>daemonCount</code> could be <code>int</code>s too.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:06:45.007",
"Id": "46949",
"ParentId": "46717",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46949",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:21:11.480",
"Id": "46717",
"Score": "3",
"Tags": [
"java",
"design-patterns"
],
"Title": "Is it correct to extend a bean class and write a class which holds logic to populate the bean we extend?"
} | 46717 |
<p>I need to re-wrap a text so that it fits a given width, font and DC. The result needs to be an array of lines. I use the following code:</p>
<pre><code>private struct SplitInfo
{
public string Word;
public string SplitChar;
public override string ToString()
{
return Word;
}
}
private static float GetWidth(Graphics gr, string text, Font font)
{
SizeF size = gr.MeasureString(text, font, 10000, StringFormat.GenericTypographic);
return size.Width;
}
public static string[] WrapText(string text, IntPtr hdc, Font font, int textWidthInLoMetric)
{
// Split words at space (functionality for splitting at multiple different chars omitted for simplicity).
// This is also why it needs SplitInfo to store the words.
List<SplitInfo> words = new List<SplitInfo>(text.Split(' ').Select(x => new SplitInfo { SplitChar = " ", Word = x }));
StringBuilder resultText = new StringBuilder();
string currentLine = string.Empty;
SplitInfo lastWord = new SplitInfo { Word = string.Empty, SplitChar = string.Empty };
using (Graphics gr = Graphics.FromHdc(hdc))
{
while (true)
{
string newString = (currentLine + lastWord.SplitChar).TrimStart(' ') + words[0].Word;
if (currentLine != string.Empty && GetWidth(gr, newString, font) > textWidthInLoMetric)
{
// Word no longer fits in line.
resultText.Append(currentLine.TrimEnd() + "\n");
currentLine = string.Empty;
}
else
{
lastWord = words[0];
words.RemoveAt(0);
currentLine = newString;
}
if (words.Count == 0)
{
resultText.Append(currentLine.TrimEnd() + "\n");
break;
}
}
}
return resultText.ToString().TrimEnd().Split('\n');
}
</code></pre>
<p>Performance measurement shows that <code>MeasureString</code> is the main time consumer here (~90%). Is there any clever way to reduce the number of <code>MeasureString</code> calls? Other than that, I don't see opportunities to make word wrapping significantly faster.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T23:36:30.180",
"Id": "81833",
"Score": "0",
"body": "I was just wondering if the width of a rendered word can calculated from the sum of the letters that make it up, if do you could cache one the size of each letter. If not an exact match it could be used an as approximation maybe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T06:01:28.037",
"Id": "81879",
"Score": "0",
"body": "Nope, that's not enough. It really needs to be accurate and match the actual drawing."
}
] | [
{
"body": "<p>First, I'd like to say that your code is written very well, and is quite readable.</p>\n\n<p>As for your question - your code runs <code>MeasureString</code> at least once per word in your text. Since a line should be (quite) longer than a single word, I think you can reduce the number of calls substantially.</p>\n\n<p>I can think of two strategies:</p>\n\n<h2>1. Binary search</h2>\n\n<ul>\n<li>Check if the whole text can fit in one line - if yes - you are done!</li>\n<li>If not - take (about) half of the text, and wrap it.</li>\n<li>Append the last line of the first half to the remaining text (unless it all fit in a single line), and wrap that text</li>\n</ul>\n\n<p>This strategy might need a little refining, but it should reduce the number of calls to <code>MeasureString</code> considerably.</p>\n\n<h2>2. Approximate line length</h2>\n\n<ul>\n<li>Use your current solution to find the first line. Note the line length (in characters).</li>\n<li>Take next X words in the remaining text whose length is at most the previous line's length, and check if it fits in a single line.\n<ul>\n<li>If it does - continue as before (add a word until it doesn't fit)</li>\n<li>If it does not repeat - take one word out, and try again.</li>\n</ul></li>\n<li>Wash, rinse, repeat</li>\n</ul>\n\n<p>In this solution all <code>MeasureString</code> calls should be relevant, as they should be <em>around</em> the actual length of each line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:36:18.807",
"Id": "81772",
"Score": "0",
"body": "\"I'd like to say that your code is written very well, and is quite readable.\" - thx, I'm glad to hear that. I feared that my approach was a bit too simplistic. Based on your suggestions though it seems like without some additional complexity it's not possible to improve the speed a lot. Something like \"binary search\" was also floating around in my head but I considered it overkill so far and believed that there might be entirely better approches for such a common problem. Maybe I indeed need to try it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:58:53.123",
"Id": "81781",
"Score": "0",
"body": "I would suggest you start from my second suggestion, while I wrote the binary search solution, I felt that it might have some nasty edge-conditions that I might have missed. The approximate length solution seems easier to describe, so it might also be easier to implement..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:24:15.887",
"Id": "46736",
"ParentId": "46718",
"Score": "3"
}
},
{
"body": "<p>One possibility is to cache the measured length for each word. I do this, when the line breaks need to be recalculated (i.e. when document needs to be reflowed) frequently, for example because the user edits words or the user resizes the width of the control.</p>\n\n<p>A second possibility is to use different APIs, for example:</p>\n\n<ul>\n<li>A different <code>StringFormat</code> value passed as a parameter</li>\n<li>A different method for example <code>TextRenderer.MeasureText</code> instead of <code>Graphics.MeasureString</code></li>\n</ul>\n\n<p>My code says ...</p>\n\n<pre><code> //http://msdn.microsoft.com/en-us/magazine/cc163630.aspx#S7 i.e. \n //\"Practical Tips For Boosting The Performance Of Windows Forms Apps\" in MSDN says,\n //\n //It's better to use the TextRenderer method overloads that do not get IDeviceContext as an argument.\n //These methods are more efficient because they use a cached screen-compatible memory device context\n //rather than retrieving the native handle for device context from the internal DeviceContext and\n //creating an internal object to wrap it.\n //\n //My profiling shows that the method without the Graphics parameter takes 0.025 msec instead of 0.1 msec.\n //However, the resulting calculation is inaccurate.\n Size size = TextRenderer.MeasureText(\n m_graphics,\n text,\n paintStyle.font,\n proposedSize,\n textFormatFlags);\n</code></pre>\n\n<p>... and ...</p>\n\n<pre><code> static TextFormatFlags textFormatFlags =\n TextFormatFlags.NoPrefix |\n TextFormatFlags.NoPadding |\n TextFormatFlags.ExternalLeading |\n TextFormatFlags.Left |\n TextFormatFlags.Bottom;\n</code></pre>\n\n<p>This code recalculates dozens of pages in a fraction of a second (and because it caches the measured word sizes it only measures all words once, when the document is first loaded).</p>\n\n<p>The corresponding method which I use for drawing the text is:</p>\n\n<pre><code> TextRenderer.DrawText(\n m_graphics,\n text,\n paintStyle.font,\n drawingPoint,\n color,\n textFormatFlags);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:08:45.100",
"Id": "81782",
"Score": "0",
"body": "I don't think `TextRenderer` measurement will match the actual drawing, I need the device context anyway (and it also needs to be somewhat accurate). Can you explain which of these `TextFormatFlags` should make a difference and why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:14:10.903",
"Id": "81783",
"Score": "0",
"body": "@floele I updated my answer. The flags are documented; they disable various types of margin which would otherwise be automatically inserted around the text. I don't want that kind of margin around each word (instead I measure my own space between words as the width of `\" \"`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:16:32.460",
"Id": "81784",
"Score": "0",
"body": "Certainly the flags are documented, but I don't think the docs say much about the actual performance difference (if any). Since I measure text drawn by a C++ application, TextRenderer is not used for drawing btw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:00:16.277",
"Id": "81814",
"Score": "2",
"body": "@floele The article I cited i.e. http://msdn.microsoft.com/en-us/magazine/cc163630.aspx#S7 comments on performance of the flags, and says that different flags have different performance (which is easy to verify by experiment)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:03:19.197",
"Id": "46738",
"ParentId": "46718",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46736",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:22:08.480",
"Id": "46718",
"Score": "6",
"Tags": [
"c#",
"performance",
"winforms"
],
"Title": "Can calculation of word wrapping be made notably faster?"
} | 46718 |
<p>I'm relatively new to JavaScript OOP and would like to know the best practice when doing a simple object such as a Model.</p>
<p>Here's a piece of code representing class named <code>Child</code>:</p>
<p>What I'm asking for is:</p>
<ol>
<li>The usage of this (and the weak reference I'm doing which I name self)</li>
<li>The global shape of the code (methods in prototype etc)</li>
<li>Declaring a class as a function, or with JSON semantics</li>
</ol>
<p></p>
<pre><code>var Child = function( json ) {
var self = this;
// Properties
this.id = 0;
this.firstname = "";
this.moneyCurrent = 0;
this.moneyDue = 0;
this.missionsPlay = 0;
this.missionsWait = 0;
this.missionsStop = 0;
this.missions = [];
this.initialize( json );
}
Child.prototype = {
initialize: function( json ) {
var self = this;
self.id = json.id_child;
self.firstname = json.firstname;
self.moneyCurrent = parseFloat(json.already_paid) + parseFloat(json.to_pay) - parseFloat(json.spent_money);
self.moneyDue = parseFloat(json.to_pay);
self.missionsPlay = json.nb_missions.in_progress;
self.missionsWait = json.nb_missions.waiting;
self.missionsStop = json.nb_missions.completed;
},
getMissions: function( type, callback ) {
var self = this;
session.requestServer( "parent_getChildMissionList", {
sid: session.sid,
id_child: self.id,
status: type ? type : "",
strict_status: false,
page: 0
}, function( data ){
var missions = [];
$(data.missionList).each(function(){
self.missions.push(new Mission(this));
missions.push(self.missions[self.missions.length-1]);
});
callback( missions );
});
},
};
</code></pre>
<p>Classic way to declare a class:</p>
<pre><code>var obj = function() {
var attribut = "foo";
this.metho = function(parameter1, parametre2) {
alert("parameters: " + parameter1 + ", " + parameter2);
}
}
</code></pre>
<p>JSON way to declare a class:</p>
<pre><code>var obj = {
attribut: "foo",
method: function(parameter1, parameter2) {
alert("parameters: " + parameter1 + ", " + parameter2);
}
}
</code></pre>
| [] | [
{
"body": "<p>For your questions:</p>\n\n<ul>\n<li>The usage of <code>this</code> : In my mind, unless you are using closures, do not use <code>self = this</code>, so only keep it in <code>getMissions</code></li>\n<li>Functions in <code>prototype</code> <- Good stuff</li>\n<li>Function <> JSON, is an odd question. You want to use constructors, and those are functions.</li>\n</ul>\n\n<p>Other than that,</p>\n\n<ul>\n<li>You are using lowerCamelCase, that is good. Though <code>firstname</code> -> <code>firstName</code></li>\n<li><code>initialize: function( json )</code> does not really get a JSON string, instead it gets an object, so I would not name that parameter <code>json</code></li>\n<li><p>The function to deal with returned missions seems a bit clumsy, I would either assign each new mission to a variable and push it to both arrays:</p>\n\n<pre><code>function( data ){\n var missions = [], mission;\n $(data.missionList).each(function(){\n mission = new Mission(this)\n self.missions.push( mission );\n missions.push( mission );\n });\n callback( missions );\n}\n</code></pre>\n\n<p>or, I would only <code>push</code> to <code>missions</code> and then concatenate <code>missions</code> into <code>self.missions</code></p>\n\n<pre><code>function( data ){\n var missions = [];\n $(data.missionList).each(function(){\n missions.push(new Mission(this));\n });\n self.missions = self.missions.concat( missions );\n callback( missions );\n}\n</code></pre></li>\n</ul>\n\n<p>All in all, nice code, very maintainable and self explanatory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:08:42.477",
"Id": "81719",
"Score": "0",
"body": "Thank you for your answer, it's wath I searched as an answer, especially the \"Other than that\" really usefull :)\nI edited my question to try to be clearer on my 3th question (sometime I lack to express myself). I read it in a course but they don't say which one could be better and why. I wonder about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:24:02.070",
"Id": "81722",
"Score": "0",
"body": "Singletons -> 'JSON Way', if you are going to have many objects of the same type -> constructor functions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:27:24.823",
"Id": "81723",
"Score": "0",
"body": "In which way JSON Way is less good for reusable class than *constructor functions* ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:28:00.840",
"Id": "81724",
"Score": "1",
"body": "I would use map instead of each in those last 2 examples"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:53:26.860",
"Id": "81824",
"Score": "0",
"body": "+1 for `self = this` seeing that convention used improperly bothers me way more than it should."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:54:38.373",
"Id": "46721",
"ParentId": "46719",
"Score": "7"
}
},
{
"body": "<p>You don't actually need the <code>self</code> variable in most of your code (the constructor doesn't use it at all). You can just use <code>this</code> directly in most cases.</p>\n\n<p>The only exception is in the <code>session.requestServer</code> callback, where you do need a way to reference the object context - and there it's perfectly fine to use <code>self</code>. Alternatively, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow\"><code>.bind()</code></a> to derive a function that's bound to the right context (but if you're targeting browsers know that <a href=\"http://kangax.github.io/es5-compat-table/#Function.prototype.bind\" rel=\"nofollow\">support for <code>bind</code> is spotty</a>).</p>\n\n<p>More generally, I'd skip the <code>initialize</code> method. It depends on what you intend of course, but having the <code>initialize</code> function there means that you can re-initialize a <code>Child</code> instance whenever you want, because it'll have a publicly accessible <code>initialize</code> function that anyone can call. But initializing an instance should be the responsibility of the constructor function, unless there's some good reason to do otherwise. In this case, however, I don't think there is.</p>\n\n<p>In other words, simply put everything in the constructor function, and remove the <code>initialize</code> function.</p>\n\n<p>I end up with this; the \"classic\" way to define a class (i.e. construtor+prototype) in javascript.</p>\n\n<pre><code>function Child(json) { // equivalent to `var Child = function ...`; just for illustration\n // properties - with defaults\n this.id = json.id_child || 0; // null might be a better default for the ID\n this.firstname = json.firstname || \"\";\n this.moneyDue = parseFloat(json.to_pay) || 0;\n this.moneyCurrent = parseFloat(json.already_paid) + this.moneyDue - parseFloat(json.spent_money) || 0;\n this.missionsPlay = json.nb_missions.in_progress || 0;\n this.missionsWait = json.nb_missions.waiting || 0;\n this.missionsStop = json.nb_missions.completed || 0;\n\n this.missions = [];\n}\n\nChild.prototype = {\n getMissions: function (type, callback) {\n var self = this;\n\n // I assume `session` is a global or closed-over variable?\n session.requestServer( \"parent_getChildMissionList\", {\n sid: session.sid,\n id_child: this.id, // we can still use `this` here\n status: type || \"\",\n strict_status: false,\n page: 0\n }, function (data) {\n var missions = [],\n mission;\n $(data.missionList).each(function () {\n mission = new Mission(this); // easier than having to go through missions[missions.length-1]\n self.missions.push(mission); // This is where we need to use the `self` var\n missions.push(mission);\n });\n callback(missions);\n });\n } // removed a stray comma on this line - some JS interpreters choke on them, some don't\n};\n</code></pre>\n\n<p>Now, you could conceivably just use the JSON more directly. Perhaps have a factory-like method that takes in the \"raw\" JSON, and add a few things or builds a new object literal from it. That'd look something like:</p>\n\n<pre><code>function buildChild(json) { // note lowercase naming; this isn't a constructor\n var child = {\n id: json.id_child || 0,\n firstname: json.firstname || \"\",\n moneyDue: parseFloat(json.to_pay) || 0,\n moneyCurrent: parseFloat(json.already_paid) + this.moneyDue - parseFloat(json.spent_money) || 0,\n missionsPlay: json.nb_missions.in_progress || 0,\n missionsWait: json.nb_missions.waiting || 0,\n missionsStop: json.nb_missions.completed || 0,\n missions: [],\n };\n\n child.getMissions = function (type, callback) {\n session.requestServer( \"parent_getChildMissionList\", {\n sid: session.sid,\n id_child: child.id, // now we use `child` instead of this\n status: type || \"\",\n strict_status: false,\n page: 0\n }, function (data) {\n var missions = [],\n mission;\n $(data.missionList).each(function () {\n mission = new Mission(this);\n child.missions.push(mission); // same here\n missions.push(mission);\n });\n callback(missions);\n });\n };\n\n return child;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:26:38.577",
"Id": "46723",
"ParentId": "46719",
"Score": "3"
}
},
{
"body": "<p>Or if you want to avoid classical style but still use prototypes for performance or manageability...</p>\n\n<pre><code>var Child = {\n // defaults values for inherited properties\n id: 0,\n firstname = \"\",\n moneyCurrent = 0,\n moneyDue = 0,\n missionsPlay = 0,\n missionsWait = 0,\n missionsStop = 0,\n missions = [],\n\n // factory method which creates new instances and prototype factories\n create: function(options) {\n var obj = Object.create(this),\n proto = obj,\n inits = [];\n\n // fetch all defined init methods in the prototype chain\n while (proto && proto !== Object.prototype) {\n if (proto.hasOwnProperty(\"init\")) inits.push(proto.init);\n proto = proto.getPrototypeOf();\n }\n\n // execute inits\n inits.reverse.forEach(function(init) {init.call(this, options);});\n },\n\n // constructor for your \"class\"\n init: function(options) {\n // validate input\n var money = parseFloat(options.already_paid) + parseFloat(options.to_pay)\n - parseFloat(options.spent_money),\n due = parseFloat(options.to_pay),\n play = parseInt(options.nb_missions.in_progress),\n wait = parseInt(options.nb_missions.waiting),\n stop = parseInt(options.nb_missions.completed);\n\n // use validated input or fallback to inherited values\n this.id = options.id_child || this.id;\n this.firstname = options.firstname || this.firstname;\n this.moneyCurrent = isNaN(money) ? this.moneyCurrent : money;\n this.moneyDue = isNaN(due) ? this.moneyDue : due;\n this.missionsPlay = isNaN(play) ? this.missionsPlay : play;\n this.missionsWait = isNaN(wait) ? this.missionsWait : wait;\n this.missionsStop = isNaN(stop) ? this.missionsStop : stop;\n\n // ensure we have our own copy of the missions array\n this.missions = this.missions.slice(0);\n },\n\n getMissions: function(type, callback) {\n // ...\n } \n};\n</code></pre>\n\n<p>So now creating a new child with Child.create will setup the appropriate\nprototype chain. You could then create a manageable inheritance hierarchy.</p>\n\n<pre><code>var c, FooChild = Child.create();\n\nc = FooChild.create();\nFooChild.foo = \"FOO!\";\nassert(c.foo == \"FOO!\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T07:25:16.943",
"Id": "81883",
"Score": "0",
"body": "Really interesting"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:28:41.180",
"Id": "46744",
"ParentId": "46719",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T12:23:51.847",
"Id": "46719",
"Score": "7",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Basic JavaScript OOP model object"
} | 46719 |
<p>I've since come up with an improved version, which isn't technically lock-free, but might be as close as you can get <a href="https://codereview.stackexchange.com/questions/47606/nearly-lock-free-job-queue-of-dynamic-size-multiple-read-write">(nearly) lock-free job queue of dynamic size (multiple read/write)</a></p>
<p><strong>code below is not thread safe</strong></p>
<hr>
<p>I was looking for a *simple lock-free job-queue which can be used in a generic way, cross-platform.</p>
<p><sub>* no external dependencies, only few calls to interface, no exotic compiler tricks which may break from compiler to compiler, preferably header only.</sub></p>
<p>Either I suck at Googling, or this isn't available ( they are not mutually exclusive, but you get the point ).</p>
<hr>
<p>This is what I eventually came up with.</p>
<p>It's a linked list, which allocates a <code>fifo_node_type</code> on the heap for each item pushed.
This items gets destroyed in the pop function.</p>
<p>fifo.h</p>
<pre><code>/**
* This is a lock free fifo, which can be used for multi-producer, multi-consumer
* type job queue
*/
template < typename Value >
struct fifo_node_type
{
fifo_node_type( const Value &original ) :
value( original ),
next( nullptr ) { }
Value value;
fifo_node_type *next;
};
template < typename Value, typename Allocator = std::allocator< fifo_node_type< Value > > >
class fifo
{
public:
typedef Value value_type;
typedef Allocator allocator_type;
typedef std::vector< value_type, allocator_type > vector_type;
fifo() :
start_(),
end_(),
allocator_() {}
~fifo()
{
clear();
}
/**
* pushes an item into the job queue, may throw if allocation fails
* leaving the queue unchanged
*/
template < typename T >
void push( T &&val )
{
node_ptr newnode = create_node( std::forward< T >( val ) );
node_ptr tmp = nullptr;
start_.compare_exchange_strong( tmp, newnode );
node_ptr prev_end = end_.exchange( newnode );
if ( prev_end )
{
prev_end->next = newnode;
}
}
/**
* retrieves an item from the job queue.
* if no item was available, func is untouched and pop returns false
*/
bool pop( value_type &func )
{
auto assign = [ & ]( node_ptr ptr, value_type &value)
{
std::swap( value, ptr->value );
destroy_node( ptr );
};
return pop_generic( func, assign );
}
/**
* clears the job queue, storing all pending jobs in the supplied vector.
* the vector is also returned for convenience
*/
vector_type& pop_all( vector_type &unfinished )
{
value_type tmp;
while ( pop( tmp ) )
{
unfinished.push_back( tmp );
}
return unfinished;
}
/**
* clears the job queue.
*/
void clear()
{
auto del = [ & ]( node_ptr ptr, value_type& )
{
destroy_node( ptr );
};
value_type tmp;
while ( pop_generic( tmp, del ) )
{
// empty
}
}
/**
* returns true if there are no pending jobs
*/
bool empty() const
{
return start_ == nullptr;
}
private:
typedef fifo_node_type< value_type > node_type;
typedef node_type* node_ptr;
typedef std::atomic< node_ptr > node;
fifo( const fifo& );
fifo& operator = ( const fifo& );
template < typename Assign >
bool pop_generic( value_type &func, Assign assign )
{
node_ptr tmp = start_;
while ( tmp )
{
if ( start_.compare_exchange_weak( tmp, tmp->next ) )
{
assign( tmp, func );
return true;
}
// if we got here, tmp was set to the value of start_, so we try again
}
return false;
}
template < typename T >
node_ptr create_node( T &&t )
{
node_ptr result = reinterpret_cast< node_ptr >( allocator_.allocate( 1 ) );
new ( result ) node_type( std::forward< T >( t ) );
return result;
}
void destroy_node( node_ptr &t )
{
allocator_.destroy( t );
allocator_.deallocate( t, 1 );
}
node start_, end_;
allocator_type allocator_;
};
</code></pre>
<p><a href="http://coliru.stacked-crooked.com/a/189255cefd561602" rel="nofollow noreferrer">Here's a silly example of how to use it</a>.</p>
<p>If it proves to be useful, I'll put it up on GitHub in a more sensible way.</p>
<p>Please let me know if you see any issues with it, or feel things could be done smarter!</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:54:51.387",
"Id": "81732",
"Score": "0",
"body": "at least one issue was pointed out in the original thread: http://stackoverflow.com/a/22963691/1078274 another issue I have since identified is the fact that there can be race conditions when destroying nodes"
}
] | [
{
"body": "<p>Herb Sutter has written a series of articles about lock-free queues: </p>\n\n<ul>\n<li><p><a href=\"http://www.drdobbs.com/cpp/lock-free-code-a-false-sense-of-security/210600279\" rel=\"nofollow\">\"Lock-Free Code: A False Sense of Security\"</a>:\nexplaining why STL containers are not suitable for lock-free code.</p></li>\n<li><p><a href=\"http://www.drdobbs.com/parallel/writing-a-generalized-concurrent-queue/211601363\" rel=\"nofollow\">\"Writing a Generalized Concurrent Queue\"</a>: a supposedly lock-free multi-producer multi-consumer queue that does contain two mutexes.</p></li>\n</ul>\n\n<p>A reason that the approach that you and Herb are using cannot be truly lock-free in the multi-producer or -consumer case is that both the <code>start_</code> or <code>end_</code> variables and the start or end of the list need to be changed in a single atomic operation, which is not possible on existing architectures. I wonder if an implementation without <code>start_</code> and <code>end_</code> variables, where each thread traverses the queue by itself, could work?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T19:54:16.163",
"Id": "83442",
"Score": "0",
"body": "What you can do is swap pointers, and replace the entire structure that needs to be under atomic control by precalculating your change, and then executing the swap transaciton if and only if no changes occurred. (i.e., put start_ and end_ in an allocated struct, atomic-read the pointer to that struct, calculate new structure, atomic-exchange with expected-old-ptr/calculated-new-ptr). This is still technically \"lock free,\" but you MUST use pointers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T10:33:38.540",
"Id": "47137",
"ParentId": "46722",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:06:13.523",
"Id": "46722",
"Score": "5",
"Tags": [
"c++",
"c++11",
"lock-free",
"atomic"
],
"Title": "lock-free job queue without size restriction (multiple read/write)"
} | 46722 |
<p>I've started working on a script that turns sections with headings into a tabbed interface.</p>
<p>The repo is at <a href="https://github.com/derekjohnson/tabs" rel="nofollow">https://github.com/derekjohnson/tabs</a> and a demo at <a href="http://derekjohnson.github.io/tabs/" rel="nofollow">http://derekjohnson.github.io/tabs/</a></p>
<p>It works in IE8 up, although I haven't fully tested it on all the devices I have access to.</p>
<p>I'm particularly interested in feedback on the tabs.js file, and welcome all comments.</p>
<p>As I mentioned in the README I know it could do with a config object, but I've never done one so I'll be learning on this project. Any tips on that gratefully received too.</p>
<p>tabs.js:</p>
<pre><code>(function(win, doc, undefined) {
'use strict';
// Quick feature test
if('querySelector' in doc) {
var tabs = function() {
/* Helper functions
========================================================================== */
// Cross browser events
var add_event = function(el, ev, fn) {
'addEventListener' in win ?
el.addEventListener(ev, fn, false) :
el.attachEvent('on' + ev, fn);
};
// Faster class selectors
// http://jsperf.com/queryselector-vs-getelementsbyclassname-0
var get_single_by_class = function(className) {
return 'getElementsByClassName' in doc ?
doc.getElementsByClassName(className)[0] :
doc.querySelector('.' + className);
}
//http://jsperf.com/byclassname-vs-queryselectorall
var get_many_by_class = function(className) {
return 'getElementsByClassName' in doc ?
doc.getElementsByClassName(className) :
doc.querySelectorAll('.' + className);
}
/* Feature detect for localStorage courtesy of
http://mathiasbynens.be/notes/localstorage-pattern
========================================================================== */
var storage,
fail,
uid;
try {
uid = new Date;
(storage = win.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch(e) {}
/* DOM nodes we'll need
========================================================================== */
var wrapper = get_single_by_class('js-tab-ui'),
panels = get_many_by_class('js-panel'),
tab_names = get_many_by_class('js-panel__title'),
i,
ii = panels.length;
/* Show hide the panels, update the tabs' attributes
========================================================================== */
var show_hide = function(x_id) {
for(i=0; i<ii; i++) {
// display the correct panel, hide the others
if(panels[i].getAttribute('aria-labelledby') === x_id) {
panels[i].style.display = 'block';
} else {
panels[i].style.display = 'none';
}
// update the ARIA
if(items[i].id === x_id) {
items[i].setAttribute('aria-selected', 'true');
} else {
items[i].setAttribute('aria-selected', 'false');
}
}
// put the tab id into localStorage
if(storage) {
localStorage['tab'] = x_id;
}
}
/* When a tab has been clicked
========================================================================== */
var clicked = function(event) {
var x,
x_id;
typeof event.target !== 'undefined' ?
x = event.target :
x = event.srcElement;
if(x.nodeName.toLowerCase() === 'li') {
// get the id of the clicked tab
x_id = x.id;
} else {
return; // stop clicks on the <ul> hiding everything
}
show_hide(x_id);
};
/* Keyboard interaction
========================================================================== */
var kbd = function(event) {
var x,
x_id,
key_code,
next,
prev;
event = event || win.event;
key_code = event.keyCode || event.which;
typeof event.target !== 'undefined' ?
x = event.target :
x = event.srcElement;
// up or right arrow key moves focus to the next tab
if(key_code === 38 || key_code === 39) {
next = x.nextSibling;
// make sure we're on an element node
if(next.nodeType !== 1) {
next = next.nextSibling;
}
next.setAttribute('tabindex', 0);
next.focus();
}
// left or down arrow key moves focus to the previous tab
if(key_code === 37 || key_code === 40) {
prev = x.previousSibling;
// make sure we're on an element node
if(prev.nodeType !== 1) {
prev = prev.previousSibling;
}
prev.setAttribute('tabindex', 0);
prev.focus();
}
// space bar
if(key_code === 32) {
show_hide(x.id);
}
// Prevent space bar moving the page down
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
/* Create each tab item
========================================================================== */
var build_tab = function(el, text, classification) {
el.innerHTML = text;
el.className = classification;
el.setAttribute('role', 'tab');
return el;
};
/* Make an empty list that will hold the tabs
========================================================================== */
var frag = doc.createDocumentFragment(),
tabs = doc.createElement('ul');
// Basic attributes for the list
tabs.className = 'product-tabs';
tabs.setAttribute('role', 'tablist');
/* Build each tab and add all required attributes to tabs & panels
========================================================================== */
var items = [];
for(i=0; i<ii; i++) {
var li = build_tab(doc.createElement('li'), tab_names[i].innerHTML, 'product-tabs__item');
// Add unique attributes to each list item
li.id = 'tab' + (i + 1);
li.setAttribute('aria-controls', panels[i].id);
if(i === 0) {
li.setAttribute('tabindex', 0);
li.setAttribute('aria-selected', 'true');
} else {
li.setAttribute('aria-selected', 'false');
}
// Stick them into the document fragment
frag.appendChild(li);
// Stick them into the items array
items[i] = li;
// Panels
panels[i].setAttribute('role', 'tabpanel');
panels[i].setAttribute('aria-labelledby', 'tab' + (i + 1));
}
/* Insert the tabs into the DOM
========================================================================== */
tabs.appendChild(frag);
wrapper.insertBefore(tabs, get_single_by_class('js-panel'));
/* Listen for clicks on the tab list
========================================================================== */
add_event(tabs, 'click', clicked);
/* Listen for key presses
========================================================================== */
add_event(tabs, 'keydown', kbd);
/* If a tab id is in localStorage open the corresponding panel
========================================================================== */
if(storage && localStorage['tab']) {
show_hide(localStorage['tab']);
}
};
// Make all that happen
tabs();
} else {
return;
}
})(this, this.document);
</code></pre>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>In general, impressive code</li>\n<li><p>The bottom part of your code is too stretched vertically, this:</p>\n\n<pre><code> /* Insert the tabs into the DOM\n ========================================================================== */\n\n tabs.appendChild(frag);\n\n wrapper.insertBefore(tabs, get_single_by_class('js-panel'));\n\n\n\n /* Listen for clicks on the tab list\n ========================================================================== */\n add_event(tabs, 'click', clicked);\n\n\n\n /* Listen for key presses\n ========================================================================== */\n add_event(tabs, 'keydown', kbd);\n\n\n\n /* If a tab id is in localStorage open the corresponding panel\n ========================================================================== */\n\n if(storage && localStorage['tab']) {\n show_hide(localStorage['tab']);\n }\n};\n\n// Make all that happen\ntabs();\n</code></pre>\n\n<p>could have been this:</p>\n\n<pre><code> // Insert the tabs into the DOM\n tabs.appendChild(frag);\n wrapper.insertBefore(tabs, get_single_by_class('js-panel'));\n // Listen for clicks on the tab list\n add_event(tabs, 'click', clicked);\n // Listen for key presses\n add_event(tabs, 'keydown', kbd);\n // If a tab id is in localStorage open the corresponding panel\n if(storage && localStorage['tab']) {\n show_hide(localStorage['tab']);\n }\n};\n\n// Make all that happen\ntabs();\n</code></pre></li>\n<li><p>I am pretty sure this</p>\n\n<pre><code> typeof event.target !== 'undefined' ?\n x = event.target :\n x = event.srcElement;\n</code></pre>\n\n<p>could be </p>\n\n<pre><code> x = event.target || event.srcElement;\n</code></pre></li>\n<li><p>The bigger picture is that this:</p>\n\n<pre><code>/* When a tab has been clicked\n ========================================================================== */\n\n\nvar clicked = function(event) {\n var x,\n x_id;\n\n typeof event.target !== 'undefined' ?\n x = event.target :\n x = event.srcElement;\n\n if(x.nodeName.toLowerCase() === 'li') {\n // get the id of the clicked tab\n x_id = x.id;\n } else {\n return; // stop clicks on the <ul> hiding everything\n }\n\n show_hide(x_id);\n};\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>// When a tab has been clicked\nvar onClicked = function(event) {\n var clickedElement = event.target || event.srcElement;\n\n if(clickedElement.nodeName.toLowerCase() === 'li') {\n show_hide(clickedElement.id);\n }\n};\n</code></pre></li>\n<li>You are not following lowerCamelCase</li>\n<li>You should used named constants for the keycodes <code>key_code === LEFT_ARROW</code> reads better than <code>key_code === 37</code></li>\n</ul>\n\n<p>On the whole, I think you should review your code to reduce the line count. I am not saying that you should play CodeGolf, but this could be written in a fewer lines while keeping the same level of quality.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:05:25.797",
"Id": "82455",
"Score": "0",
"body": "Thank you, it looks like I need to think a bit smarter to trim the fat. I had no idea keycodes had named constants, I'd never seen that before. Re. the lowerCamelCase, my understanding is that it's a matter of taste?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:09:35.673",
"Id": "46919",
"ParentId": "46727",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>I'm not a big fan of the general code structure. All the DOM helper functions should be extracted into a separate module to avoid code duplication, since other scripts will need the same/similar functions. Is there any special reason you are not using an existing DOM library?</p></li>\n<li><p>I know it's a bit due to the fact how JavaScript works, but there is a lot a scrolling involved when you want to follow the flow of the program: First scroll all the way down, until you find the start point (<code>tabs();</code>), then scroll all the way back up looking for the definition of <code>tab</code> and finally scroll almost all the way back down to find they place where it there is actually runable code. (Not having all the DOM helper functions inside the main function would help here a lot).</p></li>\n<li><p>Your code can only handle a single set of tabs on a page, which is very limiting.</p></li>\n<li><p><code>ii</code> is a terrible variable name.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:00:10.113",
"Id": "82453",
"Score": "0",
"body": "Thank you, some great tips there. I hadn't thought of more that one set of tabs, I'll look to fix that. I didn't use a lib to see if I could get away with it, it's a learning exercise too. I got a wee telling off on twitter for `ii` too, so that's going. Thanks again :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T10:48:00.920",
"Id": "83130",
"Score": "0",
"body": "\"DOM helper functions should be extracted into a separate module\".\n\nGood choice of words, it led me to figuring out the module pattern. Thank you :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T14:45:03.100",
"Id": "83192",
"Score": "0",
"body": "I though you already knew about module patterns, since your code uses one :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:53:38.157",
"Id": "46932",
"ParentId": "46727",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T13:59:35.830",
"Id": "46727",
"Score": "4",
"Tags": [
"javascript",
"dom"
],
"Title": "Accessible tabbed UI"
} | 46727 |
<h3>Notes</h3>
<p>I'm working my way through SICP, and as I got very confused by the section on folds, I decided to try to implement foldr in scheme and javascript to understand how it works differently with immutable and mutable variables.</p>
<p>I'm mostly looking for advice on whether or not what I've done makes sense idiomatically in each language, but any other feedback would be very much appreciated.</p>
<h3>Scheme</h3>
<pre><code>;Foldr implemented so I can understand it
(define (foldright function initial collection)
(if (not (pair? collection))
initial
(foldright function (function initial (car collection)) (cdr collection))))
;Test Case (should return 10)
(foldright (lambda (x y) (+ x y)) 0 (list 1 2 3 4))
</code></pre>
<h3>Javascript</h3>
<pre><code>function foldr(func, initial, collection) {
if (collection.length === 0) {
return initial
};
initial = func(initial, collection[0]);
collection.shift();
return foldr(func, initial, collection);
};
//Test case (should return 10)
var result = foldr(function (a, b) {
return a + b;
}, 0, [1, 2, 3, 4]);
console.log(result);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:00:38.820",
"Id": "81748",
"Score": "1",
"body": "In the future, it'd be nice if you could post this as two separate questions: One about the Scheme implementation, and one about the the JS (and link from one to the other, for those interested)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:37:10.910",
"Id": "81763",
"Score": "0",
"body": "@Flambino Thanks, you're probably right. In some ways the question was about if I'd properly understood the differences in the algorithm caused by design constraints of the two languages. I thought that separating them out into different questions would have made it difficult to ask for that kind of feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:39:45.140",
"Id": "81764",
"Score": "0",
"body": "I could also do with some feedback confirming that the algorithm I'm implemented is actually foldr like I think (and not foldl), I'm not 100% on that. Either way, the code works, so it belongs on code review and not SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:47:07.867",
"Id": "81766",
"Score": "0",
"body": "Yeah, I can understand that you'd like to contrast and compare the two implementations - unfortunately, I don't know enough scheme :-/ And you're right: This is actually a _leftward_ fold, not `foldr`. I'll update my answer :)"
}
] | [
{
"body": "<p>I can only speak to the JS code - which looks pretty good, by the way... except:</p>\n\n<p><em>You're modifying the array you're folding.</em> In fact, you're truncating it completely due to your use of <code>shift</code>. So your function has destructive side-effects. After the fold, you have your answer, but you've lost the question, so to speak.</p>\n\n<p>I.e.,</p>\n\n<pre><code>var question = [2, 3, 7];\nvar answer = foldr(function (a, b) { return a * b; }, 0, input);\n\nconsole.log(answer); // => 42\nconsole.log(question); // => [] ... oops\n</code></pre>\n\n<p>Hence it'd be better to do something like this, using <code>slice(1)</code> to get a copy of the array starting from index 1:</p>\n\n<pre><code>function foldl(func, initial, collection) { // not foldr (see below)\n if (collection.length === 0) {\n return initial;\n }\n initial = func(initial, collection[0]);\n return foldl(func, initial, collection.slice(1));\n}\n</code></pre>\n\n<p>By the way: You'll see I've removed the semicolon after the <code>if</code> block - it's not necessary (JS just ignores it, as it does the semicolon after the function body). But I've <em>inserted</em> a semicolon after <code>return initial</code> inside the block. That semicolon isn't strictly necessary either, since JS will see the close-brace following it, and insert its own semicolon. But better to do it properly yourself.</p>\n\n<p>You could also write the condition as simply <code>if (!collection.length)</code>, and it could be considered idiomatic. But I prefer your current - strict and explicit - condition myself.</p>\n\n<p>Lastly, I'd prefer the Node.js style of placing function arguments at the end, like <code>foldr(initial, collection, func)</code> only because it avoids the dangling arguments after an inline function. On the other hand, JavaScript itself favors putting function arguments first, as in the built-in <code>Array.prototype.reduce</code> function... it's a tough call (no pun intended).</p>\n\n<hr>\n\n<p>Update: I hadn't even noticed, until I read your comment above, but yes, your function is actually <code>foldl</code>, not <code>foldr</code>. You're reducing the array from first to last (i.e. from the left). So the first value passed to <code>func</code> is the first element in the array. A <code>foldr</code> function would pass the values in reverse order. A real <code>foldr</code> function could be:</p>\n\n<pre><code>function foldr(func, initial, collection) { // for real this time\n if( collection.length > 1) {\n initial = foldr(func, initial, collection.slice(1));\n }\n return func(initial, collection[0]);\n}\n</code></pre>\n\n<p>You can check the behavior like this:</p>\n\n<pre><code>var func = function (memo, value) {\n memo.push(value);\n return memo;\n};\n\nfoldl(func, [], [1, 2, 3, 4]); // => [1, 2, 3, 4]\nfoldr(func, [], [1, 2, 3, 4]); // => [4, 3, 2, 1] (reversed!)\n</code></pre>\n\n<hr>\n\n<p>Update 2: While I'm at it, here's a more memory efficient solution, that doesn't use <code>slice</code> and thus doesn't create <em>n</em>-1 arrays along the way. A similar technique can be used for <code>foldl</code></p>\n\n<pre><code>function foldr(func, memo, collection) {\n var l = collection.length - 1;\n function fold(offset) {\n if( offset < l ) {\n memo = fold(offset + 1);\n }\n return func(memo, collection[offset]);\n }\n return fold(0);\n}\n</code></pre>\n\n<p>Of course, neither this nor the functions above actually check whether the input array is empty (of if it's even an array)... not that that's terribly difficult to do, but I've complicated things enough already, I think :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:33:53.743",
"Id": "81761",
"Score": "0",
"body": "Thanks, that's really useful feedback. I hadn't thought about using array.slice, but now you mention it, it's blindingly obvious. I did think about putting the function argument at the end, but decided that since in the nodejs style that usually denotes a callback, and this isn't one, it was better to go with the the standard order to avoid \"confusion by convention\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:21:22.487",
"Id": "81769",
"Score": "0",
"body": "@Racheet It's true that in Node it's most often callbacks that go at the end, but that's because there are _a lot_ of callbacks in Node :) Anyway, \"callback\" doesn't have to mean \"function to call exactly once, when we're done\", it can just mean \"a function to call\". In the case of a fold, it'll be called _n_ times along the way. Also, I've updated my answer re: foldr vs foldl"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:18:27.427",
"Id": "46732",
"ParentId": "46729",
"Score": "8"
}
},
{
"body": "<p>Speaking for Scheme over here; looks pretty good. I have precisely three aesthetic quibbles, but you got the essence. Also, whether by accident or intention, you aren't doing the Scheme version destructively, so the comments Flambino had for your JS version don't apply here.</p>\n\n<ol>\n<li>The base case in a <code>list</code> recursion is usually expressed as <code>(null? foo)</code> rather than <code>(not (pair? foo))</code></li>\n<li>You can use word-separators to keep names more readable (I'd have named this one <code>fold-left</code> myself).</li>\n<li>Most implementations I've seen use the name <code>memo</code> where you have <code>initial</code>. I think it's mildly more appropriate, since by the time you've called your first recursion, it contains the previous result rather than the initial value.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:27:03.627",
"Id": "81770",
"Score": "0",
"body": "Good point about `initial` vs `memo`. I was looking at that myself, but didn't change it (oddly, I used `memo` in an example, though, without even thinking about it)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:12:00.960",
"Id": "46735",
"ParentId": "46729",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46732",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T14:52:07.390",
"Id": "46729",
"Score": "7",
"Tags": [
"javascript",
"scheme",
"sicp",
"higher-order-functions"
],
"Title": "My first accumulators"
} | 46729 |
<p>This is my first attempt at a jQuery plugin, which is a simple modal window. I'm keen for feedback of whether I've got the principle correct, the usability of the plugin and any improvements that could be made.</p>
<p>Here is a working <a href="http://jsbin.com/bagiqaru/3" rel="nofollow">JSBin</a>.</p>
<p><strong>The plugin instructions:</strong> </p>
<ol>
<li><p>Add one or more elements that will launch a modal when clicked. Give these a class of modal-open.</p></li>
<li><p>Add elements to display in the modal window. These should go in a <code></div></code> with <code>class="overlay-message hide"</code>. and the <code>div</code> needs an <code>id</code>.</p></li>
<li><p>Add a data-target attribute to the modal-open element(s) made in 1. The value of this should be the same as the id of the overlay-message element made in 2.</p></li>
<li><p>Add links to jQuery, overlay.js and overlay.css</p></li>
<li><p>Call <code>$('.modal-open').modalise()</code></p></li>
</ol>
<p><strong>The JS code:</strong></p>
<pre class="lang-js prettyprint-override"><code>(function ( $ ) {
$.fn.modalise = function( options ) {
// Add and initialise the overlay background
$('body').append('<div class="overlay modal-close hide"></div>');
$('.modal-close').on('click',function(){
$('.overlay').toggleClass("hide");
$('.overlay-message').addClass("hide");
console.log('clicked');
});
// Options for the plugin
var settings = $.extend({
// Default options
width: "700px",
closeButton: true
}, options );
return this.each(function(index){
// Dom elements
var openButton = $(this),
targetSelector = '#' + $(this).attr('data-target');
// Add and initiate close button
if(settings.closeButton){
$(targetSelector).prepend('<a href="#" class="modal-close btn">X</a>').find('.modal-close').on('click',function(){
$('.overlay').addClass("hide");
$('.overlay-message').addClass("hide");
});
}
// Show the relevant modal window on clicking the open button
openButton.on('click',function(){
var targetSelector = '#' + $(this).attr('data-target');
$(targetSelector + ', .overlay').toggleClass("hide");
});
});
};
}( jQuery ));
</code></pre>
<p><strong>The CSS code:</strong></p>
<pre class="lang-css prettyprint-override"><code>.overlay{
width: 100%;
height: 100%;
background: #000000;
filter: alpha(opacity=80);
background: rgba(0,0,0,0.8);
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1000;
}
.overlay-message{
padding: 20px;
background: white;
position: absolute;
width: 660px;
left: 50%;
margin-left: -350px;
top: 10%;
z-index: 10000;
}
.hide{
display: none;
}
.modal-close.btn{
position: absolute;
right: 8px;
top: 5px;
color: black;
background: none;
text-decoration: none;
}
.modal-open{
cursor: pointer;
}
@media only screen and (max-width: 767px){
.overlay-message{
width: auto;
left: 5%;
right: 5%;
margin-left: 0;
}
}
</code></pre>
| [] | [
{
"body": "<p>To avoid a lot of issues in the future I can recommend writing your plugin in <code>\"use strict\";</code> mode. \nNext improvement could be using variables at the beginning of your function to make it faster and cache values. For instance: </p>\n\n<pre><code>$.fn.modalise = function( options ) {\n \"use strict\";\n\n var root = $(\".body\"),\n overlay = $(\".overlay\"),\n overlayMessage = $(\".overlay-message\"));\n\n [...]\n}(jQuery));\n</code></pre>\n\n<p>Because each time your plugin is called, JavaScript will search through the DOM for <code>$(\".body\")</code> and all other elements.</p>\n\n<p><strong>Edit:</strong>\nAnd you allready cached <code>$(this)</code>, why don't you use it?</p>\n\n<pre><code>return this.each(function(index){\n // Dom elements\n var openButton = $(this),\n targetSelector = '#' + openButton.attr('data-target'),\n closeModal\n\n // Add and initiate close button\n if(settings.closeButton){\n $(targetSelector).prepend('<a href=\"#\" class=\"modal-close btn\">X</a>').find('.modal-close').on('click',function(){\n overlay.addClass(\"hide\");\n overlayMessage.addClass(\"hide\"); \n });\n }\n</code></pre>\n\n<p>I guess there are some more improvements you could make. I'm just not an expert in writing own plugins :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:19:40.297",
"Id": "81836",
"Score": "0",
"body": "I can not see how html structure.however, in my opinion, when you defined root, then all other module's objects should use root.find() to find, not $()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:23:23.413",
"Id": "81840",
"Score": "0",
"body": "I missed that another element is overlay, however, overlay is should be only-one element for this module, so it may cache to store it and use the cache variable cross the this module object, rather than search it all the time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:14:21.100",
"Id": "81908",
"Score": "0",
"body": "Thanks for the feedback. Ive made some changes based on that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:33:03.497",
"Id": "81910",
"Score": "0",
"body": "You're welcome. Furthermore you could use [JSLint](http://jslint.com/) on your plugin which will analyse your code and display potential issues."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:41:44.653",
"Id": "46758",
"ParentId": "46737",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:46:19.173",
"Id": "46737",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"css",
"plugin"
],
"Title": "jQuery Modal Plugin"
} | 46737 |
<p>I made a C++ container of an ordered list of integers, that, in order to save space, I save as ranges:</p>
<p>For example, the list \$ \{1,2,3,5,6,7,8,9,20\} \$ is saved in memory as \$ \{(1,3), (5,9), (20,20)\} \$.</p>
<p>I have doubts of the iterator used to show all the numbers that are include on one list is right. Mainly because my iterator doesn't allow to modify elements on the container.</p>
<p>And in general, I wrote it in C++11.</p>
<pre><code>template<typename T,
typename = typename std::enable_if<std::is_integral<T>::value>::type>
class RangeListIterator; // undefined
template<typename T>
class RangeListIterator<T>{
public:
using value_type = T;
using RangeItem = std::pair< value_type, value_type >;
using RangeItemList = std::list<RangeItem>;
using RangeItem_iterator = typename RangeItemList::iterator;
RangeListIterator( RangeItem_iterator it, value_type val,
RangeItem_iterator itEnd );
bool operator!=( const RangeListIterator<T> & b ) const;
RangeListIterator& operator++();
RangeListIterator operator++( int );
const value_type& operator*() const;
private:
RangeItem_iterator m_listIt;
RangeItem_iterator m_listEnd;
value_type m_val;
};
template<typename T>
RangeListIterator<T>::RangeListIterator( RangeItem_iterator it,
value_type val,
RangeItem_iterator itEnd)
: m_listIt{ it }, m_listEnd{ itEnd }, m_val{ val }
{
// empty
}
template<typename T>
bool RangeListIterator<T>::operator!=( const RangeListIterator<T> & b ) const{
return (m_listIt != b.m_listIt) or (m_val != b.m_val);
}
template<typename T>
RangeListIterator<T>& RangeListIterator<T>::operator++() {
if( m_val == std::numeric_limits<T>::max() ){
++m_listIt;
m_val = 0;
}else{
++m_val;
if( m_val > m_listIt->second ){
++m_listIt;
if( m_listIt == m_listEnd ){
m_val = 0;
}else{
m_val = m_listIt->first;
}
}
}
return *this;
}
template<typename T>
RangeListIterator<T> RangeListIterator<T>::operator++( int ) {
auto temp = *this;
++*this;
return temp;
}
template<typename T>
const typename RangeListIterator<T>::value_type&
RangeListIterator<T>::operator*() const{
return m_val;
}
template<typename T,
typename = typename std::enable_if<std::is_integral<T>::value>::type>
class RangeList; // undefined
template<typename T>
class RangeList<T>{
public:
using value_type = T;
using RangeItem = std::pair< value_type, value_type >;
using RangeItemList = std::list<RangeItem>;
using RangeItem_iterator = typename RangeItemList::iterator;
using RangeItem_const_iterator = typename RangeItemList::const_iterator;
using iterator = RangeListIterator<T>;
void insert( const value_type val );
void remove( const value_type val );
bool contains( const value_type val ) const;
RangeItem_iterator beginItem();
RangeItem_const_iterator beginItem() const;
RangeItem_iterator endItem();
RangeItem_const_iterator endItem() const;
iterator begin();
iterator end();
private:
std::list<RangeItem> m_items;
};
template<typename T>
void RangeList<T>::insert( const T val ){
for( auto it = std::begin(m_items) ; it != std::end(m_items) ; ++it ){
if( val < it->first ){
if( val == (it->first - 1) ){
it->first = val;
}else{
m_items.emplace( it, std::make_pair( val, val ) );
}
return;
}else if( val <= it->second ){
return;
}else if( val == (it->second + 1) ){
auto next = std::next(it);
if( next != std::end(m_items) ){
if( (val >= next->first - 1) and (val <= next->second) ){
it->second = next->second;
m_items.erase( next );
return;
}
}
it->second = val;
return;
}
}
m_items.emplace_back( std::make_pair( val, val ) );
}
template<typename T>
void RangeList<T>::remove( const T val ){
for( auto it = std::begin(m_items) ; it != std::end(m_items) ; ++it ){
if( val >= it->first and val <= it->second ){
if( it->first == it->second ){
m_items.erase( it );
return;
}
if( val == it->first ){
it->first = it->first + 1;
return;
}
if( val == it->second ){
it->second = it->second - 1;
return;
}
m_items.emplace( it, std::make_pair( it->first, val - 1 ) );
it->first = val + 1;
return;
}
if( val < it->first ){
return;
}
}
}
template<typename T>
bool RangeList<T>::contains( const T val ) const{
for( const auto & it: m_items ){
auto rmin = it.first <= val;
if( rmin and (it.second >= val) ){
return true;
}
if( not rmin ){
return false;
}
}
return false;
}
template<typename T>
inline
typename RangeList<T>::RangeItem_iterator
RangeList<T>::beginItem(){
return m_items.begin();
}
template<typename T>
inline
typename RangeList<T>::RangeItem_const_iterator
RangeList<T>::beginItem() const{
return m_items.begin();
}
template<typename T>
inline
typename RangeList<T>::RangeItem_iterator
RangeList<T>::endItem(){
return m_items.end();
}
template<typename T>
inline
typename RangeList<T>::RangeItem_const_iterator
RangeList<T>::endItem() const{
return m_items.end();
}
template<typename T>
typename RangeList<T>::iterator
RangeList<T>::begin(){
auto listIt = std::begin(m_items);
return RangeListIterator<T>( listIt, listIt->first, std::end(m_items) );
}
template<typename T>
inline
typename RangeList<T>::iterator
RangeList<T>::end(){
return RangeListIterator<T>( std::end(m_items), 0, std::end(m_items) );
}
</code></pre>
<p>An example of use:</p>
<pre><code>RangeList<int> range;
range.insert( 1 );
range.insert( 2 );
range.insert( 4 );
range.insert( 7 );
range.insert( 8 );
range.insert( 6 );
for( int i = 0 ; i < 10 ; ++i ){
cout << " test " << i << " = " << range.contains(i) << endl;
}
for( auto it = range.beginItem() ; it != range.endItem() ; ++it ){
cout << " range (" << it->first << " , " << it->second << ")" << endl;
}
for( auto v: range ){
cout << " val " << v << endl;
}
RangeList<unsigned int> rangeu;
rangeu.insert( 4 );
rangeu.insert( 7 );
rangeu.insert( 1 );
rangeu.insert( 2 );
rangeu.insert( 0 );
rangeu.insert( -1 );
rangeu.insert( -2 );
rangeu.insert( 6 );
for( int i = 0 ; i < 10 ; ++i ){
cout << " test " << i << " " << rangeu.contains(i) << endl;
}
for( auto it = rangeu.beginItem() ; it != rangeu.endItem() ; ++it ){
cout << " range (" << it->first << " , " << it->second << ")" << endl;
}
for( auto v: rangeu ){
cout << " val " << v << endl;
}
return 0;
</code></pre>
<p><strong>UPDATED</strong>:</p>
<ol>
<li><p>Fixed insert. Now it merges two continuous ranges when you insert the element between them. E.g: \$ \{(1,3),(5,9)\} + insert(4) \$ generates \$ \{(1,9)\} \$.</p></li>
<li><p>Added <code>remove</code> method.</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:17:18.943",
"Id": "81785",
"Score": "1",
"body": "If the iterator is not there to change the contents of the container then just make it a const iterator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:32:36.790",
"Id": "81787",
"Score": "0",
"body": "You don't need the `inline` keywords, especially in a header file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:21:38.440",
"Id": "81811",
"Score": "0",
"body": "Also, I can think a way without saving the `end` on the iterator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:24:32.463",
"Id": "81812",
"Score": "0",
"body": "@Jamal I don't think so. Maybe you are thinking on definitions inside class declaration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:58:34.440",
"Id": "81813",
"Score": "0",
"body": "I think it may be easier to represent the list with ranges that don't include the length. ie. `{[1,4),[5,10),[20,21)}` I hope my math notation is correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:14:48.783",
"Id": "81901",
"Score": "0",
"body": "@LokiAstari, I don't see the benefit of use [n,m+1) ranges instead of [n,m] ones."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:01:47.963",
"Id": "81925",
"Score": "0",
"body": "I can see several efficient ways of solving the problem. What do you intend to do with the data structure, other than save space? In other words, what operations need to be fast?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:14:35.293",
"Id": "81930",
"Score": "0",
"body": "@mrm the most important operation is check when an element is inside the range."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:17:57.393",
"Id": "81932",
"Score": "0",
"body": "@Zhen Is there an upper bound for how large your integers to be stored are? For example, if you are storing ints, can the largest value you store be MAX_INT?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:02:37.437",
"Id": "81978",
"Score": "0",
"body": "@Zhen: Its not a big deal. Technically there will be very little difference (I can see a minor optimization when inserting new items to detect range expansions and another for range merges). But they are both minor. The main reason is to stay with a standard idiom used by C++ (in that `begin`->`end` is a range where `end` is one past the end of the range). A user not familiar with your code may expect you to be using standard C++ conventions and thus introduce bugs while doing maintenance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T08:32:53.360",
"Id": "82075",
"Score": "0",
"body": "I get your point @LokiAstari, but I see that you can insert(MAX_T) with open ranges [n,MAXT_T+1), you will need to check this case always or have an error."
}
] | [
{
"body": "<p>A fairly minor point, but I'm not a huge fan of using <code>enable_if</code> here. For example, if we declare a <code>RangeList<double></code>, we'll get the following as errors:</p>\n\n<blockquote>\n <p>range_iter.cpp: In function 'int main()':</p>\n \n <p>range_iter.cpp:53:21: error: no type named 'type' in 'struct std::enable_if'\n RangeList double_range;</p>\n \n <p>range_iter.cpp:53:21: error: template argument 2 is invalid</p>\n \n <p>range_iter.cpp:53:35: error: invalid type in declaration before ';' token\n RangeList double_range;</p>\n</blockquote>\n\n<p>This also requires adding \"clutter\" like:</p>\n\n<pre><code>template<typename T,\n typename = typename std::enable_if<std::is_integral<T>::value>::type>\nclass RangeListIterator; // undefined\n\ntemplate<typename T,\n typename = typename std::enable_if<std::is_integral<T>::value>::type>\nclass RangeList; // undefined\n</code></pre>\n\n<p>Instead, I'd rather just use a <code>static_assert</code> at the top of each class:</p>\n\n<pre><code>static_assert(std::is_integral<T>::value, \"T must be an integral type!\");\n</code></pre>\n\n<p>This has the benefit of cutting down on the above clutter, as well as giving nicer compiler error messages:</p>\n\n<blockquote>\n <p>range_iter.hpp: In instantiation of 'class RangeList':</p>\n \n <p>range_iter.cpp:53:23: required from here</p>\n \n <p>range_iter.hpp:92:5: error: static assertion failed: T must be an integral type!\n static_assert(std::is_integral::value, \"T must be an integral type!\");</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:18:00.967",
"Id": "81902",
"Score": "0",
"body": "Great, I like it,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:24:45.917",
"Id": "46769",
"ParentId": "46739",
"Score": "5"
}
},
{
"body": "<p>Depending on your setting, a bitvector might be a <em>much</em> better idea (or <em>much</em> worse!). This depends on how sparse your ranges actually are. The following might give you some ideas, and perhaps you might want to incorporate it into your data structure, and use some method to change the internal representation if needed.</p>\n\n<pre><code>const static std::size_t S = 128; \nstd::bitset<S> range; // We can now store 128 values using only 128 bits\n\n// Is 5 present?\nbool five = range.test(4);\n</code></pre>\n\n<p>... and so on. You can support many operations in constant time. If you know how large S can be beforehand, great. If not, use a dynamic variant, such as boost::dynamic_bitset.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:34:52.303",
"Id": "81944",
"Score": "0",
"body": "Good to know I can use bitset, but in my problem the number of elements are thousands to hundreds of thousands, and fairly dense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:39:55.397",
"Id": "46811",
"ParentId": "46739",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46769",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:10:16.133",
"Id": "46739",
"Score": "8",
"Tags": [
"c++",
"c++11",
"integer",
"container",
"interval"
],
"Title": "Container for list of ranges"
} | 46739 |
<p>As the title says, the objective is to free a binary tree without using the stack or allocating memory.<br>
This was required for a kernel module where resources were limited.</p>
<p>Result has a complexity of \$ O \left( n \right) \$.</p>
<pre><code>template<typename T>
struct Node
{
T data;
Node* left;
Node* right;
};
// Utility function to find the bottom left
// Of the tree (because that has a NULL left
// pointer that we can use to store information.
Node* findBottomLeft(Node* t)
{
while(t->left != NULL)
{
t = t->left;
}
return t;
}
void freeTree(Node* t)
{
if (t == NULL)
{ return;
}
// Points at the bottom left node.
// Any right nodes are added to the bottom left as we go down
// this progressively flattens the tree into a list as we go.
Node* bottomLeft = findBottomLeft(t);
while(t != NULL)
{
// Technically we don't need the if (it works fine without)
// But it makes the code easier to reason about with it here.
if (t->right != NULL)
{
bottomLeft->left = t->right;
bottomLeft = findBottomLeft(bottomLeft);
}
// Now just free the curent node
Node* old = t;
t = t->left;
delete old;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:58:59.693",
"Id": "81788",
"Score": "0",
"body": "This looks mostly C-ish. Using `unique_ptr` and the like would be more idiomatic and exception safe, but as you are in a kernel environment, exceptions are not allowed and your recursion requirement rules out the use of `unique_ptr`. (Then again I am wondering why you are programming C++ in the (supposedly Linux-)kernel)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:59:59.727",
"Id": "81789",
"Score": "1",
"body": "@Nobody: You missed the point. using unique_ptr would break the whole concept of not using recursion. Who said Linux and this kernal supports exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:02:56.313",
"Id": "81790",
"Score": "1",
"body": "That is just what I said :) I just wanted to point out that without these restrictions that would be the path to follow. Hence, I made it only a comment and not an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:00:26.983",
"Id": "81924",
"Score": "0",
"body": "I can't understand what the question is. Can you make it explicit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:59:39.527",
"Id": "81947",
"Score": "0",
"body": "I like it as it is. And it's already O(n), so you can't get better than that for this. Quick note though, this doesn't compile on Visual Studio 2012, but I doubt that portability is all that important to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-21T23:17:38.980",
"Id": "123067",
"Score": "0",
"body": "Actually I was first shown this code on the core of the Windows kernel so I should have written it to be portable. Where is it breaking."
}
] | [
{
"body": "<h1>function missing templates</h1>\n\n<p>I'm sure you're aware, but the functions need the same templating as the <code>Node</code> such that <code>void freeTree(Node* t)</code> becomes:</p>\n\n<pre><code>template<typename T>\nvoid freeTree(Node<T>* t)\n</code></pre>\n\n<h1>slight reduction in memory use</h1>\n\n<p>You could slightly reduce the stack used by essentially inlining the function call to <code>findBottomLeft</code>. The rewritten function now looks like this:</p>\n\n<pre><code>template<typename T>\nvoid freeTree(Node<T>* t)\n{\n // bl points at the bottom left node.\n // Any right nodes from t are added to the bottom left as we go down.\n // This progressively flattens the tree into a list as we go. \n Node<T> *bl;\n for(bl=t ; bl != nullptr && bl->left != nullptr; bl=bl->left);\n\n while(t != nullptr)\n {\n // body of for loop deliberately empty\n for (bl->left = t->right; bl != nullptr && bl->left != nullptr; bl=bl->left);\n Node<T>* old = t;\n // Now just free the curent node\n t = t->left;\n delete old;\n }\n}\n</code></pre>\n\n<p>Note that I'm using <code>nullptr</code> rather than <code>NULL</code> here which is a C++11 feature. If you're not using a C++11 compliant compiler, you can simply use <code>NULL</code> for each of those instances.</p>\n\n<p>Also, I've eliminated the early return in the case that <code>t</code> was equal to <code>NULL</code> in the original because this case is handled correctly by the <code>for</code> loop and <code>while</code> loop.</p>\n\n<p>It's also important to realize that the body of the for loop is deliberately empty. Some people dislike having a <code>for</code> loop with just a semicolon at the end, but I think it's not a problem if there is a comment pointing it out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:54:12.127",
"Id": "81976",
"Score": "0",
"body": "Comment is correct. The call to `findBottomLeft()` is not going to de-refernece a NULL if t->right is NULL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:54:52.220",
"Id": "81977",
"Score": "0",
"body": "inlining is a job for the compiler. As a human my job is to write easy to read code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T16:15:31.610",
"Id": "90020",
"Score": "0",
"body": "The test `bl != nullptr` should be removed from the loop / inner-loop again, and replaced by the test `t != nullptr` found at the start of the function in the original, for best performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T17:18:30.367",
"Id": "90042",
"Score": "0",
"body": "A nice way to get around the empty `for` loop is to use `continue` as the loop body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T17:40:03.663",
"Id": "90049",
"Score": "0",
"body": "@RolandIllig: Some coding standards forbid the use of `continue`, but there's nothing technically wrong with your suggestion in this instance."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:26:56.923",
"Id": "46822",
"ParentId": "46740",
"Score": "6"
}
},
{
"body": "<p>If I understand your question correctly, you could build your tree using <code>std::map</code>, <code>std::set</code> or Boost graph library. They have allocators which you could use to allocate from a single pre-allocated block of memory. Your non-recursive free then becomes simply freeing the pre-allocated block. I'm not saying this is a simple approach nor the best for general work but maybe it meets your requirements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T15:41:34.183",
"Id": "90009",
"Score": "0",
"body": "While this sounds like a good suggestion, I feel like your answer is missing something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T16:25:49.140",
"Id": "90023",
"Score": "0",
"body": "This sounds like a good response but I think maybe it is missing a description of what my answer is missing. Or have I missed your point?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T16:34:57.237",
"Id": "90028",
"Score": "0",
"body": "It is missing a description of what is missing because I just have a general feeling. I would suggest some code, but It could be just noise. I have no clear idea of what you could do, I was just trying to \"warn\" you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T15:00:35.503",
"Id": "52003",
"ParentId": "46740",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46822",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:45:45.777",
"Id": "46740",
"Score": "14",
"Tags": [
"c++",
"memory-management",
"tree",
"kernel"
],
"Title": "Free a binary tree without using recursion or allocating memory"
} | 46740 |
<p>I have this code below for autocomplete feature of several inputTextbox. The input box also share same class".wikiInput". When user typed something in either of them, a relevant autocomplete dropdown box should show up. Instead of hard code one by one. How do I optimize them into a simpler format. Note the <strong>lookup</strong> has different arrays.</p>
<pre><code>(function () {
var cdTeamInput = $("#ctl00_ContentPlaceHolder1_txtAssociation");
if (cdTeamInput.length > 0) {
cdTeamInput.autocomplete({
deferRequestBy: 0,
autoSelectFirst: true,
lookup: txtAssociation,
onSelect: function (value, data) {
cdTeamInput.val(value.value);
$(".wikiSubmit").click();
}
});
}
})();
(function () {
var cdSubjectInput = $("#ctl00_ContentPlaceHolder1_txtSubject");
if (cdSubjectInput.length > 0) {
cdSubjectInput.autocomplete({
deferRequestBy: 0,
autoSelectFirst: true,
lookup: txtSubject,
onSelect: function (value, data) {
cdSubjectInput.val(value.value);
$(".wikiSubmit").click();
}
});
}
})();
</code></pre>
<p><strong>Update:</strong> I really like user2734550's first answer. however, the lookup array will be undefined in cross page situation. Like one of the page have only one lookup array but don't have others. so js file would be broken. How do I avoid this problem? Seems like if lookup.length > 0 statement doesn't work. </p>
| [] | [
{
"body": "<p>Quick answer: Use arguments.</p>\n\n<pre><code>function initAutocomplete(selector, lookup) {\n $(selector).autocomplete({\n deferRequestBy: 0,\n autoSelectFirst: true,\n lookup: lookup,\n onSelect: function (value, data) {\n cdSubjectInput.val(value.value);\n $(\".wikiSubmit\").click();\n }\n });\n}\n\ninitAutocomplete(\"#ctl00_ContentPlaceHolder1_txtAssociation\", txtAssociation);\ninitAutocomplete(\"#ctl00_ContentPlaceHolder1_txtSubject\", txtSubject);\n</code></pre>\n\n<p>Of course, it might be nice to decouple the markup and the code some more. Depending on how the lookup lists (their length and contents), you could do something like this in your HTML:</p>\n\n<pre><code><input data-lookup=\"foo,bar,baz\" ...>\n</code></pre>\n\n<p>and init every autocompleting input on the page in one go with:</p>\n\n<pre><code>$(\"input[data-lookup]\").each(function () {\n var input = $(this),\n lookup = input.data(\"lookup\").split(\",\"); // get the lookup strings\n\n input.autocomplete({\n deferRequestBy: 0,\n autoSelectFirst: true,\n lookup: lookup,\n onSelect: function (value, data) {\n cdSubjectInput.val(value.value);\n $(\".wikiSubmit\").click();\n }\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:29:35.597",
"Id": "81816",
"Score": "0",
"body": "I didn't mention the autocomplete are for cross page inputs. so not every single page shows all lookup arrays. Hence it keeps saying lookup is undefined in console even I specify"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:30:23.097",
"Id": "81817",
"Score": "0",
"body": "(connect from above) if (selector.length > 0) { $(selector).autocomplete({ }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:30:24.807",
"Id": "81888",
"Score": "0",
"body": "@user2734550 In that case, you need to check the lookup arrays - not the inputs. `$(...).length > 0` will just check whether you found an input (and you don't need to check that; if there are no inputs, nothing happens), but it doesn't say whether some other variable - like the lookup array - exists. In any case: If the code doesn't work, it belongs on StackOverflow. Code Review is for working code only, I'm afraid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:44:33.253",
"Id": "81968",
"Score": "0",
"body": "lets say a,b,c each obj returns serious of array. a,b data is retried in page 1, c (no a&b)is returned at page 2. Simply checking .length won't work. I think $.each loop function should be used. I just don't know how to use loop in this case. Wish there is a transfer btn to StackOverflow..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:53:54.467",
"Id": "46745",
"ParentId": "46742",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:11:27.923",
"Id": "46742",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"jquery",
"array"
],
"Title": "Optimize jQuery code includes autocomplete function for different input box with different autocomplete content"
} | 46742 |
<p>I am trying a stack implementation using an array. I want to know if this approach is OK or if there is a logical problem. This program is working fine.</p>
<pre><code>#include <stdio.h>
#define MAXSIZE 5
struct stack /* Structure definition for stack */
{
int stk[MAXSIZE];
int top;
} s;
void push ();
void pop();
void display ();
void search();
int main(){
int element, choice;
s.top = -1;
clrscr();
while (1)
{
printf ("------------------------------------------\n");
printf ("1. PUSH\n");
printf ("2. POP\n");
printf ("3. DISPLAY\n");
printf ("4. SEARCH\n");
printf ("5. EXIT\n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: search();
break;
case 5: return;
}
}
}
/*Function to add an element to the stack*/
void push() {
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Error: Overflow\n");
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
}
/*Function to delete an element from the stack*/
void pop ()
{
int num;
if (s.top == - 1)
{
printf ("Error: Stack Empty\n");
}
else
{
num = s.stk[s.top];
printf ("poped element is = %d\n", num);
s.top = s.top - 1;
}
}
/*Function to display the status of the stack*/
void display()
{
int i;
if (s.top == -1)
{
printf ("Error: Stack Empty\n");
}
else
{
printf ("\nItems in Stack\n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}
void search(){
int i;
int num;
int counter=0;
if (s.top == -1)
{
printf ("Error: Stack Empty\n");
}
else
{
printf ("Enter the element to be searched\n");
scanf ("%d", &num);
for (i = s.top; i >= 0; i--)
{
if(num==s.stk[i]) {
counter++;
break;
}
}
if(counter>0){
printf ("Element %d found in stack\n", num);
}
else {
printf ("Element %d not found in stack\n", num);
}
}
printf ("\n");
}
</code></pre>
| [] | [
{
"body": "<p>There is no <em>logical</em> issue to what you are doing, as indeed that is a stack and does what a stack needs to do. </p>\n\n<p>One thing you may want to consider though is that a fixed size array is typically not the manner in which stacks are implemented. For as to why, consider the case where your stack is full and you want to push more things too it. A costly solution would by to allocate a new array of greater size, and copy all values over. Moreover, what if all elements of the stack are popped off after allocating a huge space for it? The array is still allocated in full in memory. </p>\n\n<p>To avoid these problem, a <a href=\"https://en.wikipedia.org/wiki/Linked_list\">Linked List</a> is generally used instead. It allows for removals and insertions from the front and back in constant time, and is only as large as necessary. Link Lists also make a good project in general when learning C.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:19:40.340",
"Id": "81874",
"Score": "0",
"body": "Using an array and resizing it as necessarily is usually faster in practice, even though it sounds worse. Linked lists require more memory allocations, which are slow, and cause the cache to perform worse (because the memory isn't close together)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:08:42.550",
"Id": "81916",
"Score": "0",
"body": "True, not being contiguous in memory is a significant blow against linked lists as it generally yields to poor locality of reference (and hence cache missing), but for the purposes of pedagogy I am inclined towards them. They allow novice programmers to appreciate the notion (at least conceptually) of Big-O and how data may be given structure in code, which is later useful in understanding more complex structures such as trees. This is all a matter of preference admittedly, but it is worth explicating."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:57:47.510",
"Id": "46753",
"ParentId": "46748",
"Score": "5"
}
},
{
"body": "<p>Much can be improved here, but I'll mention several things:</p>\n\n<ul>\n<li><p>Everything within <code>main()</code> should be indented, just as you've already done with the other functions. Otherwise, it's hard to tell where it starts and what's in it.</p>\n\n<p>Maintain consistency throughout your program. These little things do matter.</p></li>\n<li><p>You could eliminate the function prototypes by declaring <code>main()</code> lastly. In this way, <code>main()</code> will already be aware of the other functions when calling them.</p></li>\n<li><p>Your stack would be more usable if it were dynamic as opposed to static. If it's dynamic, you can keep pushing elements without worrying about reaching a limit. But if you stay with static, you'll have to check for a full stack when pushing, otherwise you'll run into problems.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c/252810#252810\">In C, use a <code>typedef</code> with <code>struct</code> so that you don't have to type <code>struct</code> elsewhere.</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/a/2454491/1950231\">Use <code>puts()</code> instead of <code>printf()</code> when outputting an <em>unformatted</em> line with a newline</a>. This would apply to your menu item output.</p></li>\n<li><p>I would refrain from having output in <code>push()</code> and <code>pop()</code>. They should only perform their primary purposes, while the testing output should just be done in the calling code.</p>\n\n<p><code>display()</code> <em>really</em> shouldn't display anything if the stack is empty. Just <code>return</code> early if it is.</p></li>\n<li><p><code>push()</code> is doing too much; it's asking for a value <em>and</em> pushing the value. It should just be doing the latter after receiving a value as an argument from the calling code.</p></li>\n<li><p><code>search()</code> is also doing too much; it's asking for a value <em>and</em> searching for it.</p>\n\n<p>It should also not display any messages (again, this all goes in the calling code) and it should return a <code>bool</code>. If the stack is empty (check for this first), simply return <code>false</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:24:37.883",
"Id": "46755",
"ParentId": "46748",
"Score": "6"
}
},
{
"body": "<h1>sscanf is not safe</h1>\n\n<p>It's not part of your stack but part of your driver code, but <code>scanf()</code> is not a good function to use. There are <a href=\"http://c-faq.com/stdio/scanfprobs.html\">many reasons</a> for this, but the basic problem in this case is that if the user enters a letter rather than a digit for input in <code>push()</code> for example, the program will loop forever.</p>\n\n<p>Better, in this case, would be to use something like <code>getchar()</code>.</p>\n\n<h1>separate stack operations from input/output</h1>\n\n<p>Having a function like <code>push()</code> only do one thing (pushing an item to the stack) is generally better design because it makes it easier to re-use your code. In this code, <code>push()</code> cannot be easily re-used because it is tied directly to user I/O. Better would be to cleanly separate all stack operations from the I/O to better foster re-use.</p>\n\n<h1>operations should operate on passed parameters</h1>\n\n<p>In this code, there can only be one stack because it's globally defined and used by all stack operation functions. A better scheme would be to pass the address of the stack structure to each function to make it more flexible and more general. </p>\n\n<p>Additionally, a function like <code>push()</code> should also require an argument that speccifies what is to be pushed onto the stack, and a function like <code>pop()</code> should return either a copy of or a pointer to the data item that was popped from the stack.</p>\n\n<h1>use C idioms to make the code shorter and easier to read</h1>\n\n<p>Writing code such as </p>\n\n<pre><code>s.top = s.top + 1;\ns.stk[s.top] = num;\n</code></pre>\n\n<p>is not incorrect, but is not idiomatic C. The C way of writing that would be </p>\n\n<pre><code>s.stk[++s.top] = num;\n</code></pre>\n\n<p>Writing code in this way will make it easier for others to understand you, in the same way that speaking, say, idiomatic Italian will make it easier for native Italian speakers to understand you.</p>\n\n<h1>avoid non-portable code</h1>\n\n<p>The <code>clrscr()</code> call is not in <code><stdio.h></code> and is not portable. I had to comment out that line to get the code to compile and run. Ideally, you'd avoid all non-portable code. If you can't avoid that, however, you should state what dependencies the code has and also include the header files that clearly indicate those dependencies.</p>\n\n<h1>think about the user of your code</h1>\n\n<p>It's good that you avoided using \"magic numbers\" and instead you wisely chose to define <code>MAXSIZE</code> to indicate the size of your stack. However, it would be useful to have a comment indicating what it's for, and also to maybe rename it to something a little more descriptive, such as <code>MAXSTACKSIZE</code>. </p>\n\n<h1>avoid single-letter variable names</h1>\n\n<p>While <code>i</code> or <code>j</code> might be perfectly fine variable names for looping indexes, naming your stack <code>s</code> is not very user-friendly. We are long beyond the days that each line of code had to fit on an 80-character punch card!</p>\n\n<p>I hope these items inspire you to write more code, and to strive to continuously improve the quality of the code that you write. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:41:51.603",
"Id": "81891",
"Score": "0",
"body": "`s.stk[s.top++] = num;` and `s.top += 1; s.stk[s.top] = num;` are not the same thing, though. I take it you meant `s.stk[++s.top] = num;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:45:04.003",
"Id": "81895",
"Score": "0",
"body": "@EliasVanOotegem I proposed that edit already. It's in the queue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:52:02.953",
"Id": "81897",
"Score": "0",
"body": "@BrianGordon: I've noticed, and I approved the edit, probably while you were commenting :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T23:35:16.750",
"Id": "46764",
"ParentId": "46748",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "46764",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:16:27.970",
"Id": "46748",
"Score": "7",
"Tags": [
"c",
"array",
"stack"
],
"Title": "Stack implementation using an array"
} | 46748 |
<p>I have two statements that look like this: </p>
<pre><code>$('table tr td:nth-child(' + columnNumber + ')').toggle();
$('table tr th:nth-child(' + columnNumber + ')').toggle();
</code></pre>
<p>Is there a way to combine these two statements? </p>
| [] | [
{
"body": "<p>A comma.</p>\n\n<pre><code>$('table tr td:nth-child(' + rowNumber + '), table tr th:nth-child(' + rowNumber + ')').toggle();\n</code></pre>\n\n<p>jQuery's selectors are the same as CSS (with some stuff added here and there), so all the usual CSS selector rules apply:</p>\n\n<pre><code>$(\"div, h1\") // select div and h1 elements\n$(\"div h1\") // select h1 elements that are nested somewhere within a div\n$(\"div > h1\") // select h1 elements that are direct descendants of a div\n</code></pre>\n\n<p>Etc.</p>\n\n<p>By the way, <code>rowNumber</code> doesn't make sense; the code will select a given <em>column</em>, not a row.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:25:32.003",
"Id": "46750",
"ParentId": "46749",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46750",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:18:32.083",
"Id": "46749",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "consolidate table td and th query"
} | 46749 |
<p>I was <a href="https://stackoverflow.com/questions/22949027/nested-replace-js/22949369">inspired</a> to write a BBCode to HTML converter as I'm currently learning functional programming. I wanted achieve functional cohesion. <a href="http://jsfiddle.net/kN3nD/4/" rel="nofollow noreferrer"><strong>jsFiddle</strong></a></p>
<p>I'd like feedback on:</p>
<ul>
<li>structuring of the code. Should the functions <code>getHtmlTag</code> and <code>getHtml</code> be contained within <code>bbTagToHtmlTag</code> since they are coupled through the <code>rules</code> variable?</li>
<li>any regex expressions that can reduce the code base</li>
<li>any changes to the data model to reduce complexity</li>
</ul>
<p>Below is the newer version of the code. This version is slightly less coupled compared to the <a href="http://jsfiddle.net/kN3nD/" rel="nofollow noreferrer">original version</a> and the functions are separated to allow for more reuse. This new version doesn't involve any recursion, so it may be more efficient. </p>
<p>I suspect the cost of reuse is an increase in code base. Although, I'm sure there's more regex magic that can be used to slim down the code base.</p>
<pre><code>/* Escapes a string for use with regular expressions */
function escapeString(input) {
return input.replace(/([\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,
function(c){return "\\" + c;});
}
/* replaces all */
function replaceAll(search, input, replacement, ignore) {
return input.replace(
new RegExp(escapeString(search), "g"+(ignore?"i":"")),
replacement);
};
/* Check if an index is event */
function isIndexEven(val, index, context) {
return (index % 2 === 0);
};
/* Sets the attributes on an HTML string given a set of attributes */
function setHtmlAttrs(htmlCode, attrs) {
return attrs.reduce(function(htmlCode, attr, index) {
var re = new RegExp('\\$' + (index + 1), 'g');
return htmlCode.replace(re, attr);
}, htmlCode);
};
/* Gets the html tag(s) for a bbCode tag */
function eleFragsToHtml(isClosing, elementFragments) {
return '<' + elementFragments.map(function(frag) {
return (isClosing ? '/' + frag.join(' ') : frag.join(' '));
}).join('><') + '>';
};
/* Converts a single bbCode Tag to Html */
function bbTagToHtmlTag(rules, tag) {
var attrs = tag.replace(/\[\w+|\]/g, '').trim().split(' ');
var key = tag.replace(/\[\/?| .+|\]/g, '');
var isClosing = /\//.test(tag);
var htmlTemplate = (isClosing ? rules[key].map(function(rule) {
return rule.filter(isIndexEven)
}).reverse()
: rules[key]);
var output = eleFragsToHtml(isClosing, htmlTemplate);
return setHtmlAttrs(output, attrs);
};
/* Converts bbCode to HTML */
function bbCodeToHtml(rules, bbCode) {
/* Creates the Regular Expression Search */
var regex = new RegExp( ['\\[.?[',
Object.keys(rules).join('|'),
'].*?\\]'].join(''), 'g' );
return bbCode.match(regex)
.reduce(function(htmlCode, tag) {
return replaceAll(tag,
htmlCode,
bbTagToHtmlTag(rules, tag));
}, bbCode);
};
</code></pre>
<p>Below is the test setup using the same rule set as the <a href="https://stackoverflow.com/questions/22949027/nested-replace-js/22949369">linked</a> post.</p>
<pre><code>var rules = {
'b': [ ['strong'] ],
'bg': [ ['span', 'style\"background-color:$1\"'] ],
'big': [ ['span', 'style=\"font-size: larger;\"'] ],
'c': [ ['span', 'style=\"color:$1\"'] ],
'f': [ ['span', 'style=\"font-family:$1\"'] ],
'i': [ ['em'] ],
'img': [ ['a', 'href=\"$1\"'],
['img', 'src=\"$1\" style=\"max-height: 200px; max-width: 200px;\"'] ],
'p': [ ['pre'] ],
'small': [ ['small'] ],
's': [ ['span', 'style=\"text-decoration: line-through;\"'] ]
};
var sample = '[big][big][c red]WARNING[/c][/big][/big][s]test[/s][img test.jpg][/img]';
$('#console').text(bbCodeToHtml(rules, sample));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T22:13:27.277",
"Id": "81829",
"Score": "0",
"body": "Just had a thought, if this is converting a long string of bbCode, it would have to recurse many times. However, if I recurse over the ruleSets, it would only recurse by the number of rules. Going to give that a go. It'll probably make for cleaner code anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:34:39.373",
"Id": "82113",
"Score": "0",
"body": "Newer version looks much much better, however your fiddle no longer works, care to update it ? Your fiddle would be more impressive if you did `$('console').html(bbCodeToHtml(rules, sample));` by the way"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:47:34.037",
"Id": "82165",
"Score": "0",
"body": "@konijn Thanks! Updated the link and the code."
}
] | [
{
"body": "<ol>\n<li><p>Overall, it's interesting, but quite hard to read. The indentation is kinda funky, and it would be easier to parse with all those ternary branches. For instance, this:</p>\n\n<pre><code>var htmlTemplate = (isClosing ? rules[key].map(function(rule) { \n return rule.filter(isIndexEven)\n }).reverse()\n : rules[key]);\n</code></pre>\n\n<p>Could be</p>\n\n<pre><code>var htmlTemplate = rules[key];\nif (isClosing) {\n htmlTemplate = htmlTemplate.map(function (rule) { \n return rule.filter(isIndexEven);\n }).reverse();\n}\n</code></pre>\n\n<p>Similarly, a few more local variables wouldn't hurt. E.g.</p>\n\n<pre><code>return input.replace(new RegExp(escapeString(search), \"g\"+(ignore?\"i\":\"\")), replacement);\n</code></pre>\n\n<p>Could be</p>\n\n<pre><code>var flags = \"g\" + (ignore ? \"i\" : \"\"),\n regex = new RegExp(escapeString(search), flags);\nreturn input.replace(regex, replacement);\n</code></pre></li>\n<li><p>More micro-level: The pattern in <code>escapeString</code> can be simplified a great deal; you don't have to escape everything inside a character class, nor do you need the capture group. I get something like this</p>\n\n<pre><code>/[\\\\,!^${}[\\]().*+?|<>&-]/g \n</code></pre>\n\n<p>The only things that need escaping is the backslash, the close square bracket, and the dash - unless you just put the dash at the end (if it's in the middle somewhere, it'll be interpreted as a range like <code>0-9</code>). </p>\n\n<p>There's a similar thing in your <code>rules</code>; you don't need to escape double quotes inside single-quoted strings.</p>\n\n<p>I should add, though, that I haven't had the time to do a high-level review of all the regexp magic; I've looked a the individual patterns, not whether some can be combined, elided, or otherwise refactored.</p></li>\n<li><p>Speaking of the rules: Whenever possible use class names or simply rely on HTML tag names instead of hardcoded style attributes. For instance, the <code><big></code> tag exists in HTML, just like <code><small></code>, so you don't need a styled <code>span</code> element. And the <code>img</code> tag doesn't need a style attribute; just declare the style for <code>img</code> tags in a CSS file. The point is, as with all things CSS, that you won't have to change your code (behavior) to change the look (presentation).</p></li>\n<li><p>Some function names are pretty terse. E.g. <code>eleFragsToHtml</code> is a bit too truncated, if you ask me (especially considering the 2nd argument is spelled out as <code>elementFragments</code>)</p></li>\n<li><p>I'd define the unchanging regex patterns outside the functions they're in now, since they're static - or define some more functions, to make it more descriptive. For instance, this</p>\n\n<pre><code>var attrs = tag.replace(/\\[\\w+|\\]/g, '').trim().split(' ');\nvar key = tag.replace(/\\[\\/?| .+|\\]/g, '');\nvar isClosing = /\\//.test(tag);\n</code></pre>\n\n<p>Could be</p>\n\n<pre><code>var attrs = tagAttributes(tag),\n key = tagName(tag),\n isClosing = tagIsClosing(tag);\n</code></pre>\n\n<p>(yes, I've combined the <code>var</code> statements).<br>\nThe <code>tag*</code> prefix on all those functions is of course a hint that they might benefit from being namespaced in an object. Or just have one <code>parseTag</code> function that returns an object with <code>name</code>, <code>attributes</code>, and <code>closing</code> properties.</p></li>\n<li><p>Lastly, it'd be nice to stick all of this in an IIFE, like</p>\n\n<pre><code>var bbCodeToHtml = (function () {\n // shared variables, regex patterns here\n\n // various helper functions\n\n return function (string) {\n // the function that ties it all together\n }\n}());\n</code></pre>\n\n<p>The idea is that the global namespace isn't polluted with a lot of \"niche\" functions; all you'll see is a function called <code>bbCodeToHtml</code>.</p></li>\n</ol>\n\n<p>FYI, it's a toss-up whether the function should be <code>bbCodeToHTML</code> or stay as it is. The DOM is inconsistent in this regard (you have the <code>innerHTML</code> and <code>namespaceURI</code> properties, but you also have functions like <code>getElementById</code> - and I doubt they mean the Freudian \"id\" but rather \"ID\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T13:14:39.083",
"Id": "82302",
"Score": "0",
"body": "Thanks for the in depth analysis. One of my goals this year is to write more readable code and all your feedback helps immensely. Definitely learned a lot from your response. Thanks for taking the time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T00:24:25.900",
"Id": "46981",
"ParentId": "46751",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46981",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T20:30:53.087",
"Id": "46751",
"Score": "6",
"Tags": [
"javascript",
"strings",
"functional-programming",
"regex",
"converting"
],
"Title": "BBCode to HTML converter using functional programming"
} | 46751 |
<p>I'm new when it comes to Java and programming in general, but I feel I have a decent grasp on a lot of the fundamentals.</p>
<p>I've created this "random planet generator" that is virtually useless aside from minimal entertainment, but I've created it to help solidify what I've been learning. I'm not asking for code, but for a direction with as much info as possible.</p>
<p>My random planet generator lists:</p>
<ul>
<li>name:</li>
<li>temp:</li>
<li>size (circumference):</li>
<li>Density:</li>
<li>Length of Day:</li>
<li>Number of Moons:</li>
<li>Gravity:</li>
<li>If planet has rings:</li>
</ul>
<p>My problem is, that for the name, it is horribly inefficient. Before I added the name field, I could generate millions of random planets in seconds. Now, I only set it to 50,000 planets and it still takes a minute or two to generate them all.</p>
<p>Here's the method I use to name the planets:</p>
<pre><code>public void setName() throws FileNotFoundException {
String prefix = "";
String greek = "";
int number;
char suffix;
Random rand = new Random();
// randomly pull from list of star names
int randName = rand.nextInt(300);
File prefixFile = new File("StarNames.txt");
Scanner inputFilePrefix = new Scanner(prefixFile);
for (int i = 0; i <= randName; i++) {
prefix = inputFilePrefix.nextLine();
}
inputFilePrefix.close();
// randomly pull of list of Greek names
int randGreek = rand.nextInt(11);
File greekFile = new File("Greek.txt");
Scanner inputFileGreek = new Scanner(greekFile);
for (int i = 0; i <= randGreek; i++) {
greek = inputFileGreek.nextLine();
}
inputFileGreek.close();
// random number
int randNum = rand.nextInt(1000);
number = randNum;
// random letter
int randLetter = rand.nextInt(4);
if (randLetter == 0) {
suffix = 'a';
} else if (randLetter == 1) {
suffix = 'b';
} else if (randLetter == 2) {
suffix = 'c';
} else {
suffix = 'd';
}
// append to class name
this.name = prefix + " " + greek + "-" + number + "" + suffix;
}
</code></pre>
<p>As you can tell, I have 2 text files. One for actual star names, and another for (what I think is) the Greek alphabet. It randomly picks a line to read up to and uses that name.
What could be a faster, more efficient way of doing this?</p>
<p>The name structure would essentially be something like:</p>
<blockquote>
<pre><code> Name: Gemini ALPHA-229c
</code></pre>
</blockquote>
<p>I have every planet generated added to an <code>ArrayList</code> one by one after all planets fields are created.</p>
<p>Any suggestions?</p>
| [] | [
{
"body": "<p>Opening and closing both files for every name is very inefficient and is almost certainly the cause of the slow performance. A better bet would be to open both files once, outside the loop, and pass them into the function where the seek can be done.</p>\n\n<p>Alternatively, open both files once, read each of them line by line into an <code>ArrayList</code>, pass those lists to the function, and randomly index into them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:41:13.407",
"Id": "81819",
"Score": "0",
"body": "I think I understand, though I'm not sure. Right now as I have it, it's adding every name the loop iterates over to the field until it reaches randGreek or randName, and that's what's making it slow? So are you saying if I just have it iterate over all the lines in the file it needs to, WITHOUT defining a field, it would perform faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:44:08.120",
"Id": "81820",
"Score": "0",
"body": "@user3517084 - How large is the file (KB/MB/) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:45:30.390",
"Id": "81821",
"Score": "0",
"body": "The biggest one, StarNames, is 2.9KB"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:48:50.590",
"Id": "81822",
"Score": "3",
"body": "@user3517084 That's part of it -- repeatedly looping through the file. But just the overhead of opening it and closing it is also a major slowdown. You could try reading both files into an `ArrayList` at the start, pass *those* to the function, and then just randomly index into the list."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:31:16.650",
"Id": "46756",
"ParentId": "46754",
"Score": "11"
}
},
{
"body": "<h1>Review</h1>\n<p>You have posted one method for review, but that method has multiple responsibilities.</p>\n<p>Good code follows the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">"Single Responsibility Principle"</a>. Your method does the following things:</p>\n<ol>\n<li>it creates a random number generator</li>\n<li>it generates a random number</li>\n<li>it opens and reads data from a file and then closes it.</li>\n<li>it generates another random number</li>\n<li>it opens and reads data from another file, and then closes it.</li>\n<li>it generates yet another random number</li>\n<li>then another</li>\n<li>it builds a string value from a number of components.</li>\n<li>sets the value of the <code>name</code> field to this string</li>\n</ol>\n<p>That is a lot of things happening in one method.</p>\n<p>Additionally, your code has a number of magic numbers: 300 star names, 11 Greek letters, 1000 random values, and 4 letters. Each of these values are <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\" rel=\"noreferrer\">coded as magic numbers</a>.</p>\n<p>The File names are 'magic' too.</p>\n<p>In that list, I can see the following bad practices:</p>\n<ul>\n<li><p>two repeated items - selecting a random string from a file</p>\n</li>\n<li><p>a set method (<code>setName</code>) that does not take a value to set (setters should take a value, not generate a value)</p>\n</li>\n<li><p>You create a new <code>Random</code> instance each time</p>\n</li>\n<li><p>you repeatedly open/read/close multiple files.</p>\n</li>\n<li><p>you throw an <code>IOException</code> on a method which does not have a particularly IO-sounding name.</p>\n</li>\n</ul>\n<p>The above things should all be resolved.....</p>\n<h1>Alternative</h1>\n<p>Create a class that generates the names for you. Consider this class:</p>\n<pre><code>import java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.List;\nimport java.util.Random;\n\n\npublic class PlanetaryGenerator {\n \n private static final class RandomLine {\n private final List<String> lines;\n private final Random random = new Random();\n\n public RandomLine(String filename) throws IOException {\n this.lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8);\n }\n \n public String getRandom() {\n return lines.get(random.nextInt(lines.size()));\n }\n \n }\n\n private static final String[] SUFFIXES = {"a", "b", "c", "d"};\n\n private static final int MAXNUMBER = 1000;\n \n private final RandomLine stars;\n private final RandomLine greekletters;\n private final Random random;\n \n public PlanetaryGenerator(String starsfile, String greekfile) throws IOException {\n this.stars = new RandomLine(starsfile);\n this.greekletters = new RandomLine(greekfile);\n this.random = new Random();\n }\n\n public String generateName() {\n String prefix = stars.getRandom();\n String greek = greekletters.getRandom();\n int number = random.nextInt(MAXNUMBER);\n String suffix = SUFFIXES[random.nextInt(SUFFIXES.length)];\n\n // append to class name\n return String.format("%s %s-$d%s", prefix, greek, number, suffix);\n\n }\n}\n</code></pre>\n<p>Then, in your existing code you can create a single instance of this, and just call it when you need a new name:</p>\n<pre><code>static PlanetaryGenerator ....\n\n\n// get a new name:\nString name = generator.generateName();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T22:47:48.817",
"Id": "81830",
"Score": "2",
"body": "I accepted this as the answer, not for the code, but for the explanation of method responsibilities that my Java professor has failed to mention. (I mention my professor, but I'm already done with his class. This isn't an assignment) Both answers were great though, as the first one from Roger got me thinking about work arounds. and This answer gave me crucial insight into code devlopement. Thank you guys!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:45:11.927",
"Id": "81970",
"Score": "0",
"body": "I am curious, does this actually speed things up for you? If so, by how much?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:47:09.497",
"Id": "81971",
"Score": "2",
"body": "@user1477388 - each file should be opened once only. The stars and greeks instances should be kept 'permanently'. The Random number generator is also permanent. Getting a random number is fast compared to creating the Random instance. Ys, if you do it with only 1-ever stars/greeks/random then it will be faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:45:26.380",
"Id": "82205",
"Score": "0",
"body": "I haven't implemented this code, and probably wont, because it helped me to realize some of things I have to learn and relearn. Once I feel confident enough to write better methods and have a more coherent structure, I'll try my hand at making this Planet Generator from scratch, again."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T22:12:54.643",
"Id": "46761",
"ParentId": "46754",
"Score": "15"
}
},
{
"body": "<p>Expanding on the concept of passing in an array (as others have suggested) is that it decouples the method from the storage mechanism. In doing so your code becomes more testable, reusable and extensible, e.g. you can get your data from multiple sources without changing your code. Taking this approach further for more complex collections or code, you'd benefit from abstracting further by passing in an interface bound collection or provider.</p>\n\n<p>To avoid going down the rabbit hole in a single post, here's some further reading to get you started:</p>\n\n<p><a href=\"http://edn.embarcadero.com/article/30372\" rel=\"nofollow noreferrer\">Interfaces and Loose Coupling</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old\">Dependency Injection</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29#Classification_and_list\" rel=\"nofollow noreferrer\">and this list of design patterns</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:41:49.640",
"Id": "46770",
"ParentId": "46754",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:21:35.563",
"Id": "46754",
"Score": "16",
"Tags": [
"java",
"performance",
"beginner"
],
"Title": "Planetary Nomenclature"
} | 46754 |
<p>This is my solution for <a href="https://projecteuler.net/problem=26" rel="nofollow">problem 26 from Project Euler</a>:</p>
<pre><code>"""Find the value of d < 1000 for which
1/d contains the longest recurring cycle
in its decimal fraction part."""
from timeit import default_timer as timer
import math
from decimal import *
start = timer()
def longestPeriod(n): # define function
longest = [0, 0] # length, num
def isPrime(k): # checks if a # is prime
for x in range(2, int(math.ceil(math.sqrt(k)))):
if k % x == 0:
return False
return True
def primeFact(k): # returns prime factorization of # in list
if k <= 1: return []
prime = next((x for x in range(2,
int(math.ceil(math.sqrt(k))+1)) if k%x == 0), k)
return [prime] + primeFact(k//prime)
def periodIfPrime(k):
period = 1
while (10**period - 1) % k != 0:
period += 1
return period # returns period of 1/d if d is prime
def lcm(numbers): # finds lcm of list of #s
def __gcd(a, b):
a = int(a)
b = int(b)
while b:
a,b = b,a%b
return a
def __lcm(a, b):
return ( a * b ) / __gcd(a, b)
return reduce(__lcm, numbers)
for x in range(3, n): # check all up to d for 1/d
if all(p == 2 or p == 5 for p in primeFact(x)) == True: # doesn't repeat
pass
elif isPrime(x) is True: # run prime function
if longest[0] < periodIfPrime(x):
longest = [periodIfPrime(x), x]
elif len(primeFact(x)) == 2 and primeFact(x)[0] == primeFact(x)[1]:
if x == 3 or x == 487 or x == 56598313: # exceptions
period = int(math.sqrt(x))
else: # square of prime
period = periodIfPrime(primeFact(x)[0]) * x
if period > longest:
longest = [period, x]
else:
fact = primeFact(x)
periods = []
for k in fact:
if k != 2 and k != 5:
if fact.count(k) == 1:
periods.append(periodIfPrime(k))
else:
periods.append((periodIfPrime(k)) * k**(fact.count(k) - 1))
if lcm(periods) > longest[0]:
longest = [lcm(periods), x]
return longest
elapsed_time = timer() - start
elapsed_time /= 100 # milliseconds
print "Found %d in %r ms." % (longestPeriod(1000)[1], elapsed_time)
</code></pre>
<p>Can it be written in a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T12:09:59.233",
"Id": "82100",
"Score": "0",
"body": "You shouldn't update the code you've written as it makes the answers irrelevant. Please rollback your change and if you really want to, add the new code precising explicitely that you've taken answers into account."
}
] | [
{
"body": "<p>You don't have to define your own <code>gcd</code> function: it <a href=\"https://docs.python.org/3.4/library/fractions.html#fractions.gcd\">already exists</a> in the <code>fractions</code> module of the standard library. And actually, it works with any integer type. Therefore, you can rewrite <code>lcm</code> as:</p>\n\n<pre><code>def lcm(numbers):\n \"\"\"finds lcm of list of #s\"\"\"\n from fractions import gcd\n return reduce(lambda a,b: (a*b)/gcd(a, b), numbers)\n</code></pre>\n\n<hr>\n\n<p>Also, you shouldn't write <code>== True</code> in a conditional, a code like</p>\n\n<pre><code>if eggs == True:\n # do something\n</code></pre>\n\n<p>should be replaced by:</p>\n\n<pre><code>if eggs:\n # do something\n</code></pre>\n\n<hr>\n\n<p>I realized that youare actually using Python 2 (for some reason, I thought that you were using Python 3). Therefore, You can probably improve the function <code>isPrime</code>. You are currently using <code>range</code> in the function. <code>range</code> creates and returns a list. You should use <code>xrange</code> instead: <code>xrange</code> is a generator; it will generate and yield a new <code>int</code> at each iteration. Since you occasionally <code>return</code> early from your loop, you don\"t always need to compute the whole list of integers, and <code>xrange</code> should be a best fit for this job.</p>\n\n<pre><code>def isPrime(k):\n for x in xrange(2, int(math.ceil(math.sqrt(k)))):\n if k % x == 0:\n return False\n return True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:49:37.743",
"Id": "46818",
"ParentId": "46759",
"Score": "9"
}
},
{
"body": "<p>You're not measuring the elapsed time in a meaningful way. The bulk of the work is in <em>calling</em> the <code>longestPeriod()</code> function, not in <em>defining</em> it. You've stopped the timer before you even call the function.</p>\n\n<p>To convert seconds to milliseconds, multiply by 1000, don't divide by 100.</p>\n\n<pre><code>start = timer()\nanswer = longestPeriod(1000)[1] # Don't you want [0] instead?\nelapsed_time = (timer() - start) * 1000 # seconds → milliseconds\n\nprint \"Found %d in %r ms.\" % (answer, elapsed_time)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:53:21.297",
"Id": "82085",
"Score": "0",
"body": "Thanks for your answer; I used [0] because the problem asked for the number, not the length of the period."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:11:06.667",
"Id": "82088",
"Score": "1",
"body": "You're right, I read the code carelessly. I suggest using a [`namedtuple`](https://docs.python.org/2/library/collections.html#collections.namedtuple) instead of a two-element list to avoid such confusion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:09:11.993",
"Id": "46819",
"ParentId": "46759",
"Score": "5"
}
},
{
"body": "<ul>\n<li>Don't compute the same thing more than once. You call <code>primeFact(x)</code> up to 5 times for each <code>x</code>. Keep the result in a variable instead.</li>\n<li>You check if <code>x</code> is prime after you have already computed its prime factorization. Now think for a minute: how does the prime factorization of a prime turn out? </li>\n<li>Your program would greatly benefit from a precomputed list of primes. Look up sieve of Eratosthenes.</li>\n<li>The answer according to this program is 3, which cannot be right, as eg. 7 has a longer period already.</li>\n<li>Bug: <code>if period > longest</code> compares an <code>int</code> to a <code>list</code>, which is not an error in Python 2.x, but does not do what you want.</li>\n<li>To allow testing of individual functions, it is better to define them at module level. </li>\n<li>A quick test of <code>isPrime</code> shows it returns <code>True</code> for 4,9,25 etc. That's because eg. <code>ceil(2.0) == 2.0</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:00:00.467",
"Id": "82086",
"Score": "0",
"body": "When you say the answer according to the program is 3, do you mean that it returns 3? I get 983 (the correct answer) when I run it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:08:08.450",
"Id": "82087",
"Score": "0",
"body": "@jshuaf Yes. I had another look, and I see `return longest` must be at the wrong indentation level. Oh I see you just fixed it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:11:12.767",
"Id": "82089",
"Score": "0",
"body": "@jshuaf But now I see you have incorporated my suggestions in the code, which invalidates my answer. Please don't do that; you can post both versions in the question if you like."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T16:50:14.133",
"Id": "46827",
"ParentId": "46759",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46827",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:45:22.733",
"Id": "46759",
"Score": "9",
"Tags": [
"python",
"python-2.x",
"programming-challenge"
],
"Title": "Rendition of Project Euler 26 - reciprocal cycles"
} | 46759 |
<p>This is a revised version of an AI for the game <a href="http://gabrielecirulli.github.io/2048/" rel="nofollow noreferrer">2048</a>, written in Haskell.</p>
<p>Link to original thread: <a href="https://codereview.stackexchange.com/questions/46493/poor-ai-for-2048-written-in-haskell">Poor AI for 2048 written in Haskell</a></p>
<p>I think this version is a lot cleaner, thanks to the tips from Benesh.</p>
<p>I would like to know if I'm following best practice guidelines and especially if I made the right choices performance-wise.</p>
<p>I think the program is already a bit slow, and it will become a lot slower if start implementing the randomized aspects of the game.</p>
<pre><code>{--
Plays and solves the game 2048
In this implementation the randomized aspects of the game have been removed.
--}
import Data.Time
import Data.List
import Data.Ord
import Data.Maybe
import Control.Monad
emptyGrid :: [Int]
emptyGrid = [ 0 | _ <- [0..15] ]
-- Display the 16-length list as the 4 by 4 grid it represents
gridToString :: [Int] -> String
gridToString [] = ""
gridToString xs = show (take 4 xs) ++ "\n" ++ gridToString (drop 4 xs)
printGrid :: [Int] -> IO()
printGrid xs = putStrLn $ gridToString xs
-- Skip n empty tiles before inserting
addTile :: Int -> [Int] -> [Int]
addTile 0 (0:grid) = 2 : grid
addTile _ [] = []
addTile n (0:grid) = (0 : addTile (n-1) grid)
addTile n (cell:grid) = cell : addTile n grid
-- For one row of the grid, push the non-empty tiles together
-- e.g. [0,2,0,2] becomes [2,2,0,0]
moveRow :: [Int] -> [Int]
moveRow [] = []
moveRow (0:xs) = moveRow xs ++ [0]
moveRow (x:xs) = x : moveRow xs
-- For one row of the grid, do the merge (cells of same value merge)
-- e.g. [2,2,4,4] becomes [4,8,0,0]
-- [2,4,2,2] becomes [2,4,4,0]
mergeRow :: [Int] -> [Int]
mergeRow [] = []
mergeRow (a:[]) = [a]
mergeRow (a:b:xs)
| a == b = (a + b) : (mergeRow xs) ++ [0]
| otherwise = a : mergeRow (b:xs)
-- Rotate the grid to be able to do vertical moving/merging
-- e.g. [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
-- becomes [0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15]
rotate :: [Int] -> [Int]
rotate grid = [ grid !! (a + 4 * b) | a <- [0..3], b <- [0..3] ]
data Move = MoveLeft | MoveRight | MoveUp | MoveDown
deriving (Show)
allMoves :: [Move]
allMoves = [MoveLeft, MoveRight, MoveUp, MoveDown]
-- Use the definitions above to do the moves
doMove :: Move -> [Int] -> [Int]
doMove _ [] = []
doMove MoveLeft grid = mergeRow (moveRow (take 4 grid)) ++ doMove MoveLeft (drop 4 grid)
doMove MoveRight grid = reverse (doMove MoveLeft (reverse grid))
doMove MoveUp grid = rotate (doMove MoveLeft (rotate grid))
doMove MoveDown grid = reverse (doMove MoveUp (reverse grid))
-- Take a turn, i.e. make a move and add a tile
-- Return Nothing if the move is not legal
takeTurn :: Move -> [Int] -> Maybe [Int]
takeTurn move grid
| movedGrid == grid = Nothing
| otherwise = Just $ addTile 0 movedGrid
where movedGrid = doMove move grid
-- Return the best move
-- Will throw an error if there are no valid moves
bestMove :: Int -> [Int] -> Move
bestMove depth grid = snd bestValueMove
where
valueMoves = [ (value, move) |
move <- allMoves,
newGrid <- [ takeTurn move grid ],
value <- [ gridValue depth (fromJust newGrid) ],
newGrid /= Nothing ]
bestValueMove = maximumBy (comparing fst) valueMoves
-- <<< I decided not to return Nothing on a dead end, because then we can no longer
-- distinguish dead ends at different depths from eachother. >>>
--
-- Return the value of the grid,
-- + 1 for each depth traversed
-- -100 if a Game Over position is reached
gridValue :: Int -> [Int] -> Int
gridValue depth grid
| depth == 0 = length $ filter (==0) grid
| values == [] = -100
| otherwise = maximum values
where
values = [ value |
move <- allMoves,
newGrid <- [ takeTurn move grid ],
value <- [ gridValue (depth-1) (fromJust newGrid) + 1],
newGrid /= Nothing ]
gameOver :: [Int] -> Bool
gameOver grid = all (==Nothing) ([ takeTurn move grid | move <- allMoves ])
-- Take turns and prints the result of each move to the console until no more moves are possible
-- n counts the moves
-- Should normally be called with n=0
takeTurns :: Bool -> Int -> Int -> [Int] -> IO()
takeTurns isVerbose depth n grid = do
when (isVerbose || isGameOver) $ putStrLn $ gridToString grid ++ "\n# " ++ (show n)
when (isVerbose && not isGameOver) $ putStrLn $ (show move)
when (not isGameOver) $ takeTurns isVerbose depth (n+1) newGrid
where
isGameOver = gameOver grid
move = bestMove depth grid
newGrid = fromJust $ takeTurn move grid
-- Solves at depth and only prints # of moves and final grid
solveSilent :: Int -> IO()
solveSilent depth = takeTurns False depth 0 (addTile 0 emptyGrid)
-- Solves at depth and prints all boards and moves
solve :: Int -> IO()
solve depth = takeTurns True depth 0 (addTile 0 emptyGrid)
-- Solve and time the solver for multiple depth settings from start to end
solveDepths :: Int -> Int -> IO()
solveDepths start end
| start <= end = do
startTime <- getCurrentTime
solveSilent start
stopTime <- getCurrentTime
putStrLn $ "Depth " ++ (show start) ++ " done in " ++ (show $ diffUTCTime stopTime startTime)
solveDepths (start+1) end
| otherwise = putStrLn "-"
main = solveDepths 1 3
</code></pre>
| [] | [
{
"body": "<p>I am unfortunately no performance guru, but will take a stab at this as I repeatedly had to make programs faster, and there are no answer yet.</p>\n\n<p>A nitpick : I would have used a type synonym for <code>Grid</code> and <code>Row</code> :</p>\n\n<pre><code>type Grid = [Int]\ntype Row = [Int]\naddTile :: Int -> Grid -> Grid\nmoveRow :: Row -> Row\n</code></pre>\n\n<p>This doesn't help too much here, but might make things more obvious in the long run.</p>\n\n<p>Now, considering performance, the choice of a list of integer will make your program hard to optimize. Functions such as this will be really slow :</p>\n\n<pre><code>rotate grid = [ grid !! (a + 4 * b) | a <- [0..3], b <- [0..3] ]\n</code></pre>\n\n<p>As lists are linked lists, and indexing will traverse all previous elements. Profiling shows that this is the most time consuming function.</p>\n\n<p>I would suggest one or a combination of the following solutions.</p>\n\n<h1>Using the <code>ST</code> monad</h1>\n\n<p>The ST monad is a strict state monad. It is pretty useful for encapsulating value-mutating algorithms in referentially transparent functions. Basically, you would write algorithms the way you would in C, and the resulting code should be quite efficient. The <code>STArray</code> type might be a good candidate.</p>\n\n<h1>Using a library known for its performance</h1>\n\n<p>A library such as <code>repa</code> or <code>vector</code>, both are known to be able to generate crazy fast code when the right rewrite rules fire. <code>repa</code> is probably overkill, and hard to understand. You can alter vectors in the <code>ST</code> monad too.</p>\n\n<h1>Change your representation</h1>\n\n<p>The <code>doMove</code> function takes most of the time. It has an implementation for a single case (<code>MoveLeft</code>), and all other cases rotate the board, run a <code>MoveLeft</code>, and rotate it back. It might be possible to either have specialized implementations for each case, or, perhaps better, to use function composition / modification to skip the rotate / rotate back operations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T11:32:53.027",
"Id": "46997",
"ParentId": "46760",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T21:57:51.163",
"Id": "46760",
"Score": "5",
"Tags": [
"haskell",
"ai"
],
"Title": "Revised: AI for 2048 in Haskell"
} | 46760 |
<p>Most of you already know me, please be brutal, and treat this code as if it was written at a top tech interview company.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Given a binary tree and a sum, find all root-to-leaf paths where each
path's sum equals the given sum.</p>
<p>For example: Given the below binary tree and sum = 22,</p>
<pre><code> 5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
</code></pre>
<p>return</p>
<pre><code>[
[5,4,11,2],
[5,8,4,5]
]
</code></pre>
</blockquote>
<p><strong>Time taken:</strong> 26 minutes (all 110 test cases passed)</p>
<p><strong>Worst case:</strong> \$O(n^2)\$?<br>
Since when I add to resList, it copies all the elements again which can take \$O(n)\$ and I traverse \$O(n)\$ nodes.</p>
<p><strong>Space complexity:</strong> \$O(n)\$</p>
<p><strong>My code:</strong></p>
<pre><code>ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> curList = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
if(root==null){
return res;
}
curList.add(root.val);
if(root.left==null && root.right==null){
if(sum - root.val==0){
res.add(new ArrayList<Integer>(curList));
}
}
if(root.left!=null){
pathSum(root.left, sum-root.val);
}
if(root.right!=null){
pathSum(root.right, sum-root.val);
}
curList.remove(new Integer(root.val));
return res;
}
</code></pre>
| [] | [
{
"body": "<p>There are a few things that could be better:</p>\n\n<ul>\n<li>You should make it generic.</li>\n<li>Personally, I think you should use an array to store the children, even if there are only two; it can make it a lot more DRY.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:23:10.133",
"Id": "81839",
"Score": "0",
"body": "I suspect `TreeNode` was supplied by the problem description, but I still disagree with using an array in place of `left` and `right`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:40:16.463",
"Id": "81845",
"Score": "0",
"body": "@AJMansfield TreeNode was provided by the problem description."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T00:41:49.650",
"Id": "46766",
"ParentId": "46765",
"Score": "0"
}
},
{
"body": "<p>You are treating <code>res</code> and <code>curList</code> as if they are Globals, and, since they are globals, there is no reason to return <code>ret</code> in the function at all.</p>\n\n<p>As a result of this, your code is <a href=\"http://en.wikipedia.org/wiki/Reentrancy_%28computing%29\" rel=\"nofollow\">not re-entrant</a> (you can only have one method calling your <code>pathSum</code> at any one point in time).</p>\n\n<p>The right solution to this is to pass the <code>curList</code> and <code>ret</code> values as parameters to the method, convert it to private, and create a new public method which creates the instances as you need them.....</p>\n\n<pre><code>public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {\n ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();\n ArrayList<Integer> curList = new ArrayList<Integer>();\n pathSum(root, sum, curList, res);\n return res;\n}\n\n\nprivate void pathSum(TreeNode root, int sum, \n ArrayList<Integer> curList, ArrayList<ArrayList<Integer>> res) {\n ....\n ** change the methods called as part of the recursion too**\n ....\n}\n</code></pre>\n\n<p>That is the big structural change, but I would recommend more:</p>\n\n<ul>\n<li>methods should not return specific List implementation types unless those types have special features you need. your method should return <code>List<List<Integer>></code> and not <code>ArrayList<ArrayList<Integer>></code></li>\n<li>convert curList to an array of int[], and the return valye of the system to List</li>\n<li>you do the calculation <code>sum-root.val</code> in multiple places. Firstly, it should be spaced properly: <code>sum - root.val</code>, and secondly, you should save it as a variable once, and re-use that variable in the places where it currently is a function</li>\n</ul>\n\n<h2>About the complexity</h2>\n\n<p>you ask if worst case is \\$O(n^2)\\$ ... no, it is not.</p>\n\n<p>Worst case is \\$O(n \\log(n))\\$. This is my reasoning:</p>\n\n<ul>\n<li>the depth of a binary tree is about \\$\\log(n)\\$.</li>\n<li>The deepest a binary tree can be is depth <code>n</code>, but, in that case there is only one possible solution, so the complexity will be two \\$O(n)\\$ operations, one to scan the single deep branch, and another to copy the array.</li>\n<li>the worst case is actually a fully-balanced tree where every leaf node matches the intended sum, in which case the number of solutions is proportional to \\$O(n)\\$, but the actual copy to the array will be of \\$O(log(n))\\$ elements</li>\n</ul>\n\n<p>So, My assessment is <strong>\\$O(n \\log(n))\\$</strong></p>\n\n<p>Feel free to debate this... I am not 100% certain....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:20:04.347",
"Id": "81837",
"Score": "0",
"body": "Using `int[]` will necessitate copying it to add an element every time you descend into a child."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:22:19.030",
"Id": "81838",
"Score": "0",
"body": "@DavidHarkness - creating an oversize array with a size to use as a stack, and then only making a copy when I have a sum-match is the way I would do it. This is faster than copying the current-array anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:27:53.140",
"Id": "81841",
"Score": "0",
"body": "I must have misunderstood your item about using an `int[]` because your comment describes what the current code does. It doesn't overly size the list, but the default is 10 IIRC. Using an array would require the code to do manual copies to add elements to the path."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:30:06.820",
"Id": "81842",
"Score": "0",
"body": "@DavidHarkness - I was not particularly clear on the int[] stack, from a performance perspective, I know it will be faster than all the autoboxing going on. Explaining how I would do it is hard without actually doing it ;-) So I just 'recommended it'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:39:52.913",
"Id": "81844",
"Score": "0",
"body": "@rolfl is my worst time complexity analysis right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:42:31.497",
"Id": "81846",
"Score": "0",
"body": "I can't definitely say which is slower: auto-boxing or copying an array on each descent. I suspect the latter in this case since `Integer` keeps a cache of the first 128 values, but that makes quite a few assumptions. :) If `TreeNode` kept a `parent` reference, you wouldn't even need `curList`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:49:07.393",
"Id": "81847",
"Score": "0",
"body": "@bazang - Added complexity analysis"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:00:24.850",
"Id": "81854",
"Score": "0",
"body": "Your complexity analysis is spot on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:07:26.350",
"Id": "81862",
"Score": "0",
"body": "@bazang - come join us in the [2nd Monitor chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T00:51:16.130",
"Id": "46767",
"ParentId": "46765",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>You said top-tier, so go read Google's style guide and follow it: spaces around operators, a space after <code>if</code> and friends and before open curly braces, don't name collections after the specific type (<code>curPath</code> vs. <code>curList</code>).</p></li>\n<li><p>Before adding the current node's value to <code>curList</code> and checking for children, make sure the sum hasn't passed the desired total. Exit early if it has to avoid processing the subtree of impossible paths. This assumes negative values are not allowed.</p></li>\n<li><p>Recursive algorithm: +1. \"Global\" state: -10. @rolfl covered this well.</p></li>\n<li><p>I would prefer to see you use a true stack rather than treating a list as one. Under the hood it's probably the same, but there is a semantic difference that's lost by using a list.</p></li>\n<li><p>Put the left/right child handling in an <code>else</code> block to bypass it when a leaf that doesn't add up to the desired sum is found. Do this to clarify the logic rather than for the trivial performance boost.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:38:52.417",
"Id": "81843",
"Score": "0",
"body": "It does allow negatives. But my question to you is, hypothetically speaking, would you still hire me and over look my naive mistakes(entry-level, fresh college graduate)? (I will read the Google's style guide right now, and I promise you will see improvements)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:50:53.587",
"Id": "81848",
"Score": "0",
"body": "A style different from mine (you're still consistent which is key) would never raise a red flag for me in hiring. Inconsistencies in formatting of an offline code submission--which is not the case here--would merely prompt some probing from me. I know school rarely teaches these concepts, and they are trivial to pick up if you want to. Now if I hired you, gave you our style guide, and corrected you a few times, and you *continued* to violate that style, I would have a heart-to-heart with you over coffee or a beer as a last resort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:56:54.043",
"Id": "81849",
"Score": "0",
"body": "I like you, thanks for your response sir. Would it be a personal question to ask where you are employed? Feel free to ignore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:11:42.050",
"Id": "81863",
"Score": "0",
"body": "We've crossed into forum territory which is discouraged on StackExchange to keep the focus on the real topic--Q&A and (here) the code--so I'll delete this comment shortly (as I recommend you do too). But in case it helps, I can say with certainty that this advice is applied at Google. How you think overwhelms what you know and which style you follow. Peruse Programmers.SE for far more comprehensive advice on this topic. Also, on all SE sites +1 is the accepted substitute for \"thanks\", but I won't hold it against you. ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:17:05.320",
"Id": "46768",
"ParentId": "46765",
"Score": "1"
}
},
{
"body": "<p>I'm dissatisfied with</p>\n\n<pre><code>curList.remove(new Integer(root.val));\n</code></pre>\n\n<p>You should treat <code>curList</code> like a stack: push an element for each step during the descent, and pop an element for each level you backtrack. I suggest using a <code>LinkedList<Integer></code> for <code>curList</code> as a <code>Deque</code>, giving you O(1) <code>push()</code> and <code>pop()</code> operations.</p>\n\n<p>In contrast, <code>curList.remove(new Integer(root.val))</code> takes O(<em>d</em>) time, where <em>d</em> is the depth. More importantly, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(java.lang.Object)\" rel=\"nofollow\"><code>remove()</code></a> removes the <em>first</em> occurrence of the number from <code>curList</code>, not the <em>last</em>. Therefore, <strong>if the tree has duplicate values along a root-to-leaf-path, it would report the nodes in a wrong order.</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:57:43.303",
"Id": "81850",
"Score": "1",
"body": "Duh, I missed that in my review, and complexity analysis... hmmm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:59:16.407",
"Id": "81853",
"Score": "0",
"body": "@200_success so doing something like curList.remove(curList.size()-1); would be better, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:00:39.620",
"Id": "81856",
"Score": "0",
"body": "That could work too, but lacks clarity. Ideally, you want to think of it as a stack with `push()` / `pop()` operations, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:02:22.607",
"Id": "81858",
"Score": "0",
"body": "@bazang I'm curious what your 110 test cases looked like, and how it missed this bug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:05:07.493",
"Id": "81860",
"Score": "0",
"body": "@200_success it's an online judge, and it mentions how many test cases it passed. There are no duplicates, and there can be negative values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T02:14:46.177",
"Id": "81864",
"Score": "0",
"body": "Lucky that there are no duplicates. The test writers get a FAIL from me. :p"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T01:56:22.110",
"Id": "46771",
"ParentId": "46765",
"Score": "3"
}
},
{
"body": "<p>Every thing is correct, except for the removal of an integer from the path root to leaves. Removal of duplicate elements along path was not handled properly as ArrayList.remove() removes elements from starting. You just need to do the following add Collections.reverse(List) and then remove and then reverse again Collections.reverse(List). This assures that the last added element is removed first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-24T14:57:18.607",
"Id": "110526",
"Score": "0",
"body": "Or you could use `arrayList.remove(arrayList.lastIndexOf(object))`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-24T14:43:40.203",
"Id": "60923",
"ParentId": "46765",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46767",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T00:15:49.983",
"Id": "46765",
"Score": "6",
"Tags": [
"java",
"algorithm",
"interview-questions",
"tree"
],
"Title": "Find the sum along root-to-leaf paths of a tree"
} | 46765 |
<p><strong>What I'm trying to do:</strong></p>
<ol>
<li><p>Get user input for Google Play App page. </p>
<p>e.g. <a href="https://play.google.com/store/apps/details?id=jp.scn.android" rel="nofollow">https://play.google.com/store/apps/details?id=jp.scn.android</a></p></li>
<li><p>Scrape 100 reviews from Google Play App and organize them into an array. </p></li>
</ol>
<p><strong>My JavaScript function:</strong></p>
<pre><code>function test() {
var urlAdd = document.getElementById('input').value;
var urlEnglish = urlAdd + '&hl=en';
var query = {
url: urlEnglish,
type: 'html',
selector: '[class=review-body]',
extract: 'text'
},
request;
request = 'http://example.noodlejs.com/?q=' +
encodeURIComponent(JSON.stringify(query)) +
'&callback=?';
jQuery.getJSON(request, function (data) {
document.getElementById('output').innerHTML = '<pre>' +
JSON.stringify(data, null, 4) + '</pre>';
})
};
</code></pre>
<p><strong>Problems:</strong></p>
<ol>
<li><p>This function feels bulky.</p></li>
<li><p>It only returns 20 results. My guess is that this has something to do with how the Google Play DOM retrieves reviews.</p></li>
</ol>
<p><strong>Questions:</strong></p>
<ol>
<li><p>How do I streamline/improve my scraper function?</p></li>
<li><p>How do I get 100 results or more?</p></li>
</ol>
<p><strong>Comments:</strong></p>
<p>My apologies if this is a simple solution. I just started learning JavaScript piecemeal in February. </p>
| [] | [
{
"body": "<p>Use scraping as last resort. <em>I suggest you find available APIs for that</em>. It's more robust, and easy to work with. One issue with scraping is that it fetches the static HTML generated by the url. You can't fetch what is loaded via JS. Although there are ways to do it, it's just adds too much complexity.</p>\n\n<p>In terms of hacking the code, you could check out how Google Play loads the rest of the comments. It should be an AJAX call, check the network tab of your browser. You checkout that url, the response and modify it to your needs.</p>\n\n<p>As for your script: You're using jQuery, use it all the way!</p>\n\n<pre><code>// Cache as well as put configurables here\nvar input = $('#input');\nvar output = $('#output');\nvar noodleUrl = 'http://example.noodlejs.com/?';\n\nvar query = {\n // You should check if the url ends with parameters. Otherwise, this fails.\n url: input.val() + '&hl=en',\n type: 'html',\n selector: '[class=review-body]',\n extract: 'text'\n};\n\n// $.param\nvar request = noodleUrl + $.param({\n q : JSON.stringify(query),\n callback : '?'\n});\n\n$.getJSON(request, function (data) {\n output.html('<pre>' + JSON.stringify(data, null, 4) + '</pre>');\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:49:49.373",
"Id": "84382",
"Score": "0",
"body": "Hi Joseph, I really need some guidance. I have tried searching everywhere for an API to use with Google Play and I have not found anything worthwhile. Any suggestions? If I cannot go the API route, where should I start with getting multiple reviews from Google Play using web scraping? (I did not find an AJAX call in the network tab, instead it looked like json, but I'm not sure)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T21:51:57.450",
"Id": "84383",
"Score": "0",
"body": "@Coder314 You can filter network requests. Select XHR in filters (Chrome dev tools), and you should see what's using XHR. You see JSON? That could be the data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T22:33:12.443",
"Id": "84390",
"Score": "0",
"body": "Link to Plants VS Zombies App Details: https://play.google.com/store/apps/details?id=com.ea.game.pvz2_na How would you get the most reviews from this site?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T23:59:00.397",
"Id": "84396",
"Score": "0",
"body": "I know this is essentially the original question, but I need some evidence with a real example that says, \"there is an API way\" or \"scraping two pages of Google Play is possible using X\", keeping in mind that I want to use JavaScript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:02:01.573",
"Id": "84413",
"Score": "0",
"body": "@Coder314 Load the page and open the dev tools networking tab. Clear the logs first. Go to the reviews section and click the arrow to the right. Then you'll start to see the network tab flood with requests. There'll be one named `getReviews` with a JSON response containing the reviews. **That's the request you'll need to replicate**. Note that there is a `token` parameter indicating that each request needs authorization. You need to find where the script got it in order to get the data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:52:30.373",
"Id": "84418",
"Score": "0",
"body": "Thanks for the tip. I will respond with a progress update after I have explored this further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T19:54:35.827",
"Id": "96801",
"Score": "0",
"body": "Okay, so I went off and explored using an API... not much luck. Let's continue to work on mimicking a request. Here is a [JSFiddle to start](http://jsfiddle.net/rjAj8/19/). Thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-04T22:18:21.563",
"Id": "98792",
"Score": "0",
"body": "Hey, if you are too busy, just let me know."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T10:34:43.520",
"Id": "46795",
"ParentId": "46774",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T03:04:01.203",
"Id": "46774",
"Score": "4",
"Tags": [
"javascript",
"json"
],
"Title": "Scraping reviews from Google Play using JavaScript"
} | 46774 |
<p>I have written a piece of code for removing duplicated values from a string. Any suggestions on improvements?</p>
<pre><code>public static String removeDuplicate(String s)
{
char [] temp = s.toCharArray();
int length =temp.length;
for (int i=0;i<length;i++)
{
for (int j = i+1; j<length;j++)
{
if(temp[i]==temp[j])
{
int test =j;
for(int k=j+1; k<length ; k++)
{
temp[test] = temp[k];
test++;
}
length--;
j--;
}
}
}
return String.copyValueOf(temp).substring(0,length);
}
</code></pre>
| [] | [
{
"body": "<h2>Style</h2>\n<p>Java Code-style conventions put:</p>\n<ul>\n<li>the <code>{</code> brace at the end of the line that introduces the compound statement block, not on the next line.</li>\n<li>spaces between variables and operators: <code>for (int i=0;i<length;i++)</code></li>\n</ul>\n<p>Your code should look like:</p>\n<blockquote>\n<pre><code>public static String removeDuplicate(String s) {\n char[] temp = s.toCharArray();\n int length = temp.length;\n for (int i = 0; i < length; i++) {\n for (int j = i + 1; j < length; j++) {\n if (temp[i] == temp[j]) {\n int test = j;\n for (int k = j + 1; k < length; k++) {\n temp[test] = temp[k];\n test++;\n }\n length--;\n j--;\n }\n }\n }\n return String.copyValueOf(temp).substring(0, length);\n}\n</code></pre>\n</blockquote>\n<h2>Algorithm</h2>\n<p>You have three nested loops. This is inefficient.</p>\n<p>A slight nit-pick is that you also use an inefficient way to get the resulting String using the <code>copyValueOf(...)</code> and then the <code>substring(...)</code>.</p>\n<p>I believe if you take an 'additive' approach to the process you will have a faster system. By extracting the onle loop in to a function it is also more readable:</p>\n<pre><code>private static final boolean foundIn(char[] temp, int size, char c) {\n for (int i = 0; i < size; i++) {\n if (temp[i] == c) {\n return true;\n }\n }\n return false;\n}\n\npublic static String removeDuplicateY(String s) {\n char[] temp = s.toCharArray();\n int size = 0; //how many unique chars found so far\n for (int i = 0; i < temp.length; i++) {\n if (!foundIn(temp, size, temp[i])) {\n // move the first-time char to the end of the return value\n temp[size] = temp[i];\n size++;\n }\n }\n return new String(temp, 0, size);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:28:29.023",
"Id": "46779",
"ParentId": "46777",
"Score": "10"
}
},
{
"body": "<p>This can be simplified a great deal with an auxiliary data structure. Basically, we want to scan the string, and only add characters that we have not yet seen. Hence, if we use a data structure with fast insert/lookup, we can quickly tell if we've already seen that character without having to rescan over the string. In this case, this suggests a <code>Set</code>:</p>\n\n<pre><code>import java.util.Set;\nimport java.util.HashSet;\n\npublic static String removeDuplicate(String s)\n{\n StringBuilder sb = new StringBuilder();\n Set<Character> seen = new HashSet<Character>();\n\n for(int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n if(!seen.contains(c)) {\n seen.add(c);\n sb.append(c);\n }\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>This trades time for space, so in this case, it should make the algorithm \\$O(N)\\$ time (as opposed to \\$O(N^3)\\$) at the cost of using \\$O(N)\\$ extra space.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-05T09:14:16.807",
"Id": "174945",
"Score": "0",
"body": "You can completely avoid the contain check by using `LinkedHashSet` instead of `HashedSet`. Don't forget your range-based `for` when extracting `char`s from a `String`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-19T06:06:59.113",
"Id": "178092",
"Score": "0",
"body": "Sir in the above answer can you please tell what charsCount[ch]++; does?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T06:02:10.667",
"Id": "46783",
"ParentId": "46777",
"Score": "12"
}
},
{
"body": "<p>Yusshi's code is perfectly fine. If you know that all the characters are in a specific range (e.g., ASCII code 0 to 255), you could also use either of the following codes which is faster. They uses an array rather than a hash set. The time complexity is O(n) and the space complexity is O(1). You cannot go lower in either case.</p>\n\n<p><strong>This one sorts the characters in the output string:</strong></p>\n\n<pre><code>public static String removeDuplicates(String str) {\n int charsCount[] = new int[256];\n\n for (int i = 0; i < str.length(); i++) {\n char ch = str.charAt(i);\n charsCount[ch]++;\n }\n\n StringBuilder sb = new StringBuilder(charsCount.length);\n for (int i = 0; i < charsCount.length; i++) {\n if (charsCount[i] > 0) {\n sb.append((char)i);\n }\n }\n\n return sb.toString();\n}\n</code></pre>\n\n<p><strong>This one preserves the order of the characters:</strong></p>\n\n<pre><code>public static String removeDuplicates(String str) {\n boolean seen[] = new boolean[256];\n StringBuilder sb = new StringBuilder(seen.length);\n\n for (int i = 0; i < str.length(); i++) {\n char ch = str.charAt(i);\n if (!seen[ch]) {\n seen[ch] = true;\n sb.append(ch);\n }\n }\n\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:11:21.483",
"Id": "46789",
"ParentId": "46777",
"Score": "17"
}
}
] | {
"AcceptedAnswerId": "46789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:03:57.627",
"Id": "46777",
"Score": "11",
"Tags": [
"java",
"strings"
],
"Title": "Eliminate duplicates from strings"
} | 46777 |
<p>I'm doing some research for a meta post on <a href="http://gardening.stackexchange.com">Gardening.SE</a> (where I'm a pro tempore moderator). I'm using the Stack Exchange Data Explorer (SEDE) to find information about first time users who post questions in our [identification] tag, and how they subsequently interact with the people who respond to their question, whether that's comments on the post, comments on answers, editing the post to provide more information, and so on.</p>
<p>I have the following query which gives me the list of people with no answers and one question that includes the [identification] tag. I plan to refine it by adding extra criteria, e.g. to find instances where the OP leaves a comment replying to someone else.</p>
<pre><code>-- Find users who have exactly one post
-- with that post being a question
-- and the question has the [identification] tag
SELECT
Users.Id AS [User Link], Posts.Id AS [Post Link]
FROM
Users INNER JOIN Posts ON Posts.OwnerUserId = Users.Id
INNER JOIN PostTags ON Posts.Id = PostTags.PostId
INNER JOIN Tags ON Tags.Id = PostTags.TagId
WHERE
Tags.TagName LIKE 'identification' AND
Posts.ParentId IS NULL AND -- ParentId is NULL if post is a question
Users.Id in (
-- Users with exactly one question
SELECT Users.Id
FROM
Users INNER JOIN Posts ON Posts.OwnerUserId = Users.Id
WHERE
Posts.ParentId IS NULL
GROUP BY
Users.id
HAVING
Count(Posts.Id) = 1
) AND
Users.Id NOT IN (
-- Users with 1 or more answers
SELECT Users.Id
FROM
Users INNER JOIN Posts ON Posts.OwnerUserId = Users.Id
WHERE
Posts.ParentId IS NOT NULL
GROUP BY
Users.id
HAVING
Count(Posts.Id) > 0
)
ORDER BY
Users.Id DESC -- newest users first.
</code></pre>
<p>My concern is that this SQL is far from optimal. I'm looking especially at the repeated inner joins between the Users and Posts tables, and the similarity between the sub-queries to find users with one question and users with at least one answer. </p>
<p><a href="http://gardening.stackexchange.com">Gardening.SE</a> is a small site, so this query consistently takes less than 75ms to return its 101 records, but even so I'd like to make it run more efficiently, if possible. As I said, I plan to enhance this query, which will mean pulling in more tables, so I'm also concerned about it scaling that way.</p>
<p>Data Explorer links:</p>
<ul>
<li><a href="http://data.stackexchange.com/gardening/query/182080/users-with-one-identification-question-and-no-answers">Users with one [identification] question and no answers</a> — the above query.</li>
<li><a href="http://data.stackexchange.com/gardening/query/181790/drive-by-users-with-one-identification-question">Drive-by users with one [identification] question</a> — a derived query for users who post and are never seen again. </li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:37:33.490",
"Id": "81875",
"Score": "2",
"body": "Hey, and welcome to CR... we have a long history of messing with SEDE too."
}
] | [
{
"body": "<p>Half of the tricks with optimizing SQL is knowing the database schema.</p>\n\n<p>The schema documentation can be found in this Meta post: <a href=\"https://meta.stackexchange.com/questions/2677/database-schema-documentation-for-the-public-data-dump-and-sede\">Database schema documentation for the public data dump and SEDE</a>.</p>\n\n<p>There are four functional issues I see with your query, and a couple of suggestions after that:</p>\n\n<ol>\n<li>Use PostTypeId - it describes what the Post is (Question == 1, Answer == 2) and is well indexed.</li>\n<li>you are querying closed posts (which have a non-null <code>ClosedDate</code>)</li>\n<li>you join to <code>Tags</code> for a single record. This can be resolved independantly</li>\n<li>you have Posts three times in your query, and it can be there only twice if you do double-duty in the 'Only One Question' part of the query....</li>\n</ol>\n\n<p>As for the suggestions:</p>\n\n<ul>\n<li>I like parametrize things, and being able to change the tag you are interested makes sense, so I would parametrize that.</li>\n<li>The SQL Server syntax allows for 'with' sections in a query, and that makes the code a lot more readable than the query-in-from-clause syntax</li>\n</ul>\n\n<p>Using these suggestions I restructured your query to do a few things:</p>\n\n<ul>\n<li>add a User-Name sort column (SEDE does not sort [User Link] columns well)</li>\n<li>parametrized the tag, with a default value of <code>identification</code></li>\n<li>made the group-by and having a much smaller component in the query.</li>\n<li>added the closed-query support (and community-wiki - if there are).</li>\n</ul>\n\n<p><a href=\"http://data.stackexchange.com/gardening/query/182103/users-with-one-identification-question-and-no-answers?tag=identification\" rel=\"nofollow noreferrer\">I forked your query here...</a> ... for me it ran through in 33 milliseconds</p>\n\n<pre><code>-- Find users who have exactly one post\n-- with that post being a question\n-- and the question has the [xxxx] tag (default identification)\n\ndeclare @tag as nvarchar(25) = ##tag:string?identification##\n;\ndeclare @tagid as int\n;\n\n-- get the tag id here so it is not needed as a join table\nselect @tagid = Id\nfrom Tags\nwhere TagName = lower(@tag)\n\n;\n\nprint 'Tag for ' + @tag + ' is ' + Convert(NVarchar(10), @tagid)\n\n;\n\nwith Answerers as (\n\n select distinct OwnerUserId as [UserId]\n from Posts p\n where PostTypeId = 2 -- answers\n and CommunityOwnedDate is null -- not CW\n and ClosedDate is null -- not closed\n\n), SingleQ as (\n\n Select OwnerUserId as [UserId],\n Min(Id) as [FirstPost],\n Sum(Score) as [Score],\n count (*) as [QCount]\n from Posts p\n where PostTypeId = 1 -- question\n and CommunityOwnedDate is null -- not CW\n and ClosedDate is null -- not closed\n and not exists (\n select UserId\n from Answerers\n where UserId = OwnerUserId) -- active answerers.\n group by OwnerUserId\n having count(*) = 1\n)\n\nSELECT\n ROW_NUMBER() OVER (order by Users.Id Desc) as [Recent],\n Users.Id AS [User Link],\n Users.DisplayName AS [Sort By Name],\n SingleQ.FirstPost AS [Post Link],\n SingleQ.Score AS [Score]\nFROM Users \n INNER JOIN SingleQ ON Users.Id = SingleQ.UserId\n INNER JOIN PostTags ON SingleQ.FirstPost = PostTags.PostId\nWHERE PostTags.TagId = @tagid\nORDER BY \n Users.Id DESC -- newest users first.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T05:33:22.410",
"Id": "46782",
"ParentId": "46780",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46782",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T04:34:57.747",
"Id": "46780",
"Score": "6",
"Tags": [
"optimization",
"sql",
"sql-server",
"t-sql",
"stackexchange"
],
"Title": "SEDE query to find users with exactly one post in a particular tag"
} | 46780 |
<p>I have a backup script which should backup a folder and send it to email. This should be done once a day. As this is on my laptop which is not online 24/7 I need to check that I am online and can send email. For this script I have an entry in crontab running every 2 hours.</p>
<p>Because the folder is a really important to me and I am quite new to BASH, I would like to ask you if there are any weak points in my code:</p>
<pre><code>#!/usr/bin/env bash
cd ~/projects
DATE=`date +%Y%m%d`
PASS="mysecretpasswordiwontwritehere"
# lastbackup file stores date of last backup in YYYYMMDD format
LASTBACKUP=$(< ./personalwiki/lastbackup)
# Check if backup already exists for current date
# and exit if yes.
if [[ "$LASTBACKUP" == "$DATE" ]]; then
echo "Do nothing, already backed up."
exit 0
fi
# Check if we are online
# and exit if not.
ping -c 1 www.google.com
if [[ $? -ne 0 ]]; then
echo "Offline, cannot do anything."
exit 0
fi
echo "Online and not equal, need to start backup"
# Pack an encrypt folder
tar cz personalwiki | openssl enc -aes-256-cbc -e -pass pass:$PASS > $DATE.enc
# Send email
MTO="mybackupemail@gmail.com"
MSUB="PW backup as on $DATE"
MATT="$DATE.enc"
EMAIL="backuprobot@mymachine.com" mutt -s "$MSUB" -a $MATT -- $MTO < /dev/null
# Write date of backup to file
echo -n $DATE > ./personalwiki/lastbackup
</code></pre>
| [] | [
{
"body": "<p>This is an incomplete answer; I'd just like to contribute more comments than easily fit in an actual comment.</p>\n\n<ol>\n<li><p>Consider replacing <code>PASS=\"mysecretpasswordiwontwritehere\"</code> with <code>PASS=`cat mysecretpassword.file`</code> and moving your password into that file. Then you don't have to worry about always remembering to hide it when sharing your source code (or when editing/debugging it).</p></li>\n<li><p>For the test whether the laptop is online, consider being more specific, such as pinging the actual hostname you need to be up (<code>gmail.com</code> rather than <code>www.google.com</code>). Logging (repeated) failure could be a good idea. Beware of the possibility that Google might decide to disable ICMP ping responses (without stopping email processing). If you want to improve further, you may want to look into testing if the service you use for email submission (SMTP/IMAP/whatever) is up. Maybe (I am guessing) there is an option to let <code>mutt</code> do that for you, such that you aren't effectively doubling email configuration? I'm guessing because I barely know <code>mutt</code>.</p></li>\n<li><p>Beware that your <code>tar</code> invocation depends on the environment variable <code>TAPE</code> not being set. Unless you're willing to write its sensitive output into a temporary file, specifying <code>/dev/stdout</code> may be the only alternative, though.</p></li>\n<li><p>You are not logging any other failures, at least not beyond relying on whatever <code>cron</code> is configured to do for you. If <code>tar</code> or <code>openssl</code> somehow aborts, you may be much better off aborting (and logging that there was an error) rather than continuing to the point of logging the date of the completed backup. Likewise in case <code>mutt</code> fails, but that is more complicated since your code may(?) start an asynchronous email transfer. For the rest, you can re-use your code for aborting upon ping failure to detect other errors, ideally logging and aborting (use e.g. <code>exit 1</code> rather than <code>exit 0</code> for errors).</p></li>\n<li><p>Beware that aspects on how this works or fails depend on how <code>cron</code> is configured. Don't accidentally make the mistake of having it run as root rather than under your user account, for example.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:30:46.683",
"Id": "46791",
"ParentId": "46786",
"Score": "6"
}
},
{
"body": "<p>I would make the following changes, in order to make it more robust, and simpler:</p>\n\n<ol>\n<li><p>Do not use <code>openssl</code> and symmetric encryption. Use <code>gpg</code> and public key encryption. The advantage is that you do not have to store any passwords, anywhere (keep the secret key away from the backup script). Public key encryption is great for backups (you only need to access your secret key when you have to restore a backup, which happens rarely).</p></li>\n<li><p>Do not mess around with timestamp files. Instead, keep the last archive around, and inspect the datestamp of the archive (you can use <code>find <path> -ctime 1</code> to see if the archive is older than 24 hours). If your last backup is too old, make a new one. Keeping one old backup around is another safety line for you, even though it's only stored locally.</p></li>\n<li><p>Do not use a cron job. Instead, invoke your script from a DHCP <em>exit hook</em>, which is run whenever your computer acquires an IP address. You can then check if you have Internet access, and mail your backup straight away. This also works if you're only online for a short while (and your cron job might miss that window of opportunity).</p></li>\n<li><p>Check exit codes of <em>everything</em> and make sure your script alerts you somehow if things went wrong. You might need to find a way to interface with your desktop environment in order to do that (<code>notify-send</code> works in Ubuntu).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:12:01.620",
"Id": "48385",
"ParentId": "46786",
"Score": "7"
}
},
{
"body": "<p>Just a few minor things to add on top of what others already said.</p>\n\n<h2>Prefer <code>$(...)</code> instead of <code>`...`</code></h2>\n\n<p>This is the modern way and it's easier to nest:</p>\n\n<pre><code>DATE=$(date +%Y%m%d)\n</code></pre>\n\n<h2>No need to quote inside <code>[[...]]</code></h2>\n\n<p>This will work just fine:</p>\n\n<pre><code>if [[ $LASTBACKUP == $DATE ]]; then\n echo \"Do nothing, already backed up.\"\n exit\nfi\n</code></pre>\n\n<p>And the 0 in <code>exit 0</code> is redundant, as 0 is the default value.</p>\n\n<h2>Simplify exit code checking</h2>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>ping -c 1 www.google.com\n\nif [[ $? -ne 0 ]]; then\n echo \"Offline, cannot do anything.\"\n exit 0\nfi\n</code></pre>\n</blockquote>\n\n<p>I recommend this way:</p>\n\n<pre><code>if ! ping -c1 www.google.com; then\n echo \"Offline, cannot do anything.\"\n exit 1\nfi\n</code></pre>\n\n<p>That is, you could move the <code>ping</code> in the <code>if</code> condition, and in this case I think <code>exit 1</code> is more appropriate, as not being able to ping is kind of an error/failure.</p>\n\n<h2>The trailing newline really bothers you?</h2>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>echo -n $DATE > ./personalwiki/lastbackup\n</code></pre>\n</blockquote>\n\n<p>This will work just as fine:</p>\n\n<pre><code>echo $DATE > ./personalwiki/lastbackup\n</code></pre>\n\n<p>So unless you really don't want the trailing newline for some reason, I recommend to simplify by dropping that <code>-n</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-30T23:03:32.003",
"Id": "52129",
"ParentId": "46786",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T07:33:38.307",
"Id": "46786",
"Score": "7",
"Tags": [
"beginner",
"bash",
"cryptography",
"email",
"openssl"
],
"Title": "Encrypt and backup folder to email daily, when online"
} | 46786 |
<p>I am working in an inherited code (as in "everybody related to it left before I arrived at the job and left no documentation") and I have noticed an strange pattern.</p>
<p>Almost(*) each <code>Struts</code> (Struts 1.3.8) method that is invoked begins with a code such as</p>
<pre><code>public ActionForward myMethod(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, SerletException {
String method = request.getParameter("method");
if (method != null && "myMethod".equals(method)) {
// Perform the actual work
...
</code></pre>
<p>I mean, I would be pretty confident that <code>Struts</code> would redirect each request to its associated method and I should not need to double-check it in the logic (also, if <code>Struts</code> fails to properly redirect, then the application would fail because the desired operation would not be executed).</p>
<p>I have asked Google for reasons for this code (existing or old bugs, etc.) but found none; anyone with experience in <code>Struts</code> can provide a reason that justifies the existence of such a code and so much (apparently) wasted effort? I want to know if I am free to delete such code to simplify the methods (which are messy enough without these "improvements").</p>
<p>(*) There are a few instances in which the code does not appear, but it smells just of the programmer forgetting it.</p>
| [] | [
{
"body": "<p>I don't believe there's any good use-case for this code. I know it makes for a boring answer, but sometimes the correct thing really is simple and boring. As you say, the Struts framework should always redirect to the appropriate method and fail entirely otherwise.</p>\n\n<p>Even the scant lines you posted have some bad/useless programming practices, so my guess is that the developer thought he was being thorough and clever by tacking on needless framework.</p>\n\n<pre><code>if (method != null && \"myMethod\".equals(method)) {\n // Perform the actual work\n</code></pre>\n\n<p>He already checks for <code>method != null</code> and then checks for <code>\"myMethod\".equals(method)</code>. The only reason to use the second construction for a <code>String</code> comparison is to avoid a <code>NullPointerException</code>... which he's already done by checking against <code>null</code>. So either he doesn't know that Java short-circuits conditions, or he has no idea what the purpose is behind the second construction.</p>\n\n<p>Also, it's generally a bad idea to have huge wrappers around entire method bodies. It would be a better design to have something like this (if it were needed at all):</p>\n\n<pre><code>if(method == null || !method.equals(\"myMethod\") {\n return;\n}\n\n//do stuff\n</code></pre>\n\n<p>... Or you could write the conditional as <code>if(!\"myMethod\".equals(method))</code>, but I honestly really hate the flipped comparison rather than explicitly checking for <code>null</code>. I suppose it's a matter of taste, though.</p>\n\n<p>Anyway, bottom line: no, there's no use for it, and there's evidence that the original programmer didn't entirely know what he was doing, anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:20:00.270",
"Id": "82174",
"Score": "0",
"body": "+1 I agree with you... My guess is that someone told them of \"single exit point\" and tried to do it this way, but I have begun to swap that code for `if (!\"myMethod\".equals(request.getParameter(\"method\"))) { return [method default mapping, usually \"\"]; }` so at the very least I get one less level of indentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:25:23.920",
"Id": "82176",
"Score": "1",
"body": "And for the fact the answer is boring, it is what I already expected. At least now I can show some \"due diligence\" investigating the possible outcome of the changes before performing them, in case there is some surprise waiting for me (being the sole developer makes it difficult to blame somewhere else :-D)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:11:46.763",
"Id": "46920",
"ParentId": "46788",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46920",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T08:12:27.330",
"Id": "46788",
"Score": "2",
"Tags": [
"java"
],
"Title": "Inherited code checking Struts method name"
} | 46788 |
<p>I have been developing this plugin architecture, mostly for fun and education, its a simple WinForm with some plugin logic and two plugins, i want to know if there is a better way of doing it. </p>
<p>Form1.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Plugin_architecture
{
public partial class Form1 : Form
{
// -----------------------Plugin logic ----------------------------------
private static IEnumerable<Type> getDerivedTypesFor(Type baseType)
{
var assembly = Assembly.GetExecutingAssembly();
return assembly.GetTypes().Where(baseType.IsAssignableFrom).Where(t => baseType != t);
}
public void invokePlugin(object sender, EventArgs e, string pluginIdentifier) {
Type type = Type.GetType(pluginIdentifier);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("start");
method.Invoke(instance, null);
}
public void registerPlugins() {
// Register plugins at application startup
IEnumerable<Type> plugins = getDerivedTypesFor(typeof(Plugin));
foreach(Type plugin in plugins) {
LinkLabel pluginLabel = new LinkLabel();
pluginLabel.Text = plugin.ToString();
pluginLabel.Click += delegate(object sender, EventArgs e) { invokePlugin(sender, e, plugin.ToString()); };
pluginContainer.Controls.Add(pluginLabel);
}
}
// --------------------------------------------------------------------------
public Form1()
{
InitializeComponent();
registerPlugins();
}
}
}
</code></pre>
<p>Plugin.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
abstract class Plugin
{
/*
* Base class for plugins
* Implement the start method and add any functionality you want. The start method will be
* called each time the plugin is started. Use the stop method to do any nessesary cleanup.
*/
//public void init() {
// // Initialize plugin
//}
//public void register() {
// // Register plugin in application
//}
abstract public void start();
abstract public void stop();
}
</code></pre>
<p>ServicePlugin.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
class ServicePlugin : Plugin
{
override public void start() {
const string message = "Yeahh! Plugins!!";
const string caption = "Plugins!";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
override public void stop() {
}
}
</code></pre>
<p>ClientPlugin.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Plugin_architecture.Plugins.ClientPlugin;
class ClientPlugin : Plugin
{
override public void start() {
Client frm = new Client();
frm.Show();
}
override public void stop() {
}
}
</code></pre>
<p>Client.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Plugin_architecture.Plugins.ClientPlugin
{
public partial class Client : Form
{
public Client()
{
InitializeComponent();
}
}
}
</code></pre>
<p>The code works great, and should compile without problems. </p>
| [] | [
{
"body": "<p>You should use an interface instead of an abstract class:</p>\n\n<pre><code>public interface IPlugin {\n void Start();\n void Stop();\n}\n</code></pre>\n\n<p>There are many reasons for this, as detailed in <a href=\"https://stackoverflow.com/questions/56867/interface-vs-base-class\">https://stackoverflow.com/questions/56867/interface-vs-base-class</a></p>\n\n<p>I would also separate the plugin logic out of the form, and create a \"PluginResolver\" class to handle these concerns (This is where you hide the ugly reflection stuff you don't want to touch again).</p>\n\n<p>In terms of the rest of the code, it's pretty basic, so not much to add.</p>\n\n<p>In terms of creating a \"plugin architecture\" it's kind of a waste without using dependency injection (or a dependency resolver of some kind), because there's no obvious way for plugins to communicate with each other, unless they get coupled together (which defeats the whole point of the plugin architecture), instead by having a set of root services that can be injected into the particular plugins, you can have a disconnected way of giving them all access to say \"the primary error logger\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:06:00.440",
"Id": "46801",
"ParentId": "46790",
"Score": "3"
}
},
{
"body": "<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx\" rel=\"nofollow\">MEF</a>. For example:</p>\n\n<pre><code>// This would preferably be in an assembly outside the main app\n[InheritedExport]\npublic abstract class Plugin\n{\n public abstract void Start();\n public abstract void Stop();\n}\n\n// This can be in an assembly outside the main app\npublic class MyPlugin : Plugin\n{\n public override void Start()\n {\n // whatever\n }\n\n public override void Stop()\n {\n // whatever\n }\n}\n\npublic class CompositionRoot\n{\n public CompositionRoot()\n {\n var catalog = new AggregateCatalog();\n catalog.Catalogs.Add(new DirectoryCatalog(\"PluginsPath\"));\n\n var container = new CompositionContainer(catalog);\n container.ComposeParts(this);\n }\n\n [ImportMany(typeof(Plugin))]\n public IEnumerable<Plugin> Plugins { get; set; }\n\n public void StartPlugins()\n {\n foreach (var plugin in Plugins)\n {\n plugin.Start();\n }\n }\n\n public void StopPlugins()\n {\n foreach (var plugin in Plugins)\n {\n plugin.Stop();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:10:54.773",
"Id": "46802",
"ParentId": "46790",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:19:55.433",
"Id": "46790",
"Score": "4",
"Tags": [
"c#",
"winforms"
],
"Title": "WinForm plugin architecture"
} | 46790 |
<p>I've written it for an assessment. It works but my assessment also requires a peer to review it in terms of how it could be improved, how it rates as a piece of JavaScript, etc, any comments would be appreciated (I don't know anyone else to ask).</p>
<p>As a bit of background this is JavaScript written to be embedded in a HTML doc. It calculates the balance of two accounts when they each increment daily by a certain value. It reports when they will be equal, when the lesser balance exceeds the greater, or if the accounts will always be unequal. All values can be entered by a user. </p>
<p>I look forward to your comments. </p>
<p>/<em>process function is called by user pressing a Process button</em>/</p>
<pre><code>function process()
{
var account1 = document.getElementById("account_1").value;
var account2 = document.getElementById("account_2").value;
var increm1 = document.getElementById("increm_1").value;
var increm2 = document.getElementById("increm_2").value;
blankOrSame(account1,account2,increm1,increm2);
account1 = Number(account1);
account2 = Number(account2);
increm1 = Number(increm1);
increm2 = Number(increm2);
alwaysDiff(account1,account2,increm1,increm2);
sameGreater(account1,account2,increm1,increm2);
}
</code></pre>
<p>/*field_vldn function is performed onchange when user updates fields*/</p>
<pre><code>function field_vldn(name) //onchange validation for account & increment fields.
{
var num = document.getElementById(name).value;
if ( isNaN(num))
{
alert("Please enter a number.");
return document.getElementById(name).value = null;
}
}
</code></pre>
<p>/<em>below functions are called by process function</em>/</p>
<pre><code>function blankOrSame(account1,account2,increm1,increm2)//validation for blank fields or if accounts will always be equal.
{
if (account1 == "" || account2 == "" || increm1 == "" || increm2 == "")
{
alert("Please complete all fields then press the 'Process' button.");
}
else if (account1 == account2 && increm1 == increm2)
{
alert("Based on the values entered the both Accounts will always have an equal balance.");
}
}
function alwaysDiff(account1,account2,increm1,increm2)//determined if accounts will always be inequal. Variables must first be converted to numbers.
{
if ((account1 <= account2 && increm1 < increm2) || (account1 < account2 && increm1 == increm2))
{
alert("The accounts will never be equal. Account 1 will always contain less money than Account 2.");
}
else if ((account1 >= account2 && increm1 > increm2) || (account1 > account2 && increm1 == increm2))
{
alert("The accounts will never be equal. Account 2 will always contain less money than Account 1.");
}
}
function sameGreater(account1,account2,increm1,increm2)//determines when accounts will be same or lesser exceeds greater.
{
if (account1 < account2 && increm1 > increm2)//statement for when account 1 is initally lesser.
{
var n = 0;
while (account1 < account2)
{
account1 = account1 + increm1;
account2 = account2 + increm2;
n = ++n
}
if (account1 == account2)//accounts eventually become equal, will also report when account1 exceeds account2.
{
alert("After " + n + " day/s Account 1 and Account 2 will be the same balance ($" + account1 + ").\nIn "
+ (n+1) + " day/s Account 1 ($" + (account1+increm1) + ") will be greater than Account 2 ($" + (account2+increm2)
+ ").");
}
else if (account1 > account2)//account1 exceeds account2 without ever becoming equal.
{
alert("After " + n + " day/s Account 1($" + account1 + ") will be greater than Account 2 ($" + account2 + ").");
}
}
else if (account1 > account2 && increm1 < increm2)//statement for when account 2 is initally lesser.
{
var n = 0;
while (account1 > account2)
{
account1 = account1 + increm1;
account2 = account2 + increm2;
n = ++n
}
if (account1 == account2)//accounts eventually become equal, will also report when account2 exceeds account1.
{
alert("After " + n + " day/s Account 1 and Account 2 will be the same balance ($" + account1 + ").\nIn "
+ (n+1) + " day/s Account 2 ($" + (account2+increm2) + ") will be greater than Account 1 ($" + (account1+increm1)
+ ").");
}
else if (account1 < account2)//account2 exceeds account1 without ever becoming equal.
{
alert("After " + n + " day/s Account 2 ($" + account2 + ") will be greater than Account 1 ($" + account1 + ").");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T10:28:15.527",
"Id": "81904",
"Score": "0",
"body": "`document.getElementById` may not work on all of the js enabled browsers. See e.g. this Q/A: http://stackoverflow.com/questions/4069982/document-getelementbyid-vs-jquery"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T10:30:38.053",
"Id": "81906",
"Score": "0",
"body": "`if (account1 == \"\" || account2 == \"\" || increm1 == \"\" || increm2 == \"\")` is a bad way to check the fields. What if the user inputs something other than a number? e.g., an space char?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:35:46.287",
"Id": "81951",
"Score": "0",
"body": "@Mohsen You are wrong, and that link does not state that. Please check https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById#Browser_Compatibility"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T04:23:56.060",
"Id": "82042",
"Score": "0",
"body": "There are incompatibilities in some older browsers, such as IE 6 and 7 and it's safer to use jQuery to select an elelment: http://remysharp.com/2007/02/10/ie-7-breaks-getelementbyid/"
}
] | [
{
"body": "<ol>\n<li><p>In JavaScript, it's generally a good idea to use the brace-on-same-line style, i.e.</p>\n\n<pre><code>if( ... ) {\n ...\n} else {\n ...\n}\n</code></pre>\n\n<p>because of javascript's policy of <a href=\"http://inimino.org/~inimino/blog/javascript_semicolons\" rel=\"nofollow\">automatic semicolon insertion</a>. While it's usually not a problem, it may bite you one day if you use the brace-on-new-line style.</p></li>\n<li><p><code>field_vldn</code> is a strange name - your other functions are named more descriptively, and use the conventional <code>camelCase</code> style - why doesn't <code>field_vldn</code> do the same?</p></li>\n<li><p>Your validation is being done in two places (<code>field_vldn</code> and in <code>blankOrSame</code>). Combine that logic.</p></li>\n<li><p>The logic for comparing the accounts is too complicated. Or, each part of it is simple, but there's too much repetition, and using the <code>while</code> loops (two of them even, instead of extracting a function) is very brute-force, when a more generic solution is possible.</p></li>\n</ol>\n\n<p>For that last point, here's the deal: this is a simple math problem. An account's balance can be expressed as:</p>\n\n<p>$$\nf(x) = ax + b\n$$</p>\n\n<p>where \\$x\\$ is the number of days, \\$a\\$ is the daily increment, and \\$b\\$ is the initial balance.</p>\n\n<p>To figure out when - if ever - the two accounts, \\$f{_1}\\$ and \\$f{_2}\\$, will be equal, you simply isolate \\$x\\$ in \\$f{_1}(x) = f{_2}(x)\\$:</p>\n\n<p>$$\nx = \\frac{b{_2} - b{_1}}{a{_1}-a{_2}}\n$$</p>\n\n<p>If \\$x\\$ is zero, the accounts are already equal at day 0.<br>\nIf \\$x\\$ is negative, the accounts won't ever be equal (unless you go back in time).<br>\nIf \\$x\\$ is positive and an integer, the two accounts will end up being exactly equal after \\$x\\$ days.<br>\nIf \\$x\\$ is positive but fractional, you simply round up to the next integer, and that's the number of days it'll take for one account to \"overtake\" the other.<br>\nIf \\$x\\$ is ±<code>Infinity</code> (which is how JS expresses \\$\\frac{n}{0}\\$, and which you can check with <code>Number.isFinite()</code>) the two balances will progress in parallel, and will never be equal or intersect.<br>\nIf \\$x\\$ is <code>NaN</code>, the two accounts are identical (\\$x = \\frac{0}{0}\\$) and will always be equal.</p>\n\n<p>Note that while you can simply use <code>x === Infinity</code> instead of <code>!Number.isFinite()</code>, you <em>can't</em> use <code>x === NaN</code> or <code>x == NaN</code>. In JavaScript <code>NaN</code> isn't equal to anything - it's not even equal to <code>NaN</code> (don't ask why).</p>\n\n<p>You can also calculate the numerator and denominator of the fraction separately, and do some checks there instead of doing the division. Once you have the mathematical approach, you can make some practical optimizations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:32:47.713",
"Id": "46806",
"ParentId": "46793",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:51:05.030",
"Id": "46793",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Balancing Accounts Daily"
} | 46793 |
<p>Consider a method (let's call it <code>IsPrimeHybrid</code>) which calls at least two methods (let's call them <code>IsPrimeNaive</code> and <code>IsPrimeBySearch</code>) that calculate an identical result using different approaches and the outer method returns the result when any of the inner methods finishes.</p>
<p>The following is my first attempt to write such a method, but I'd like to hear what issues it may have and what's a good way to fix them. (For example, how to implement thread safety in a scenario like this.)</p>
<pre><code> public static bool IsPrimeHybrid(BigInteger number)
{
var result = default(bool);
var byPureCalc = Task.Run(() => result = IsPrimeNaive(number));
var bySearchFirst = Task.Run(() => result = IsPrimeBySearch(number));
Task.WaitAny(byPureCalc, bySearchFirst);
return result;
}
</code></pre>
<p><em>For the sake of simplicity, please assume that none of the called methods will consume any common resources, apart from processing power and memory (that is, there will never be two methods that both use file I/O or network I/O, etc).</em></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T10:28:49.097",
"Id": "81905",
"Score": "1",
"body": "The code looks ok, but I am a little confused by your objectives. If your intention is to find which method is faster, maybe a classic benchmark (lots of iterations, not competition for resources) would be better, specially if the difference is small (also, you will learn not only which method is faster but also *how much* faster it is)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T10:42:04.140",
"Id": "81907",
"Score": "0",
"body": "@SJuan76 I understand what you're saying, but I'd like to be able to also use this pattern in a wider scope than what I've shown here. There may be cases (other than primality tests) where the input isn't one-dimensional and possibly not easily reproducible or there may be external factors (such as server load, noise, etc) playing a role in the performance of one or more of the candidate methods."
}
] | [
{
"body": "<p>Edit: since the question is already using Tasks, it is better to use Cancellation tokens instead of ManualResetEvents. Also there is no need to explicitly create a Mutex, in C# we can use lock() on any shared Object for this. I am including source code at the bottom.</p>\n\n<p>It would be quite wasteful if one algorithm took 3 seconds and the other one took 1 minute, you never know with edge cases ... </p>\n\n<p>rather than </p>\n\n<pre><code> Task.Run(() => result = IsPrimeNaive(number));\n</code></pre>\n\n<p>you could do (see below about abortHandle)</p>\n\n<pre><code> Task.Run(() => IsPrimeNaive(abortHandle, number, ref result));\n</code></pre>\n\n<p>You could Create a ManualResetEvent (which I call abortHandle) with state 'false' (<a href=\"https://stackoverflow.com/questions/5538902/how-to-use-wait-handles-in-c-sharp-threading\">https://stackoverflow.com/questions/5538902/how-to-use-wait-handles-in-c-sharp-threading</a>) and pass it to each of the methods. Implement each method in a way that they check as often as possible if the event has been set externally, if so, simply stop the calculation and return. When a method is finishing it should check again for the abortHandle and if not set then set the result value and the event itself.</p>\n\n<p>Note that there is a tiny chance that 2+ methods would finish at exactly the same time and both check the still reset abortHandle at the same time. If you want to be certain, then you would need to pass an extra Mutex or CriticalSection (see <a href=\"https://stackoverflow.com/questions/800383/what-is-the-difference-between-mutex-and-critical-section\">https://stackoverflow.com/questions/800383/what-is-the-difference-between-mutex-and-critical-section</a>) to make sure only one process is setting the result.</p>\n\n<p>Also about thread safety and regarding the input parameters, it is tricky : depends on which types of objects you will be passing, if you are passing primitives like int and string I believe you will be fine (see <a href=\"https://stackoverflow.com/questions/10792603/how-are-strings-passed-in-net\">https://stackoverflow.com/questions/10792603/how-are-strings-passed-in-net</a>), but if you are passing classes, then you might have trouble even if you only read things from it -it will depend how the classes are implemented: they need to be thread safe themselves.</p>\n\n<pre><code>using System;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n\n static void IsPrimeNaive(Object lockSync, CancellationToken cancellationToken, int n, ref bool result)\n {\n Random rnd = new Random(System.Convert.ToInt32((Thread.CurrentThread.ManagedThreadId)%Int32.MaxValue));\n\n for (var i=2; i<n; i++)\n {\n if (cancellationToken.IsCancellationRequested){\n //if cancellation is set (another thread already finished, or process simply is shutting down, leave)\n Console.WriteLine(\"worker: I was too slow, another thread already finished...\");\n return;\n }\n\n if (n%i == 0)\n {\n //make sure we have exclusive access to the result\n lock (lockSync)\n {\n result = false;\n }\n Console.WriteLine(\"worker: \" + n + \" is not prime.\");\n\n return;\n }\n\n Thread.Sleep(rnd.Next(3));\n }\n\n\n if (!cancellationToken.IsCancellationRequested)\n { \n //make sure we have exclusive access to the result\n lock (lockSync)\n {\n result = true;\n }\n\n Console.WriteLine(\"worker: \" + n + \" is indeed a prime.\"); \n }\n }\n\n\n static void Main(string[] args)\n {\n Object syncLock = new Object();\n ManualResetEvent abortHandle = new ManualResetEvent(false);\n CancellationTokenSource cancellationSource = new CancellationTokenSource();\n\n bool result = false;\n Task[] tasks = new Task[3];\n\n int target = 269;\n\n //I only have 1 implementation, but there is some Thread.Sleep inside to make sure they end at different times\n tasks[0] = Task.Run(() => IsPrimeNaive(syncLock, cancellationSource.Token, target, ref result));\n tasks[1] = Task.Run(() => IsPrimeNaive(syncLock, cancellationSource.Token, target, ref result));\n tasks[2] = Task.Run(() => IsPrimeNaive(syncLock, cancellationSource.Token, target, ref result));\n\n Task.WaitAny(tasks, cancellationSource.Token);\n Console.WriteLine(String.Format(\"main: {0} is {1} a prime\", target, result ? \"\" : \"not\"));\n\n //now cancel any threads still running (because they are checking for \n cancellationSource.Cancel();\n\n\n //expect the other threads to write the 'i am too late' message at some point here\n\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:11:59.830",
"Id": "46796",
"ParentId": "46794",
"Score": "7"
}
},
{
"body": "<p><code>Task</code>s can have results, you should take advantage of that, instead of assigning a local variable from a lambda. And <code>WaitAny()</code> returns the index of the <code>Task</code> that finished first. This means you can do something like:</p>\n\n<pre><code>public static bool IsPrimeHybrid(BigInteger number)\n{\n var byPureCalc = Task.Run(() => IsPrimeNaive(number));\n var bySearchFirst = Task.Run(() => IsPrimeBySearch(number));\n var tasks = new[] { byPureCalc, bySearchFirst };\n int firstIndex = Task.WaitAny(tasks);\n return tasks[firstIndex].Result;\n}\n</code></pre>\n\n<p>Also, CPU and memory are also resources that you shouldn't waste. So, you may want to cancel the slower <code>Task</code>, after the faster one finished. For that, you can use <code>CancellationToken</code>, which the two computations will periodically check (you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.throwifcancellationrequested\"><code>ThrowIfCancellationRequested ()</code></a> for that):</p>\n\n<pre><code>public static bool IsPrimeHybrid(BigInteger number)\n{\n var cts = new CancellationTokenSource();\n\n var byPureCalc = Task.Run(() => IsPrimeNaive(number, cts.Token));\n var bySearchFirst = Task.Run(() => IsPrimeBySearch(number, cts.Token));\n var tasks = new[] { byPureCalc, bySearchFirst };\n\n int firstIndex = Task.WaitAny(tasks);\n\n cts.Cancel();\n return tasks[firstIndex].Result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:11:53.790",
"Id": "81929",
"Score": "0",
"body": "Yeah, I somehow missed the fact that `WaitAny` returned a value! This indeed means there's no need for an outer variable and any safety issues that could have arisen from that. Thank you, this addresses my most critical concern!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-03T18:57:08.510",
"Id": "243413",
"Score": "0",
"body": "Under what circumstances would WaitAny() never return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-03T19:36:13.893",
"Id": "243425",
"Score": "0",
"body": "@gonzobrains Not sure how is that relevant here, but that can only happen when none of the `Task`s complete."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:25:24.597",
"Id": "46804",
"ParentId": "46794",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "46804",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T09:53:47.693",
"Id": "46794",
"Score": "12",
"Tags": [
"c#",
"multithreading"
],
"Title": "Returning the result of whichever method finishes first"
} | 46794 |
<p>This is my constructor to transform an Outlook contact into a Dynamics CRM contact:</p>
<pre><code>public Contact(ContactItem contactItem)
{
LogicalName = EntityLogicalName;
FirstName = contactItem.FirstName;
LastName = contactItem.LastName;
//if no last name, use the first name
if (String.IsNullOrEmpty(LastName))
{
LastName = contactItem.FirstName;
//if no First name, use the Full Name.
if (String.IsNullOrEmpty(LastName))
{
LastName = contactItem.FullName;
//if no last name or first name, use the company name
if (String.IsNullOrEmpty(LastName))
{
LastName = contactItem.CompanyName;
//If no last name, no first name and no company name, use the email address.
if (String.IsNullOrEmpty(LastName))
{
LastName = contactItem.Email1Address;
//if no Last name, no first name, no company name, no email address, default to naam niet bekend.
if (String.IsNullOrEmpty(LastName))
{
LastName = @"Naam niet bekend";
}
}
}
}
else
{
FirstName = "";
}
}
Address1_City = contactItem.BusinessAddressCity;
Address1_Country = contactItem.BusinessAddressCountry;
Address1_Line1 = contactItem.BusinessAddressStreet;
Address1_PostalCode = contactItem.BusinessAddressPostalCode;
Telephone1 = contactItem.BusinessTelephoneNumber;
Telephone2 = contactItem.HomeTelephoneNumber;
Fax = contactItem.BusinessFaxNumber;
Address2_Line1 = contactItem.HomeAddressStreet;
Address2_City = contactItem.HomeAddressCity;
Address2_PostalCode = contactItem.HomeAddressPostalCode;
Address2_Country = contactItem.HomeAddressCountry;
EMailAddress1 = contactItem.Email1Address;
EMailAddress2 = contactItem.Email2Address;
EMailAddress3 = contactItem.Email3Address;
}
</code></pre>
<p>As you can see, I got 5 nested <code>if</code>s to determine what I should use for <code>LastName</code>. I don't like how it looks, but the only other option I can see is putting them in sequence instead of nested. However, that would mean that instead of usually having only 1-3 ifs, it would be forced into doing 5 ifs every single time. during tests with 1800 records, it already felt noticeably slower if it got to the literal string.</p>
<p>Is there some really easy way (or some really obscure way) of doing this which I missed?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:50:44.590",
"Id": "81914",
"Score": "3",
"body": "You should avoid pre-mature optimization at the expense of readability until it's absolutely required. Then you should measure to see what your really slow parts are and address those first. (If a simple string null check is your biggest problem, then I applaud you for your pure awesome)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:43:25.553",
"Id": "81923",
"Score": "0",
"body": "IFs are lightning fast, null check and zero length checks are lightning fast, how could it be possible to perceive slowness over this??. In any case, regardless the implementation you should create a DisplayName property with only get and put the logic there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:19:53.193",
"Id": "81933",
"Score": "0",
"body": "When i'm referring to \"noticeably slower\", I meant that during the creation of 1800 contacts in-memory, the \" X contacts created\" console statements scrolled by at an approximate rate of 100-150 per second instead of 200 per second. it still was done quite fast (inserting them into CRM took quite a lot more time using a simple foreach(){context.addobject()} followed by a savechanges()), but it felt like it went somewhat slower."
}
] | [
{
"body": "<ol>\n<li><p>You could create a helper function with a loop:</p>\n\n<pre><code>public string getFirstNonNullOrEmpty(params string[] names) {\n foreach (string name in names) {\n if (String.IsNullOrEmpty(name)) {\n continue;\n }\n return name;\n }\n return @\"Naam niet bekend\";\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>LastName = getFirstNonNullOrEmpty(contactItem.LastName, contactItem.FirstName, \n contactItem.FullName, contactItem.CompanyName, contactItem.Email1Address);\n</code></pre>\n\n<p>You might also need this because of the <code>else</code> branch:</p>\n\n<pre><code>if (String.IsNullOrEmpty(contactItem.LastName)) \n && !String.IsNullOrEmpty(contactItem.FirstName)) {\n FirstName = \"\";\n}\n</code></pre></li>\n<li><p>You might want to use <code>IsNullOrWhiteSpace</code> instead of <code>IsNullOrEmpty</code>.</p></li>\n</ol>\n\n<p>(I'm not too familiar with C# and don't have a C# compiler right now so the syntax might be invalid.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:40:52.013",
"Id": "81922",
"Score": "4",
"body": "You could avoid that `continue` and simplify the code a bit by negating the condition: `if (!String.IsNullOrEmpty(name)) { return name; }`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:07:30.773",
"Id": "81928",
"Score": "0",
"body": "@svick: I know that but I like guard clauses."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:44:02.700",
"Id": "81935",
"Score": "3",
"body": "using Linq body of `getFirstNonNullOrEmpty` can be changed to `return names.SkipWhile(String.IsNullOrEmpty).FirstOrDefault() ?? @\"Naam niet bekend\";`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:36:50.750",
"Id": "46799",
"ParentId": "46797",
"Score": "10"
}
},
{
"body": "<p>You could reverse the condition, and build an if - else - if ladder. \nOnly the worst case scenario would have 5 evaluations.</p>\n\n<pre><code>...\n if (String.IsNullOrEmpty(LastName))\n {\n if (!string.IsNullOrEmpty(contactItem.FirstName))\n {\n LastName = ...\n }\n else if (!string.IsNullOrEmpty(contactItem.FullName))\n {\n LastName = ...\n }\n else if (!string.IsNullOrEmpty(contactItem.CompanyName))\n {\n LastName = ...\n }\n else if (!string.IsNullOrEmpty(contactItem.Email1Address))\n {\n LastName = ...\n }\n else\n {\n LastName = ...\n }\n }\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:47:40.193",
"Id": "81912",
"Score": "0",
"body": "That's really similar to what I currently have, because I also currently have 5 evaluations in worst-case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:49:11.053",
"Id": "81913",
"Score": "0",
"body": "true, but the nesting stays at one level, and indentation doesn't move further right. I find it personally more readable. It approaches \"switch clarity\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:51:33.213",
"Id": "81915",
"Score": "0",
"body": "You could of course build a list with all the potential \"LastName\" values in order of priority, and use a FirstOrDefault(s => !string.IsNullOrEmpty(s)), but I think it goes a bit too far. But maybe it's something?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:46:36.617",
"Id": "46800",
"ParentId": "46797",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>Contact and ContactItem should in some way be child and parent, or at-least share a common ancestor so that you don't have to manually copy over all that identical contact information.</p></li>\n<li><p>I'm not certain, but I think you might have wanted all this to be done with the <code>LogicalName</code> and not the <code>LastName</code> of this contact.</p></li>\n<li><p>You should be using <code>string.IsNullOrWhiteSpace</code> in-case these strings haven't been trimmed or something.</p></li>\n<li><p>As for simplifying your nest of ifs there are two solutions that fit the program as is.</p>\n\n<ol>\n<li><p>Use a less ugly ternary statement to do exactly what you were doing before</p>\n\n<pre><code>if(string.IsNullOrWhiteSpace(LastName))\n{\n LastName = \n !String.IsNullOrEmpty(contactItem.FirstName) ? contactItem.FirstName : \n !String.IsNullOrEmpty(contactItem.FullName) ? contactItem.FullName : \n !String.IsNullOrEmpty(contactItem.CompanyName) ? contactItem.CompanyName : \n !String.IsNullOrEmpty(contactItem.Email1Address) ? contactItem.Email1Address : \n @\"Naam niet bekend\";\n if(LastName == FirstName)\n FirstName = string.Empty;\n}\n</code></pre></li>\n<li><p>Using Linq: I created a list of all the possible values that you considered valid, then calling the <code>First()</code> Extension method on our string array, would by default return just the first item in our array. By passing in a lambda expression I override that behavior to return the first value which matches my condition, which is <code>!string.IsNullOrWhiteSpace()</code></p>\n\n<pre><code>if (string.IsNullOrWhiteSpace(LastName))\n{\n LastName = new string[] { contactItem.FirstName, contactItem.FullName, contactItem.CompanyName, contactItem.Email1Address, @\"Naam niet bekend\" }\n .First(str => !string.IsNullOrWhiteSpace(str));\n if (LastName == FirstName)\n FirstName = string.Empty;\n}\n</code></pre></li>\n</ol></li>\n<li><p>If you were certain that all your empty strings were actually null instead of empty strings you could have just used the null-coalescing operator <code>??</code>, which returns the first side of the argument which proves to not be null while moving from left to right. In this case, your code would have looked like this.</p>\n\n<p><strong>Note</strong>: To make a string null use <code>string str = default(string);</code></p>\n\n<pre><code>if (string.IsNullOrWhiteSpace(LastName))\n{\n LastName = contactItem.FirstName ?? contactItem.FullName ?? contactItem.CompanyName ?? contactItem.Email1Address ?? @\"Naam niet bekend\";\n if (LastName == FirstName)\n FirstName = string.Empty;\n}\n</code></pre></li>\n<li><p>The code I posted in <code>4.1</code> is the most efficient because it only does as many comparisons as is needed, and cuts out when it finds the correct value. One advantage 4.1 has over the code you posted is that it doesn't do a string assignment before it does the comparison. Your code could have been re-written to avoid that as-well. </p>\n\n<p>The code in <code>4.2</code> is sleek, however it does require you to create an array, which is not expensive at all.</p>\n\n<p>I am only mentioning this, because it is something to consider when choosing the right code for you. While the differences here may not even be noticeable by the computer its self in terms of run-time speed, efficiency is something to keep in mind at all times when coding.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:09:48.460",
"Id": "81938",
"Score": "0",
"body": "I can already answer to the first item that that's just not relevant because they're from entirely different software: ContactItem is from Microsoft Outlook 2013 and Contact is from Microsoft Dynamics CRM 2013. I had to write a custom import tool because I couldn't use the CRM Outlook connector. And there's a 1 to 1 relationship between the 2, but 1 is basically a COM-object while the other is derived from a CRM-specific Object called Entity. LogicalName is unrelated to LastName, instead indicating what implementation of the Entity object we're talking about (in this case Contact)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:11:21.570",
"Id": "81939",
"Score": "0",
"body": "@NateKerkhofs I completely understand... Working with foreign APIs always does this to me too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:57:02.990",
"Id": "46813",
"ParentId": "46797",
"Score": "3"
}
},
{
"body": "<p>Take advantage of inline assignment and the short-circuiting behavior of the && operator. This code has the same behavior as your original, but it collapses the innermost three if-statements together into one:</p>\n\n<pre><code>if (String.IsNullOrEmpty(LastName))\n{\n if (String.IsNullOrEmpty(LastName = contactItem.FirstName))\n {\n if (String.IsNullOrEmpty(LastName = contactItem.FullName)\n && String.IsNullOrEmpty(LastName = contactItem.CompanyName)\n && String.IsNullOrEmpty(LastName = contactItem.Email1Address))\n {\n LastName = @\"Naam niet bekend\";\n }\n }\n else\n {\n FirstName = \"\";\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:23:04.887",
"Id": "46839",
"ParentId": "46797",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46799",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T11:13:27.960",
"Id": "46797",
"Score": "10",
"Tags": [
"c#",
"performance"
],
"Title": "Constructor to transform an Outlook contact into a Dynamics CRM contact"
} | 46797 |
<p>I have a <code>Timer</code> class executing a function in a specified interval:</p>
<pre><code>#include <chrono>
#include <functional>
#include <future>
#include <iostream>
#include <list>
#include <mutex>
#include <thread>
using namespace std;
// Timer
// =====
template <typename Result>
class Timer
{
public:
typedef std::chrono::milliseconds interval_type;
typedef Result result_type;
typedef std::list<result_type> results_type;
private:
typedef std::function<Result ()> function_type;
typedef std::future<result_type> future_type;
typedef std::mutex mutex;
public:
template <typename Callable, typename... Arguments>
Timer(Callable&& callable, Arguments&&... arguments)
: m_interval(interval_type::zero()),
m_function(std::bind(
std::move(callable),
std::forward<Arguments>(arguments)...))
{}
Timer(const Timer&) = delete;
Timer& operator = (const Timer&) = delete;
~Timer() { stop(); }
bool running() const { return m_interval != interval_type::zero(); }
template <typename Interval>
void start(const Interval& interval, Interval delay = Interval::zero()) {
m_interval = std::chrono::duration_cast<interval_type>(interval);
m_thread = std::thread([this, delay]() {
std::this_thread::sleep_for(delay);
if( ! this->running()) this->m_results.push_back(this->m_function());
else {
m_future = std::async(std::launch::async, this->m_function);
while(true) {
std::this_thread::sleep_for(this->m_interval);
if(this->running()) {
if(this->m_future.wait_for(interval_type::zero()) == std::future_status::ready) {
try {
std::lock_guard<mutex> guard(this->m_result_mutex);
this->m_results.push_back(this->m_future.get());
}
catch(const std::exception &) {}
m_future = std::async(std::launch::async, this->m_function);
}
}
else {
this->m_future.wait();
try {
std::lock_guard<mutex> guard(this->m_result_mutex);
this->m_results.push_back(this->m_future.get());
}
catch(const std::exception &) {}
break;
}
}
}
});
}
void stop() {
m_interval = interval_type::zero();
if(m_thread.joinable())
m_thread.join();
}
// Results
// =======
bool empty() const { return m_results.empty(); }
results_type results() const {
results_type results;
{
std::lock_guard<mutex> guard(m_result_mutex);
results.swap(m_results);
}
return results;
}
result_type result() {
std::lock_guard<mutex> guard(m_result_mutex);
result_type result = m_results.front();
m_results.pop_front();
return result;
}
private:
interval_type m_interval;
function_type m_function;
std::thread m_thread;
future_type m_future;
mutable mutex m_result_mutex;
mutable results_type m_results;
};
template <>
class Timer<void>
{
// Implementation details for the simpler case omitted.
};
// Test
// ====
char f() {
return '.';
}
int main()
{
using std::chrono::milliseconds;
Timer<char> timer(f);
timer.start(milliseconds(10));
for(unsigned i = 0; i <= 10; ++i) {
std::this_thread::sleep_for(milliseconds(100));
if(i == 10) timer.stop();
auto results = timer.results();
for(const auto& r : results)
std::cout << r;
std::cout << '\n';
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:20:18.760",
"Id": "81942",
"Score": "2",
"body": "Please, never edit the question code on Code Review: it generally invalidates the answers (and here, it was actually the case)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T22:41:03.297",
"Id": "83069",
"Score": "0",
"body": "A follow-up is at http://codereview.stackexchange.com/questions/47347/follow-up-timer-utilizing-stdfuture"
}
] | [
{
"body": "<p>Kudos! This is on the whole a well-written class, and you appear to have written code that is correct in the face of asynchronicity, which is quite difficult!</p>\n\n<hr>\n\n<p>To start with, I think <code>Timer</code> is a misleading name for this class. When I think of a timer, I think of a clock that counts down a particular interval once. This is something like a <code>PeriodicRunner</code> or <code>PeriodicFunction</code>; these names call out the fact that the function is called multiple times.</p>\n\n<hr>\n\n<p>There is no particular reason that the period and delay need be the same type of duration. Instead of using a default argument, I might instead write this as two functions:</p>\n\n<pre><code>template <typename Duration>\nstart(const Duration& period) { start(period, std::chrono::milliseconds(0); }\n\ntemplate <typename Duration1, typename Duration2>\nstart(const Duration1& period, const Duration2& delay) {...}\n</code></pre>\n\n<hr>\n\n<p>You have made a few design decisions with <code>start</code> that are reasonable decisions, but not the only or obvious choice. These decisions should be called out in documentation:</p>\n\n<ul>\n<li>If the previous call has not completed when the period next comes up, a call will be dropped silently.</li>\n<li>Exceptions thrown by the function will be dropped silently.</li>\n<li><code>this->m_results.push_back(...)</code> is within your try-catch block. <code>push_back</code> may throw e.g. because of memory exhaustion; this will also be dropped silently. On the other hand, <code>std::async</code> will throw if the implementation is unable to start a new thread, but it is called outside of any try-catch block, so will caused <code>std::terminate</code> to be called. Likewise, <code>std::this_thread::sleep_for</code> may throw if the duration type or clock is not from the standard library.</li>\n</ul>\n\n<hr>\n\n<p>There's quite a bit going on in <code>start</code> including some repetition; as an aid to the reader, consider pulling out some functions. For example, you repeat the code snippet</p>\n\n<pre><code>try {\n std::lock_guard<mutex> guard(...);\n m_results.push_back(m_future.get());\n} catch (const std::exception&) {}\n</code></pre>\n\n<p>which you could pull out into a private method.</p>\n\n<hr>\n\n<p><code>Timer::m_results</code> should not be mutable, and <code>Timer::results() const</code> should not be const. One rule of thumb for this is that const methods should be <a href=\"http://en.wikipedia.org/wiki/Idempotence\" rel=\"nofollow noreferrer\">idempotent</a>. You can implement <code>Timer::results()</code> like so:</p>\n\n<pre><code>results_type results() {\n std::lock_guard<mutex> guard(m_result_mutex);\n return std::move(m_results);\n}\n</code></pre>\n\n<p>I feel that this is clearer than the swap-into-temp implementation you currently have.</p>\n\n<hr>\n\n<p>I strongly suggest removing the <code>using namespace std;</code> line. You don't even appear to use it, and it can <a href=\"https://stackoverflow.com/a/1453605/66509\">cause problems</a>.</p>\n\n<hr>\n\n<p>You should document the public interface of your class. One good idea put a large comment at the top of the header file explaining use cases. You should also document most public methods of your class. Questions you should try to answer in the comments include:</p>\n\n<ul>\n<li>Are there restrictions on the parameters?</li>\n<li>Is the period the time between the start of two function invocations, or between the end of one invocation and the start of the next?</li>\n<li>Is the period a floor, a ceiling, or neither on the time between invocations?</li>\n<li>What happens if you call <code>start</code> twice on the same <code>Timer</code>?</li>\n<li>What happens if you call <code>start</code> and <code>stop</code> in different threads?</li>\n<li>Does <code>stop</code> block? Might the function be called again (or still be running) when <code>stop</code> returns?</li>\n<li>Must <code>stop</code> return before calling <code>result</code> or <code>results</code>?</li>\n<li>What does <code>result</code> return? Is it sensible to call <code>result</code> multiple times? What happens if you call <code>result</code> and no results remain?</li>\n</ul>\n\n<hr>\n\n<p>Consider marking the class <code>final</code>; I can't imagine a reasonable subclass.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:06:21.650",
"Id": "46815",
"ParentId": "46807",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46815",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:35:53.580",
"Id": "46807",
"Score": "7",
"Tags": [
"c++",
"c++11",
"timer"
],
"Title": "Timer utilizing std::future"
} | 46807 |
<p>This is my first attempt at creating a game in Haskell, and I would greatly appreciate some feedback.</p>
<p>Here is <code>Main.hs</code>:</p>
<pre><code>module Main where
import Deck
import Data.List
import System.Random
import Control.Monad.State
-- |'main' is the entry point for the program. This function will bind a
-- random number generator and pass it into a new 'Game' state. Finally, it will
-- evaluate the 'gameLoop'.
main :: IO ()
main = do
stdGen <- getStdGen
evalStateT gameLoop $ mkGame stdGen hitUnlessTwentyOne
-- |The 'Game' data type contains all of the state information about a
-- blackjack game.
data Game = Game
{ deck :: Deck
, playerHand :: [Card]
, playerAction :: Action
, dealerHand :: [Card]
, dealerAction :: Action
, dealerStrategy :: Strategy }
-- |The 'GameS' type represents the current state of the 'Game'.
type GameS a = StateT Game a
-- |The 'Action' data type represents the possible actions a player can take.
data Action = Hit | Stay deriving (Eq, Read)
-- |The 'Strategy' type is the signature of all AI functions used by the dealer.
type Strategy = [Card] -> GameS IO (Action)
-- |'gameLoop' will repeatedly evaluate an iteration of the game. It updates the
-- game state based on the actions of the player and the dealer, and then
-- determines if the game is over.
gameLoop :: GameS IO ()
gameLoop = do
curr <- get
when ((playerAction curr) == Hit) handlePlayer
when ((dealerAction curr) == Hit) handleDealer
gameOver <- isGameOver
when gameOver handleGameOver
when (not gameOver) gameLoop
handlePlayer :: GameS IO ()
handlePlayer = do
curr <- get
input <- liftIO $ do
let playerH = playerHand curr
putStrLn $ "Your hand: " ++ (show playerH)
putStrLn $ "Dealer's hand: " ++ (showDealer $ dealerHand curr)
putStrLn "What do you want to do? (Hit/Stay)"
input <- getLine
return input
let action = read input :: Action
when (action == Hit) $ do
let (card, deck') = runState draw $ deck curr
put curr { deck = deck'
, playerHand = card : playerHand curr }
new <- get
let playerH = playerHand new
liftIO . putStrLn $ "Your hand: " ++ (showDealer playerH)
when (action == Stay) $ do
put curr { playerAction = Stay }
handleDealer :: GameS IO ()
handleDealer = do
curr <- get
action <- dealerStrategy curr $ dealerHand curr
when (action == Hit) $ do
let (card, deck') = runState draw $ deck curr
put curr { deck = deck'
, dealerHand = card : dealerHand curr }
new <- get
let dealerH = dealerHand new
liftIO . putStrLn $ "The dealer hit."
liftIO . putStrLn $ "Dealer's hand: " ++ (showDealer dealerH)
when (action == Stay) $ do
put curr { dealerAction = Stay }
liftIO . putStrLn $ "The dealer stayed."
isGameOver :: GameS IO Bool
isGameOver = do
curr <- get
let playerA = playerAction curr
dealerA = dealerAction curr
playerH = playerHand curr
dealerH = dealerHand curr
bothStayed = (playerA == Stay && dealerA == Stay)
playerBust = bust playerH
dealerBust = bust dealerH
gameOver = bothStayed || playerBust || dealerBust
when playerBust $ liftIO . putStrLn $ "You busted out!"
when dealerBust $ liftIO . putStrLn $ "The dealer busted out!"
return gameOver
handleGameOver :: GameS IO ()
handleGameOver = do
curr <- get
let playerH = playerHand curr
dealerH = dealerHand curr
winner = won playerH dealerH
liftIO . putStrLn $ "Your hand: " ++ (show playerH) ++ ", " ++ (show (possiblePoints playerH))
liftIO . putStrLn $ "Dealer's hand: " ++ (show dealerH) ++ ", " ++ (show (possiblePoints dealerH))
when winner $ liftIO . putStrLn $ "You win!"
when (not winner) $ liftIO . putStrLn $ "You lose..."
won :: [Card] -> [Card] -> Bool
won playerH dealerH = playerScore > dealerScore
where playerScore = score playerH
dealerScore = score dealerH
score :: [Card] -> Int
score h
| bust h = 0
| otherwise = best h
bust :: [Card] -> Bool
bust = and . map ((<) 21) . possiblePoints
twentyOne :: [Card] -> Bool
twentyOne = any ((==) 21) . possiblePoints
best :: [Card] -> Int
best = maximum . filter ((>=) 21) . possiblePoints
showDealer :: [Card] -> String
showDealer hand = "[" ++ (show $ head hand) ++ "," ++ (intersperse ',' hidden) ++ "]"
where n = length $ tail hand
hidden = replicate n '?'
mkGame :: StdGen -> Strategy -> Game
mkGame g strat = Game
{ deck = d'
, playerHand = playerH
, playerAction = Hit
, dealerHand = dealerH
, dealerAction = Hit
, dealerStrategy = strat }
where d = execState shuffle $ mkDeck g
((playerH, dealerH), d') = runState deal $ d
deal :: DeckS ([Card], [Card])
deal = do
mine <- draw
yours <- draw
mine' <- draw
yours' <- draw
let me = [mine, mine']
you = [yours, yours']
return (me, you)
hitUnlessTwentyOne :: Strategy
hitUnlessTwentyOne hand
| twentyOne hand = return Stay
| otherwise = return Hit
hitSometimes :: Double -> Strategy
hitSometimes threshold _ = do
curr <- get
let deck' = deck curr
(num, gen') = random $ gen deck'
put curr { deck = deck' { gen = gen' } }
if num > threshold
then return Hit
else return Stay
</code></pre>
<p>Here is <code>Deck.hs</code>:</p>
<pre><code>module Deck
( Card
, possiblePoints
, Deck
, DeckS
, cards
, gen
, mkDeck
, draw
, shuffle
, takeRandomCard
, takeCardAt ) where
import System.Random
import Control.Monad.State
-- |The 'Card' data type represents the possible playing card ranks.
data Card = Ace
| Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine
| Ten
| Jack
| Queen
| King
deriving (Enum, Show)
-- |'possiblePoints' calculates all possible scores for a given hand.
possiblePoints :: [Card] -> [Int]
possiblePoints = go [0]
where go n [] = n
go ns (Ace:rest) = go (map ((+) 1) ns ++ map ((+) 11) ns) rest
go ns (Two:rest) = go (map ((+) 2) ns) rest
go ns (Three:rest) = go (map ((+) 3) ns) rest
go ns (Four:rest) = go (map ((+) 4) ns) rest
go ns (Five:rest) = go (map ((+) 5) ns) rest
go ns (Six:rest) = go (map ((+) 6) ns) rest
go ns (Seven:rest) = go (map ((+) 7) ns) rest
go ns (Eight:rest) = go (map ((+) 8) ns) rest
go ns (Nine:rest) = go (map ((+) 9) ns) rest
go ns (Ten:rest) = go (map ((+) 10) ns) rest
go ns (Jack:rest) = go (map ((+) 10) ns) rest
go ns (Queen:rest) = go (map ((+) 10) ns) rest
go ns (King:rest) = go (map ((+) 10) ns) rest
-- |The 'Deck' data type represents a deck of cards that can be shuffled.
data Deck = Deck
{ cards :: [Card]
, gen :: StdGen }
deriving (Show)
-- |'mkDeck' will construct a 52-card deck.
mkDeck :: StdGen -> Deck
mkDeck g =
Deck { cards = [ card | card <- [Ace ..], _ <- [1..4] :: [Int] ]
, gen = g }
-- |The 'DeckS' is the current state of the 'Deck'.
type DeckS a = State Deck a
-- |'draw' will take one card off the top of the deck.
draw :: DeckS Card
draw = takeCardAt 0
-- |'shuffle' takes a 52-card deck and randomly shuffles its elements.
shuffle :: DeckS ()
shuffle = do
curr <- get
shuffled <- replicateM 52 takeRandomCard
put curr { cards = shuffled }
-- |'takeRandomCard' will pick one random card from the deck and remove it.
-- It is a helper-function used by 'shuffle'.
takeRandomCard :: DeckS Card
takeRandomCard = do
curr <- get
let n = length $ cards curr
(i, gen') = randomR (0, n) $ gen curr
card <- takeCardAt i
put curr { gen = gen' }
return card
-- |'takeCardAt' will pick the card at the given index and remove it from the
-- deck.
takeCardAt :: Int -> DeckS Card
takeCardAt i = do
curr <- get
let (cards', cards'') = splitAt (i + 1) $ cards curr
card = last cards'
newCards = init cards' ++ cards''
put curr { cards = newCards }
return card
</code></pre>
| [] | [
{
"body": "<p>I am not a Haskell programmer but I can't help suggest an improvement for <code>possiblePoints</code>. That much repetition hurt my eyes. :)</p>\n\n<pre><code>-- first factor out the mapping from a card to its value(s)\npossibleValues :: Card -> [Int]\npossibleValues card\n | card == Ace = [1, 11]\n | card `elem` [Jack,Queen,King] = [10]\n | otherwise = fromEnum card\n\n\npossiblePoints :: [Card] -> [Int]\npossiblePoints hand = nub $ map sum $ mapM possibleValues hand\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:20:09.340",
"Id": "81964",
"Score": "0",
"body": "Ahhh, that is a very nice solution. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:11:15.007",
"Id": "46820",
"ParentId": "46809",
"Score": "8"
}
},
{
"body": "<p>Warning : I never played this game, so I might be wrong.</p>\n\n<h1>Syntactic nitpicking</h1>\n\n<p>There is quite a bit of syntactic noise, that you can catch by using <code>hlint</code>. For example :</p>\n\n<pre><code>input <- getLine\nreturn input\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>getLine\n</code></pre>\n\n<p>There is however a couple instances that are not properly flagged :</p>\n\n<pre><code>when winner $ liftIO . putStrLn $ \"You win!\"\nwhen (not winner) $ liftIO . putStrLn $ \"You lose...\"\n</code></pre>\n\n<p>I believe the intent here is not properly encoded, as you might modify one of the two lines, and have both branches (or none) executed. I think that the following makes it more obvious :</p>\n\n<pre><code>liftIO . putStrLn $ if winner\n then \"You win\"\n else \"You lose\"\n</code></pre>\n\n<p>And as the whole section is lifted, it could be replaced by something like :</p>\n\n<pre><code>handleGameOver :: GameS IO ()\nhandleGameOver = get >>= \\curr -> liftIO $ do\n let playerH = playerHand curr\n dealerH = dealerHand curr\n winner = won playerH dealerH\n putStrLn $ \"Your hand: \" ++ show playerH ++ \", \" ++ show (possiblePoints playerH)\n putStrLn $ \"Dealer's hand: \" ++ show dealerH ++ \", \" ++ show (possiblePoints dealerH)\n putStrLn $ if winner then \"You win!\" else \"You lose...\"\n</code></pre>\n\n<p>But those are all minor nitpicks. The main issue, for me, is that the whole design is unnecessarily coupling orthogonal concepts.</p>\n\n<h1>Decoupling stuff</h1>\n\n<p>There are several concerns that are mixed :</p>\n\n<ul>\n<li>Player strategy and its effect are coupled in the <code>handlePlayer</code> and <code>handleDealer</code> functions.</li>\n<li>The dealer and player are handled as if they were completely distinct, which leads to code duplication. In practice they are following the same rules (I suppose).</li>\n<li>The dealer strategy is part of the game state, even though it is immutable</li>\n<li>IO is mixed with the game logic</li>\n</ul>\n\n<p>Here is a quick rewrite of <code>Main.hs</code> (it might be buggy, I just checked it typechecks) :</p>\n\n<pre><code>{-# LANGUAGE GADTs #-}\nmodule Main where\n\nimport Deck\n\nimport Data.List\nimport System.Random\nimport Control.Monad.State\nimport Control.Monad.Operational\nimport qualified Data.Map.Strict as M\n\ndata PlayerType = Dealer | Player\n deriving (Ord, Eq)\n\ndata GameActions a where\n GetAction :: PlayerType -> GameActions Action\n ShowState :: GameActions ()\n Win :: GameActions ()\n Lose :: GameActions ()\n\ntype GameS = ProgramT GameActions (State Game)\n\nmain :: IO ()\nmain = do\n stdGen <- getStdGen\n interpretIO M.empty (mkGame stdGen) gameLoop\n\ninterpretIO :: M.Map PlayerType (Game -> IO Action) -> Game -> GameS a -> IO a\ninterpretIO strats s instr = case runState (viewT instr) s of\n (a, ns) -> evalinstr ns a \n where\n evalinstr _ (Return x) = return x \n evalinstr stt (a :>>= f) = \n let runC a' = interpretIO strats stt (f a')\n in case a of\n GetAction pt ->\n let strategy = M.findWithDefault (const (return Stay)) pt strats\n in strategy stt >>= runC\n ShowState -> putStrLn \"show state\" >>= runC\n Win -> putStrLn \"You win\" >>= runC\n Lose -> putStrLn \"You lose\" >>= runC\n\n\ndata Game = Game\n { deck :: Deck\n , hands :: M.Map PlayerType [Card]\n }\n\ndata Action = Hit | Stay deriving (Eq, Read)\n\nrunAction :: PlayerType -> GameS Action\nrunAction pt = do\n action <- singleton (GetAction pt)\n when (action == Hit) $ do\n curr <- get\n let (card, deck') = runState draw $ deck curr\n put curr { deck = deck'\n , hands = M.insertWith (++) pt [card] (hands curr)\n }\n return action\n\ngameLoop :: GameS ()\ngameLoop = do\n playerAction <- runAction Player\n dealerAction <- runAction Dealer\n pbust <- isBust Player\n dbust <- isBust Dealer\n let bothStayed = playerAction == Stay && dealerAction == Stay\n gameOver = bothStayed || pbust || dbust\n if gameOver\n then handleGameOver\n else gameLoop\n\nhandleGameOver :: GameS ()\nhandleGameOver = do\n singleton ShowState\n hs <- gets hands\n let playerH = M.findWithDefault [] Player hs\n dealerH = M.findWithDefault [] Dealer hs\n singleton $ if won playerH dealerH then Win else Lose\n\nwon :: [Card] -> [Card] -> Bool\nwon playerH dealerH = playerScore > dealerScore\n where playerScore = score playerH\n dealerScore = score dealerH\n\nscore :: [Card] -> Int\nscore h\n | bust h = 0\n | otherwise = best h\n\nisBust :: PlayerType -> GameS Bool\nisBust pt = gets (check . hands)\n where\n check h = case M.lookup pt h of\n Just cs -> bust cs\n Nothing -> True\n\nbust :: [Card] -> Bool\nbust = all (21 <) . possiblePoints\n\ntwentyOne :: [Card] -> Bool\ntwentyOne = elem 21 . possiblePoints\n\nbest :: [Card] -> Int\nbest = maximum . filter (21 >=) . possiblePoints\n\nshowDealer :: [Card] -> String\nshowDealer hand = \"[\" ++ show (head hand) ++ \",\" ++ intersperse ',' hidden ++ \"]\"\n where n = length $ tail hand\n hidden = replicate n '?'\n\nmkGame :: StdGen -> Game\nmkGame g = Game\n { deck = d'\n , hands = M.fromList [(Player, playerH), (Dealer, dealerH)]\n }\n where d = execState shuffle $ mkDeck g\n ((playerH, dealerH), d') = runState deal d\n\ndeal :: DeckS ([Card], [Card])\ndeal = do\n mine <- draw\n yours <- draw\n mine' <- draw\n yours' <- draw\n let me = [mine, mine']\n you = [yours, yours']\n return (me, you)\n</code></pre>\n\n<p>It is a lot more complex now :) Here are the main takeaways :</p>\n\n<h2>An interpreter</h2>\n\n<p>This is a major technique in Haskell : transform an effectful computation into a pure computation that is then interpreted. You can use the <code>free</code> or <code>operational</code> packages for that. You now have the game logic running in the <code>GameS</code> monad, that can run effectful instructions encoded as the <code>GameActions</code> type. Those instructions are then interpreter by the <code>interpretIO</code> function.</p>\n\n<p>You gain several things from that move :</p>\n\n<ul>\n<li>All IO is in a single place, instead of being intertwined with game logic</li>\n<li>You can easily write an <code>interpretPure :: Game -> GameS a -> Identity a</code> function that can be used for unit tests</li>\n<li>You can also write it in any other monad, for example to have this work as part of a Web application</li>\n</ul>\n\n<p>However, it makes things a bit more complicated to lay out at first ...</p>\n\n<h2>All players are handled in the same way</h2>\n\n<p>There is now less code duplication (the <code>handlePlayer</code> and <code>handleDealer</code> functions were almost identical), and it would probably be easier to increase the player count.</p>\n\n<h2>Pluggable strategies</h2>\n\n<p>Now all strategies are pluggable, not just that of the dealer.</p>\n\n<h1>Well ...</h1>\n\n<p>I basically said \"rewrite your whole program in the way <em>I</em> like\", and there is definitively a question of taste here with the whole \"free monad\" or \"operational\" decoupling. You gain nice effect separation with \"magical behavior\" that might turn into cargo cult programming ...</p>\n\n<p>There is also the problem that I turned fixed fields (<code>playerHand</code> and <code>dealerHand</code>) into a <code>Map</code>, which might return Nothing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:05:02.563",
"Id": "47134",
"ParentId": "46809",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47134",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:28:15.120",
"Id": "46809",
"Score": "14",
"Tags": [
"game",
"haskell",
"playing-cards"
],
"Title": "Blackjack in Haskell"
} | 46809 |
<p>I have this code that compares all version numbers of servers. (The version numbers are stored in an XML file) Before the code would compare the current version number with the previous. This caused some problems because in the cluster of servers, one has a different version number than the rest. If my code happened to connect to that server, it would think it was a change. So then I made it compare the three previous version numbers. The same issue was happening. So I got frustrated and made it load all the version numbers in a list and check the current one against the list. Will this cause a huge performance decrease (the list would be 50 elements at most)? Is there a better way?</p>
<pre><code>#Loads all version numbers in list,
#starts at index 1 because the the first
#element in the XML file is has version number of 0
def loadAllVersions(self, hist):
historyLength = len(hist)
l =[]
for i in range(historyLength):
if i >= 1:
l.append(hist[len(hist)-i].get("version"))
return l
#Checks the current version number to each element
#in the list to see if it is the same. If there is a
#match then the it is not a newer version number,
#otherwise it is a new version number and the function
#returns True.
def checkAllVersions(self, currentVersion, allHist):
historyLength = len(allHist)
for i in range(historyLength):
if(allHist[i] == currentVersion):
return False
return True
def compareVersions(self,parent,componentTarget, write):
componentsTree = parent.findall("component")
currentVersion = self.componentVersions[self.components.index(componentTarget)]
for comp in componentsTree:
if(comp.get("id") == componentTarget):
hist = comp.findall("history")
allHist = self.loadAllVersions(hist)
isNewVersion = self.checkAllVersions(currentVersion, allHist)
if isNewVersion:
if write and currentVersion != None and self.getComponentURL(componentTarget) != None:
event = ET.SubElement(comp,"history")
event.set("time",str(int(time.time())))
event.set("version",currentVersion)
event.set("sourceUrl",self.getComponentURL(componentTarget))
event.set("pretty",self.componentsPretty[self.components.index(componentTarget)])
return True
return False
</code></pre>
| [] | [
{
"body": "<p>Before anything, I reckon you should have a look at <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a> which is the usual Style Guide for Python Code. Among other things, your names for variables and functions does not follow the <code>lowercase_with_words_separated_by_underscores</code> convention.</p>\n\n<hr>\n\n<p>In :</p>\n\n<pre><code>def checkAllVersions(self, currentVersion, allHist):\n historyLength = len(allHist)\n for i in range(historyLength):\n if(allHist[i] == currentVersion):\n return False\n return True\n</code></pre>\n\n<p>this does not correspond to the pythonic way of looping over a container. There's a cleaner way that doesn't involve indices.</p>\n\n<pre><code>def checkAllVersions(self, currentVersion, allHist):\n for e in allHist:\n if(e == currentVersion):\n return False\n return True\n</code></pre>\n\n<p>As an additional tip, there's a cool way to write this using <a href=\"https://docs.python.org/2/library/functions.html#all\">all</a> or <a href=\"https://docs.python.org/2/library/functions.html#any\">any</a> :</p>\n\n<pre><code>def checkAllVersions(self, currentVersion, allHist):\n return all(e != current version for e in allHist)\n</code></pre>\n\n<p><em>Edit:</em></p>\n\n<p>And there is an even more obvious way to write it and I completely missed it :</p>\n\n<pre><code>def checkAllVersions(self, currentVersion, allHist):\n return currentVersion not in allHist\n</code></pre>\n\n<hr>\n\n<p>In :</p>\n\n<pre><code>def loadAllVersions(self, hist):\n historyLength = len(hist)\n l =[]\n for i in range(historyLength):\n if i >= 1:\n l.append(hist[len(hist)-i].get(\"version\"))\n return l\n</code></pre>\n\n<p>instead of iterating from <code>0</code> to <code>historyLength-1</code> and then consider only values i such that <code>i >= 1</code>, you could just iterate from <code>1</code> to <code>historyLength-1</code>. Just use <code>range(1,historyLength)</code>.</p>\n\n<pre><code>def loadAllVersions(self, hist):\n historyLength = len(hist)\n l =[]\n for i in range(1,historyLength):\n l.append(hist[len(hist)-i].get(\"version\"))\n return l\n</code></pre>\n\n<p>However, it seems like something even smarter could be done here.</p>\n\n<p>At the end of the day, my assumption is that what you want to do is just to iterate over <code>hist</code> from the beginning to the end and call <code>.get(\"version\")</code> on each element. This is not what you are currently doing because you are not processing the first element of the list (index is 0 and would correspond to <code>i = historyLength</code>).</p>\n\n<p>You have more than one way to do it but the most straight-forward solution involves looping over your list in reversed order with <a href=\"https://docs.python.org/2/library/functions.html#reversed\">reversed</a> :</p>\n\n<pre><code>def loadAllVersions(self, hist):\n l =[]\n for e in reversed(hist):\n l.append(e.get(\"version\"))\n return l\n</code></pre>\n\n<p>and then, this calls for list comprehension :</p>\n\n<pre><code>def loadAllVersions(self, hist):\n return [e.get(\"version\") for e in reversed(hist)]\n</code></pre>\n\n<hr>\n\n<p>It is now time to have a look at <code>def compareVersions(self,parent,componentTarget, write)</code>, a much bigger chunk.</p>\n\n<p>First thing I'd like to point out, you do no follow this part of PEP 8 :</p>\n\n<blockquote>\n <p>Comparisons to singletons like None should always be done with is or\n is not, never the equality operators.</p>\n</blockquote>\n\n<p><em>I'd like you to confirm my assumption about <code>loadAllVersions</code> before going any further.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:58:40.510",
"Id": "81946",
"Score": "0",
"body": "That is very very helpful, thank you so much. The reason why I start at 1 and not 0 in `loadAllVersions` is because index 0 is just a blank XML with version number 0. So I just skipped that entry since it is blank and start at 1 of hist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:17:45.627",
"Id": "81949",
"Score": "0",
"body": "I added comments to my code to explain why I did some things I did a little more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:35:10.117",
"Id": "81950",
"Score": "0",
"body": "Since I am ignoring the version number that is '0' the list comprehension would be change to `return [e.get(\"version\") for e in reversed(hist) if e.get(\"version\") != '0']` correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T12:40:51.480",
"Id": "82101",
"Score": "0",
"body": "I don't really get `loadAllVersions` is iterating from end to beginning. Also, I don't understand if you are expecting to skip the first or the last element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:56:32.537",
"Id": "82182",
"Score": "0",
"body": "I didnt write loadAllVersions, a worker before me did, and im expecting to skip the first one since its empty"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:38:45.570",
"Id": "46817",
"ParentId": "46812",
"Score": "10"
}
},
{
"body": "<p>Josay's answer is excellent. Just wanted to add one more detail:</p>\n\n<p>In your code, you use large blocks of comments above your functions to describe what they do. You should consider using <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> <a href=\"https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format\">instead</a>.</p>\n\n<p>So, for example, your first function would look something like...</p>\n\n<pre><code>def loadAllVersions(self, hist):\n \"\"\"\n Load all version numbers into a list. Begin at\n index 1 to skip the first line in the XML file,\n which always has a version number of 0.\n\n Arguments:\n hist: list of version XML entries\n\n Returns:\n a list of version numbers\n \"\"\"\n historyLength = len(hist)\n l =[]\n for i in range(historyLength):\n if i >= 1:\n l.append(hist[len(hist)-i].get(\"version\"))\n return l\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:35:57.033",
"Id": "46930",
"ParentId": "46812",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "46817",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T13:54:44.203",
"Id": "46812",
"Score": "8",
"Tags": [
"python",
"performance",
"xml",
"python-2.x"
],
"Title": "Comparing Server Version Number History"
} | 46812 |
<p>I'm crawling Flickr for data for my university research project. However it's very slow and I'm not sure what it is exactly. It could be the <code>FileWriter</code> slowing it down. Any advice on speeding it up?</p>
<pre><code>try {
String userID = file.getUserIDFromList(i);
System.out.println(i + "." + " " + userID);//to screen
String urlString = "https://api.flickr.com/services/rest/?method=flickr.people.getPublicGroups&api_key=myAPIKey&user_id=" + userID;
System.out.println(urlString);
//print userID to file
file.writeGroupID(userID);
Collection<Group> groupNames = people.getPublicGroups(userID);
String groupCount = Integer.toString(groupNames.size());
//write number of groups to the file
file.writeFile(groupCount);
Iterator<Group> iteratorDetails = groupNames.iterator();
//iterate over list to get each group's details
while (iteratorDetails.hasNext()) {
Group groupName = (Group)iteratorDetails.next();
//get group name
String name = groupName.getName();
//get group id
String id = groupName.getId();
GroupsInterface groupInter = flickr.getGroupsInterface();
Group gInfo = groupInter.getInfo(id);
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(urlString);
doc.getDocumentElement().normalize();
NodeList items = doc.getElementsByTagName("group");
Node n = items.item(poolCounter);
Element e = (Element) n;
//get total photos in group
String numberOfPhotos = e.getAttribute("pool_count");
//get members in the group
int numberOfMembers = gInfo.getMembers();
//write group details to file
file.writeFile("\t" + name + " " + numberOfPhotos + " photos" + ", " + numberOfMembers + " members");
System.out.println("\t" + name + " " + numberOfPhotos + " photos" + ", " + numberOfMembers + " members");
poolCounter++;
}
file.newLine();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:01:29.453",
"Id": "81948",
"Score": "2",
"body": "Your code is broken, buggy, or confusing. Why do you have just one URL `urlString` defined as `\"https://api.flickr.com/services/rest/?method=flickr.people.getPublicGroups&api_key=myAPIKey&user_id=\" + userID` but then you repeatedly re-parse it inside the group-loop? What value does that add?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:40:10.493",
"Id": "81967",
"Score": "0",
"body": "Interestingly, the `<group>` elements returned from the `flickr.people.getPublicGroups` REST method contain a `pool_count` attribute ([example](https://api.flickr.com/services/rest/?method=flickr.people.getPublicGroups&api_key=af3ac3bb7df2e70aa56921478847b6c2&user_id=62826388%40N02&format=rest)), but that attribute is [not documented](https://www.flickr.com/services/api/flickr.people.getPublicGroups.htm)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:07:32.977",
"Id": "82062",
"Score": "0",
"body": "You're right 200_success. Also pool_count represents the number of photos in a group but the method from the group class getPhotoCount returns 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:09:20.453",
"Id": "82064",
"Score": "0",
"body": "Ah yes you're right too rolfl. Will update that in my code, and review your answer."
}
] | [
{
"body": "<p>There are a number of things going on here, but it boils down to <a href=\"http://en.wikipedia.org/wiki/Amdahl%27s_law\" rel=\"nofollow\">Amdahl's Law</a>.</p>\n\n<p>I am going to take a stab at some guessing here, but I expect my numbers to be in the right ballparks. Your code does:</p>\n\n<ul>\n<li>Collection groupNames = people.getPublicGroups(userID);</li>\n<li>For each Group:\n<ul>\n<li>you connect to flickr</li>\n<li>you download the data</li>\n<li>you parse it</li>\n<li>you write-to-file.</li>\n</ul></li>\n</ul>\n\n<p>Here are things that you are doing slower than necessary:</p>\n\n<ol>\n<li>you are parsing the same URL many times (as many times as you have groups to process), as the URL does not change inside the loop. If you process it once outside the loop, you will get the same results.</li>\n<li>Is you file output buffered?</li>\n<li>Do you need to <code>doc.getDocumentElement().normalize();</code> ?</li>\n</ol>\n\n<p>Now, as for the real application of Amdahl's law, and, assuming the URL is wrong that you are processing (and that there should be 1 URL per group), you should: <em>run things in parallel</em>.</p>\n\n<p>Consider something like:</p>\n\n<pre><code>ExecutorService service = Executors.newFixedThreadPool(....);\n....\nLinkedList<Future<String>> futureops = new LinkedList<>();\n\nwhile (...) {\n futureops.add(service.submit(new Callable<Integer>() {\n public String call() throws IOException {\n // ****** Will need to probably do this as a separate class to get *****\n // ****** it to compile right, or use `final` judiciously. *****\n DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();\n DocumentBuilder b = f.newDocumentBuilder();\n Document doc = b.parse(urlString);\n\n doc.getDocumentElement().normalize();\n NodeList items = doc.getElementsByTagName(\"group\");\n Node n = items.item(poolCounter);\n Element e = (Element) n;\n\n //get total photos in group\n String numberOfPhotos = e.getAttribute(\"pool_count\");\n //get members in the group\n int numberOfMembers = gInfo.getMembers(); \n return \"\\t\" + name + \" \" + numberOfPhotos + \" photos\" + \", \" + numberOfMembers + \" members\"; \n }\n });\n\n while (!futureops.isEmpty()) {\n String result = futureops.removeFirst();\n file.writeFile(result);\n System.out.println(result);\n poolCounter++;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:26:53.570",
"Id": "46821",
"ParentId": "46816",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46821",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T14:36:16.503",
"Id": "46816",
"Score": "6",
"Tags": [
"java",
"performance",
"parsing",
"xml"
],
"Title": "Extraction of data from Flickr"
} | 46816 |
<p>I have 2 vectors of Facebook-like pages which are represented by an ID from 2 different users. I want to verify the number of liked pages that are similar between these 2 users.</p>
<p>This is my algorithm that I am using right now, which is basically a search into all rows and columns of a matrix:</p>
<pre><code>for(int i = 0; i < 100; i++) {
val = [user_like objectAtIndex:i];
id like_user = [[val allValues] objectAtIndex:0];
NSLog(@"like user %d is %@",i, like_user);
for (int j = 0; j < 100; j++) {
val2 = [friend_like objectAtIndex:j];
id like_friend = [[val2 allValues] objectAtIndex:2];
NSLog(@"like friend %d is %@",j, like_friend);
if (like_user == like_friend) {
//do something
}
}
}
</code></pre>
<p>How can I optimize this search/match algorithm?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-13T01:40:06.283",
"Id": "145524",
"Score": "1",
"body": "Here at Code Review, we like to review **the full code**. Looking at your code, you write `//do something`, which shows that you did not post the full code, therefore making it off-topic."
}
] | [
{
"body": "<p>Your algorithm is O(<em>n</em><sup>2</sup>), which is inefficient. Use an <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableSet_Class/Reference/NSMutableSet.html\" rel=\"nofollow\"><code>NSMutableSet</code></a> to compute the intersection of two sets.</p>\n\n<pre><code>NSSet *userLikeSet = [NSSet setWithArray:user_like];\nNSMutableSet *commonLikeSet = [NSMutableSet setWithArray:friend_like];\n[commonLikeSet intersectSet:userLikeSet];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:43:20.757",
"Id": "82013",
"Score": "0",
"body": "This answer is fine if the order of the objects is not important."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:50:32.173",
"Id": "82015",
"Score": "0",
"body": "After rereading the question though, he actually just needs a count, so this is a good option."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T16:30:49.910",
"Id": "46826",
"ParentId": "46823",
"Score": "3"
}
},
{
"body": "<p>Some problems with this code I want to address before I even get into optimization of speed.</p>\n\n<p>First of all, there's absolutely no indentation, which makes this very hard to read.</p>\n\n<p>Second of all, your variable names are both lacking, and not in keeping with Objective-C standard conventions. Variable names like <code>val</code> and <code>val2</code> aren't really descriptive enough. A variable name like <code>like_user</code> may be descriptive enough (I don't know, it's borderline), but Objective-C standards suggest that the variable should instead be named <code>likeUser</code>. We prefer camel casing to underscoring.</p>\n\n<p>Next, you're using a <code>for</code> loop where you should be using a <code>forin</code> (I'll get to that later), but we're using the loop iterator as an index into an array... which is fine-ish... but you're concerning yourself with the array's length in the <code>for</code>'s condition. You're risking an index out of bounds exception.</p>\n\n<p>But we really don't want to use a <code>for</code> loop anyway. Any time we need to do something with each object in an Objective-C collection, we should use a <code>forin</code> loop anytime we can. <code>forin</code> loops run faster than regular <code>for</code> loops--they're processed in batches.</p>\n\n<p>But as 200_success points out, in this specific instance, we don't need to iterate through the indexes.</p>\n\n<p>You stated you just want to count the number of common liked pages.</p>\n\n<p>So, just as 200_success suggested:</p>\n\n<pre><code>NSSet *userLikeSet = [NSSet setWithArray:userLike];\nNSMutableSet *commonLikeSet = [NSMutableSet setWithArray:friendLike];\nNSSet *commonLikes = [commonLikeSet intersectSet:userLikeSet];\n\nNSInteger commonLikeCount = [commonLikes count];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:55:23.957",
"Id": "46858",
"ParentId": "46823",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46858",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T15:39:21.300",
"Id": "46823",
"Score": "3",
"Tags": [
"algorithm",
"objective-c",
"matrix",
"facebook"
],
"Title": "Search/match algorithm between 2 vectors"
} | 46823 |
<p>In my Python application, I am using Tarjan's algorithm to compute strongly connected components. Unfortunately, it shows up under profiling as one of the top functions in my application (at least under cPython, I haven't figured out how to profile under Pypy yet). </p>
<p>I've looked at the code, but I don't see any obvious performance mistakes, and I can't figure out how to make it faster. Any suggestions?</p>
<p>Note: The profiler reports a lot of time spent inside the function, so it's not just a matter of slow callbacks.</p>
<pre><code>def tarjanSCC(roots, getChildren):
"""Return a list of strongly connected components in a graph. If getParents is passed instead of getChildren, the result will be topologically sorted.
roots - list of root nodes to search from
getChildren - function which returns children of a given node
"""
sccs = []
indexCounter = itertools.count()
index = {}
lowlink = {}
removed = set()
subtree = []
#Use iterative version to avoid stack limits for large datasets
stack = [(node, 0) for node in roots]
while stack:
current, state = stack.pop()
if state == 0: #before recursing
if current not in index: #if it's in index, it was already visited (possibly earlier on the current search stack)
lowlink[current] = index[current] = next(indexCounter)
children = [child for child in getChildren(current) if child not in removed]
subtree.append(current)
stack.append((current, 1))
stack.extend((child, 0) for child in children)
else: #after recursing
children = [child for child in getChildren(current) if child not in removed]
for child in children:
if index[child] <= index[current]: #backedge (or selfedge)
lowlink[current] = min(lowlink[current], index[child])
else:
lowlink[current] = min(lowlink[current], lowlink[child])
assert(lowlink[current] <= index[current])
if index[current] == lowlink[current]:
scc = []
while not scc or scc[-1] != current:
scc.append(subtree.pop())
sccs.append(tuple(scc))
removed.update(scc)
return sccs
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>You iterate twice over the children in both branches. Avoid that by combining these lines</p>\n\n<pre><code>children = [child for child in getChildren(current) if child not in removed]\nstack.extend((child, 0) for child in children)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>stack.extend((child, 0) for child in getChildren(current) if child not in removed)\n</code></pre>\n\n<p>and these</p>\n\n<pre><code>children = [child for child in getChildren(current) if child not in removed]\nfor child in children:\n</code></pre>\n\n<p>to </p>\n\n<pre><code>for child in getChildren(current):\n if child not in removed:\n</code></pre></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>Instead of looping in Python and moving one item at a time here</p>\n\n<pre><code> scc = []\n while not scc or scc[-1] != current:\n scc.append(subtree.pop())\n sccs.append(tuple(scc))\n</code></pre>\n\n<p>try to use slicing like this. A possible disadvantage is that <code>index</code> searches from the beginning.</p>\n\n<pre><code> i = subtree.index(current)\n scc = tuple(reversed(subtree[i:]))\n del subtree[i:]\n sccs.append(scc)\n</code></pre></li>\n<li><p>Use local variables to reduce dictionary lookups. You can also bind methods such as <code>stack.pop</code> to local variables to avoid attribute lookup inside the loop.</p></li>\n<li><p>Also to reduce dictionary lookups, you could combine <code>index</code> and <code>lowlink</code> dictionaries. Put the pair of values in as a tuple or a list to take advantage of unpacking into local variables:</p>\n\n<pre><code>next_index = next(indexCounter)\nindex[current] = [next_index, next_index]\n...\nindex_current, lowlink_current = index[current]\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T18:05:33.120",
"Id": "47078",
"ParentId": "46832",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:36:28.817",
"Id": "46832",
"Score": "5",
"Tags": [
"python",
"performance",
"python-2.x",
"graph"
],
"Title": "Strongly connected components algorithm"
} | 46832 |
<p>I am building a Tic Tac Toe game with AngularJS and making it online playable with AngularFire. The Tic Tac Toe logic is all there so this question concerns Angularfire a little bit more. I want to be able to match a user with an opponent as well as delete inactive games.</p>
<p>I have done my homework and at this point I want to get the smell out of my code. Since I am handling asynchronous requests, I built a factory that returns a promise.</p>
<pre><code>app.factory("GameCreator", ["$q","$firebase",function($q, $firebase){
var deferred = $q.defer();
var ref = new Firebase("https://myfirebase.firebaseio.com/");
$firebase(ref).$on("loaded",function(value){
var games = $firebase(ref);
var IDs = games.$getIndex();
var initGame = function(n){
games.$add({
//the board's state and turns, shared by all users
board:[['','',''],['','',''],['','','']],
xTurn:true,
turns:0,
playerone:{piece:'x', ready:false,won:false},
playertwo:{piece:'o',ready:false,won:false},
//helpers to sync and assign player
xIsAvailable:false,
oIsAvailable:true
});
//my opponent did something. His/her actions need to appear on my screen.
games.$on("change",function(){
deferred.resolve( games.$child(games.$getIndex()[n]) );
});
};
var n = IDs.length;
//if no games, then build a game
if(n == 0){
initGame(n);
}
//else, determine placement in new vs existing game
else{
//if last - 1 has a spot, put me in that game, else create me a new game
var checkThisGame = games.$child(IDs[n-1]);
checkThisGame.$on('loaded',function(){
if(checkThisGame.oIsAvailable == true){
checkThisGame.oIsAvailable = false;
checkThisGame.$save();
deferred.resolve(checkThisGame);
}
else{
initGame(n);
}
});
}
return deferred.promise;
});
}])
</code></pre>
<p>In my controller, I then use the resolved promise to fulfill my objectives:</p>
<pre><code>app.controller ('BoardCtrl', function($scope,$timeout,GameCreator,$window) {
GameCreator.then(function(returnedData){
returnedData.$on('loaded',function(){
$scope.game = returnedData;
var piece;
if(returnedData.oIsAvailable == true) {
piece = 'x';
}
else {
piece = 'o';
}
$scope.myPiece = {
val:piece
};
$window.onbeforeunload = function (event) {
//delete this game from the firebase I/O
returnedData.$remove();
return null;
}
//the rest of the tic tac toe game logic follows here,
//with all proper calls to $scope.game.$save()
});
});
);
</code></pre>
<p>Since I do not completely know what I am doing, I will ask: did I do this right? Is there some refactoring that could be done? It works as expected but I thought I would ask for a review.</p>
| [] | [
{
"body": "<p>I am not an angular expert, but this </p>\n\n<pre><code>var piece;\nif(returnedData.oIsAvailable == true) {\n piece = 'x';\n}\nelse {\n piece = 'o';\n}\n$scope.myPiece = {\n val:piece\n};\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>$scope.myPiece = {\n val: returnedData.oIsAvailable ? 'x' : 'o'\n};\n</code></pre>\n\n<p>Also</p>\n\n<ul>\n<li>I know the firebase API calls the object returned by <code>new Firebase</code> a (root) reference. It still irks me since my brain keeps thinking what is <code>ref</code>?? I would probably go against the grain and call it <code>db</code>, but that could be because I am simply not familiar enough with the API</li>\n<li><code>if(checkThisGame.oIsAvailable == true){</code> should be <code>if(checkThisGame.oIsAvailable){</code> or <code>if(checkThisGame.oIsAvailable === true){</code></li>\n<li>the game is well documented</li>\n<li>JsHint.com finds a number of small things, you should use the site</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:32:41.867",
"Id": "46912",
"ParentId": "46833",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:45:33.150",
"Id": "46833",
"Score": "5",
"Tags": [
"javascript",
"game",
"angular.js",
"api",
"promise"
],
"Title": "AngularFire Tic Tac Toe Game"
} | 46833 |
<p>I have the below class which moves the AI towards the given plant, this works well however it feels really messy.</p>
<p>Any input as to a better way to lay out the logic would be really grateful, the logic follows the idea that we will take the x and y positions of the AI from the plants position, if the values are positive we add 30 and if it is negative we take away 30 </p>
<p>If you need any more explaining of the logic let me know. </p>
<pre><code>private void movePosistion(Plant p) {
/*
* set which direction to move,the number generated relates to the
* direction as below:
* 1 2 3
* 4 5
* 6 7 8
*/
int xdiff = p.getXpos() - xpos;
int ydiff = p.getYpos() - ypos;
if (xdiff > 0){
if (ydiff > 0){
//8
xpos += 30;
ypos += 30;
}else if(ydiff < 0){
//3
xpos += 30;
ypos -= 30;
}else{
//5
xpos += 30;
}
}else if(xdiff < 0){
if (xdiff > 0){
//6
xpos -= 30;
ypos += 30;
}else if(xdiff < 0){
//1
xpos -= 30;
ypos -= 30;
}else{
//4
xpos -= 30;
}
}else{
if (ydiff < 0){
//7
ypos -= 30;
}else{
//2
ypos += 30;
}
}
if (xpos > 720)
xpos = 1;
if (ypos > 720)
ypos = 1;
if (xpos < 1)
xpos = 720;
if (ypos < 1)
ypos = 720;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:29:56.577",
"Id": "81993",
"Score": "2",
"body": "Is your position always \"1 + 30x\", for some x? I think this is a decision that could eventually lead to off-by-one errors; generally, if you have a width of 720 points, it is better to have coordinates ranging from 0 to 719; math operations then fit more naturally, without having to add or remove 1; for example, you could use the modulus operator : `xpos = xpos % 720` in your last lines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T08:03:57.677",
"Id": "82073",
"Score": "0",
"body": "I edited my answer to provide more explanations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:51:37.437",
"Id": "82128",
"Score": "0",
"body": "I just noticed that the function is called \"movePosistion\"; I corrected it in my answer. Btw, thanks for accepting it."
}
] | [
{
"body": "<p>Pre-computing the possible moves, and reducing the conditionals to a simple mathematical expression is a nice way to solve problems like this.</p>\n\n<p>Your code also suffers from repeating blocks, and duplicated logic: DRY - Don't Repeat Yourself.</p>\n\n<p>Solve that by doing function extraction.</p>\n\n<p>Finally, your code is full of magic numbers, which are prone to leak bugs.....</p>\n\n<p>Consider the following code, which, though longer than yours in terms of lines, is actually significantly more readable (except for the complicated 2D array, I admit).</p>\n\n<pre><code>private static final int DELTA = 30;\nprivate static final int MINPOS = 0;\nprivate static final int MAXPOS = 720;\nprivate static final int XINDEX = 0;\nprivate static final int YINDEX = 1;\n\nprivate final int[][] MOVES = {\n {-DELTA, DELTA}, {0, DELTA}, {DELTA,DELTA},\n {-DELTA, 0}, {0, 0}, {DELTA,0},\n {-DELTA, -DELTA},{0, -DELTA},{DELTA,-DELTA},\n\n};\n\nprivate final int step(final int diff) {\n return diff < 0 ? 0 : (diff > 0 ? 2 : 1);\n}\n\nprivate final int boundPos(int pos) {\n return pos < MINPOS ? MAXPOS : (pos > MAXPOS ? MINPOS : pos);\n}\n\nprivate void movePosistion(Plant p) {\n /*\n * set which direction to move,the number generated relates to the\n * direction as below:\n * 1 2 3 \n * 4 5\n * 6 7 8\n */\n\n int xdiff = step(p.getXpos() - xpos);\n int ydiff = step(p.getYpos() - ypos);\n // Convert the two x/y directions to an index in to MOVES.\n int index = ydiff * 3 + xdiff;\n xpos += MOVES[index][XINDEX];\n ypos += MOVES[index][YINDEX];\n xpos = boundPos(xpos);\n ypos = boundPos(ypos);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:42:59.910",
"Id": "81987",
"Score": "1",
"body": "@coredump - thanks... and good spotting. You're right. Fixing now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:58:37.300",
"Id": "81989",
"Score": "0",
"body": "Even though a table is good approach in principle, I don't think this is needed here; see my answer (I reuse `boundPos`, btw)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:51:45.467",
"Id": "82094",
"Score": "1",
"body": "@coredump - nice. Your answer too. You should visit the [2nd Monitor chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) to discover another side of Code Review."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T18:44:50.770",
"Id": "46836",
"ParentId": "46834",
"Score": "11"
}
},
{
"body": "<p>I agree with <em>@rolfl</em> that you need to extract methods and use a <a href=\"https://codereview.stackexchange.com/a/22821/7076\">decision table</a>.</p>\n\n<p>From Code Complete 2nd Edition, Chapter 19: General Control Issues, page 431:</p>\n\n<blockquote>\n <p><strong>Use decision tables to replace complicated conditions</strong></p>\n \n <p>Sometimes you have a complicated test involving several variables. It can be helpful to use a decision table to perform the test rather than using ifs or cases. A decision-table lookup is easier to code initially, having only a couple of lines of code and no tricky control structures. This minimization of complexity minimizes the opportunity for mistakes. If your data changes, you can change a decision table without changing the code; you only need to update the contents of the data structure.</p>\n</blockquote>\n\n<p>I would be more verbose here for the sake of readability. First, an enum for the possible differences:</p>\n\n<pre><code>public enum Difference {\n ZERO,\n BELOW_ZERO,\n ABOVE_ZERO\n}\n</code></pre>\n\n<p>Then a class which contains the available rules:</p>\n\n<pre><code>public class MoveLogic {\n\n private final Map<Rule, Move> rules = new LinkedHashMap<>();\n\n public MoveLogic() {\n addRule(Difference.ABOVE_ZERO, Difference.ABOVE_ZERO, 30, 30); // 8\n addRule(Difference.ABOVE_ZERO, Difference.BELOW_ZERO, 30, -30); // 3\n addRule(Difference.ABOVE_ZERO, Difference.ZERO, 30, 0); // 5\n\n addRule(Difference.BELOW_ZERO, Difference.ABOVE_ZERO, -30, 30); // 6\n addRule(Difference.BELOW_ZERO, Difference.BELOW_ZERO, -30, -30); // 1\n addRule(Difference.BELOW_ZERO, Difference.ZERO, -30, 0); // 4\n\n addRule(Difference.ZERO, Difference.BELOW_ZERO, 0, -30); // 7\n addRule(Difference.ZERO, Difference.ABOVE_ZERO, 0, 30); // 2\n }\n\n private void addRule(Difference xDifference, Difference yDifference, int x, int y) {\n rules.put(new Rule(xDifference, yDifference), new Move(x, y));\n }\n\n public Move getMove(Difference xDifference, Difference yDifference) {\n return rules.get(new Rule(xDifference, yDifference));\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>final Difference xDifference = calculateDifference(plant.getXpos(), xpos);\nfinal Difference yDifference = calculateDifference(plant.getXpos(), ypos);\n\nfinal Move move = moveLogic.getMove(xDifference, yDifference);\nxpos += move.getX();\nypos += move.getY();\n</code></pre>\n\n<p>Finally, the helper method to create <code>Difference</code> references:</p>\n\n<pre><code>private Difference calculateDifference(final int plantPosition, final int position) {\n final int difference = plantPosition - position;\n if (difference > 0) {\n return Difference.ABOVE_ZERO;\n }\n if (difference < 0) {\n return Difference.BELOW_ZERO;\n }\n return Difference.ZERO;\n}\n</code></pre>\n\n<p>as well as <code>Rule</code>:</p>\n\n<pre><code>public class Rule {\n\n private Difference xDifference;\n private Difference yDifference;\n\n public Rule(Difference xDifference, Difference yDifference) {\n this.xDifference = xDifference;\n this.yDifference = yDifference;\n }\n\n // generate hashCode and equals, the Map needs it!\n\n}\n</code></pre>\n\n<p>and <code>Move</code>:</p>\n\n<pre><code>public class Move {\n\n private int x;\n private int y;\n\n public Move(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n}\n</code></pre>\n\n<p>It might seem too verbose but it avoids repeated conditions as well as magic computations with indexes and arrays.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:11:45.067",
"Id": "81990",
"Score": "4",
"body": "It definitely seems too verbose. I would even say over-engineered, to be honest. Why represent rules at runtime (this is not in the spec)? why encode the concept of `Difference` in a class? why take a complex approach? Dont add getters/setters that just set and get values: use public fields; you can always evolve towards more complexity if needed, in the future, but only if this becomes necessary. This is just my opinion, hope it helps :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:17:07.997",
"Id": "46838",
"ParentId": "46834",
"Score": "11"
}
},
{
"body": "<p>Here is my take on it. Since the motions in x and y are independent, I define a class for motion in one direction.</p>\n\n<pre><code>public class Coordinate {\n private final int worldSize;\n private final int stepSize;\n private int value;\n\n public Coordinate(int worldSize, int stepSize, int initialValue) {\n this.worldSize = worldSize;\n this.stepSize = stepSize;\n if (initialValue < 0 || initialValue >= worldSize)\n throw new IllegalArgumentException();\n this.value = initialValue;\n }\n\n // TODO getters\n\n\n public void moveStepUp() {\n value = (value + stepSize) % worldSize;\n }\n\n public void moveStepDown() {\n value = (value - stepSize + worldSize) % worldSize;\n }\n\n public void moveStepCloserTo(Coordinate other) {\n // TODO it would better to consider \"closer\" through the periodic boundaries too.\n if (this.value < other.value)\n moveStepUp();\n else if (this.value > other.value)\n moveStepDown();\n }\n}\n\npublic class Coordinate2D {\n private final Coordinate x;\n private final Coordinate y;\n\n // TODO constructors, getters, moves\n\n public void moveStepCloserTo(Coordinate2D other) {\n x.moveStepCloserTo(other.x);\n y.moveStepCloserTo(other.y);\n }\n}\n\npublic class World {\n private Coordinate2D playerPosition;\n private Coordinate2D plantCoordinate;\n\n // TODO Constructors ...\n\n // loop over:\n playerPosition.moveStepCloserTo(plantCoordinate);\n\n}\n</code></pre>\n\n<p>It would change all of your whole code quite a bit. But you can at least use the idea that the motions in x and y are independent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:35:01.163",
"Id": "81994",
"Score": "0",
"body": "in `Coordinate` constructor, why not also throw an exception when `initialValue` is negative?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:28:54.330",
"Id": "82012",
"Score": "0",
"body": "Corrected. I guess many other things would need to be fixed. For example, it's possible at the moment to moveCloser to a coordinate which has a different worldSize."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:22:36.977",
"Id": "46846",
"ParentId": "46834",
"Score": "10"
}
},
{
"body": "<p>Here is my refactoring:</p>\n<pre><code>private void movePosition(Plant p) {\n xpos += Integer.signum(p.getXpos() - xpos) * DELTA_X;\n ypos += Integer.signum(p.getYpos() - ypos) * DELTA_Y;\n\n xpos = Math.floorMod(xpos, MAX_X);\n ypos = Math.floorMod(ypos, MAX_Y);\n}\n</code></pre>\n<p>With the right <code>import static</code> this can also be:</p>\n<pre><code>private void movePosition(Plant p) {\n xpos = floorMod(xpos + signum(p.getXpos() - xpos) * DELTA_X, MAX_X);\n ypos = floorMod(ypos + signum(p.getYpos() - ypos) * DELTA_Y, MAX_Y);\n}\n</code></pre>\n<ol>\n<li>Signum\n--\n<code>signum</code> implements the sign function, which gives -1, 0 or 1 for negative integers, zero and positive integers respectively. It encodes the original logic in a very short and readable expression.\nThe sign is multiplied by the appropriate amount of units (constants are not detailed in the code, btw).</li>\n</ol>\n<p>I have nothing against decision tables in principle (see rolfl's answer), but I don't think this is necesary here.\nIn his answer, palacsint cited "Code Complete". <em>I can do that too!</em></p>\n<p>From Code Complete 2nd Edition, Chapter 19: General Control Issues, page 431:</p>\n<blockquote>\n<p><strong>Use decision tables to replace complicated conditions</strong></p>\n<p>Sometimes you have a complicated test involving several variables. [...]</p>\n</blockquote>\n<p>... and sometimes you don't ;-)</p>\n<ol start=\"2\">\n<li>Modulus</li>\n</ol>\n<ul>\n<li></li>\n</ul>\n<p>The wrap-around behaviour of the original code can be achieved with a modulus operation. Note that you cannot just use the <code>%</code> operator in Java because it computes the remainder, which can be negative when your position goes below zero. The <code>floorMod</code> operation actually computes modular arithmetic.</p>\n<p>Now, you might think: <em>this is wrong, the original code does not work like this!</em>\nYes, but let me explain:</p>\n<ul>\n<li><p>First, OP's coordinates range from 1 to 720 (both inclusive). I have an issue with this and I deliberately changed the approach here. The reason is that, in the original code, instead of using a coordinate space that have the origin at (0,0), the origin is translated at (1,1).</p>\n<p>Most of the time, you end up having to add or substract 1 to you operations. That can eventually lead to off-by-one errors. If coordinates are from 0 to 719, however, the wrap-around logic is simply given by the modulus operation.</p>\n</li>\n<li><p>"<em>But the original behavior is not like a modulus!</em>", you might say. Why do you say this? because, suppose <code>x</code> is 710, and then I add 30: with modulus, I goes back to 20, whereas using OP's code, I would have 1 because when we are out of bounds, we go back to the minimal (or maximal) position.</p>\n<p>To that, I reply that you never are at position 710, but only at 0, 30, 60, ..., 690. At least, this is what I understand from OP's code, where the object seems to move on a grid, and not freely around. I suppose the object is always located initially at a multiple of 30, and then can only move by 30 units.</p>\n<p>If I am wrong, then (1) sorry, and (2) yes, the modulus is not exactly the good answer; you might better use the <code>boundPos</code> function from rolfl.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T12:54:16.807",
"Id": "82103",
"Score": "1",
"body": "I really really like this answer primarily for the fact of its simplicity, all the answers given are great and very different approach to take."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-10T20:54:13.387",
"Id": "46847",
"ParentId": "46834",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "46847",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T18:18:07.520",
"Id": "46834",
"Score": "24",
"Tags": [
"java",
"coordinate-system"
],
"Title": "Refining AI movement logic"
} | 46834 |
<pre><code>/*The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
#include <iostream>
#include <vector>
using namespace std;
int main(){
//We will be storing the primes as bool in a vector.
vector<bool>primes(2000000,true);
// This is the Sieve of Eratosthenes. It is not perfect, but It solve's the problem.
primes[1] = false;
for(int a = 2; a*a < primes.size(); ++a){
if(primes[a]==true){
for(int b = 0; a*a+b*a < primes.size(); ++b){
primes[a*a+b*a] = false;
}
}
}
//This simply add's all the prime numbers
long long total = 0;
for(int c = 1; c < primes.size(); c++){
if(primes[c] == true)
total +=c;
}
std::cout << total;
return 0;
}
</code></pre>
<p>This works well. I'm trying to improve my C++ and was wondering if there is a way to improve on it. I'm just learning, and would welcome any advice.</p>
| [] | [
{
"body": "<p>There are three relatively simple improvements you can make, that should be relatively trivial to implement.</p>\n\n<ol>\n<li><p>treat 2 as a special prime:</p>\n\n<ul>\n<li><p>Change initializer of <code>total</code>:</p>\n\n<pre><code>long long total = 2;\n</code></pre></li>\n<li><p>Change step in for loop (start at 3, increment by 2):</p>\n\n<pre><code>for(int a = 3; a*a < primes.size(); a+=2){\n</code></pre></li>\n<li><p>have a special case for if the desired sum is for primes less than 2.... but this is the main method, and the value is a constant, so unnecessary.</p></li>\n</ul></li>\n<li><p>precompute the sqrt of <code>primes.size()</code>:</p>\n\n<ul>\n<li><p>initialize it:</p>\n\n<pre><code>int limit = (int)sqrt(primes.size());\n</code></pre></li>\n<li><p>and use this as the limit in the loop:</p>\n\n<pre><code>for(int a = 3; a <= limit; a+=2){\n</code></pre></li>\n</ul></li>\n<li><p>include the total addition inside the prime loop:</p>\n\n<pre><code> long long total = 2;\n int limit = (int)sqrt(primes.size());\n for(int a = 3; a<=limit; a+=2){\n if(primes[a]==true){\n total += a;\n .......\n</code></pre>\n\n<p>then there is no need for the second loop.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:06:14.437",
"Id": "46837",
"ParentId": "46835",
"Score": "9"
}
},
{
"body": "<p>I have several things to add onto @rolfl's great advice:</p>\n\n<ul>\n<li><p>Since you have a container of <code>bool</code>s, which doesn't store the <em>actual</em> primes, consider renaming <code>primes</code> to <code>is_prime</code> or something similar. This sounds more conditional and makes more sense with the type of values being stored.</p></li>\n<li><p>I might still assign the <code>2000000</code> to a constant to make this more understandable for users without the full documentation (someone might otherwise think that there should be 2M <em>primes</em>, looking at the vector's name). It would also help in case you'll need this number elsewhere.</p>\n\n<p>You could have something like this (feel free to use a better name):</p>\n\n<pre><code>const int maxNumbers = 2000000;\n\nstd::vector<bool> primes(maxNumbers, true);\n</code></pre></li>\n<li><p>You can leave out the <code>true</code> from your <code>if</code> statements:</p>\n\n<p>This</p>\n\n<pre><code>if(primes[a]==true)\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>if(primes[a])\n</code></pre>\n\n<p>If you were to do something with <code>false</code>, you would use <code>!</code>:</p>\n\n<pre><code>if(!primes[a])\n</code></pre></li>\n<li><p>You're hard-coding <code>a*a+b*a</code> in some places, and it's not quite clear what this computation corresponds to (especially with your single-character variable names).</p>\n\n<p>You could assign it to a local variable and use it where it's needed. To keep it within a close scope (it's only needed within a small space), initialize it within the loop.</p></li>\n<li><p>Some of your comments seem noisy/useless:</p>\n\n<pre><code>// We will be storing the primes as bool in a vector.\n</code></pre>\n\n<p>The \"we\" sounds like you're demonstrating this code for a tutorial or such, and this doesn't appear to be the intent. Just a simple \"this does...\" or \"this is...\" will do.</p>\n\n<p>Other than that, the entire comment is not helpful. It's clear that it's an <code>std::vector</code> of <code>bool</code>s that stores primes. There's no need to state the obvious; the code speaks for itself.</p>\n\n<pre><code>// This is the Sieve of Eratosthenes. It is not perfect, but It solve's the problem.\n</code></pre>\n\n<p>The second sentence is just noisy and adds nothing of value; just remove it. The first sentence, however, is okay because it's <em>not</em> entirely obvious that this is the Sieve.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:14:41.930",
"Id": "81991",
"Score": "0",
"body": "Agree in general; the next logical step would be renaming `primes` to `is_prime`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:18:08.177",
"Id": "81992",
"Score": "0",
"body": "@user58697: That is also good."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:35:56.157",
"Id": "46843",
"ParentId": "46835",
"Score": "14"
}
},
{
"body": "<p>Since you're writing in C++, I'd suggest making a class. Here's a class declaration: </p>\n\n<pre><code>class Sieve \n{\npublic:\n Sieve(unsigned maxval=4000000);\n long long sum(unsigned val = 0) const;\n unsigned primesBelow(unsigned val) const;\n bool isPrime(unsigned val) const;\nprivate:\n bool clr(unsigned val) { nums[val>>1] = false; }\n bool get(unsigned val) const { return nums[val>>1]; } \n unsigned adjust(unsigned val) const { return (val == 0 || val > maxnum) ? maxnum : val; }\n unsigned maxnum;\n std::vector<bool>nums;\n};\n</code></pre>\n\n<p>When it's implemented, you create the <code>Sieve</code> object once, which does the actual sieve algorithm in the constructor, and then use it as many times as needed to get multiple answers very quickly. For example:</p>\n\n<pre><code>int main()\n{\n const unsigned maxprime = 2000000;\n Sieve sv(maxprime);\n std::cout << sv.sum() << '\\t' << sv.primesBelow(maxprime) << '\\n';\n std::cout << sv.sum(10) << '\\t' << sv.primesBelow(10) << '\\n';\n}\n</code></pre>\n\n<p>This prints: </p>\n\n<pre><code>142913828922 148933\n17 4\n</code></pre>\n\n<p>Some further optimizations are also possible above those mentioned already by others. For example, since all even numbers except 2 are composite (that is, not prime), one can write the <code>isPrime()</code> function this way:</p>\n\n<pre><code>bool Sieve::isPrime(unsigned val) const \n{\n if (val < 2 || val > maxnum) \n return false;\n if (val == 2)\n return true;\n return (val & 1) ? get(val) : false;\n}\n</code></pre>\n\n<p>The code, as written, returns <code>false</code> if the number passed in is larger than the <code>maxnum</code> used for the constructor. Better alternative approaches include <code>throw</code>ing an exception and automatically extending the internal array to accomodate. I'll leave it for you to implement those if you care to.</p>\n\n<p>You may also wonder why I've used <code>get(val)</code> instead of accessing the <code>vector</code> directly. The reason is that because of the earlier observation that all even numbers greater than 2 are composite, there's not really any need to store them. For that reason, the <code>private</code> <code>get()</code> function is defined as </p>\n\n<pre><code>bool get(unsigned val) const { return nums[val>>1]; } \n</code></pre>\n\n<p>Because the contructor sets every member to <code>true</code> during construction, all we need to provide is a <code>clr</code> function rather than the more typical <code>set()</code> function. It's defined as </p>\n\n<pre><code>bool clr(unsigned val) { nums[val>>1] = false; }\n</code></pre>\n\n<p>Both of these are implemented as <code>private</code> because they assume that they will only be called with odd numbers less than the maximum. No error checking is done within them, so making them private means they're less likely to be improperly called.</p>\n\n<p>Now the constructor, which actually implements the sieve function can put all of these optimizations to use:</p>\n\n<pre><code>Sieve::Sieve(unsigned maxval) : maxnum(maxval), nums(maxnum>>1, true) \n{\n unsigned limit = sqrt(maxnum);\n for(unsigned a = 3; a <= limit; a+=2)\n if(isPrime(a)) \n for(unsigned c=a+a, b=a+c; b < maxnum; b+=c)\n clr(b);\n}\n</code></pre>\n\n<p>Another optimization is here that isn't yet mentioned. In the inner loop, we could step through every multiple of <code>a</code>, but that's really not necessary. Since the construction of the outer loop means that <code>a</code> is always an odd number, <code>a+a</code> would be an even number and therefore already known to not be prime. All we want to check is odd numbers, so we start with <code>a+a+a</code> and increment by <code>a+a</code> ever inner loop iteration. This gives us <code>3*a</code>, <code>5*a</code>, <code>7*a</code>, etc. which are all odd numbers and doubles the speed of that loop versus stepping through by <code>a</code> each time.</p>\n\n<p>Another potential optimization that I didn't implement was to rewrite the constructor such that the loop variables didn't need shifting within the <code>clr()</code> function. </p>\n\n<p>Finally, the <code>sum</code> function which was the point of your original program is implemented.</p>\n\n<pre><code>long long Sieve::sum(unsigned val) const \n{\n val = adjust(val);\n long long total = 0;\n for(unsigned i = 1; i < val; ++i) {\n total += isPrime(i) ? i : 0;\n }\n return total;\n}\n</code></pre>\n\n<p>Note that an optimization not done here is to take advantage of the fact that it's not really necessary to step through all numbers when we know that other than 2, only odd numbers are prime. On my machine, this code runs fast enough that it was hard to measure the difference when I did that optimization, so I just left it as this more straightforward implementation. The nice part about defining this as a member function within a class is that the interface (and therefore all users of the code) would be unaffected by such a change.</p>\n\n<p>As a bonus, if we want to know the number of primes below a certain number, it comes essentiall \"for free\" because the sieve has already done the hard part.</p>\n\n<pre><code>unsigned Sieve::primesBelow(unsigned val) const\n{\n val = adjust(val);\n unsigned count = 0;\n for (unsigned i = 1; i < val; ++i)\n count += isPrime(i) ? 1 : 0;\n return count;\n}\n</code></pre>\n\n<p>The potential problem with both of these is that they <code>adjust()</code> their incoming argument to a value within range. This is probably not the best solution and the same discussion about remedies for <code>isPrime()</code> apply here, too.</p>\n\n<p>On my machine this code ran about 4 times faster that the original code and takes a vector half as long. It's also adjustable at runtime, avoiding the inflexibility of hard-coding a constant like 2000000.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> One other thing I should have mentioned: Please don't get into the habit of <code>using namespace std</code> in your code because it reintroduces the name collision problem that namespaces were introduced to solve! See <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this StackOverflow question</a> for further info on that topic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T01:48:35.290",
"Id": "82028",
"Score": "0",
"body": "I've tried to avoid using namespace std. I can't recall why I did here. I had a hard time understanding classes till I read this, and it really helped. I don't think I can replicate it on my own yet though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T03:05:49.613",
"Id": "82037",
"Score": "0",
"body": "You introduce this optimization but didn't call it out AFAICT: by checking `isPrime(x * y)` in the sieve, you avoid knocking out multiples of `x * y` since you've already knocked out those of `x`. This pays off in spades with large ranges."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T23:29:16.580",
"Id": "46859",
"ParentId": "46835",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "46859",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T18:23:53.717",
"Id": "46835",
"Score": "12",
"Tags": [
"c++",
"primes",
"programming-challenge"
],
"Title": "Project Euler Problem 10 - Sum of primes < 2mil"
} | 46835 |
<p>I'm making some changes to a JavaScript plugin on a site I've been made steward over. This main plugin has it's own sub-plugins and I'm trying to make certain aspects modular. </p>
<p>Currently, I'm attempting to make a reusable modal window that the sub-plugins ferry data to. This main plugin uses extensive use of prototype.</p>
<p>Right now, the main <code>Plugin</code> calls the sub-plugins <code>"callback"</code> method. The callback method then calls the <code>Plugin.prototype.openModal</code> and supplies it with a html template (html), callback function (what should be done after everything is done), validation (function that will validate the inputs of the modal, if present), and prerender (function that is fired before the modal is launched). </p>
<p>My code is pretty pseudo-cody, but this is what I have:</p>
<p><strong>Prototype for reusable modal window, contained in main plugin:</strong></p>
<pre><code>Plugin.prototype.openModal = function(html, callback, validation, prerender) {
var self = this;
var headerFragment = html.hasOwnProperty('header') ? html.header : '',
bodyFragment = html.hasOwnProperty('body') ? html.body : '',
closeButtonText = html.hasOwnProperty('closeText') ? html.closeText : 'Cancel',
confirmButtonText = html.hasOwnProperty('confirmText') ? html.confirmText : 'Save changes';
// Only create the modal when it's called for the first time!
if(!document.getElementById('confirm-modal')) this.createModal();
var modal = $('#modal');
modal.find('.modal-header h3').html(headerFragment);
modal.find('.modal-body').html(bodyFragment);
modal.find('.close-btn').html(closeButtonText);
modal.find('.confirm-btn').html(confirmButtonText);
modal.find('.modal-validation span').text('');
if(typeof prerender === 'function') prerender();
function closeModal(input) {
if(callback && typeof callback === 'function') {
input = input ? input : $('#modal').find('input').val();
callback.call(self, input);
}
$('#modal').modal('hide');
}
function handleAlert(text) {
var alert = modal.find('.modal-validation span');
if(alert.text() != text) {
alert.fadeOut(function(){
alert.text(text).fadeIn();
})
}
}
$('#modal').modal('show');
$('.confirm-btn').unbind('click').on('click', function(){
var input;
if(modal.find('input').length > 1) {
var inputLength = modal.find('input').length
input = [];
modal.find('input').each(function(){
if($(this).val()) input.push($(this).val());
});
if(input.length < inputLength) input = null;
} else if(modal.find('input').length === 1) {
input = modal.find('input').val();
}
if(input) {
if(typeof validation === 'function') {
var isValid = validation(input);
if(typeof isValid === 'object' && isValid.type === 'valid') {
isValid.value ? closeModal(isValid.value) : closeModal();
} else {
handleAlert(isValid);
}
} else {
if(input) {
typeof input === 'object' ? closeModal(input) : closeModal();
} else {
handleAlert('You must enter something!');
}
}
} else {
handleAlert('You must enter something!');
}
})
}
</code></pre>
<p><strong>Function being called by sub plugin which is sending and receiving data to the prototype:</strong></p>
<pre><code>Plugin.Plugins['Link'] = (function () {
var template = {
header: 'Add a link, bro',
body: [
'<div>What the header said</div>',
'<input type="text" value="http://" />'
].join(''),
// closeText: 'NOPE',
confirmText: 'Insert Link'
},
validationErrorMessage = 'You did not enter a valid URL';
return {
'callback': function (input, change) {
var self = this;
this.plugin.openModal(template, function(input){
document.execCommand('createLink', false, input);
}, function(input){
return self.validate(input);
});
},
validate: function(input) {
var isValid = this.validateUrl(input);
if(isValid) {
return {type: 'valid'};
}
return validationErrorMessage;
},
'validateUrl': function (url) {
url = url.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
if (url.charAt(0) == "/" ) {
return true;
} else {
var regexp = /(ftp|http|https|gopher|telnet):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
return regexp.test(url);
}
}
}
}
</code></pre>
<p>This works perfectly fine across all versions of sub-plugins, but I can't help to think that there is a better way to ferry data. The whole:</p>
<pre><code> var self = this;
this.parchment.openModal(template, function(input){
document.execCommand('createLink', false, input);
}, function(input){
return self.validate(input);
});
</code></pre>
<p>Bit seems like it could be a lot more elegant. </p>
<p>I'm namely struggling to keep contexts correct across the data being passed to <code>Plugin.prototype</code>. Namely validation and the data returned to the plugins callback.</p>
<p>Can anyone recommend a better structure for this? This is my first attempt to do JavaScript of this sort.</p>
| [] | [
{
"body": "<p>Interesting question,</p>\n\n<p>your code is fairly easy to follow, JsHint cannot find anything serious to complain about.</p>\n\n<p>Since you have a <code>validate</code> function, I would also create a <code>callback</code> function this way your call to <code>openModal</code> could be </p>\n\n<pre><code>this.parchment.openModal(template, this.createLinkCallback, this.validate );\n</code></pre>\n\n<p>Because you provide the functions themselves as parameters, you no longer need <code>self</code>, and you have a very readable line of code. ( Personally I might have called <code>validate</code> -> <code>validationCallback</code> ). </p>\n\n<p>Furthermore, there is something smelly about the fact that you sprinkle your code with <code>typeof something === 'function'</code>, I am not very fond of it, if you are going to check parameter types, you probably should do it up front in your code. Also this line : <code>typeof input === 'object' ? closeModal(input) : closeModal();</code> so basically if there is an array of inputs you would not return anything, why ? After going thru the trouble of collection the values into an array etc.</p>\n\n<p>Also, consider caching some of your jQuery calls, especially <code>modal.find('input')</code> is pretty expensive computing wise and you use this one a lot.</p>\n\n<p>Finally, you are checking <code>if(input)</code> twice, so that <code>handleAlert('You must enter something!');</code> under the first <code>if(input)</code> true block becomes dead code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:23:26.740",
"Id": "82201",
"Score": "0",
"body": "Thanks for the advice. The code is pretty rough and some things needs to be cleaned up. I was mostly worried about passing the values around. I tried to do what you said calling `this.createLinkCallback` and `this.validate` but I had an issue getting the input to send between the prototype and back. I'll take a look at it in a little bit and revise my code above."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:01:52.793",
"Id": "46904",
"ParentId": "46840",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46904",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:29:36.317",
"Id": "46840",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"regex",
"plugin",
"scope"
],
"Title": "Communicating between plugins whilst maintaining context in Javascript"
} | 46840 |
<p>Trying to learn shell sort, I kinda understood what wikipedia was trying to say, but I wanted a bit of confirmation, so I went on youtube, <a href="https://www.youtube.com/watch?v=IlRyO9dXsYE" rel="nofollow">here</a>, but this code does not work and does not look like what I read on wikipedia. I go to hi's website just in case I misspelled anything to copy+paste hi's code, nop not working either.</p>
<p>So here is my version, or rather what I understood of it. It does work (as in it gives me a correctly sorted array) but I'm not 100% sure this is even shell sort, or is it ? I don't know.</p>
<pre><code>public int[] shellSort(int[] numbers, compare compare) {
int firstPivot, secondPivot, temp;
int interval = numbers.Length / 2;
while (interval > 0) {
System.Diagnostics.Debug.WriteLine(interval);
// Start from interval, go all the way to the end
for (secondPivot = interval; secondPivot < numbers.Length; secondPivot++) {
firstPivot = secondPivot;
temp = numbers[secondPivot];
// Compare with predecesors from interval to interval
while ((firstPivot - interval >= 0) && compare(temp, numbers[firstPivot - interval])) {
numbers[firstPivot] = numbers[firstPivot - interval];
firstPivot -= interval;
}
// At the end we find the almost correct position for our "secondPivot" number
numbers[firstPivot] = temp;
}
// Decrease interval
interval = interval / 2;
} // Untill interval is "1" then we practically get an insertion sort that cleans up
// and have a properly sorted array
return numbers;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:44:24.977",
"Id": "81975",
"Score": "2",
"body": "Just thought I'd mention your brackets are Java-style. Not to start any Holy Wars, but C#-style curly braces go on the next line ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:05:18.400",
"Id": "81979",
"Score": "0",
"body": "@Mat'sMug that was the first thing I did when I got Visual studio: Went to formating options and change that ASAP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:09:20.963",
"Id": "82009",
"Score": "4",
"body": "That's cool and all, @Kalec, but sticking to another language's standards isn't exactly good practice. I see you also name methods in lowercase. You'll notice that your code is, therefore, entirely unlike every object in the framework itself. While that's nice for you, if you ever consider doing non-solo projects, I'd suggest being a bit more flexible. Java and C# have a lot in common, but you shouldn't break the standards anymore than you should in LISP or some other entirely different language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:52:03.700",
"Id": "82016",
"Score": "0",
"body": "@Magus I get that, but the non-inline opening brackets just mess me up so bad. In my personal projects I'll keep it this way no doubt. But if I work with others, then yes ... of-course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T03:25:54.740",
"Id": "82039",
"Score": "0",
"body": "Wow, I never considered brace placement--of which there are at least five variants across many languages--to be language-specific. Naming conventions I get, but I feel that whitespace should be left to the project owners. No biggie, just a surprise. :)"
}
] | [
{
"body": "<p>First, the good points: your code is quite cleanly written. Although some may argue over the naming convention(s) you've chosen, your names are reasonable, readable, and you do seem to have followed the naming convention fairly consistently.</p>\n\n<p>At least if I'm reading it correctly, yes, this does implement a Shell sort. Unfortunately, however, it uses a sequence of gap values (powers of 2) that is known to be fairly inefficient. With the right sequence, Shell-sort can give around O(N<sup>1.2</sup>). There are a couple of fairly easy sequences to generate that give only somewhat worse than that (around N<sup>1.3</sup> to N<sup>1.5</sup>). Although I don't believe a theoretical basis for it is known, the best sequences mostly follow ratios of <em>around</em> 2.2 to 2.25 or so.</p>\n\n<p>Starting with N/2 doesn't seem to be the best choice either. At least in most cases, starting somewhere around N/3 (or smaller) tends to work better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T05:18:21.260",
"Id": "82043",
"Score": "0",
"body": "I was going to math it up a bit with the fractions but I am tired and I can't find the syntax...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:35:19.627",
"Id": "82059",
"Score": "1",
"body": "@Malachi The answer and notation are fine as-is."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T04:51:20.077",
"Id": "46881",
"ParentId": "46841",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:31:34.730",
"Id": "46841",
"Score": "4",
"Tags": [
"c#",
"sorting"
],
"Title": "Is this Shell sort?"
} | 46841 |
<p>A few months ago I put up a <a href="https://codereview.stackexchange.com/questions/38452/python-port-scanner">port scanner for review</a>. Now, I've updated it with some new Python knowledge and integraing the feedback I got.</p>
<p>Some things I specifically think might be wrong with it or feel clunky to me:</p>
<ol>
<li>Default argument values for the <code>scan_ports</code> function. I set the default values, but then I have to check for <code>None</code> again when I enter the block. I was actually kind of surprised and disappointed that, if the arg was <code>None</code>, it didn't just automatically take the default. Any better way to handle this?</li>
<li>The <code>is_address_valid</code> function. I'm not entirely sure I did this the proper way, with catching multiple exception types. Not sure if I'm catching things I shouldn't be, or if there's a more elegant way to approach it.</li>
<li>Detecting the operating system. Not sure if the standard is to use <code>os.name</code> or <code>platform.system()</code>.</li>
<li>When is it acceptable to actually add line-breaks into your function bodies? Most of the scripts I've seen are really, really loathe to do so, and I kind of get it since everything in Python is space-based instead of bracket-based. But sometimes the function bodies seem to be a bit too long and it starts to look bad.</li>
<li>(More of a StackOverflow question, but still, if someone wants to throw it in as a tidbit...) Why do the arguments in <code>socket.socket().connect((host, 80))</code> have to be wrapped in another set of parentheses? Found that this was the way to do it, but couldn't find in the API <em>why</em> it has to be that way.</li>
</ol>
<p>Any tips or feedback are greatly appreciated!</p>
<p>Also, I think @GarethRees was skeptical in the other question that I might be using this for malicious purposes. I'm actually just learning from a book called <a href="http://rads.stackoverflow.com/amzn/click/1597499579" rel="nofollow noreferrer">Violent Python</a>, and a port scanner is the first thing it goes over in the book. The book is a bit more interesting than a normal textbook that goes over different variations of "Hello World!", haha.</p>
<hr>
<pre><code>#!/usr/bin/env python3
import argparse
import errno
import functools
import multiprocessing
import os
import platform
import socket
from concurrent.futures import ThreadPoolExecutor
DEFAULT_HOST = '127.0.0.1'
DEFAULT_TIMEOUT = 2
DEFAULT_CORES = 4
DEFAULT_THREADS = 512
PORT_RANGE = range(1, 65536)
def ping(host, port):
try:
socket.socket().connect((host, port))
print(str(port) + " Open")
return port
except socket.timeout:
return False
except socket.error as socket_error:
if socket_error.errno == errno.ECONNREFUSED:
return False
raise
def thread_scan(host, threads):
print('Scanning ' + host + ' with threads ...')
with ThreadPoolExecutor(max_workers = threads) as executor:
ping_partial = functools.partial(ping, host)
return list(filter(bool, executor.map(ping_partial, PORT_RANGE)))
def fork_scan(host, cores):
print('Scanning ' + host + ' with forks ...')
pool = multiprocessing.Pool(cores)
ping_partial = functools.partial(ping, host)
return list(filter(bool, pool.map(ping_partial, PORT_RANGE)))
def is_address_valid(host):
try:
socket.socket().connect((host, 80))
return True
except socket.gaierror:
return False
except (socket.timeout, socket.error):
return True
def get_os_info():
return os.name + ' [' + platform.system() + ' ' + platform.version() + ']'
def scan_ports(host = DEFAULT_HOST,
timeout = DEFAULT_TIMEOUT,
threads = DEFAULT_THREADS,
cores = DEFAULT_CORES):
if host is None:
host = DEFAULT_HOST
if timeout is None:
timeout = DEFAULT_TIMEOUT
if threads is None:
threads = DEFAULT_THREADS
if cores is None:
cores = DEFAULT_CORES
available_ports = []
socket.setdefaulttimeout(timeout)
if not is_address_valid(host):
print('DNS lookup for \'' + host + '\' failed.')
return
if os.name == 'nt':
print('Windows OS detected.')
available_ports = thread_scan(host, threads)
elif os.name == 'posix':
print('*Nix OS detected.')
available_ports = fork_scan(host, cores)
else:
print('Unidentified operating system: ' + get_os_info())
available_ports = fork_scan(host, cores)
print('Done.')
available_ports.sort()
print()
print(str(len(available_ports)) + ' ports available.')
print(available_ports)
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-ip', '--host', help = 'IP address/host to scan')
arg_parser.add_argument('-to', '--timeout', help = 'Connection timeout in seconds', type = int)
arg_parser.add_argument('-t', '--threads', help = 'Maximum number of threads to spawn (Windows only)', type = int)
arg_parser.add_argument('-c', '--cores', help = 'Number of cores to utilize (*Nix only)', type = int)
args = arg_parser.parse_args()
scan_ports(args.host, args.timeout, args.threads, args.cores)
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:28:07.460",
"Id": "82055",
"Score": "1",
"body": "[Follow-up question here](http://codereview.stackexchange.com/q/46866/9357)"
}
] | [
{
"body": "<p>You're opening a lot of sockets but not closing them. Those are likely file descriptor leaks. (Whether or not it actually leaks depends on the garbage collector's behaviour.)</p>\n\n<p>If you're using <code>concurrent.futures.ThreadPoolExecutor</code> for the multithreaded version, then you should also use <a href=\"https://docs.python.org/dev/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor\" rel=\"nofollow\"><code>concurrent.futures.ProcessPoolExecutor</code></a> for the multiprocess version.</p>\n\n<p><code>ping</code> usually implies an ICMP echo. If you're actually doing a TCP scan, call it <code>tcp_ping</code> or something.</p>\n\n<p>The status messages are misleading. \"Windows OS detected\" sounds like you performed <a href=\"http://en.wikipedia.org/wiki/TCP/IP_stack_fingerprinting\" rel=\"nofollow\">OS fingerprinting</a> on the remote peer, but you actually mean that the port scanner is running on a Windows host.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:14:56.037",
"Id": "81981",
"Score": "0",
"body": "Thanks for your comments. How does one close the socket appropriately?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:23:19.637",
"Id": "81984",
"Score": "0",
"body": "I guess just storing the reference to `socket.socket()` and then calling `.close()` on it later. Thanks. I'll try it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-09T17:23:23.943",
"Id": "275415",
"Score": "2",
"body": "Actually, you should [prefer Python's `with` construct](//stackoverflow.com/q/1369526) if you can."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:12:13.053",
"Id": "46845",
"ParentId": "46842",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46845",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:35:22.063",
"Id": "46842",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"networking",
"concurrency"
],
"Title": "Python Port Scanner 2.0"
} | 46842 |
<p>I've put together a simple application in order for me to learn sqlite and OOP in PHP. The application basically outputs two random words, e.g. "Angry Badger", from two database tables, one called Animals & the other named Adjectives. At present both tables contain the same columns (but could change in future).</p>
<p>The code uses an interface, iWord with two methods to be implemented by their concrete classes (Animal, Adjective). The database object has been passed in on the constructors so I can create some unit tests later. </p>
<p>If I were to introduce a new class, fruit, with the same methods: getRandomItem() & listRandomItems($numerOfItems) I would need to create the another DB table, class, implement the same DB error handling and processing of data. This doesn't feel correct.</p>
<p>An alternative may be to combine the database tables into one and have one class that I pass in an item to lookup, e.g. animal, fruit, adjective, & dynamically build the SQL. </p>
<p>Any recommendations or patterns that I should be following?</p>
<p>Please note: this is test code for learning & not for production use ;) </p>
<pre><code><?php
interface iWord
{
public function getRandomItem();
public function listRandomItems($numerOfItems);
}
class Animal implements iWord
{
private $database;
public function _construct(PDO $pdo)
{
$this->database = $pdo;
}
public function getRandomItem()
{
$rAnimal = NULL;
try
{
$query = $this->database->prepare("SELECT animalName FROM animal ORDER BY RANDOM() LIMIT 1;");
$query->execute();
$sqlres1 = $query->fetch(PDO::FETCH_OBJ);
$rAnimal = $sqlres1->animalName;
}
catch (PDOException $ex)
{
echo $ex->getMessage();
}
return $rAnimal;
}
public function listRandomItems($numerOfItems)
{
// not yet implemented
throw new Exception('Not Implemented');
}
}
class Adjective implements iWord
{
private $database;
public function _construct(PDO $pdo)
{
$this->database = $pdo;
}
public function getRandomItem()
{
// exception handling required
$query = $this->database->prepare("SELECT adjective FROM adjectives ORDER BY RANDOM() LIMIT 1;");
$query->execute();
$sqlres2 = $query->fetch(PDO::FETCH_OBJ);
return $sqlres2->adjective;
}
public function listRandomItems($numerOfItems)
{
throw new Exception('Not Implemented');
}
}
try {
$pdo = new PDO("sqlite:c:/htdocs/mydb.sqlite");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$adj = new Adjective($pdo);
$rAdjective = $adj->getRandomItem();
$anm = new Animal($pdo);
$rAnimal = $anm->getRandomItem();
echo $rAdjective . " " . $rAnimal;
unset($pdo);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:11:25.473",
"Id": "82106",
"Score": "0",
"body": "Just a quick suggestion: you can use Registry pattern for db connections in order to avoid passing it to the __construct(). Here is an example: https://bitbucket.org/t1gor/strategy/src/242e58cdcd60c61d02ae26d420da9d415117cb0d/application/utils/Registry.php?at=default"
}
] | [
{
"body": "<p>Extract an abstract base class <code>AbstractWordTable</code> that implements the better-named interface <code>WordTable</code> by moving all code that's duplicated between <code>Adjective</code> and <code>Animal</code> (all but the table and column names). This is a major step in the DRY direction that will simplify your code.</p>\n\n<p>I won't attempt to produce this code on my phone, but the key is for those concrete implementations to contain only unique code. The end result will be with a simple one-line constructor.</p>\n\n<p>Another improvement would be to decouple reading the table contents from picking random words by splitting these functions between <code>WordTable</code> that reads words from a database table into an array and <code>WordList</code> that provides various ways to consume it, including choosing random words and subsets. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:45:16.737",
"Id": "46873",
"ParentId": "46844",
"Score": "1"
}
},
{
"body": "<p>This code is probably challenging because it is dealing with two different levels of abstraction: getting a word, and talking to a database. We need to separate those concerns into abstractions. This also brings us up against the Law of Demeter, as we are asking for a database object, only to reach through it and get something else. Since you want to talk patters, I'll talk about two: Iterator and Template.</p>\n\n<p>I'd first replace the database parameter with an iterator, namely a <code>RandomWordIterator</code> (which will be an interface). The interface will look as so:</p>\n\n<pre><code>interface RandomWordIterator {\n public function next();\n}\n</code></pre>\n\n<p>You can also add on other typical iterator methods like <code>hasNext()</code>, but since it looks like it will represent a random, infinite stream, this should suffice. Now your classes become like:</p>\n\n<pre><code>class Animal implements iWord\n{\n private $wordIterator;\n\n public function _construct(RandomWordIterator $wordIterator)\n {\n $this->wordIterator = $wordIterator;\n }\n\n public function getRandomItem() \n {\n return $this->wordIterator->next(); \n }\n\n public function listRandomItems($numerOfItems)\n {\n $arr = array();\n for($i = 0; $i < $numberOfItems; $i++)\n {\n $arr[] = $this->getRandomItem();\n }\n return $arr;\n }\n}\n</code></pre>\n\n<p>Now you'll need to implement a <code>RandomWordIterator</code>. We could build one based around an array, or a web service, or a database. This flexibility could be useful in production, and is definitely useful in testing. Let's create an abstract (I'll explain why abstract soon) <code>DBTableRandomWordIterator</code> to start off.</p>\n\n<pre><code>abstract class DBTableRandomWordIterator implements RandomWordIterator\n{\n protected $database;\n\n public function __construct(PDO $pdo)\n {\n $this->database = $pdo;\n }\n\n abstract function getTableName();\n abstract function getColumnName();\n\n public function next()\n {\n $tableName = $this->getTableName();\n $columnName = $this->getColumnName();\n $rWord = NULL;\n try\n {\n $query = $this->database->prepare(\"SELECT $columnName AS word FROM $tableName ORDER BY RANDOM() LIMIT 1;\");\n $query->execute();\n $sqlres1 = $query->fetch(PDO::FETCH_OBJ);\n $rWord = $sqlres1->word;\n }\n catch(PDOException $e)\n {\n echo $ex->getMessage();\n }\n return $rWord;\n }\n}\n</code></pre>\n\n<p>We've created a base implementation, while leaving open hooks for specifying details through subclassing (thus the <code>abstract</code>). Now we can make use of the second pattern, the Template pattern (though it could just as easily be called the Factory pattern as you are making string objects, but in this case the result is the same). We now implement concrete classes for each table type, implementing the two abstract methods.</p>\n\n<pre><code>class RandomAnimalIterator extends DBTableRandomWordIterator\n{\n public function getTableName() { return 'animal'; }\n public function getColumnName() { return 'animalName'; }\n}\n</code></pre>\n\n<p>We need one concrete class per table. This localizes changes when the database tables change, and allows us to vary table and column name formats with ease.</p>\n\n<p>Now let's put all the pieces together:</p>\n\n<pre><code>try {\n $pdo = new PDO(\"sqlite:c:/htdocs/mydb.sqlite\");\n $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n}\ncatch(PDOException $e) {\n echo $e->getMessage();\n}\n\n$adj = new Adjective(new RandomAdjectiveIterator($pdo));\n$rAdjective = $adj->getRandomItem();\n$anm = new Animal(new RandomAnimalIterator($pdo));\n$rAnimal = $anm->getRandomItem();\n\necho $rAdjective . \" \" . $rAnimal;\n\nunset($pdo);\n</code></pre>\n\n<p>Now, this is a complete solution using patterns, but it may bother people that classes like <code>Adjective</code> and <code>Animal</code> are basically empty shells now. I would probably combine those classes with their respective iterators if I were making this as a real project, though there is no requirement to do so. Leaving them separate may allow for separation of responsibilities at some point later if you start to hang more behavior off of those classes like <code>Animal</code> and <code>Adjective</code>.</p>\n\n<p>The other option could have been to have a single, concrete <code>DBTableRandomWordIterator</code> and pass in a delegate object containing the table and column names. This would change the relationships a bit, and could allow for better object reuse (a single <code>DBTableRandomWordIterator</code> where the delegates are swapped out), with all the caveats expected.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:20:01.030",
"Id": "46888",
"ParentId": "46844",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T19:44:48.397",
"Id": "46844",
"Score": "4",
"Tags": [
"php",
"object-oriented"
],
"Title": "Reduce similar methods via pattern?"
} | 46844 |
<p>Quite a specific question can the below code be made more clearer / pythonic in any way.</p>
<p>Essentially based on the condition of the string <code>x((len(x) / 3) - 1)</code>, I use this to extract out parts of the string.</p>
<pre><code>def split_string(x):
splitted_string = [x[counter*3:(counter*3)+3] for counter in range ((len(x) /3) - 1)]
return splitted_string
>>> split_string('ABCDEFGHI')
['ABC', 'DEF']
</code></pre>
| [] | [
{
"body": "<p>For integer division, use the <code>//</code> operator. <a href=\"https://stackoverflow.com/a/183870/1157100\">In Python 3, <code>/</code> will do floating-point division.</a></p>\n\n<p>The task could be more succinctly accomplished using <a href=\"https://docs.python.org/2/library/re.html#re.findall\" rel=\"nofollow noreferrer\"><code>re.findall()</code></a>.</p>\n\n<p>Also, the goal of the function is not obvious. Pythonic code would include a docstring explaining its purpose.</p>\n\n<pre><code>import re\n\ndef split_string(s):\n \"\"\"\n Splits a string into a list, with each element consisting of\n three characters. Any incomplete group at the end is discarded,\n and then the last complete group is also discarded.\n \"\"\"\n return re.findall(r'.{3}', s)[:-1]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:38:43.740",
"Id": "46851",
"ParentId": "46849",
"Score": "6"
}
},
{
"body": "<p>The <code>range</code> command has a step argument.</p>\n\n<pre><code>def split_string(x):\n return [x[i:i+3] for i in range(0, len(x) - 5, 3)]\n\n>>> split_string('ABCDEFGHI')\n['ABC', 'DEF']\n</code></pre>\n\n<p>I also used <code>i</code> instead of <code>counter</code> since it's shorter and <code>i</code> is the standard way of expressing an array index in most langauges.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:43:23.527",
"Id": "82003",
"Score": "1",
"body": "That's a nice idea, but the behaviour is quite different from the original code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:29:51.487",
"Id": "82031",
"Score": "0",
"body": "It was just missing the `-1` on the end of the range."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:39:27.403",
"Id": "82068",
"Score": "0",
"body": "@DavidHarkness It's still not equivalent to the original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T08:09:43.450",
"Id": "82074",
"Score": "0",
"body": "@200_success I corrected my correction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:23:41.883",
"Id": "82082",
"Score": "0",
"body": "@DavidHarkness There was still an off-by-one error, which I've fixed in [Rev 4](http://codereview.stackexchange.com/revisions/46852/4)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:41:19.020",
"Id": "46852",
"ParentId": "46849",
"Score": "4"
}
},
{
"body": "<p>I always try to evaluate my function and see if there's anything else that could enhance it.</p>\n\n<p>You're already evenly splitting these strings, so why not add a default parameter, size to control the section size. You also don't take the last cut (<em>I'm guessing to avoid index error</em>), you can add that as a default parameter as well.</p>\n\n<p>Also, just return the comprehension</p>\n\n<pre><code>def split_string(word, size = 3, trim = 1):\n return [word[ii*size:(ii+1)*size] for ii in range(len(word)/size - trim )]\n\n>>> split_string('ABCDEFGHI')\n['ABC', 'DEF']\n>>> split_string('ABCDEFGHI',4)\n['ABCD', 'EFGH']\n>>> split_string('ABCDEFGHI',3,0)\n['ABC', 'DEF','GHI']\n>>> split_string('ABCDEFGHI',3,2)\n['ABC']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:56:51.250",
"Id": "82005",
"Score": "3",
"body": "Menaningful parameter names would be even better :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:57:23.527",
"Id": "82006",
"Score": "1",
"body": "@Morwenn I agree,.. I was just lazy :p"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T21:42:29.870",
"Id": "46853",
"ParentId": "46849",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:59:14.590",
"Id": "46849",
"Score": "4",
"Tags": [
"python",
"strings"
],
"Title": "Can this list comprehension be made more pythonic?"
} | 46849 |
<p>I have some PHP code where I use variable functions to call the right function. I need to build a chart array (for example), and the chart array that comes out has a fixed format. But the data that goes into the chart or table comes from varying places in the underlying objects.</p>
<p>An example:</p>
<pre><code>private function buildChartGroups(PropelCollection $groups, $propertyForDisplay) {
$groupDisplayFunction = "getSum$propertyForDisplay";
$chart = array();
foreach ($groups as $group) {
$chart[] = array('name' => $group->getName(),
'y' => $group->$groupDisplayFunction()
);
}
}
return $chart;
}
</code></pre>
<p>and then the function gets called something like:</p>
<pre><code>$result = $this->buildChartGroups($groups, "Total");
...elsewhere...
$result = $this->buildChartGroups($groups, "Count");
</code></pre>
<p>where <code>$groups</code> is an array of <code>Group</code> objects:</p>
<pre><code>class Group {
private $name;
private $sumTotal;
private $sumCount;
public function getName() {
return $this->name;
}
public function getSumTotal() {
return $this->sumTotal;
}
public function getSumCount() {
return $this->sumCount;
}
}
</code></pre>
<p>This works fine and lets me re-use <code>buildChartGroups()</code> which I would otherwise not be able to do. But using variable functions and passing function names as strings always seems a little dirty, even though I'm sure it has its place.</p>
<p>Is there a way to refactor this or is there some pattern I can use to avoid them?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:24:44.690",
"Id": "82010",
"Score": "0",
"body": "Welcome to Code Review! To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your actual code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Unfortunately, it's a bit hard to review code like this because the code you're showing is looking more like example code rather than code that you're actually using in a real project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:49:05.497",
"Id": "82014",
"Score": "0",
"body": "Got it, thanks. Adding more of the real code."
}
] | [
{
"body": "<p>I agree, it does feel dirty to compute the function name like that.</p>\n\n<p>A typical way to do dynamic dispatching is using polymorphism. You could formalize the mechanism for determining which function to call by making some property-extracting objects:</p>\n\n<pre><code>abstract class PropertyExtractor {\n public abstract function getProperty($group);\n}\n\nclass SumTotalExtractor extends PropertyExtractor {\n public function getProperty($group) {\n return $group->getSumTotal();\n }\n}\n\nclass SumCountExtractor extends PropertyExtractor {\n public function getProperty($group) {\n return $group->getSumCount();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Your <code>buildChartGroups()</code> would take one of those extractors as the second parameter:</p>\n\n<pre><code>private function buildChartGroups(PropelCollection $groups, $propertyExtractor) {\n $chart = array();\n foreach ($groups as $group) {\n $chart[] = array('name' => $group->getName(), \n 'y' => $propertyExtractor->getProperty($group));\n }\n return $chart;\n}\n</code></pre>\n\n<hr>\n\n<p>Here it is in use:</p>\n\n<pre><code>$result = $this->buildChartGroups($groups, new SumTotalExtractor());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:52:27.437",
"Id": "82167",
"Score": "0",
"body": "This is nice and clean! I'm accepting the other answer because it fit a little better with the rest of my code but both are great ideas, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:14:13.510",
"Id": "46861",
"ParentId": "46855",
"Score": "5"
}
},
{
"body": "<p>There are several other ways to solve this, but which one I'd go with depends a lot on the <code>Group</code> class.</p>\n\n<ul>\n<li>Do you plan to have more than a handful of properties to choose from?</li>\n<li>Do you have control over the <code>Group</code> implementation?</li>\n<li>Is this property-choosing behavior needed anywhere else?</li>\n</ul>\n\n<p>Here's an example that assumes the answers to the above are all \"no\": use constants to pick the property and provide one-liner public methods to avoid exposing them to callers:</p>\n\n<pre><code>const TOTAL = 1;\nconst COUNT = 2;\n\npublic function buildChartGroupTotals(PropelCollection $groups) {\n return $this->buildChartGroups($groups, self::TOTAL);\n}\n\npublic function buildChartGroupCounts(PropelCollection $groups) {\n return $this->buildChartGroups($groups, self::COUNT);\n}\n\nprivate function buildChartGroups(PropelCollection $groups, $property) {\n return array_map(function ($group) {\n switch ($property) {\n case self::TOTAL:\n $value = $group->getSumTotal();\n break;\n case self::COUNT:\n $value = $group->getSumCount();\n break;\n default:\n throw new InvalidArgumentException(\"Invalid property\");\n }\n return array(\n 'name' => $group->getName(), \n 'y' => $value,\n );\n }, $groups);\n}\n</code></pre>\n\n<p>If you have control over the <code>Group</code> implementation, I would prefer to move the constants and switch into it and add <code>getSumProperty($property)</code>.</p>\n\n<pre><code>class Group {\n const TOTAL = 1;\n const COUNT = 2;\n ...\n public function getSumProperty($property) {\n switch ($property) {\n case self::TOTAL:\n return $this->sumTotal;\n case self::COUNT:\n return $this->sumCount;\n default:\n throw new InvalidArgumentException(\"Invalid property\");\n }\n }\n}\n</code></pre>\n\n<p>Now you can pass one of the constants to <code>buildChartGroups</code> which will forward it to <code>getSumProperty</code> and greatly simplify the code at the cost of exposing those constants. You could still provide the property-specific one-liners, though.</p>\n\n<pre><code>private function buildChartGroups(PropelCollection $groups, $property) {\n return array_map(function ($group) {\n return array(\n 'name' => $group->getName(), \n 'y' => $group->getSumProperty($property),\n );\n }, $groups);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:55:02.783",
"Id": "82168",
"Score": "0",
"body": "I do have control over the Group class, and this fits in well with that implementation. I can actually pass that $property down to the classes that the Group actually holds and it makes for much more readable code. And this will make it much easier to find where the getSumProperty methods are used, as opposed to my Variable functions solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:15:22.937",
"Id": "46862",
"ParentId": "46855",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46862",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:11:49.600",
"Id": "46855",
"Score": "6",
"Tags": [
"php",
"design-patterns"
],
"Title": "Calling functions with variable functions"
} | 46855 |
<p>I've recently been asked to make some emergency changes to a legacy application written in VB.NET. I come from a C# background so am not overly familiar with this language, though there are enough similarities for me to get by.</p>
<p>The current code has no separation of concerns (e.g. DAL code is written in the codebehind of each page rather than separated out). To make it usable without introducing too much risk I'm avoiding libraries but extracting the DAL code to separate classes. Since my DB code's going to be used from a lot of places in the app, I wanted to check that this all makes sense, that it is reasonably efficient and that I haven't made some schoolboy error in creating this.</p>
<pre class="lang-vb prettyprint-override"><code>Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Collections.Generic
Public Class DB
Private _connectionString As String
Public Sub New(connectionString As String)
_connectionString = connectionString
End Sub
Public Sub ExecuteNonQuery(cmdTxt As String, params As Dictionary(Of String, Object))
Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
cmd.ExecuteNonQuery()
End Using
End Sub
Public Function ExecuteReader(cmdTxt As String, params As Dictionary(Of String, Object)) As SqlDataReader
Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
Return cmd.ExecuteReader()
End Using
End Function
Public Function ExecuteScalar(cmdTxt As String, params As Dictionary(Of String, Object)) As Object
Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
Return cmd.ExecuteScalar()
End Using
End Function
Private Function BuildCommand(cmdTxt As String, params As Dictionary(Of String, Object)) As SqlCommand
Using con As New SqlConnection(_connectionString)
Using cmd As SqlCommand = con.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = cmdTxt
AddParameters(cmd, params)
con.Open() 'working on the assumption this command will be run as soon as it's retuned; so this open is left as late as possible but here to avoid duplicate code
Return cmd
End Using
End Using
End Function
Private Sub AddParameters(ByRef cmd As SqlCommand, params As Dictionary(Of String, Object))
If Not params Is Nothing Then
For Each kvp As KeyValuePair(Of String, Object) In params
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value)
Next
End If
End Sub
End Class
</code></pre>
| [] | [
{
"body": "<p>This looks really good and clean to me as well, but I too come from a C# Background.</p>\n\n<p>I think there are only a couple of things missing that I would personally like to see myself.</p>\n\n<ol>\n<li>Error Handling</li>\n<li>Constructor</li>\n</ol>\n\n<p>there is only one thing that I would probably change.</p>\n\n<p>your <code>BuildCommand</code> Function should not open the connection. I think that the open and close should be done in the Execute functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:46:02.783",
"Id": "46857",
"ParentId": "46856",
"Score": "6"
}
},
{
"body": "<p>Now that's some coincidence! No later than this week I wrote an ADODB \"wrapper\" for some <a href=\"/questions/tagged/vb6\" class=\"post-tag\" title=\"show questions tagged 'vb6'\" rel=\"tag\">vb6</a> legacy code (<a href=\"https://codereview.stackexchange.com/q/46312/23788\">here</a>). This looks very much similar, only for ADO.NET.</p>\n\n<p>I don't like the name. <code>DB</code> is not respecting the <em>PascalCase</em> naming convention for VB.NET classes (same in C#) - I realize it's a short handy name, but it looks like a variable's name. I'd rename the class to, say, <code>AdoCommandBuilder</code>; the name of the object should say what the object's role is. In this case, <em>building an ADO.NET command</em>.</p>\n\n<p>I might be completely wrong here, but it seems to me that a thread entering <code>BuildCommand</code> from <code>ExecuteReader</code> would open up a connection, and then when the function returns, the connection would be disposed before the client code can start iterating the reader. Thus I wouldn't wrap an <code>IDisposable</code> in a <code>Using</code> block if I'm going to be returning it.</p>\n\n<p>Anyway your command is being disposed twice. Once in <em>BuildCommand</em>:</p>\n\n<pre><code> Using cmd As SqlCommand = con.CreateCommand()\n cmd.CommandType = CommandType.StoredProcedure\n cmd.CommandText = cmdTxt\n AddParameters(cmd, params)\n con.Open()\n Return cmd\n End Using '<<<<<< here\n</code></pre>\n\n<p>...and once more in the <em>ExecuteXxxxx</em> methods:</p>\n\n<pre><code> Using cmd As SqlCommand = BuildCommand(cmdTxt, params)\n Return cmd.ExecuteReader()\n End Using ' <<<<<< here too!\n</code></pre>\n\n<p>I'd remove the <code>Using cmd As SqlCommand</code> from the <em>CreateCommand</em> method.</p>\n\n<p>I agree with @Malachi, that <code>BuildCommand</code> shouldn't be opening the connection - its concern is <em>building a command</em>, so it should be <em>taking</em> a connection as a parameter; by doing that you enable extending your class with methods that take a connection, which enables running your commands in a transaction.</p>\n\n<p>Hence, I think I would drop the parameterized constructor, add a <code>Connect(connectionString As String)</code> method instead, encapsulate the connection (, implement <code>IDisposable</code>) and give each <em>ExecuteXxxxxx</em> method an overload that takes an <code>IDbConnection</code> parameter; if you're not going to be taking in a connection, then you should <em>own</em> the whole process and return the <em>data</em>, not the <em>reader</em> itself - the idea is that you generally want the object that creates an <code>IDisposable</code> to be the one calling <code>Dispose</code> on it, so I'd only return a <code>SqlDataReader</code> when the client code owns the connection.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:34:49.987",
"Id": "46863",
"ParentId": "46856",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46857",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:15:24.283",
"Id": "46856",
"Score": "8",
"Tags": [
"sql-server",
"vb.net"
],
"Title": "Database access class using VB.NET"
} | 46856 |
<p>I have written code to send a simple email submission form to a sql table so that I can manage the data. I would like feedback on whether or not the code that I have written is efficient and secure. I have a config file that defines constants for database credentials.</p>
<p>HTML FORM</p>
<pre><code><form method="post" action="index.php">
<input class="bt-email" type="email" name="email" placeholder="enter email address">
<input class="bt-submit" type="submit" value="let's get moving!">
</form>
</code></pre>
<p>PHP Database Code File</p>
<pre><code>try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";port=" . DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Could not connect to the database.";
exit;
}
</code></pre>
<p>PHP/SQL Submission Code</p>
<pre><code><?php
require_once("inc/config.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["email"];
require(ROOT_PATH . "inc/database.php");
try {
$db->exec("REPLACE INTO launch_email VALUES ('$email')");
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
header("Location: index.php?status=thanks");
exit;
}
?>
</code></pre>
| [] | [
{
"body": "<p>You could possibly move the database include before the server checks and sets the <code>$_POST</code> variable, as it would not be needed if the database is unable to connect.</p>\n\n<p>I notice there is no sanitization of the email variable. <a href=\"https://stackoverflow.com/questions/17103318/correct-way-to-sanitize-input-in-mysql-using-pdo\">This may be helpful</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:53:08.600",
"Id": "46865",
"ParentId": "46860",
"Score": "3"
}
},
{
"body": "<p>I will extend mulquin's short post.</p>\n\n<p>Sanitizing your POST will enable you to make sure there are no SQL injection. Since you are using PDO - you should use prepare() function reather than exec(). exec doesn't escape your query. (as shown in the link provided by mulquin)</p>\n\n<p>Furthermore - you are not checking if the email is indeed an email or not what happens if its not a real email address (ie the format is not john@doe.com) - you will be storing gebrish at this point. So a bit of validation so that not only spammers won't just enter anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T03:06:00.357",
"Id": "82038",
"Score": "0",
"body": "yeah i plan on adding some server-side validation, i just wanted to see if my code was efficient and secure from a sql standpoint. thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:45:56.067",
"Id": "46874",
"ParentId": "46860",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T23:54:21.213",
"Id": "46860",
"Score": "2",
"Tags": [
"php",
"html",
"sql"
],
"Title": "Submit form data to MYSQL table with PHP execute"
} | 46860 |
<p>An optimisation question:</p>
<p>Currently I have entities stored in text files in the following format:</p>
<pre><code>Attribute1,Attribute2,Attribute3
Value1-1,Value1-2,Value1-3
Value2-1,Value2-2,Value2-3
Value3-1,Value3-2,Value3-3
</code></pre>
<p>And convert it into a 2D array in the following format:</p>
<pre><code>$array = array(array('Attribute1' => 'Value1-1',
'Attribute2', => 'Value1-2',
'Attribute3', => 'Value1-3'),
array('Attribute1' => 'Value2-1',
'Attribute2', => 'Value2-2',
'Attribute3', => 'Value2-3'),
array('Attribute1' => 'Value3-1',
'Attribute2', => 'Value3-2',
'Attribute3', => 'Value3-3'));
</code></pre>
<p>Using the following PHP code:</p>
<pre><code>$lines = array();
$dump = normaliseNewLine($dump);
$dump = explode("\n", $dump);
$attributes = explode(',', array_shift($dump));
for($i = 0; $i < count($dump); $i++) {
$tmp = explode(',', $dump[$i]);
for ($j = 0; $j < count($tmp); $j++) {
$lines[$i][$attributes[$j]] = $tmp[$j];
}
}
</code></pre>
<p>I was wondering if there was a more efficient method of completing this task?</p>
| [] | [
{
"body": "<p>PHP provides functions to <a href=\"http://uk1.php.net/manual/en/function.fgetcsv.php\" rel=\"nofollow\">parse CSV files</a> and <a href=\"http://uk1.php.net/manual/en/function.str-getcsv.php\" rel=\"nofollow\">strings</a> line-by-line.</p>\n\n<pre><code>$file = ...\n$headers = fgetcsv($file);\n$lines = array();\nwhile (($line = fgetcsv($file)) !== false) {\n $lines[] = array_combine($headers, $line);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:17:00.557",
"Id": "46871",
"ParentId": "46864",
"Score": "4"
}
},
{
"body": "<p>This version uses fewer lines, and is <a href=\"http://i110.photobucket.com/albums/n92/General-Jazza/TestPHP_zpsf07b8814.png\" rel=\"nofollow\">slightly quicker</a> for me:</p>\n\n<pre><code>function($fileName)\n{\n $handle = fopen($fileName, 'r');\n $attributes = fgetcsv($handle);\n for($i = 0; $line = fgetcsv($handle); $i++)\n {\n foreach($attributes as $k => $attribute)\n {\n $lines[$i][$attribute] = $line[$k];\n }\n }\n return $lines;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T05:34:30.767",
"Id": "82046",
"Score": "0",
"body": "Just noticed that this code does not produce the correct output!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:32:41.057",
"Id": "82144",
"Score": "0",
"body": "@mulquin You're right- updated the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:25:39.580",
"Id": "46872",
"ParentId": "46864",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46871",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T00:42:32.367",
"Id": "46864",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "Assigning array keys based on the values of another array"
} | 46864 |
<p>I made lots of changes to the script presented in <a href="https://codereview.stackexchange.com/questions/46842/python-port-scanner-2-0">my previous question</a>. I was tempted to edit that one with the new code, but it would invalidate @200_success's helpful answer. It was also disallowed <a href="https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c">on a Meta thread</a>. So I apologize for the new question, but it seemed like the right thing to do.</p>
<p>Again, any and all tips are appreciated! Also, this is my first time writing any docstrings, so if I'm breaking convention, let me know.</p>
<pre><code>#!/usr/bin/env python3
import argparse
import errno
import functools
import multiprocessing
import os
import platform
import socket
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
DEFAULT_HOST = '127.0.0.1'
DEFAULT_TIMEOUT = 1
DEFAULT_THREADS = 512
PORT_RANGE = range(1, 65536)
def tcp_ping(host, port):
"""
Attempts to connect to host:port via TCP.
Arguments:
host: IP address or URL to hit
port: Port to hit
Returns:
port number, if it's available; otherwise False
"""
try:
with socket.socket() as sock:
sock.connect((host, port))
print(str(port) + ' Open')
return port
except socket.timeout:
return False
except socket.error as socket_error:
if socket_error.errno == errno.ECONNREFUSED:
return False
raise
def perform_scan(host, use_threads = False):
"""
Perform a scan on all valid ports (1 - 65535), either by
spawning threads or forking processes.
Arguments:
host: IP address or URL to scan
use_threads: whether or not to use threads; default
behaviour is to fork processes
Returns:
list of available ports
"""
if use_threads:
executor = ThreadPoolExecutor(max_workers = DEFAULT_THREADS)
else:
executor = ProcessPoolExecutor()
with executor:
ping_partial = functools.partial(tcp_ping, host)
return list(filter(bool, executor.map(ping_partial, PORT_RANGE)))
def is_address_valid(host):
"""
Validate the host's existence by attempting to establish
a connection to it on port 80 (HTTP).
Arguments:
host: IP address or URL to validate
Returns:
bool indicating whether the host is valid
"""
try:
with socket.socket() as sock:
sock.connect((host, 80))
return True
except socket.gaierror:
return False
except (socket.timeout, socket.error):
return True
def scan_ports(host = DEFAULT_HOST, timeout = DEFAULT_TIMEOUT):
"""
Scan all possible ports on the specified host. If the
operating system is detected as Windows, the ports will be
scanned by spawning threads. Otherwise, new processes will
be forked.
Arguments:
host: IP address or URL to scan
timeout: connection timeout when testing a port
"""
# Set defaults if CLI arguments were passed in but not specified
if host is None:
host = DEFAULT_HOST
if timeout is None:
timeout = DEFAULT_TIMEOUT
# Strip the protocol from the URL, if present
if '://' in host:
host = host[host.index('://') + 3:]
# Set the timeout for all subsequent connections
socket.setdefaulttimeout(timeout)
# Validate the IP/host by testing a connection
if not is_address_valid(host):
print('DNS lookup for \'' + host + '\' failed.')
return
# Perform the scan. On Windows, thread. On all others, fork.
print('Scanning ' + host + ' ...')
start_time = time.clock()
if os.name == 'nt':
print('Running on Windows OS.')
available_ports = perform_scan(host, use_threads = True)
elif os.name == 'posix':
print('Running on *Nix OS.')
available_ports = perform_scan(host)
else:
print('Unidentified operating system: ' + os.name
+ ' [' + platform.system() + ' ' + platform.version() + ']')
available_ports = perform_scan(host)
end_time = time.clock()
print('Done.')
# Display results
print()
print('Time elapsed: ' + format(end_time - start_time, '.2f') + ' sec')
available_ports.sort()
print()
print(str(len(available_ports)) + ' ports available.')
print(available_ports)
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-ip', '--host', help = 'IP address/host to scan')
arg_parser.add_argument('-t', '--timeout', help = 'Connection timeout in seconds', type = int)
args = arg_parser.parse_args()
scan_ports(args.host, args.timeout)
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:27:33.233",
"Id": "82054",
"Score": "12",
"body": "Asking a new question is the right thing to do!"
}
] | [
{
"body": "<p>Trying to connect to TCP port 80 in order to check whether the DNS lookup succeeds is overkill. You should just call <a href=\"https://stackoverflow.com/a/2805413/1157100\"><code>socket.gethostbyname()</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:58:05.030",
"Id": "46953",
"ParentId": "46866",
"Score": "4"
}
},
{
"body": "<p>I notice a few little things that I would adjust just from a housekeeping perspective.</p>\n\n<ol>\n<li>You import multiprocessing but I don't see where it is used.. I would remove if it is not needed.</li>\n<li>some small pep8 stuff - Keyword args should not have spaces around the equal, 2 blank lines between each function, and more than 80 line length on the argpase.add_arg near the bottom.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T03:50:48.960",
"Id": "47041",
"ParentId": "46866",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T01:18:54.203",
"Id": "46866",
"Score": "12",
"Tags": [
"python",
"python-3.x",
"networking",
"concurrency"
],
"Title": "Python Port Scanner 2.1"
} | 46866 |
<p>I recently self-taught myself MySQL as quickly as possible because it was needed for a project that I'm working on. Now that I've got some time I've been working on improving some thrown together SQL procedures. I've already done a few things, like logic improvements and removal of sub-queries, but I'm wondering if anyone can quickly skim through the procedure and point out anything specifically bad that I might have missed.</p>
<pre><code>CREATE PROCEDURE `userstatsUpdate`(IN userauth VARCHAR(32))
BEGIN
DECLARE mapcount INT DEFAULT 0;
DECLARE stagecount INT DEFAULT 0;
DECLARE bonuscount INT DEFAULT 0;
DECLARE mapmult FLOAT DEFAULT 0;
DECLARE stagemult FLOAT DEFAULT 0;
DECLARE bonusmult FLOAT DEFAULT 0;
DECLARE pc FLOAT DEFAULT 0;
DECLARE stagerecs INT DEFAULT 0;
DECLARE bonusrecs INT DEFAULT 0;
DECLARE maprecs INT DEFAULT 0;
DECLARE tops INT DEFAULT 0;
DECLARE p_comps FLOAT DEFAULT 0;
DECLARE p_tops FLOAT DEFAULT 0;
DECLARE counter INT DEFAULT 0;
DECLARE ranknum INT DEFAULT 0;
DECLARE userID INTEGER DEFAULT 0;
SELECT playerID INTO userID FROM cs_players WHERE cs_players.userauth = userauth;
WHILE counter < 10 DO
SET ranknum = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid=cs_maps.mapid WHERE stage = 0 AND rank = counter+1 AND playerid = userID AND active = 1);
SET p_tops = p_tops + (((10-counter)+(10-counter+2)*30)*ranknum);
SET counter = counter + 1;
END WHILE;
SELECT count(*),
COALESCE(
(count(*)*((difficulty+4)/5)),0)
AS points INTO mapcount, mapmult from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage = 0 AND playerid = userID AND cs_maps.active = 1;
SELECT count(*), COALESCE(
(count(*)*((difficulty+4)/5)),0)
AS points INTO stagecount, stagemult from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 0 AND playerid = userID AND cs_maps.active = 1;
SELECT count(*), COALESCE(
(count(*)*((difficulty+4)/5)),0)
AS points INTO bonuscount, bonusmult from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 1 AND playerid = userID AND cs_maps.active = 1;
SET maprecs = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage = 0 AND rank = 1 AND playerid = userID AND cs_maps.active = 1);
SET stagerecs = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 0 AND rank = 1 AND playerid = userID AND cs_maps.active = 1);
SET bonusrecs = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage > 0 AND cs_times.type = 1 AND rank = 1 AND playerid = userID AND cs_maps.active = 1);
SET tops = (SELECT count(*) from cs_times INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid WHERE stage = 0 AND rank <= 10 AND rank > 0 AND playerid = userID AND cs_maps.active = 1);
SET @TotalStage = (SELECT sum(checkpoints) FROM cs_maps WHERE mtype = 0 AND active = 1);
SET @TotalBonus = (SELECT sum(cp_bonus) FROM cs_maps WHERE active = 1);
SET @TotalMaps = (SELECT COUNT(*) FROM cs_maps WHERE active = 1);
SET @div1 = ((mapcount*2)+stagecount+(bonuscount*1.5));
SET @div2 = ((@TotalMaps*2)+@TotalStage+(@TotalBonus*1.5));
SET pc = @div1/@div2;
SET p_comps = (mapmult * 50) + (bonusmult * 20) + (stagemult * 5);
INSERT INTO cs_userstats(playerid, c_maps, c_stages, c_bonuses, wr_m, wr_s, wr_b, wr_top, p_top, p_comp, percomp) VALUES (userID, mapcount, stagecount, bonuscount, maprecs, stagerecs, bonusrecs, tops, p_tops, p_comps, pc)
ON DUPLICATE KEY UPDATE c_maps = mapcount, c_stages = stagecount, c_bonuses = bonuscount, wr_m = maprecs, wr_s = stagerecs, wr_b = bonusrecs, wr_top = tops, p_top = p_tops, p_comp = p_comps, percomp = pc;
END$$
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T01:44:35.880",
"Id": "82026",
"Score": "0",
"body": "are `playerid` and `userID` in the same table? are you looking to see if they are in the same row?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:19:44.510",
"Id": "82030",
"Score": "0",
"body": "Yeah userID is just an INT to store the playerID from the input userauth. It added another query, but it prevents redundant joins to always redetermine the playerID from userauth for every query. Hopefully that made sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:31:37.777",
"Id": "82032",
"Score": "0",
"body": "it's hard to see your parameters, I am used to SQL SERVER parameters they always start with a `@`. you should mark that as a variable/parameter somehow."
}
] | [
{
"body": "<p>the first thing that I see here is that it is going to be hard to read because you don't use standard ... \"notation\" like indentation and new lines for each column you are selecting in a SELECT statement. all of this is going to matter when you are going to be returning to the code to read it again or maintain it later.</p>\n\n<hr>\n\n<p>where you have this:</p>\n\n<pre><code>WHERE stage = 0 AND playerid = userID\n</code></pre>\n\n<p>the <code>playerid = userID</code> part should really be in a join statement if possible.</p>\n\n<hr>\n\n<p>some of your <code>SET</code> statements look very similar, you should look at these and see if you can't create a Temp Table with them, or even a CTE (I don't remember if this is possible with MySQL or not)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:56:45.953",
"Id": "82034",
"Score": "2",
"body": "[MySQL does not support Common Table Expressions.](http://bugs.mysql.com/bug.php?id=16244)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:58:45.257",
"Id": "82035",
"Score": "0",
"body": "sounds like TEMP Tables can't be used more than once in a query either"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T02:59:52.827",
"Id": "82036",
"Score": "1",
"body": "Dang that Bug report is 8 years old and they still haven't fixed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T05:21:55.590",
"Id": "82045",
"Score": "2",
"body": "Avoid temporary tables unless there's a good reason to use them. A workaround for the lack of Common Table Expressions is to create views instead. The main drawback is that creating views pollutes the global namespace."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T01:42:29.553",
"Id": "46869",
"ParentId": "46867",
"Score": "6"
}
},
{
"body": "<p>I have to agree with @Malachi about the lack of indentation. Your code is unreadable because of it. It would also be beneficial to insert a few spaces into the complex arithmetic expressions.</p>\n\n<p>Also take care to consistently use UPPERCASE for keywords such as <code>FROM</code>.</p>\n\n<p>For your benefit and the benefit of other reviewers, here is your code, with no changes other than indentation and capitalization. That's the first step towards understanding the code and making further improvements.</p>\n\n<pre><code>CREATE PROCEDURE `userstatsUpdate`(IN userauth VARCHAR(32))\nBEGIN\n\n DECLARE mapcount INT DEFAULT 0;\n DECLARE stagecount INT DEFAULT 0;\n DECLARE bonuscount INT DEFAULT 0;\n\n DECLARE mapmult FLOAT DEFAULT 0;\n DECLARE stagemult FLOAT DEFAULT 0;\n DECLARE bonusmult FLOAT DEFAULT 0;\n\n DECLARE pc FLOAT DEFAULT 0;\n\n DECLARE stagerecs INT DEFAULT 0;\n DECLARE bonusrecs INT DEFAULT 0;\n DECLARE maprecs INT DEFAULT 0;\n DECLARE tops INT DEFAULT 0;\n\n DECLARE p_comps FLOAT DEFAULT 0;\n DECLARE p_tops FLOAT DEFAULT 0;\n DECLARE counter INT DEFAULT 0;\n DECLARE ranknum INT DEFAULT 0;\n\n DECLARE userID INTEGER DEFAULT 0;\n\n SELECT playerID\n INTO userID\n FROM cs_players\n WHERE cs_players.userauth = userauth;\n\n WHILE counter < 10 DO\n SET ranknum = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid=cs_maps.mapid\n WHERE stage = 0\n AND rank = counter+1\n AND playerid = userID AND active = 1\n );\n\n SET p_tops = p_tops + (((10-counter) + (10-counter+2)*30) * ranknum);\n SET counter = counter + 1;\n END WHILE;\n\n\n\n SELECT count(*), \n COALESCE((count(*) * ((difficulty+4)/5)), 0) AS points\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n INTO mapcount, mapmult\n WHERE\n stage = 0\n AND playerid = userID\n AND cs_maps.active = 1;\n\n SELECT count(*),\n COALESCE((count(*) * ((difficulty+4)/5)), 0) AS points\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n INTO stagecount, stagemult\n WHERE\n stage > 0\n AND cs_times.type = 0\n AND playerid = userID\n AND cs_maps.active = 1;\n\n SELECT count(*),\n COALESCE((count(*) * ((difficulty+4)/5)), 0) AS points\n INTO bonuscount, bonusmult\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n WHERE\n stage > 0\n AND cs_times.type = 1\n AND playerid = userID\n AND cs_maps.active = 1;\n\n SET maprecs = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n WHERE\n stage = 0\n AND rank = 1\n AND playerid = userID\n AND cs_maps.active = 1\n );\n SET stagerecs = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n WHERE\n stage > 0\n AND cs_times.type = 0\n AND rank = 1\n AND playerid = userID\n AND cs_maps.active = 1\n );\n SET bonusrecs = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n WHERE\n stage > 0\n AND cs_times.type = 1\n AND rank = 1\n AND playerid = userID\n AND cs_maps.active = 1\n );\n SET tops = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n WHERE\n stage = 0\n AND rank <= 10\n AND rank > 0\n AND playerid = userID\n AND cs_maps.active = 1\n );\n SET @TotalStage = (SELECT sum(checkpoints) FROM cs_maps WHERE mtype = 0 AND active = 1);\n SET @TotalBonus = (SELECT sum(cp_bonus) FROM cs_maps WHERE active = 1);\n SET @TotalMaps = (SELECT count(*) FROM cs_maps WHERE active = 1);\n\n SET @div1 = ((mapcount*2) + stagecount + (bonuscount*1.5));\n SET @div2 = ((@TotalMaps*2) + @TotalStage + (@TotalBonus*1.5));\n\n SET pc = @div1/@div2;\n\n SET p_comps = (mapmult * 50) + (bonusmult * 20) + (stagemult * 5); \n\n INSERT INTO cs_userstats(playerid, c_maps, c_stages, c_bonuses, wr_m, wr_s, wr_b, wr_top, p_top, p_comp, percomp)\n VALUES (userID, mapcount, stagecount, bonuscount, maprecs, stagerecs, bonusrecs, tops, p_tops, p_comps, pc) \n ON DUPLICATE KEY UPDATE\n c_maps = mapcount,\n c_stages = stagecount,\n c_bonuses = bonuscount,\n wr_m = maprecs,\n wr_s = stagerecs,\n wr_b = bonusrecs,\n wr_top = tops,\n p_top = p_tops,\n p_comp = p_comps,\n percomp = pc;\n\nEND$$\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T04:09:01.413",
"Id": "82041",
"Score": "0",
"body": "Thanks. I sort of learned from unindented code so the bad habits just stuck with me, but yeah that definitely looks a lot better. I'll try to keep every procedure I write formatted like that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T03:26:51.637",
"Id": "46875",
"ParentId": "46867",
"Score": "5"
}
},
{
"body": "<p>This loop is problematic. You should avoid running any query in a loop, both for performance and readability reasons.</p>\n\n<pre><code>WHILE counter < 10 DO\n SET ranknum = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid=cs_maps.mapid\n WHERE stage = 0\n AND rank = counter+1\n AND playerid = userID AND active = 1\n );\n\n SET p_tops = p_tops + (((10-counter) + (10-counter+2)*30) * ranknum);\n SET counter = counter + 1;\nEND WHILE;\n</code></pre>\n\n<p>The only purpose of this loop is to compute <code>p_tops</code>. Let's see if we can find a better way.</p>\n\n<p>First, let's change the dummy iteration variable to <code>r</code>, where <code>r = counter + 1</code>, so that it matches the <code>rank</code>. I'll also rename <code>ranknum</code> to <code>row_count</code> to emphasize that it came from <code>count(*)</code>.</p>\n\n<pre><code>SET r=1;\nWHILE r <= 10 DO\n SET row_count = (\n SELECT count(*)\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid=cs_maps.mapid\n WHERE stage = 0\n AND rank = r\n AND playerid = userID AND active = 1\n );\n\n SET p_tops = p_tops + (((10 - (r-1)) + (10 - (r-1)+2) * 30) * row_count);\n SET r = r + 1;\nEND WHILE;\n</code></pre>\n\n<p>Next, let's simplify <code>((10 - (r-1)) + (10 - (r-1) + 2) * 30)</code>. That works out to <code>(401 - 31 * r)</code>. Therefore,</p>\n\n<pre><code>SET p_tops = p_tops + (((10 - (r-1)) + (10 - (r-1)+2) * 30) * row_count);\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>SET p_tops = p_tops + (401 - 31 * r) * row_count;\n</code></pre>\n\n<p>Now we can rewrite the whole loop as</p>\n\n<pre><code>SET p_tops = (\n SELECT sum((401 - 31 * rank) * count(*))\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid=cs_maps.mapid\n WHERE\n stage = 0\n AND playerid = userId AND active = 1\n AND rank BETWEEN 1 and 10\n);\n</code></pre>\n\n<p>I have no idea <em>why</em> you would want to calculate such a sum, but there it is. It should be equivalent to the original loop, assuming that <code>rank</code> consists only of integers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T05:04:40.590",
"Id": "46882",
"ParentId": "46867",
"Score": "4"
}
},
{
"body": "<p>Four of your queries (for <code>maprecs</code>, <code>stagerecs</code>, <code>bonusrecs</code>, and <code>tops</code>) are similar to each other. <strong>Those queries could be combined into one.</strong></p>\n\n<p>The trick is to use the fact that <a href=\"https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count\" rel=\"nofollow\"><code>COUNT(…)</code> only counts the rows for which the expression being counted is non-NULL</a>.</p>\n\n<pre><code>SELECT count(CASE WHEN stage = 0 AND rank = 1 THEN 1 ELSE NULL END CASE) AS maprecs,\n count(CASE WHEN stage > 0 AND rank = 1 THEN 1 ELSE NULL END CASE) AS stagerecs,\n count(CASE WHEN stage > 0 AND rank = 1 AND cs_times.type = 1 THEN 1 ELSE NULL END CASE) AS bonusrecs,\n count(CASE WHEN stage = 0 AND rank BETWEEN 1 AND 10 THEN 1 ELSE NULL END CASE) AS tops\n FROM cs_times\n INNER JOIN cs_maps ON cs_times.mapid = cs_maps.mapid\n WHERE\n playerid = userID\n AND cs_maps.active = 1\n INTO maprecs, stagerecs, bonusrecs, tops;\n</code></pre>\n\n<p>In rewriting <code>rank <= 10 AND rank > 0</code> as <code>rank BETWEEN 1 AND 10</code>, I've assumed that there are no values where 0 < <code>rank</code> < 1.</p>\n\n<p>Note that according to the MySQL manual, <a href=\"https://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"nofollow\"><code>SELECT … INTO</code></a> queries should be written such that the <strong><code>INTO</code> clause comes near the end.</strong> In several of your queries, you've put the <code>INTO</code> clause after the <code>FROM</code> clause and before the <code>WHERE</code> clause. Even if MySQL understands them, those queries are not standard practice, nor do they read naturally.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:01:21.247",
"Id": "46885",
"ParentId": "46867",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T01:28:17.403",
"Id": "46867",
"Score": "8",
"Tags": [
"mysql",
"sql"
],
"Title": "Bad practices in this procedure to calculate player statistics?"
} | 46867 |
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
int main () {
int n1 = 1, n2 = 0, i = 0, limit = 0, neg = 0, pos = 0;
printf("Enter first number > ");
scanf("%d",&n1);
printf("Enter the seconed number > ");
scanf("%d",&n2);
printf("Enter the number of terms > ");
scanf("%d",&limit);
for (i; i < limit; i++ ) {
if (n2 >=1) { pos ++; printf( RESET "%i\n" RESET, n2); }
if (n2 <=0) { neg ++; printf( MAGENTA "%i\n" MAGENTA, n2); }
int temp = n2;
n2 += n1;
n1 = temp;
}
printf(RESET"\n***************************************************"RESET);
printf("\nPositive numbers in range %i : %i\n",limit,pos);
printf("Negitive : %i",neg);
printf("\n***************************************************");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:09:14.490",
"Id": "82272",
"Score": "5",
"body": "-1 Please provide the problem description and your desired level of review at a bare minimum. Questions solely comprising \"Code!\" merit only \"You posted some code which probably could be improved\" as a response. If this is your desired response, simply email your code to yourself. Everyone wins! :p"
}
] | [
{
"body": "<h1>Things you could improve</h1>\n\n<h3>Using Headers</h3>\n\n<ul>\n<li><p>Right now you are defining some items at the top of your source file.</p>\n\n<blockquote>\n<pre><code>#define RED \"\\x1b[31m\"\n#define GREEN \"\\x1b[32m\"\n#define YELLOW \"\\x1b[33m\"\n#define BLUE \"\\x1b[34m\"\n#define MAGENTA \"\\x1b[35m\"\n#define CYAN \"\\x1b[36m\"\n#define RESET \"\\x1b[0m\"\n</code></pre>\n</blockquote>\n\n<p>These are all relatable, and reusable ANSI escape codes to color your text in a terminal, so you could put them all in their own header (<code>color.h</code>) for easy use with other files.</p>\n\n<pre><code>#define BLACKTEXT(x) \"\\033[30;1m\" x \"\\033[0m\"\n#define REDTEXT(x) \"\\033[31;1m\" x \"\\033[0m\"\n#define GREENTEXT(x) \"\\033[32;1m\" x \"\\033[0m\"\n#define YELLOWTEXT(x) \"\\033[33;1m\" x \"\\033[0m\"\n#define BLUETEXT(x) \"\\033[34;1m\" x \"\\033[0m\"\n#define MAGENTATEXT(x) \"\\033[35;1m\" x \"\\033[0m\"\n#define CYANTEXT(x) \"\\033[36;1m\" x \"\\033[0m\"\n#define WHITETEXT(x) \"\\033[37;1m\" x \"\\033[0m\"\n</code></pre>\n\n<p>Then you can just <code>#include \"color.h\"</code> in all of your files where you need some color in your terminal.</p></li>\n<li><p>As you can see from my own <code>color.h</code> header file, I don't have a <code>RESET</code> macro. I didn't find a use for it, since I would always end up resetting the color right after I used it. The way I have it defined, my macros can do that for me.</p></li>\n</ul>\n\n<h3>User Experience</h3>\n\n<ul>\n<li><p>I find it useless to have to enter a first and second number.</p>\n\n<blockquote>\n<pre><code> printf(\"Enter first number > \");\n scanf(\"%d\",&n1);\n printf(\"Enter the seconed number > \");\n scanf(\"%d\",&n2);\n</code></pre>\n</blockquote>\n\n<p>What is the point of this? Just start from \\$ 0 \\$ and \\$ 1 \\$, and go to \\$ n \\$ number of terms.</p></li>\n</ul>\n\n<h3>Efficiency/Algorithm</h3>\n\n<ul>\n<li><p>Right now you can't compute that many fibonacci numbers, because of the maximum size of an <code>int</code>; you can only calculate numbers up to 32767. </p>\n\n<p>We aren't expecting negative numbers in our sequence, so we easily increase this restriction, you could use an <code>unsigned int</code> which has a maximum value of 65535, or even better, a <code>long long unsigned int</code> with a maximum value of 18446744073709551615. That's 562967131565294 times larger than your current program!</p></li>\n<li><p>Your algorithm can be simplified down using method extraction and recursion.</p>\n\n<blockquote>\n<pre><code> for (i; i < limit; i++ ) {\n if (n2 >=1) { pos ++; printf( RESET \"%i\\n\" RESET, n2); }\n if (n2 <=0) { neg ++; printf( MAGENTA \"%i\\n\" MAGENTA, n2); }\n int temp = n2;\n\n n2 += n1;\n n1 = temp;\n }\n</code></pre>\n</blockquote>\n\n<p>Move the computing of the fibonacci sequence to it's own method. All you should be passing it is the number of the term you want to compute.</p>\n\n<pre><code>unsigned long long int fibonacci(unsigned long long int n)\n{\n if (memoization[n] != -1) return memoization[n];\n\n return (n < 2)? n : (memoization[n] = fibonacci(n-1) + fibonacci(n-2));\n}\n</code></pre></li>\n<li><p>You might notice that I have included an array in my previous point named <code>memoization</code>. We want to use this to decrease computation time with the recursion. Basically, if we have already computed a number, we put it into the array so we don't have to calculate it the next time we want to find a fibonacci number. If we haven't found the number, we can indicate that in the array by storing a <code>-1</code> there instead.</p></li>\n</ul>\n\n<h3>Style</h3>\n\n<ul>\n<li><p>Put all of your variable declarations to separate lines. From <em>Code Complete, 2nd Edition</em>, p. 759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom,\n instead of top to bottom and left to right. When you’re looking for a\n specific line of code, your eye should be able to follow the left\n margin of the code. It shouldn’t have to dip into each and every line\n just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>I can't follow your tabbing scheme.</p>\n\n<blockquote>\n<pre><code> printf(\"Enter first number > \");\n scanf(\"%d\",&n1);\n printf(\"Enter the seconed number > \");\n scanf(\"%d\",&n2);\n printf(\"Enter the number of terms > \");\n scanf(\"%d\",&limit);\n</code></pre>\n</blockquote>\n\n<p>This makes it harder for me to read. You should align all of the left characters in a block to make them more readable.</p></li>\n<li><p>You should declare your parameters as <code>void</code> if you don't take in any arguments.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n</ul>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p>You should be declaring <code>i</code> inside of your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for (int i = 0; i < limit; i++)\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h1>Final code:</h1>\n\n<ul>\n<li><h3>Iterative: \\$ O(1) \\$</h3>\n\n<p>The calculation of the fibonacci sequence here is a bit different than my point I made above. I didn't mention it, since it was so different than how you were calculating your sequence. This is one of the most optimal solutions for calculating a fibonacci sequence.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nlong long unsigned int fibonacci(long long unsigned int n)\n{\n return round((1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)));\n}\n\nint main(void)\n{\n unsigned int num = 0;\n\n printf(\"Enter how far to calculate the series: \");\n if (scanf(\"%i\", &num) <= 0)\n {\n puts(\"Invalid input.\");\n return -1;\n }\n\n for(unsigned int n = 1; n < num + 1; ++n) printf(\"%llu\\n\", fibonacci(n));\n}\n</code></pre></li>\n<li><h3>Recursion: \\$ O(n) \\$</h3>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n#define ARRAYLENGTH 100 // keep in mind the result must fit in an llu int (fibonacci values grow rapidly)\n // you will run into issues after 93, so set the length at 100\nlong long int memoization[ARRAYLENGTH];\n\nlong long unsigned int fibonacci(long long unsigned int n)\n{\n if (memoization[n] != -1) return memoization[n];\n\n return (n < 2)? n : (memoization[n] = fibonacci(n-1) + fibonacci(n-2));\n}\n\nint main(void)\n{\n unsigned int num = 0;\n\n for(unsigned int i = 0; i < ARRAYLENGTH; i++) memoization[i] = -1; // preset array\n\n printf(\"Enter how far to calculate the series: \");\n if (scanf(\"%i\", &num) <= 0)\n {\n puts(\"Invalid input.\");\n return -1;\n }\n if (num < ARRAYLENGTH)\n {\n for(unsigned int n = 1; n < num + 1; ++n) printf(\"%llu\\n\", fibonacci(n));\n }\n else\n {\n puts(\"Input number is larger than the array length.\");\n return -2;\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:17:25.587",
"Id": "82273",
"Score": "0",
"body": "Minor quibble: `signed` to `unsigned` doubles the maximum value, but you specify the same value for both."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:25:35.977",
"Id": "82274",
"Score": "1",
"body": "@DavidHarkness Turns out I had the wrong values in there for some reason. They have been fixed, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T23:58:07.923",
"Id": "82364",
"Score": "0",
"body": "Iterative is O(1) .... really?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:19:59.197",
"Id": "82366",
"Score": "0",
"body": "@rolfl I was more looking inside of the loop, within the function call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T17:25:21.850",
"Id": "82997",
"Score": "1",
"body": "I would like to point out that the boundaries you gave for different types are true on most modern platforms, but they are not given by any standard. `long` is usually already 64-bits on UNIX systems whereas it's 32-bit on Windows, where you'll need to use `long long`. I strung suggest using `<inttypes.h>`and then using fixed size types such as `uint64_t` where applicable."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:14:39.413",
"Id": "46921",
"ParentId": "46880",
"Score": "11"
}
},
{
"body": "<p>Short style comment, you will avoid much future pain by using <code>fgets()</code> into a buffer and then <code>sscanf()</code> to convert the buffer data to a type rather than using <code>scanf()</code> directly.</p>\n\n<p>For more detail, see the <a href=\"http://c-faq.com/stdio/scanfprobs.html\">comp.lang.c FAQ</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:51:23.413",
"Id": "82264",
"Score": "2",
"body": "Yes, but the C11 standard `gets_s()` (that replaces `gets()`) would be a better option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:37:56.257",
"Id": "82286",
"Score": "0",
"body": "Thanks! That's what I get for being an old-timer... hadn't caught up to C11 yet b/c the environment I code in doesn't have compliant compilers on all platforms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:39:58.140",
"Id": "82289",
"Score": "0",
"body": "Your welcome! I'm still adjusting to the new standards myself. Hopefully you can stick around and learn them with me!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:03:27.150",
"Id": "85507",
"Score": "1",
"body": "@syb0rg C11dr spec K.3.5.4.1 6 `gets_s()` has the **recommended practice** of \"... Consider using `fgets` (...) instead of `gets_s`. ...\". IMO, `gets_s()` is a good replacement for `gets()`, but `fgets()` is better than both of them. (especially with that pesky `gets_s()` `rsize_t` type."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:31:26.010",
"Id": "46974",
"ParentId": "46880",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T04:39:12.063",
"Id": "46880",
"Score": "6",
"Tags": [
"c",
"console",
"fibonacci-sequence"
],
"Title": "Basic Fibonacci sequence in C"
} | 46880 |
<p>I have this uniform cost search that I created to solve Project Euler Questions 18 and 67. It takes the numbers in the txt file, places them into a two dimensional list, and then traverses them in a uniform cost search (that I hoped was a kind of implementation of an a* search). It looks like this:</p>
<pre><code>f = open('triangle.txt', 'r')
actualRows = [[n for n in p.split(" ")] for p in f.read().split('\n')]
actualRows.pop()
actualRows = [[int(n) for n in p] for p in actualRows]
rows = [[100 - n for n in p] for p in actualRows]
def astar(pq):
m = min(pq,key=lambda w: w[3])
if len(m[2]) + 1 is len(actualRows):
return m
pq.remove(m)
toAdd = list(m[2])
toAdd.append(m[0])
pq.append((actualRows[m[4]+1][m[5]], rows[m[4]+1][m[5]], toAdd, m[3] + m[1], m[4]+1, m[5]))
pq.append((actualRows[m[4]+1][m[5]+1], rows[m[4]+1][m[5]+1], toAdd, m[3] + m[1], m[4]+1, m[5]+1))
return astar(pq)
# Each tuple is: (actualScore, minScore, previous, totalScore, y, x)
priorityQueue = [(actualRows[0][0], rows[0][0], [], 0, 0, 0)]
a = astar(priorityQueue)
print a
print str(sum(a[2]) + a[0])
</code></pre>
<p>I'm not asking for you to tell me how to solve the Problem, I just want to optimize this search so that it doesn't crash going past the 17th row of numbers. How would I optimize this? Or how would I write a proper uniform cost search?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:06:54.593",
"Id": "82061",
"Score": "0",
"body": "It could be helpful to include a link to details of an a* search so that people who aren't familiar with this algorithm can help you. I know there is Google and Wikipedia, but if you have a specific resource that you know is better you should link to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:17:50.633",
"Id": "82065",
"Score": "0",
"body": "The resource that I used to get the idea of how it works comes from a cached version of an EDX Artificial Intelligence Course Lecture that I started, but was never able to finish, so I don't think that I can link anyone to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:23:35.717",
"Id": "82067",
"Score": "0",
"body": "It should work, as it gave me the correct solution for problem 18. I think your problem with trying it with 4 lines comes from line 9: `if len(m[2]) is 99:` If you want to try it with 4 lines, you have to change the number to 3 from 99. Sorry for that bit that I left out."
}
] | [
{
"body": "<p>You mentioned in the comments that the size of the triangle is hard-coded into the code. The very first thing you should do is make this a variable which you declare at the start of your code. (In many other languages, this would be a constant). You also use the number 100 in line 5. If this is supposed to be one more than the number of lines, it should be defined in terms of the same constant, so that the two can be changed in the same place. (Edit: I see from the problem that 99 and 100 are not related. If you had had two variables, NUM_ROWS and MAX_VALUE defined at the top, the meaning of each of the numbers would have been clear to me immediately.)</p>\n\n<p>A level of sophistication above, but still very easy, would be to give some reasonable error to a user like @JanneKarila who has used the wrong number of lines. This might be overkill for code that you and only you are ever going to run, but a one-line check with an error message might help you if you debug using the wrong file (it's easy to spend hours taking your program to pieces and forget to check which input you are using), and it makes life much easier for anyone else who wants to try it.</p>\n\n<p>Another stylistic thing which can be very important - for me the hardest part of your code to read is the lines that start <code>pq.append</code>. For each expression on these lines, I have to glance several times back to the definition of <code>priorityQueue</code> and the comment with it to find out exactly what each element of your tuple represents. If you defined a very simple class, then rather than <code>m[3] + m[1]</code> I would see <code>m.totalScore + m.currentValue</code>. Just doing this by itself would make the code easier to read (these two lines are going to be among the most important to debug). It might be the case that your class could also have methods or 'smart' constructors which could do some of the trickier work and make your inner loop more readable.</p>\n\n<p>Ultimately, I don't think it is realistic to 'optimize' this program to be able to solve a problem of the same size as Euler problem 67. If you try and store the lists inside your tuples more efficiently you might get to 18, 19 or 20 levels before crashing. However, the fundamental flaw of the algorithm is that you are going to store almost every path in your list in <code>priorityQueue</code>, with probably up to half of them present at any one time. This is unworkable from a memory perspective (the number of paths grows very rapidly as you increase the size of the triangle) and also from a run time perspective (if you try and measure the time taken for levels up to 17 you should be able to see this). Using the a* algo has made it a little bit less obvious to see that you are doing exactly what the Project Euler page recommends against - trying all paths. (EDIT: I didn't run the code. Turns out a stack overflow and not running out of memory is the reason for your crash. If you get rid of the recursion as suggested in @JanneKarila's answer, you will probably make it to quite a few more levels before running out of memory, but still nowhere near 100. The comments below still apply.)</p>\n\n<p>You need to go back to the drawing board and think of another way to solve the problem. A good starting point is to try and solve a few small triangles by hand, and see what methods you come across. Don't worry though - writing this program has given you a chance to learn both about an interesting algo and some things about programming, which I'm sure have made it worthwhile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:41:22.267",
"Id": "82069",
"Score": "1",
"body": "I added something that makes that unnecessary."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:35:29.377",
"Id": "46890",
"ParentId": "46883",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>Unpack your tuple to improve readability. There's already a comment </p>\n\n<pre><code># Each tuple is: (actualScore, minScore, previous, totalScore, y, x)\n</code></pre>\n\n<p>Put those names in code like this so you can use eg. <code>actualScore</code> instead of <code>m[0]</code>:</p>\n\n<pre><code>(actualScore, minScore, previous, totalScore, y, x) = m\n</code></pre></li>\n<li><p>You are using recursion to implement a simple loop. I get <code>RuntimeError: maximum recursion depth exceeded</code> even from problem 18. That's because you recurse from every node on every path until you find a solution. Just use a <code>while</code> loop instead.</p></li>\n<li>Use the <a href=\"https://docs.python.org/2/library/heapq.html\" rel=\"nofollow\"><code>heapq</code></a> module to implement a priority queue to avoid the linear search done by <code>min</code>.</li>\n<li>Compare numbers using <code>==</code>. Only use <code>is</code> for object identity.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li>To learn about the A* algorithm, see the highly readable tutorial at <a href=\"http://theory.stanford.edu/~amitp/GameProgramming/\" rel=\"nofollow\">Amit’s A* Pages</a>.</li>\n<li>You'll notice that your approach is different. In particular, you don't compute a heuristic. On the other hand I'm not sure if a useful heuristic exists for this problem, but in any case your approach is more like Dijkstra'a algorithm.</li>\n<li>You should keep track of already visited nodes to avoid exploring the same multiple times.</li>\n<li>When you add nodes to the priority queue, you should already compute their scores. Now you add both children with the score of the parent. When you eventually pop these nodes from the queue, you get the left child even though you need the better one first. Try the small example at the top of <a href=\"https://projecteuler.net/problem=18\" rel=\"nofollow\">the problem 18 page</a>: program answers 19 instead of 23, because at the bottom row the 5 pops from the queue before the 9.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T08:38:08.033",
"Id": "46891",
"ParentId": "46883",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46890",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T05:06:55.193",
"Id": "46883",
"Score": "3",
"Tags": [
"python",
"optimization",
"recursion",
"programming-challenge",
"pathfinding"
],
"Title": "Recursive uniform cost search that needs to be optimized"
} | 46883 |
<p>I would like to put the following design to your consideration. This is the pattern I use to follow when I'm building a Model and Data Access Layer for an MVC Application (using Entity Framework 5). I'm looking for any advises about how to improve me design (feel free to provide a new one) because I feel that it can be done better.</p>
<p>I want to focus on a model to be consumed for MVC Applications using Entity Framework 5 Code First, because this way we have a more specific scenario.</p>
<p>First I have the interface <code>IEntity</code>. All entities in my model implement it and this way is ensured that all entities have a numeric key.</p>
<pre><code>interface IEntity
{
int Id { get; set; }
}
</code></pre>
<p>Next I define entities like this:</p>
<pre><code>class Person : IEntity
{
public virtual int Id {get;set;}
public virtual string Name {get;set;}
public virtual int Age {get;set;}
public virtual int PetId {get;set;}
public virtual Pet Pet {get;set;}
}
class Pet : IEntity
{
public virtual int Id {get;set;}
public virtual string Name {get;set;}
public virtual int OwnerId {get;set}
public virtual Person Owner {get;set}
}
</code></pre>
<p>This is the important part:</p>
<p>I use a mix between Unit of Work and Repository to build a Data Access layer that let me decouple the Business logic from my data.</p>
<p>The abstract definition of a Unit of Work is like this:</p>
<pre><code>public interface IUnitOfWork
{
int SaveChanges();
}
</code></pre>
<p>In this case I need a repository for People and other for Pets.</p>
<pre><code>interface IPersonRepository
{
// Here I declare each method that my application needs.
// Each database dependent implementation will implement those methods.
void Add(Person person);
void Edit(Person person);
void Remove(Person person);
void RemoveById(int id);
IQueriable<Person> GetByName(string name);
}
interface IPetRepository
{
// Similar to IPersonRepository
}
</code></pre>
<p>Now in my case I build a concrete implementation of my repositories and <strong>UoW</strong> using Entity Framework.</p>
<pre><code>public class EFUnitOfWork : DbContext, IUnitOfWork
{
public DbSet<Person> People { get; set; }
public DbSet<Pet> Pets { get; set; }
}
public class EFPersonRepository : IPersonRepository
{
private readonly EFUnitOfWork context;
public EFPersonRepository(EFUnitOfWork context)
{
this.context = context;
}
public Directory GetById(int id)
{
return context.People.Find(id);
}
// Other methods of the interface IPersonRepository.
}
public class EFPetRepository : IPetRepository
{
// Similar to EFPersonRepository.
}
</code></pre>
<p>I use Ninject as my Dependency Injection framework. In configuration I bind each abstract definition (interface) with the concrete implementation. I'm doing the binding using <code>InRequestScope</code> and this way all repositories that are instantiated on each Http Request share the same <code>DbContext</code> (through the same UnitOfWork). I'm concerned if <code>InRequestScope</code> really does what I'm expecting because sometimes I get an exception that says that the <code>DbContext</code> has been disposed.</p>
<pre><code>public class NinjectControllerFactory : DefaultControllerFactory
{
private readonly IKernel kernel;
public NinjectControllerFactory()
{
kernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, System.Type controllerType)
{
return controllerType == null ? null : (IController)kernel.Get(controllerType);
}
private void AddBindings()
{
kernel.Bind<EFUnitOfWork>().To<EFUnitOfWork>().InRequestScope();
kernel.Bind<IPersonRepository>().To<EFPersonRepository>().InRequestScope();
kernel.Bind<IPetRepository>().To<EFPetRepository>().InRequestScope();
}
}
</code></pre>
<p>And that's all.</p>
<p><strong>Remarks</strong></p>
<p><em>Pros:</em></p>
<ul>
<li>I can replace my concrete implementation of the data access by implementing a new set of repositories and configure the bindings.</li>
<li>The business logic only see the methods exposed in repositories. This prevent using complex queries outside the data access layer.</li>
</ul>
<p><em>Cons:</em></p>
<ul>
<li>The <strong>master object</strong> (a mean the context in case of <strong>EF</strong>) that has all functionality remains hidden. So we don't have any information about tracking entities, etc, in the code outside the repository. Sometimes that info is useful when debugging.</li>
<li>Each query to the data must be declared in the abstract definition of the repository and then implemented on all concrete implementation. Which I think is good but someone may think that this is tedious.</li>
</ul>
| [] | [
{
"body": "<p>I've used this kind of approach myself in the past and it's worked well. However lately I've been considering whether it's overkill. Considering Entity framework is already following the repository and unit of work pattern you are essentially just adding the same pattern over the same pattern and that may potentially not give you any extra benefit.</p>\n\n<p>I've tended to find myself using more of a <em>service</em> architecture while still using dependency injection etc to manage the dependencies into my various classes. I've found it's meant less layers without losing any benefits of abstraction and TDD. It will still allow you to decouple your business logic from the data access whilst not having that extra layer of complexity.</p>\n\n<p>I'm also not sure about enforcing all your entities to requiring an <code>Id</code>. There are plenty of situations when Id's are not required on model table definitions so to enforce such a restriction seems to me potentially limiting? Situations such as link tables, or where a table might have a composite primary key rather than just an Id field.</p>\n\n<p>In saying all that, nice implementation. Seems to follow conventions of the patterns you are hoping to achieve.</p>\n\n<p>As requested here's an example of abstracting away EF as much as I was able whilst not requiring a seperate repository layer and using a service type approach instead (don't sue me for spelling errors :)) </p>\n\n<blockquote>\n <p>NOTE: Example was using Code first methodology of Entity Framework.</p>\n</blockquote>\n\n<pre><code>public interface IDataContext\n{\n IDbSet<Address> Addresses { get; set; }\n IDbSet<Contact> Contacts { get; set; }\n\n System.Data.Entity.Database Database { get; }\n DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;\n int SaveChanges();\n}\n\npublic class MyDataContext : DbContext, IDataContext\n{\n public IDbSet<Address> Addresses { get; set; }\n public IDbSet<Contact> Contacts { get; set; }\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();\n modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();\n }\n}\n</code></pre>\n\n<p>Using a service layer is primarily where I will now store my business logic</p>\n\n<pre><code>public class BaseService\n{\n protected readonly IDataContext DataContext;\n public BaseService(IDataContext dataContext) { DataContext = dataContext; } \n}\n</code></pre>\n\n<p>Potentially for mocking I might consider creating an interface for each service I create </p>\n\n<pre><code>public interface IAddressService\n{\n IEnumerable<Address> All(int id);\n Address GetById(int id);\n IEnumerable<Address> GetAddressWithinRange(string street, int rangeInMetres);\n}\n\npublic class AddressService : BaseService, IAddressService\n{\n public AnalogService(IG5DataContext dataContext) : base(dataContext)\n {\n }\n\n public IEnumerable<Address> All()\n {\n return DataContext.Addresses.Where(p => !p.Deleted).ToList();\n }\n\n public Address GetById(int id)\n {\n return DataContext.AnalogInputs.Find(id);\n }\n\n public IEnumerable<Address> GetAddressWithinRange(string street, int rangeInMetres)\n {\n return DataContext.Addresses\n .AsQueryable()\n .Where(p => p.Street == street && p.DistanceFromCentre < rangeInMetres);\n .ToList();\n }\n\n // Other business methods here\n\n private IQueryable<Address> AsQueryable(Machinery machinery)\n {\n return DataContext.Entry(machinery).Collection(v => v.AnalogReadings).Query();\n }\n}\n</code></pre>\n\n<p>Then using an IOC container (Ninject, AutoFac, Unity are a few I've used. Or see this <a href=\"http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx\" rel=\"nofollow\">blog by Scott Hanselman</a> for a list of what's around) I would inject these into my controller. The setup of the dependency registration would\nbe dependant on the IOC implementation.</p>\n\n<pre><code>public class AddressController\n{\n private readonly IDataContext _dataContext;\n private readonly IAddressService _addressService;\n\n public AddressController(IDataContext dataContext, IAddressService addressService)\n {\n _dataContext = dataContext;\n _addressService = addressService;\n }\n\n [HttpGet]\n public ActionResult Index()\n {\n var addresses = _addressService.All();\n\n return View(\"Index\", addresses);\n }\n\n [HttpGet]\n public ActionResult Details(int addressId)\n {\n var address = _addressService.GetById(id);\n\n if(address == null)\n return HttpNotFound();\n\n return View(\"Address\", address);\n }\n\n [HttpPost]\n public ActionResult Details(Address address)\n {\n var model = _addressService.GetById(address.Id);\n\n if(address == null)\n return HttpNotFound();\n\n // I might consider using A mapping framework like AutoMapper here. Not sure if this is correct\n // syntax but hopefully you get the point\n Mapper.Map(address, model); \n _dataContext.SaveChanges();\n\n return RedirectToAction(\"Details\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:10:59.660",
"Id": "82793",
"Score": "0",
"body": "Thank you for your answer, it was really helpful. I agree with you in most of it. But I can't understand how you archive abstraction from EF without adding an extra layer (maybe using a different kind of dependency injection). If you can put some example that will be great."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:43:50.067",
"Id": "82829",
"Score": "0",
"body": "@agarwaen I guess I'm considering EF already being the data layer and providing that abstraction. I'll try and put an example of a layer using a service type approach (or my understanding of it anyway)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:01:21.743",
"Id": "82830",
"Score": "0",
"body": "Thanks a lot. I'll wait for your example. Just a thought: If you consider EF as your data layer then if you want to mock its functionality you need to provide a custom implementation for IDbContext, IDbSet, etc. Interesting... I never implemented those interfaces before. Can't be too hard. Every time I needed to mock data access I just implemented new repositories. One more thing. By using this approach you are giving up to change data access technology in the future. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:11:08.073",
"Id": "82831",
"Score": "0",
"body": "@agawrwaen yes I guess to a certain extent you are however there are entity framework implementations for other databases. It's not just tied to sql (I think). Also, how often do you honestly change data access technology in the life of a project?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:18:38.137",
"Id": "82832",
"Score": "0",
"body": "you are right. I think that the ability of mocking for TDD and maintainability are the main benefit of having good abstraction. I'll take a deep look at your code. Thanks again. This post was very helpful to me. +1 and accepted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:22:41.880",
"Id": "82833",
"Score": "0",
"body": "@agarwaen Just a note. I'm not completely saying to not use a separate repository layer. Just at times it might not be required so this is a potential alternative. Glad it helped anyway."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:11:25.980",
"Id": "46898",
"ParentId": "46884",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T05:23:02.637",
"Id": "46884",
"Score": "5",
"Tags": [
"c#",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Model Design for MVC4 Applications using Entity Framework Code First"
} | 46884 |
<p>I have a MySQL table with a very large data. What I need is to find and separate duplicates from the unique rows</p>
<p>Let's say this is my table:</p>
<pre><code>indx, data_lname, data_fname, data_mname, data_dob, data_mobile
</code></pre>
<p>What I'm doing right now is selecting all the rows in one query and then comparing each row with the same table using a different query. This works ok but slow as hell.</p>
<p>Can this be done with a single query?</p>
<pre><code>private sub poplist()
DBstrSQL = "SELECT * from tbl_data order by indx asc"
Dim myCmd As New MySqlCommand
myCmd.CommandTimeout = 300
myCmd.CommandText = DBstrSQL
myCmd.Connection = MySqlConn
Dim myReader As MySqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows = True Then
While myReader.Read()
if checkifdup(myReader.GetString("indx"),myReader.GetString("data_fname"),myReader.GetString("data_mname"),myReader.GetString("data_lname"),myReader.GetString("data_dob"),myReader.GetString("data_mobile"))=false then
With lstUnique.Items.Add(myreader.getstring("data_lname"))
.SubItems.Add(myreader.getstring("data_fname"))
.SubItems.Add(myreader.getstring("data_mname"))
.SubItems.Add(myreader.getstring("data_dob"))
.SubItems.Add(myreader.getstring("data_mobile"))
End With
else
With lstDup.Items.Add(myreader.getstring("data_lname"))
.SubItems.Add(myreader.getstring("data_fname"))
.SubItems.Add(myreader.getstring("data_mname"))
.SubItems.Add(myreader.getstring("data_dob"))
.SubItems.Add(myreader.getstring("data_mobile"))
End With
end if
End While
end if
myReader.Close()
end sub
private function checkifdup(dataindx sa string, data1 as string,data2 as string, data3 as string, data4 as string, data5 as string) as boolean
myCmd.CommandText = "SELECT * from tbl_data where indx<>@indx and data_lname=@lname and data_mname=@mname and data_fname=@fname and (date_format(data_dob,'%m-%d-%Y')=@dob or data_mobile=@mobile) limit 1"
myCmd.Prepare()
myCmd.Parameters.AddWithValue("@lname", data3)
myCmd.Parameters.AddWithValue("@mname", data2)
myCmd.Parameters.AddWithValue("@fname", data1)
myCmd.Parameters.AddWithValue("@dob", data4)
myCmd.Parameters.AddWithValue("@mobile", data5)
myCmd.Parameters.AddWithValue("@indx", dataindx)
Dim myReader As MySqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows = True Then
myReader.Close()
return True
Else
myReader.Close()
return false
End If
end function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:23:20.590",
"Id": "82051",
"Score": "0",
"body": "It is working but it takes a lot of time to complete, say 1 hour for about 20k records. What im thinking is if there is another way of doing this that yields faster results. the code is quite simple, the first query is selecting a range of records, say, the first 20k rows, and then looping through each of the rows and cross checking them in another query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:07:39.657",
"Id": "82063",
"Score": "0",
"body": "*code edited. basically if checkifdup()=false, it will add to unique table, if true, it will add to duplicate table"
}
] | [
{
"body": "<p>You should <strong>never run a query in a loop,</strong> especially a loop where the number of queries issued scales with the size of the data. There is almost always a way to formulate the SQL such that you get the results you want with a small, fixed number of queries.</p>\n\n<p>In your case, you want two queries: one to find rows that are unique (ignoring the <code>indx</code> column), and another to find the rows that appear more than once (ignoring the <code>indx</code> column). You could formulate those queries as:</p>\n\n<pre><code>SELECT data_lname, data_fname, data_mname, data_dob, data_mobile\n FROM tbl_data\n GROUP BY data_lname, data_fname, data_mname, data_dob, data_mobile\n HAVING COUNT(indx) = 1\n ORDER BY indx;\n\nSELECT data_lname, data_fname, data_mname, data_dob, data_mobile\n FROM tbl_data\n GROUP BY data_lname, data_fname, data_mname, data_dob, data_mobile\n HAVING COUNT(indx) > 1\n ORDER BY indx;\n</code></pre>\n\n<p>Use those queries to populate <code>lstUnique</code> and <code>lstDup</code>, respectively.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> I read the code carelessly, and misinterpreted the criteria for considering two records to be \"duplicates\". I would reformulate the query close to the way your VB code worked.</p>\n\n<p>To find the unique records:</p>\n\n<pre><code>SELECT *\n FROM tbl_data AS a\n WHERE NOT EXISTS (\n SELECT indx\n FROM tbl_data AS b\n WHERE\n a.indx <> b.indx\n AND a.data_lname = b.data_lname\n AND a.data_fname = b.data_fname\n AND a.data_mname = b.data_mname\n AND (a.data_dob = b.data_dob OR a.data_mobile = b.data_mobile)\n );\n</code></pre>\n\n<p>To find the records with duplicates, change <code>WHERE NOT EXISTS</code> to <code>WHERE EXISTS</code>.</p>\n\n<p>This assumes that none of the fields can have a NULL value.</p>\n\n<hr>\n\n<p>For performance, be sure that indexes exist on the table. I assume that <code>indx</code>, being the primary key, already has a <code>UNIQUE INDEX</code>. In addition, there should be an index on <code>(data_lname, data_fname, data_mname)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:48:56.567",
"Id": "82071",
"Score": "1",
"body": "I think that should do the trick. But the next problem will be the GROUP BY. You see, on my code, there are 2 criteria for duplicates, 1. same name & dob regardless of mobile#, OR 2. same name & mobile# regardless of dob. How do I do that with group by? TIA you've been really helpful so far"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:27:52.770",
"Id": "46889",
"ParentId": "46886",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:12:43.193",
"Id": "46886",
"Score": "5",
"Tags": [
"beginner",
"mysql",
"vb.net"
],
"Title": "Separating Duplicates from Uniques"
} | 46886 |
<p>The following is a small class I extended MySQLi with. I'm going to use this in my upcoming projects, but my main reason to do this class is learning, so I would like to submit this for your review, tell me if there are any bugs or improvements to be made.</p>
<p>NOTES:</p>
<ol>
<li><p>I know about prepared statements, but I am not going to only run the same queries with different parameters, I'm expecting very different queries in each page, So I don't want to use prepared statements. Don't suggest prepared statements.</p></li>
<li><p>I am aware of PDO, but I will use MySQL only, so I'm better with MySQLi. So please don't suggest PDO.</p></li>
</ol>
<p></p>
<pre><code>class Dbquery extends MySQLi
{
public $host,$user,$password,$database,$connection;
public function __construct($host,$user,$password,$database)
{
$this -> host = $host;
$this -> user = $user;
$this -> password = $password;
$this -> database = $database;
$this -> connect_me();
}
private function connect_me()
{
$this -> connection = $this-> connect($this->host,$this->user,$this->password,$this->database);
if( $this -> connect_error )
die($this->connect_error);
}
private function extracts($data) // function used to append data and column names for insert query
{
$column = array("","");
foreach ($data as $index => $details)
{
$column[0].= $index.",";
$column[1].= "'".$this ->real_escape_string($details)."',";
}
$column[0] = rtrim($column[0],",");
$column[1] = rtrim($column[1],",");
return $column;
}
private function append($data) // function used to append data and column names for update query
{
$string = "";
foreach($data as $index => $details)
{
$string.= $index."='".$this -> real_escape_string($details)."',";
}
$string = rtrim($string,",");
return $string;
}
public function insert($table,$data)
{
$extracted = $this -> extracts($data);
$this -> query("INSERT INTO ".$table." (".$extracted[0].") VALUES(".$extracted[1].")");
if($this -> error)
return $this -> error;
else
return $this -> insert_id;
}
public function update($table,$data,$where)
{
$extracted = $this -> append($data);
$this -> query("UPDATE ".$table." SET ".$extracted." WHERE ".$where);
if($this -> error)
return $this -> error;
}
public function select($table,$column = "",$where = 1,$orderby = "",$limit = "")
{
if($column == "")
$column='*';
if($orderby == "")
$orderby = 'NULL';
if($limit != "")
{
$limit = "LIMIT ".$limit;
}
$result = $this -> query("SELECT ".$column." FROM ".$table." WHERE ".$where." ORDER BY ".$orderby."".$limit."");
if($this -> error)
{
return $this -> error;
}
else
{
$index = 0;
while($row = $result -> fetch_assoc())
{
$data[$index] = $row;
}
return $data;
}
}
public function delete($table,$where)
{
$this -> query("DELETE FROM ".$table." WHERE ".$where."");
if($this -> error)
{
return $this -> error;
}
else
{
return true;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:46:28.767",
"Id": "82070",
"Score": "3",
"body": "First thing I notice is a lack of sanitization. You seem to be passing the arguments into the SQL string straight up. Can you supply some examples of your usage in a theoretical project? These methods seem to wrap around simple methods already provided by mysqli, and dare I say, pdo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T07:54:04.720",
"Id": "82072",
"Score": "0",
"body": "the real_escape_string is not enough? I'm searching for a way to send the values of select functions into real escape string. soon I'll take PDO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T04:34:04.627",
"Id": "82699",
"Score": "0",
"body": "@Paul can I run complex queries like join queries inner join using prepared statements, and can I run different query each time using prepared statements? is that efficient?"
}
] | [
{
"body": "<p>I'm not a PHP programmer so I will only address what I see from your use of MySQLi:</p>\n\n<pre><code>public function update($table,$data,$where)\n {\n $extracted = $this -> append($data);\n $this -> query(\"UPDATE \".$table.\" SET \".$extracted.\" WHERE \".$where);\n if($this -> error)\n return $this -> error;\n }\n</code></pre>\n\n<p>Your <code>UPDATE</code> clause seems to be missing a few arguments to be proper SQL syntax which is:</p>\n\n<pre><code>UPDATE table_name SET column_name = value1 WHERE column_name = value2\n</code></pre>\n\n<p>I would say the same about this section:</p>\n\n<pre><code>}\n $result = $this -> query(\"SELECT \".$column.\" FROM \".$table.\" WHERE \".$where.\" ORDER BY \".$orderby.\"\".$limit.\"\");\n if($this -> error)\n {\n</code></pre>\n\n<p>Correct syntax is:</p>\n\n<pre><code>SELECT values FROM table_name WHERE column_name = some_value ORDER BY column_name [ASC] | [DESC]\n</code></pre>\n\n<p>That's all I got as far as MySQLi is concerned.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T00:04:17.503",
"Id": "88670",
"Score": "3",
"body": "Of course this would be much better and safer if you passed your values to MySQL via a stored procedure, but as you have indicated in your OP you don't want prepared statements, which doesn't make sense to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T12:44:40.370",
"Id": "89430",
"Score": "0",
"body": "I decided to use PDO and looking at it now thanks for your help"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T23:38:44.953",
"Id": "51344",
"ParentId": "46887",
"Score": "5"
}
},
{
"body": "<p>Note: I don't think this is what you want to hear. But I have to write "the truth". This is my personal opinions about your code.</p>\n<h1><a href=\"http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/\" rel=\"noreferrer\">Give me parameterized SQL or give me death!</a></h1>\n<blockquote>\n<p>tell me if there are any bugs or improvements to be made.</p>\n</blockquote>\n\n<blockquote>\n<p>Don't suggest prepared statements.</p>\n</blockquote>\n<p>I'm sorry, but those two requests really don't fit together in the same Code Review question.</p>\n<p>I understand what you're doing here, and it's nice that you're doing it for learning purposes. It's nice to be able to extend the mysqli class in PHP.</p>\n<p>However, I wouldn't recommend using the methods you have in this class. As you say:</p>\n<blockquote>\n<p>I'm expecting very different queries in each page</p>\n</blockquote>\n<p>Consider then: What functionality does this class provide you with? How much code does it save for you? Will it make your code more readable?</p>\n<p>As I see it, there are primarily four lines that summarize what your class is all about:</p>\n<pre><code>$this -> query("INSERT INTO ".$table." (".$extracted[0].") VALUES(".$extracted[1].")");\n$this -> query("UPDATE ".$table." SET ".$extracted." WHERE ".$where);\n$result = $this -> query("SELECT ".$column." FROM ".$table." WHERE ".$where." ORDER BY ".$orderby."".$limit."");\n$this -> query("DELETE FROM ".$table." WHERE ".$where."");\n</code></pre>\n<p>That is, you're essentially making it a little "easier" to write the SQL queries.</p>\n<p><a href=\"https://codereview.stackexchange.com/questions/46887/my-database-class-extends-mysqli/51344#comment82699_46887\">In your comment</a> you ask if you can run different queries each time using prepared statements, and if you can use joins and stuff. The answer to these questions is: <strong>YES!</strong> Is it efficient? <strong>YES!</strong>. We're often talking milliseconds of difference between prepared statements and non-prepared statements (except when you perform the same prepared statement multiple times with different parameters, in which a prepared statement performs significantly faster!). If you are worried about the <em>speed</em> of prepared statements, don't be. They're fast. If they're slow, then there's something wrong with your database structure or your query, not with the fact that you're using prepared statements.</p>\n<p>Here is what I personally think:</p>\n<ul>\n<li>Other developers reading your code will be confused as they are not familiar with your <code>Dbquery</code> class</li>\n<li>By not using your class you will be more experienced with writing SQL statements, it will probably go faster writing the SQL statements than you think.</li>\n<li>Your class does not provide that much functionality. In fact, it can act as a restriction as writing something like <code>select("mytable LEFT JOIN table2 ON (mytable.a = table2.b)", "table2.c, mytable.a", "mytable.a > 4", "table2.c", 5)</code> just feels completely strange, wrong, and hard to remember what the parameters are, and you'll likely end up trying to reconstruct the resulting SQL query in your mind anyway (or is that just me?)</li>\n</ul>\n<p>The point I'm trying to make here is: If you expect "very different queries in each page", then write those queries in each page. As long as they're not entirely dynamic queries, use prepared statements! Prepared statements are <em>the</em> way to go in the "real" PHP world.</p>\n<blockquote>\n<p>I am aware of PDO, but I will use MySQL only, so I'm better with MySQLi. So please don't suggest PDO.</p>\n</blockquote>\n<p>Sure, I have nothing against MySQLi myself. That's also what I tend to use when working in PHP. I think the choice of PDO vs. mySQLi is mostly opinion-based. The main advantage of PDO is that it can work with other databases except mySQL, but as you will use mySQL only, it's perfectly fine in my opinion to use mySQLi. At least you're not using the old mySQL functions!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T01:08:26.083",
"Id": "88684",
"Score": "5",
"body": "+1 for the prepared statements part. Not only does it make it look better & easier to code with, it also makes it *much more* secure. You really don't want to be vulnerable to SQL injection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-23T12:32:49.170",
"Id": "230472",
"Score": "5",
"body": "@Simon Forsberg : It may be a little late to thank you, but your answer really lead me to the right direction. Since I was a beginner, I know laugh at this question on the words like don't suggest pdo, don't suggest prepared statements. Thanks man, you gave me the hurting truth at the right time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-23T13:24:50.837",
"Id": "230483",
"Score": "0",
"body": "@Vignesh It's never too late for a comment like that, thanks. Consider asking a CR question for how your code looks today, it could be impressive to see how much you have developed as a programmer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-30T14:58:27.970",
"Id": "398497",
"Score": "0",
"body": "To elaborate on db extension choice. There are benefits that MySQLi has over PDO like [asynchronous queries](http://php.net/manual/en/mysqli.reap-async-query.php), and others PDO has over MySQLi (aside from supporting multiple DBs), like `stmt::fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN)`, using named parameters, not forced to specify parameter data types, ability to set parameter data using `stmt::bindValue(':param', 'value')` or `stmt::execute([':param' => 'value'])`. In general for \"ease of use\", PDO is preferred. In complex apps MySQLi is preferred. Use what can accomplish your goals."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T01:01:00.703",
"Id": "51355",
"ParentId": "46887",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "51355",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T06:16:43.570",
"Id": "46887",
"Score": "5",
"Tags": [
"object-oriented",
"php5",
"database",
"mysqli"
],
"Title": "My database class extends MySQLi"
} | 46887 |
<p>Given a postfix expression, construct an expression tree. Looking code code review, optimizations and best practices.</p>
<pre><code>public class ExpressionTree {
private final String postfix;
private TreeNode root;
/**
* Takes in a valid postfix expression and later its used to construct the expression tree.
* The posfix expression, if invalid, leads to invalid results
*
* @param postfix the postfix expression.
*/
public ExpressionTree(String postfix) {
if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
if (postfix.length() == 0) { throw new IllegalArgumentException("The postfix should not be empty"); }
this.postfix = postfix;
}
private static class TreeNode {
TreeNode left;
char ch;
TreeNode right;
TreeNode(TreeNode left, char ch, TreeNode right) {
this.left = left;
this.ch = ch;
this.right = right;
}
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
/**
* Constructs an expression tree, using the postfix expression
*/
public void createExpressionTree() {
final Stack<TreeNode> nodes = new Stack<TreeNode>();
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix.charAt(i);
if (isOperator(ch)) {
TreeNode rightNode = nodes.pop();
TreeNode leftNode = nodes.pop();
nodes.push(new TreeNode(leftNode, ch, rightNode));
} else {
nodes.add(new TreeNode(null, ch, null));
}
}
root = nodes.pop();
}
/**
* Returns the prefix notation
*
* @return the prefix notation
*/
public String prefix() {
if (root == null) {
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder prefix = new StringBuilder();
preOrder(root, prefix);
return prefix.toString();
}
private void preOrder(TreeNode node, StringBuilder prefix) {
if (node != null) {
prefix.append(node.ch);
preOrder(node.left, prefix);
preOrder(node.right, prefix);
}
}
/**
* Returns the infix expression
*
* @return the string of infix.
*/
public String infix() {
if (root == null) {
throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
}
final StringBuilder infix = new StringBuilder();
inOrder(root, infix);
return infix.toString();
}
private void inOrder(TreeNode node, StringBuilder infix) {
if (node != null) {
inOrder(node.left, infix);
infix.append(node.ch);
inOrder(node.right, infix);
}
}
public static void main(String[] args) {
ExpressionTree expressionTree1 = new ExpressionTree("AB*CD/+");
expressionTree1.createExpressionTree();
assertEquals("+*AB/CD", expressionTree1.prefix());
assertEquals("A*B+C/D", expressionTree1.infix());
ExpressionTree expressionTree2 = new ExpressionTree("ABC+*D/");
expressionTree2.createExpressionTree();
assertEquals("/*A+BCD", expressionTree2.prefix());
assertEquals("A*B+C/D", expressionTree2.infix());
ExpressionTree expressionTree3 = new ExpressionTree("ABCD/+*");
expressionTree3.createExpressionTree();
assertEquals("*A+B/CD", expressionTree3.prefix());
assertEquals("A*B+C/D", expressionTree3.infix());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:14:07.290",
"Id": "82153",
"Score": "1",
"body": "It way not be part of your problem definition, but the infix notation you currently output is ambiguous. You should consider adding brackets: `\"ABC+*D/\"` => `\"((A*(B+C))/D)\"`"
}
] | [
{
"body": "<p><strong>Make your structs immutable</strong><br>\n<code>TreeNode</code> is a helper structure, with public members, which is fine, but you better make them <code>final</code>, so you know they won't be changed after the object is created.</p>\n\n<p><strong>Choose your validations</strong><br>\nDon't throw <code>NullPointerException</code> on your own. It may confuse a future debugger. Either throw an <code>IllegalArgumentException</code> or let the runtime throw the <code>NullPointerException</code> for you.</p>\n\n<p><strong>Choose your comments</strong><br>\nMost of your comments do not add much to the methods, and are therefore redundant. Let the names of the method and variables do the work for you. If you feel the name <code>prefix</code> is not clear enough on its own, it is better to rename it (maybe to <code>toPrefixNotation()</code>) and then you can safely remove your comments.</p>\n\n<p><strong>Being nice is better than being strict</strong><br>\nUnless there is some requirement restriction, I don't think you need to throw an exception if <code>root</code> is <code>null</code> - why not simply call <code>createExpressionTree()</code> instead of telling the developer <em>he</em> should?<br>\nSince there is no meaning for calling <code>createExpressionTree()</code> twice (<code>postfix</code> is <code>final</code>...), you might as well hide it altogether, and call it when needed.</p>\n\n<p><strong>Use the power of String</strong><br>\nUse <code>String#indexOf</code> to make <code>isOperator</code> more succinct:</p>\n\n<pre><code>private boolean isOperator(char c) {\n return \"+-*/\".indexOf(c) != -1\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:30:05.740",
"Id": "82111",
"Score": "2",
"body": "+1 for *choose your validations*, +1 for methods explicit names, +1 for automatic call to `createExpressionTree()`. -1 I don't really like using `indexOf()` like this, because it gets away from its initial meaning, thus reducing readability. Also it might be worse in terms of performance, but it's just a guess here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:52:46.353",
"Id": "46897",
"ParentId": "46894",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46897",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:00:18.427",
"Id": "46894",
"Score": "5",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Expression tree creation from postfix expression"
} | 46894 |
<p>I have an abstract class that represents data request. The request is in XML format. There are a few classes that derive from abstract class and they do similar things.</p>
<p>Some basic XML operations such as create XML document, write the elements and attributes of XML document and so on are implemented as methods of abstract class and they can be used from derived classes as well.</p>
<p>I should refactor the abstract class. I think I could write some kind of XML helper class outside of request-based classes, but I'm not sure if it's right way.</p>
<p>The code looks as following:</p>
<pre><code>public abstract class MWRequest
{
public static string WebServiceURL = "url";
protected XmlDocument xmlDoc = new XmlDocument();
protected MWRequest()
{
xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><request/>");
}
public XmlDocument XmlDocument
{
get { return xmlDoc; }
}
protected void PrepareRequest(string requestType)
{
LoadElement("protocol-version", "4.00");
LoadElement("request-type", requestType);
LoadExtraElement("password", password);
LoadElement("terminal-id", terminalId);
}
protected void LoadElement(string elemName, string val)
{
XmlElement elem = xmlDoc.CreateElement(elemName);
elem.InnerText = val;
xmlDoc.DocumentElement.AppendChild(elem);
}
protected void LoadExtraElement(string name, string val)
{
// <extra name="ltime">60</extra>
XmlElement elem = xmlDoc.CreateElement("extra");
XmlAttribute attrName = xmlDoc.CreateAttribute("name");
attrName.Value = name;
elem.Attributes.Append(attrName);
elem.InnerText = val;
xmlDoc.DocumentElement.AppendChild(elem);
}
...
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:30:56.527",
"Id": "82091",
"Score": "4",
"body": "The word `Load` is certainly inappropriate since you actually mean `Add` or `Append`."
}
] | [
{
"body": "<blockquote>\n<pre><code>public abstract class MWRequest\n{\n public static string WebServiceURL = \"url\";\n protected XmlDocument xmlDoc = new XmlDocument();\n\n protected MWRequest()\n {\n xmlDoc.LoadXml(\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?><request/>\");\n }\n</code></pre>\n</blockquote>\n\n<p><strong>Class name</strong></p>\n\n<p>I get the <code>Request</code> part of the class name, but <code>MW</code> could be just about anything, and itsn't descriptive. I suggest you rename the class, and drop this abbreviation.</p>\n\n<p><strong>Static field</strong></p>\n\n<p>Anything <code>public static</code> in an abstract class, smells. You're not showing how it's used, but being <code>static</code>, the value stops being an <em>instance-level</em> value and becomes a <em>type-level</em> value, which means <em>all instances</em> of that class will have the same <code>WebServiceURL</code> (which should be named <code>WebServiceUrl</code> - <em>PascalCase</em> FTW!), which just doesn't sound right, especially in a base/abstract class.</p>\n\n<p><strong>Public fields</strong></p>\n\n<p>Don't do that, you're breaking encapsulation. Derived classes can do anything they want with <code>xmlDoc</code>, and bypass everything you've coded as <code>protected</code> methods.</p>\n\n<p>Encapsulation enables abstraction. Your base class could encapsulate an <code>XmlDocument</code> and provide an abstraction layer that hides this implementation detail to its clients and derived types. If you need to expose the XML, then override <code>ToString</code> and return the encapsulated XML instead of exposing the whole <code>xmlDoc</code>, or expose a <code>Xml</code> property that does that.</p>\n\n<pre><code>public XmlDocument XmlDocument\n{\n get { return xmlDoc; }\n}\n</code></pre>\n\n<p>If a derived type wants to set the <code>XmlDocument</code> reference, the parameterless constructor will still run and call <code>LoadXml</code> with the hard-coded string there. I think you should have a protected constructor that just takes an <code>XmlDocument</code> from the derived type, and chain the constructor calls:</p>\n\n<pre><code>protected MWRequest()\n : this(new XmlDocument())\n{\n _xmlDoc.LoadXml(\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?><request/>\");\n}\n\nprotected MWRequest(XmlDocument xmlDoc)\n{\n _xmlDoc = xmlDoc;\n}\n\nprivate readonly XmlDocument _xmlDoc;\npublic XmlDocument xmlDocument { get { return _xmlDoc; } }\n</code></pre>\n\n<p>This way a derived type has only 1 way of setting the <code>XmlDocument</code> reference, through the constructor.</p>\n\n<hr>\n\n<p>A word about <code>LoadElement</code> and <code>LoadExtraElement</code>: they're both badly named, <code>protected</code> and useless - a derived type can access the <code>XmlDocument</code> from the <code>XmlDocument</code> property, and do everything it needs to do with it, including destroying/replacing the entire DOM.</p>\n\n<p>Either make them <code>protected virtual</code> and drop the <code>XmlDocument</code> property (and add any members to expose whatever other types need out of it), <strong>or</strong> keep the <code>XmlDocument</code> property and drop the helper methods - at the end of the day, it's a design decision you need to make.</p>\n\n<p>If you decide to keep them, I'd suggest to change the signatures a bit:</p>\n\n<pre><code>protected virtual XmlElement CreateElement(string name, string innerText)\n{\n // ...\n}\n</code></pre>\n\n\n\n<pre><code>protected virtual XmlElement CreateExtraElement(string name, string value)\n{\n // ...\n}\n</code></pre>\n\n<p>By making <code>CreateElement</code> a function that returns the <code>XmlElement</code> it's creating (instead of adding it itself to <code>xmlDoc</code>), you can delete some of the code from <code>CreateExtraElement</code> and call <code>CreateElement</code> from within <code>CreateExtraElement</code></p>\n\n<pre><code>var element = CreateElement(\"extra\", value);\nvar attribute = _xmlDoc.CreateAttribute(\"name\"); // \"attrName\" is a bad name\nattribute.Value = name;\nelement.Attributes.Append(attribute);\nreturn element;\n</code></pre>\n\n<p>The client code is a derived class, so it can do this:</p>\n\n<pre><code>var element = CreateExtraElement(\"foo\", \"bar\");\nXmlDocument.DocumentElement.AppendChild(element);\n</code></pre>\n\n<p>And if the base class implementation for <code>CreateExtraElement</code> doesn't suit that class' needs, it can always <code>override</code> it, because it's <code>virtual</code>.</p>\n\n<hr>\n\n<p><strong>LINQ to XML</strong></p>\n\n<p>I'd suggest you use the <code>System.Xml.Linq</code> namespace and its <code>XDocument</code> and <code>XNode</code>, <code>XElement</code>, and <code>XAttribute</code> classes, instead of the older <em><code>XmlDocument</code> & friends</em> classes from <code>System.Xml</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:21:46.793",
"Id": "82175",
"Score": "0",
"body": "`XmlDocument` is likely referring to the class from the much older `System.Xml` namespace. LINQ to XML objects are definitely much nicer to work with in most cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:26:39.610",
"Id": "82177",
"Score": "0",
"body": "@DanLyons thanks! (edited) - I should have known that! I jumped straight from VB6 `IXMLDOMNode` to Linq-to-Xml, skipping everything in-between. I guess I haven't missed much ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:58:37.617",
"Id": "46933",
"ParentId": "46896",
"Score": "7"
}
},
{
"body": "<p>When i was facing a similar task i decided to separate request/response classes from writing/parsing logic for better encapsulation. It doesnt take much time, but it allows you to change protocol or format in the future without changing your request classes.</p>\n\n<p>I ended up implementing two interfaces, lets call them <code>IMessageReader</code> and <code>IMessageWriter</code> for example. Resulting classes ended up looking a lot like <code>BinaryReader</code> and <code>BinaryWriter</code> classes you might know.</p>\n\n<p>In your case it might look like this:</p>\n\n<pre><code>interface IMessageWriter : IDisposable\n{\n void Write(Version version);\n void Write(RequestType type);\n ...\n void Write(string element, string value);\n}\n\nabstract class MWRequest\n{\n ....\n\n public void Write(IMessageWriter writer)\n {\n writer.Write(Version);\n writer.Write(Type);\n ...\n OnWrite(writer);\n }\n\n protected virtual void OnWrite(IMessageWriter writer)\n {\n\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public void Send(MWRequest request)\n{\n var xDoc = new XmlDocument();\n using(var writer = new XmlMessageWriter(xDoc))\n {\n request.Write(writer);\n //send xDoc somewhere\n ...\n }\n}\n</code></pre>\n\n<p>I would also recommend using Linq to Xml instead instead of XmlDocument.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:17:59.820",
"Id": "47123",
"ParentId": "46896",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46933",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T09:44:40.690",
"Id": "46896",
"Score": "9",
"Tags": [
"c#"
],
"Title": "Refactoring class methods to helper class?"
} | 46896 |
<p>I am coding a web based solution which consists of <em>N</em> number of tiers, these are:</p>
<ul>
<li>UI</li>
<li>Web API</li>
<li>Business</li>
</ul>
<p>The question I have is related to validation, repository and CRUD operations. I am adopting the command / query pattern whereby I have my repositories for <strong>data retrieval</strong> only (see below) and its query dependencies injected in. I have seen people use repositories for CRUD too, but then I get the impression it is doing too much thus warrants further abstraction. </p>
<pre><code>public interface IAddressRepository
{
Address GetById(int id);
IEnumerable<Address> GetByPersonId(int personId);
IEnumerable<Address> GetByPostalCode(string postalCode);
}
public AddressRepository(IGetAddressByIdQuery getAddressByIdQuery
, IGetAddressesByPersonIdQuery getAddressesByPersonIdQuery
, IGetAddressesByPostalCodeQuery getAddressesByPostalCodeQuery)
{
this.getAddressByIdQuery = getAddressByIdQuery;
this.getAddressesByPersonIdQuery = getAddressesByPersonIdQuery;
this.getAddressesByPostalCodeQuery = getAddressesByPostalCodeQuery;
}
</code></pre>
<p>Should my repository return validation errors? For example, the <code>GetById(int id)</code> method will be checking if the <code>id > 0</code> then make a DB call or simply return a new instance, likewise with a postal code lookup. However, I also think going by the SOLID design principle everything should be autonomous thus this approach of returning no validation errors is the correct choice. I choose to NOT return null on all my methods simply because checking for null is considered as an anti-pattern.</p>
<p>The encompassing of the CRUD logic. I have seen uses of a <code>Manager</code> and/or <code>Service</code> classes, for example:</p>
<pre><code>public interface IAddressManager
{
IEnumerable<Error> Delete(Address address);
IEnumerable<Error> Save(Address address);
IEnumerable<Error> IsValid(Address address);
}
public AddressManager(IAddressValidator addressValidator, IAddressCommand addressCommand)
{
this.addressValidator = addressValidator;
this.addressCommand = addressCommand;
}
</code></pre>
<p>Is the general consensus to have a manager class which encompasses these operations but have the dependencies (the commands injected in)? This way, before I call <code>save()</code>, I validate the object before persisting it. I can also control this behavior via TDD.</p>
<p>Query code example:</p>
<pre><code>public interface IGetAddressByIdQuery
{
Address Execute(int id);
}
public class GetAddressByIdQuery : IGetAddressByIdQuery
{
private readonly string connectionString;
public GetAddressByIdQuery(string connectionString)
{
this.connectionString = connectionString;
}
public Address Execute(int id)
{
using (var conn = new SqlConnection(this.connectionString))
{
return conn.Get<Address>(new { Id = id });
}
}
}
</code></pre>
<p>The data access tier is not apparent as at the moment as the business library is fairly small. I am a firm believer in not creating several libraries for the sake of it. Only create them when it is warranted to do so, i.e. a library is getting too big.</p>
<p>What are your thoughts as to whether or not a better approach / pattern exists?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T11:39:30.770",
"Id": "82097",
"Score": "0",
"body": "Are you using an ORM layer like Entity-Framework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:18:56.287",
"Id": "82108",
"Score": "0",
"body": "Yeah, using Dapper. I have a clear separation though whereby I have entities representing rows in a table and a contract assembly for public facing. Automapper is then used for conversion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:23:33.183",
"Id": "82109",
"Score": "0",
"body": "Can you clarify a little what `IGetAddressByIdQuery` and likewise are in your constructor?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:26:48.223",
"Id": "82110",
"Score": "0",
"body": "These are query objects, i.e. have a single method called Execute(int id). Reason for this is to clearly separate each query (updated post to include this code)."
}
] | [
{
"body": "<p>I'll address your separate classes for the queries first. I definitely see where you're coming from with this approach and I can dig it, but it gives too much duplication as it is.</p>\n\n<p>I assume you'll have more entities than just <code>Addresses</code> so using your approach, you would have to create a new interface for each entity you want to get by its ID. If you instead added some generics, you can do all of this with one interface:</p>\n\n<pre><code>interface IGetEntityByIdQuery<T> {\n T execute(int id);\n}\n</code></pre>\n\n<p>Now you can have these implementations:</p>\n\n<pre><code>class GetAddressByIdQuery : IGetEntityByIdQuery<Address> {\n Address execute(int id) { }\n}\n\nclass GetOrderByIdQuery : IGetEntityByIdQuery<Order> {\n Order execute(int id) { }\n}\n</code></pre>\n\n<p>However even though I first said I can dig it, this will still be very cumbersome to work with. Having to create a new class for the retrieval for each entity for each parameter? That's too much.</p>\n\n<p>I can agree on a setup where you combine them by entity:</p>\n\n<pre><code>interface IGetEntity<T> {\n T GetEntityById(int id);\n T GetEntityByPersonId(int id);\n}\n</code></pre>\n\n<p>Now on to your remark about CRUD:</p>\n\n<blockquote>\n <p>I have seen people use repositories for CRUD too but then I get the impression it is doing too much thus warrants further abstraction.</p>\n</blockquote>\n\n<p>The entire idea behind repositories is CRUD. In fact, your <code>GetXByY</code> classes are simply executing the R part in CRUD. Repositories exist to provide communication from your model to your datasource, which is what we understand under CRUD.</p>\n\n<p>Another red flag here should have been your name choice: when you have a class named <code>XManager</code> you have to really overthink your design and be sure that this is the way to go. Often it is an indication something is wrong because in essence, a \"manager\" class doesn't convey much meaning. </p>\n\n<p>What does this class do? Other names for such encompassing classes are a lot more informative, for example <code>XFactory</code> indicates the class will construct instances of <code>X</code>. A manager.. manages?</p>\n\n<p>Therefore these actions should be added to your repository. This will now keep these related actions (CRUD) together which prevents any confusion with other programmers.</p>\n\n<p>That being said: it might very well be a suitable name for a class, this is definitely not a general rule. I have had to use <code>XManager</code> classes as well before, but this was more because I simply couldn't come up with a better one (and no, it wasn't a repository ;)). </p>\n\n<p>For more reflection upon the subject, I suggest reading <a href=\"https://softwareengineering.stackexchange.com/questions/129537/can-manager-classes-be-a-sign-of-bad-architecture\">this post</a>.</p>\n\n<p>As for your final question on the topic of errors: why are you doing validation logic in your data access layer? That is way too late!</p>\n\n<p>You should have the guarantee that when an object is constructed, it has valid data. The entire idea behind getters and setters (aka: properties) is that the actual data is hidden and that the data can be validated. </p>\n\n<p>When you construct a new object of type <code>Address</code>, it should be validated. This can be done in several places: properties, constructor, the factory that creates <code>Address</code> objects using some service layer, etc. There are many options to do this validation, but once the object is constructed you should have the implicit guarantee that the object contains valid data.</p>\n\n<p>Lastly, for the boundary checks (like <code>id > 0</code>): this is up to your own preference. You <em>could</em> add a service layer in front of your repository that validates the incoming data and if you have several validation requirements then this might be a good solution. If on the other hand you only have this one boundary check then it's a little minor.</p>\n\n<p>But I haven't come across the explicit recommendation to use a service layer in front of your data access layer just for validation yet, so as far as I'm concerned this is up to yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:30:18.393",
"Id": "82141",
"Score": "0",
"body": "I definitely agree with you on the fact that the data should go through validation before the repository gets a handle of it. However, the generic approach I can see some benefit to it but also the evil side to it as well. I find with generics, you often find yourself making it too generic and tries to cater for too much, i.e. an object that fits all shapes and sizes. Do you agree?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:38:03.183",
"Id": "82148",
"Score": "0",
"body": "Sure, you should be careful to make sure you don't have a `DoEverything` repository, but there is a balance to strike here. You would have a lot of duplicate code for no real reason (and many, many classes for some CRUD actions with just a few entities). With the approach I proposed I don't think there's any of the evil side in it yet. You can split it up as you want ofcourse, but I think your current approach is doing exactly that: nearing the evil side of Separation of Concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:04:33.823",
"Id": "82152",
"Score": "1",
"body": "Essentially, what I have done now is encompassed all my query and command objects in a repository (to encapsulate dependency injection) and implemented a generic IRepository<T> which exposes, GetById(), Create(), Update() and Delete() operations. Will see how this goes. This approach still allows me to use TDD."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:03:36.447",
"Id": "46917",
"ParentId": "46899",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46917",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T10:55:11.917",
"Id": "46899",
"Score": "5",
"Tags": [
"c#",
"validation"
],
"Title": "Amalgamation of the repository and command / query pattern"
} | 46899 |
<p>Please give thoughts and optimization tips on my thread library. </p>
<p><strong>Update 1 :</strong> I have renamed the different method types.</p>
<pre><code>unit AgThread13;
interface
uses
SysUtils, Classes, Windows, Rtti;
type
{$SCOPEDENUMS ON$}
TAgCallType = ( Direct, Synchronize, Queue );
TAgThread = class;
TAgThreadSimpleObjectMethod = procedure of object;
TAgThreadSimpleAnonymousMethod = procedure;
TAgThreadObjectMethodWithSelf = procedure ( const AThread: TAgThread ) of object;
TAgThread = class ( TThread )
strict private
FTag : NativeInt;
FInterval : NativeInt;
FEvent : THandle;
FRun : Boolean;
FOnExecute : TAgThreadSimpleObjectMethod;
FOnRun : TAgThreadSimpleObjectMethod;
FSimpleObjectMethod : TAgThreadSimpleObjectMethod;
FSimpleAnonymousMethod : TAgThreadSimpleAnonymousMethod;
FObjectMethodWithSelf : TAgThreadObjectMethodWithSelf;
FName : String;
FCallType : TAgCallType;
procedure SetRun ( const AValue : Boolean );
function GetInterval: NativeInt;
procedure SetInterval ( const AValue : NativeInt );
procedure SetSimpleObjectMethod ( const AValue : TAgThreadSimpleObjectMethod );
procedure SetSimpleAnonymousMethod ( const AValue : TAgThreadSimpleAnonymousMethod );
procedure SetObjectMethodWithSelf ( const AValue : TAgThreadObjectMethodWithSelf );
procedure DirectCallSimpleObjectMethod; inline;
procedure DirectCallSimpleAnonymousMethod; inline;
procedure DirectCallObjectMethodWithSelf; inline;
procedure SynchronizeSimpleObjectMethod;
procedure SynchronizeSimpleAnonymousMethod;
procedure SynchronizeObjectMethodWithSelf;
procedure QueueSimpleObjectMethod;
procedure QueueSimpleAnonymousMethod;
procedure QueueObjectMethodWithSelf;
strict protected
procedure Execute; override;
procedure ExecuteSimpleObjectMethod; virtual;
procedure ExecuteSimpleAnonymousMethod; virtual;
procedure ExecuteObjectMethodWithSelf; virtual;
public
constructor Create ( const AInterval : NativeInt; const ARun : Boolean = True;
const ACallType : TAgCallType = TAgCallType.Direct;
const AName : String = '' );
destructor Destroy; override;
property Name : String
read FName;
property CallType : TAgCallType
read FCallType;
property Run : Boolean
read FRun write SetRun;
property Interval : NativeInt
read GetInterval write SetInterval;
property Tag : NativeInt
read FTag write FTag;
property OnRun1 : TAgThreadSimpleObjectMethod
write SetSimpleObjectMethod;
property OnRun2 : TAgThreadSimpleAnonymousMethod
write SetSimpleAnonymousMethod;
property OnRun3 : TAgThreadObjectMethodWithSelf
write SetObjectMethodWithSelf;
end;
implementation
constructor TAgThread.Create
( const AInterval : NativeInt;
const ARun : Boolean = True;
const ACallType : TAgCallType = TAgCallType.Direct;
const AName : String = '' );
begin
FEvent := CreateEvent ( nil, TRUE, FALSE, nil );
FInterval := AInterval;
Run := ARun;
FName := AName;
FCallType := ACallType;
inherited Create ( False );
end;
destructor TAgThread.Destroy;
begin
SetEvent ( FEvent );
WaitFor;
inherited;
end;
procedure TAgThread.SetRun
( const AValue: Boolean );
begin
FRun := AValue;
end;
function TAgThread.GetInterval: NativeInt;
begin
Result := FInterval;
end;
procedure TAgThread.SetInterval
( const AValue : NativeInt );
begin
if AValue > 0 then
FInterval := AValue;
end;
procedure TAgThread.SetSimpleObjectMethod
( const AValue : TAgThreadSimpleObjectMethod );
begin
if not Assigned ( AValue ) then Exit;
FSimpleObjectMethod := AValue;
FOnExecute := ExecuteSimpleObjectMethod;
case FCallType of
TAgCallType.Direct : FOnRun := DirectCallSimpleObjectMethod;
TAgCallType.Synchronize : FOnRun := SynchronizeSimpleObjectMethod;
TAgCallType.Queue : FOnRun := QueueSimpleObjectMethod;
end;
end;
procedure TAgThread.SetSimpleAnonymousMethod
( const AValue : TAgThreadSimpleAnonymousMethod );
begin
if not Assigned ( AValue ) then Exit;
FSimpleAnonymousMethod := AValue;
FOnExecute := ExecuteSimpleAnonymousMethod;
case FCallType of
TAgCallType.Direct : FOnRun := DirectCallSimpleAnonymousMethod;
TAgCallType.Synchronize : FOnRun := SynchronizeSimpleAnonymousMethod;
TAgCallType.Queue : FOnRun := QueueSimpleAnonymousMethod;
end;
end;
procedure TAgThread.SetObjectMethodWithSelf
( const AValue : TAgThreadObjectMethodWithSelf );
begin
if not Assigned ( AValue ) then Exit;
FObjectMethodWithSelf := AValue;
FOnExecute := ExecuteObjectMethodWithSelf;
case FCallType of
TAgCallType.Direct : FOnRun := DirectCallObjectMethodWithSelf;
TAgCallType.Synchronize : FOnRun := SynchronizeObjectMethodWithSelf;
TAgCallType.Queue : FOnRun := QueueObjectMethodWithSelf;
end;
end;
procedure TAgThread.DirectCallSimpleObjectMethod;
begin
FSimpleObjectMethod;
end;
procedure TAgThread.DirectCallSimpleAnonymousMethod;
begin
FSimpleAnonymousMethod;
end;
procedure TAgThread.DirectCallObjectMethodWithSelf;
begin
FObjectMethodWithSelf ( Self );
end;
procedure TAgThread.SynchronizeSimpleObjectMethod;
begin
Synchronize ( FSimpleObjectMethod );
end;
procedure TAgThread.SynchronizeSimpleAnonymousMethod;
begin
Synchronize ( FSimpleAnonymousMethod );
end;
procedure TAgThread.SynchronizeObjectMethodWithSelf;
begin
Synchronize ( procedure
begin
FObjectMethodWithSelf ( Self )
end );
end;
procedure TAgThread.QueueSimpleObjectMethod;
begin
Queue ( FSimpleObjectMethod );
end;
procedure TAgThread.QueueSimpleAnonymousMethod;
begin
Queue ( FSimpleAnonymousMethod );
end;
procedure TAgThread.QueueObjectMethodWithSelf;
begin
Queue ( procedure
begin
FObjectMethodWithSelf ( Self )
end );
end;
procedure TAgThread.Execute;
begin
FOnExecute;
Terminate;
end;
procedure TAgThread.ExecuteSimpleObjectMethod;
begin
while True do
begin
if WaitForSingleObject ( FEvent, FInterval ) = WAIT_OBJECT_0 then
break;
if FRun then
if Assigned ( FSimpleObjectMethod ) then
FOnRun;
end;
end;
procedure TAgThread.ExecuteSimpleAnonymousMethod;
begin
while True do
begin
if WaitForSingleObject ( FEvent, FInterval ) = WAIT_OBJECT_0 then
break;
if FRun then
if Assigned ( FSimpleAnonymousMethod ) then
FOnRun;
end;
end;
procedure TAgThread.ExecuteObjectMethodWithSelf;
begin
while True do
begin
if WaitForSingleObject ( FEvent, FInterval ) = WAIT_OBJECT_0 then
break;
if FRun then
if Assigned ( FObjectMethodWithSelf ) then
FOnRun;
end;
end;
end.
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T12:52:57.643",
"Id": "82102",
"Score": "0",
"body": "What's with the Identifier{1,2,3}? Is there really nothing that differentiates those enough for them to warrant their own names?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:28:19.867",
"Id": "82140",
"Score": "0",
"body": "@cHao The identifier suffixes 1,2,3 signify the type of method to expect at execution. That can be named but would end up being too explanatory. The arguments would suffice for meaningfulness here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:31:31.690",
"Id": "82143",
"Score": "0",
"body": "All the more reason to actually give them descriptive names. I sure don't know WTF a \"type 3\" method is, without rooting around in the code. Unless it's is a Delphi thing, which i rather doubt."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:32:47.540",
"Id": "82145",
"Score": "0",
"body": "@cHao noted. I'll think of some appropriate names."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T11:53:53.660",
"Id": "46902",
"Score": "2",
"Tags": [
"optimization",
"multithreading",
"delphi"
],
"Title": "Optimizing a thread library"
} | 46902 |
<p>Say I have an array with 60 elements, and I want to select 40 elements from this array. The subset should consist of elements with evenly spaced indices. In theory I would need to select every 1.5th point, which is obviously not possible.</p>
<p>I tried doing it with a recursive function, kind of a divide & conquer approach. It selects the point in the middle between two boundaries and adds it to the result, then it splits this range up into two sub-ranges and executes the function again for these ranges:</p>
<pre><code>Private Sub AddMiddlePoint(ByRef data() As Double, ByRef Result As List(Of Double), Lowerindex As Integer, Upperindex As Integer, MaxVals As Integer, MinSize As Integer)
Dim middle As Integer = CInt((Upperindex + Lowerindex) / 2)
Dim newBorderLower1 As Integer = Lowerindex
Dim newBorderUpper1 As Integer = middle
Dim newBorderLower2 As Integer = middle + 1
Dim newBorderUpper2 As Integer = Upperindex
If Result.Count < MaxVals Then
Result.Add(data(middle))
If newBorderUpper1 - newBorderLower1 > MinSize Then AddMiddlePoint(data, Result, newBorderLower1, newBorderUpper1, MaxVals, MinSize)
If newBorderUpper2 - newBorderLower2 > MinSize Then AddMiddlePoint(data, Result, newBorderLower2, newBorderUpper2, MaxVals, MinSize)
End If
End Sub
</code></pre>
<p>I call this function like this:</p>
<pre><code>Private Function ThinOutData(source() As Double, Percentage As Integer) As Double()
Dim newData As New List(Of Double)
Dim amount As Integer = CInt(Percentage / 100 * source.Count)
AddMiddlePoint(source, newData, 0, source.Count - 1, amount, CInt(Int(1 / Percentage) + 1))
Return newData.ToArray
End Function
</code></pre>
<p>It basically works, but the subset that is selected isn't very evenly spaced. Some huge gaps, some small gaps and so on.</p>
<p>Does anyone have a suggestion how this can be improved? I am of course aware that you can't get perfectly even spacing for fractional steps, but my method returns uneven points even if it needs to pull every second or third value from the array.</p>
<p>My code is in VB.NET but feel free to use other languages that you are familiar with. It shouldn't be too hard to translate, I guess.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:15:29.963",
"Id": "82133",
"Score": "4",
"body": "This question appears to be off-topic because it is about altering a core functionality of the code, and therefore the code is not considered to be \"working\" (as in \"working as you want it to\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:20:00.030",
"Id": "82154",
"Score": "0",
"body": "That could be true, however in my opinion it was also working too well for Stack Overflow, so I used Code Review."
}
] | [
{
"body": "<p>change all of your integer values to <code>Float</code> variables, for a start. since I assume that you want a Decimal representation for numbers in between two numbers.</p>\n\n<p>if that is not the case and you actually want to select every other number, then you should use a <code>for</code> code block</p>\n\n<hr>\n\n<p>I am still not exactly sure what you are trying to do, and this kind of sounds like it might be an off-topic question</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:22:37.410",
"Id": "46910",
"ParentId": "46905",
"Score": "2"
}
},
{
"body": "<p>Your math was wrong, but don't worry it was a simple fix. And I have provided an easier way to do it on top of that.</p>\n\n<p>The key to this review is that we're going to take advantage of the .Net libraries, which you should remember can practically do anything you want them to. That is IF you know how to use them.</p>\n\n<p>in C#.Net</p>\n\n<pre><code>double percent = 40d / 60d;\nvar newValues = myList.Where((value, index) => index % (1 / percent) < percent).ToList();\n</code></pre>\n\n<p>in VB.Net </p>\n\n<pre><code>Dim percent As Double = 40.0 / 60.0\nDim newValues = myList.Where(Function(value, index) index Mod (1 / percent) < percent).ToList()\n</code></pre>\n\n<p>They are practically the same. But now let me explain how this works a bit now. </p>\n\n<p><code>List<T></code> in .Net inherits from the <code>IEnumerable<T></code> class which has the <a href=\"http://msdn.microsoft.com/en-us/library/bb549418%28v=vs.110%29.aspx\" rel=\"nofollow\">Where()</a> overloaded extension method from the Linq library. Using linq in combination with a lambda expression <code>Function(value, index) index Mod (1 / percent) < percent</code> I was able to specify to the <code>Where</code> method exactly what values to give back. I specifically did this with some math involving the index of the item that was being iterated over internally. Suffice to say, the Where method loops over given list, and returns all values which meet the criteria given in that lambda expression. At the end I convert the <code>IEnumeral<double></code> to a <code>List<double></code> to work like the data you had before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:20:41.103",
"Id": "82155",
"Score": "2",
"body": "Using LinQ is a great idea. I will check how it performs and then accept this answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:26:38.767",
"Id": "82157",
"Score": "1",
"body": "This works flawlessly, great job!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T16:29:58.253",
"Id": "82171",
"Score": "0",
"body": "The power of Linq! Glad it worked out for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-29T12:20:43.540",
"Id": "398337",
"Score": "0",
"body": "This does not work correctly for all values as can be seen in fiddle here (with 7 of 36): https://dotnetfiddle.net/QBw3zU"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:35:15.343",
"Id": "46929",
"ParentId": "46905",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46929",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:04:59.063",
"Id": "46905",
"Score": "3",
"Tags": [
"array",
"vb.net"
],
"Title": "Select evenly spaced subset from array"
} | 46905 |
<p>I was going through the Project Euler problem #3 and made a program to solve it. The problem is as follows:</p>
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29. What is the largest
prime factor of the number 600851475143 ?</p>
</blockquote>
<p>My code is as follows:</p>
<pre><code>#include<iostream>
#include<vector>
using std::cout;
using std::endl;
using std::vector;
typedef long long int llint;
vector<llint> computeFactors(llint);
vector<llint> computePrimeFactors(vector<llint>&);
llint getLargestPrimeFactor(const llint);
bool isPrime(const llint);
int main() {
llint num = 600851475143;
llint prime;
cout<<"The number to factorize is : "<<num<<endl;
//call the function getLargestPrimeFactor to get the factor
prime = getLargestPrimeFactor(num);
cout<<"The largest prime factor is : "<<prime<<endl;
return 0;
}
//////////////////////////////////////////////////////////////
////////// GET THE LARGEST PRIME FACTOR BY MAGIC /////////////
//////////////////////////////////////////////////////////////
llint getLargestPrimeFactor(const llint n) {
vector<llint> list, primeList;
list = computeFactors(n);
//if n itself is prime then return n;
if(list.size()==2) {
return *(primeList.end());
} else {
primeList = computePrimeFactors(list);
}
for(vector<llint>::iterator i=primeList.begin(); i<primeList.end(); i++) {
cout<<*i<<endl;
}
vector<llint>::iterator i = primeList.end() - 1;
return *i;
}
//////////////////////////////////////////////////////////////
/////////// GET THE FACTORS /////////////////////////////////
//////////////////////////////////////////////////////////////
vector<llint> computeFactors(llint n) {
vector<llint> list;
//iterate through every number in the range
for(llint i=1; i<=n; i++) {
//find out whether any of the number divides n
if(n%i==0) {
//if it does push it into the vector
list.push_back(i);
n=n/i;
}
}
return list;
}
//////////////////////////////////////////////////////////////
/////////// GET THE PRIME FACTORS ////////////////////////////
//////////////////////////////////////////////////////////////
vector<llint> computePrimeFactors(vector<llint>& factorList) {
vector<llint> prime;
//iterate through every number in the vector
for(vector<llint>:: iterator i=factorList.begin();
i<factorList.end();
i++)
{
//check whether each of the element is prime
if(isPrime(*i)) {
prime.push_back(*i);
}
}
return prime;
}
//////////////////////////////////////////////////////////////
/////////// WHETHER A PRIME NUMBER ///////////////////////////
//////////////////////////////////////////////////////////////
bool isPrime(const llint n) {
int count = 0;
for(llint i=1; i<=n; i++) {
if(n%i==0) {
count++;
}
}
if(count == 2) {
return true;
} else {
return false;
}
}
</code></pre>
<p>My doubts start from here:</p>
<ol>
<li><p>I called a single function from <code>main()</code> that gives me the result.</p></li>
<li><p>Now that function calls other functions from itself rather than in <code>main()</code>.</p></li>
<li><p>Those sub-functions call other functions to achieve the task.</p></li>
</ol>
<p>So now while designing the program, I just had to think about a single function that gave me the result. Now I decompose the function into different parts.</p>
<p>So when I call the <code>getLargestPrimeFactor()</code>, others are <strong>implicitly</strong> called.</p>
<p>But what I could have done is that I could have called each function <strong>explicitly</strong> in <code>main()</code>.</p>
<p>Is there a difference in between the two approaches ? Does it really matter ? In what cases thinking like this can be harmful ? I have studied a bit about cohesion and coupling. I just want to get the habits right from the beginning.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:28:54.927",
"Id": "82218",
"Score": "0",
"body": "what do you know about all of the factors you are testing above the square root of n?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T01:36:24.873",
"Id": "82271",
"Score": "0",
"body": "This code is very inefficient. Try it on 600851475177 instead and it takes forever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:23:16.577",
"Id": "82281",
"Score": "0",
"body": "@SpiderPig - I am sorry but I am quite new to programming. Can you please give me a hint for a faster algorithm ? :)"
}
] | [
{
"body": "<p>This is absolutely fine. By calling only one function in <code>main</code> and letting it handle what it has been asked for, you are achieving the concept of <a href=\"http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29\" rel=\"nofollow\">abstraction</a>, leaving out the unnecessary crunchy-details and just saying what you want, which is the largest prime factor of a given number. The user of this method does not need to know anything about how it works internally.</p>\n\n<p>Abstraction is one of the key concepts of <a href=\"http://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow\">OOP</a>, and since you are programming in C++, you'll start to see the benefits of using such patterns soon, when you start to use classes that can grow out bigger and more complex than expected. Then, you'll need to use <a href=\"http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29\" rel=\"nofollow\">encapsulation</a>, which is achieved <strong>through</strong> abstraction. So, the earlier your adopt this kind of pattern, the easier it will be in the future for you to resolve other issues like these.</p>\n\n<p>Now, regarding your code: one thing that I'd definitely do is drop these <code>/* magic stuff happens here */</code> comments, which do more harm than good. They do not explain anything and just yell that this code <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">probably smells</a>. Also, you should pay more attention to your one-character-name variables, like <code>n</code>, which does not mean much and is hard (actually <em>impossible</em>, depending on the size of your code) to find through <kbd>CTRL</kbd><kbd>F</kbd> if needed.</p>\n\n<p>If you have access to C++11, you could also take a peek on it's features to improve your code. For example, loops such as</p>\n\n<pre><code>for(vector<llint>:: iterator i=factorList.begin();\n i<factorList.end();\n i++) {}\n</code></pre>\n\n<p>could become <a href=\"http://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow\">ranged-for loops</a></p>\n\n<pre><code>for(auto i: factorList) {}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:35:35.453",
"Id": "82146",
"Score": "1",
"body": "And I had this major confusion with whether to use one lettered variable names or not. You cleared it up."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:27:46.420",
"Id": "46911",
"ParentId": "46906",
"Score": "4"
}
},
{
"body": "<h2>Naming</h2>\n<p>What's the name of your function? "getLargestPrimeFactor"? So it must do all the work to solve the problem.</p>\n<p>More generally, you want to make your code easy to use, and, if the user doesn't care about how it is done, providing one function with a correct name to do all the work is a welcome sight.</p>\n<h2>Customization</h2>\n<ol>\n<li>In one hand, you must provide a robust, bug-resistant, easy way for the user to get the result (here, the largest prime factor).</li>\n<li>In the other, you could want to provide a way for the users to call the functions as it suits them. This should be optional, and this can be done different ways, depending on the type of customization you want to provide.</li>\n</ol>\n<p><strong>your priority is to provide the first part: A user should be able to easy have the expected result, the same way starting your car is just turning the key (or pressing the button).</strong></p>\n<p>If you really want to provide customization, then you must think carefully about the kind of customization you can, and thus, common idioms will apply.</p>\n<p>For example, one naive solution would be to provide one class with all customization points being virtual methods. The users can then override the method they want to customize, while leaving the others as is. This needs research to find the right solution to your specific problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:36:41.877",
"Id": "82115",
"Score": "0",
"body": "Could you explain what you mean in your naming paragraph? I feel the `getLargestPrimeFactor` does what it is supposed to do. Also, it looks as if customization points are a bit overkill for some simple arithmetic calculations. What would you customize in this special instance (could you give a code example)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:42:15.850",
"Id": "82119",
"Score": "0",
"body": "@Nobody : My point with the \"naming\" part is that if one function says it will do something, then it must do it. If someone needs a getTheJobDone function, then providing doFirstPart, doSecondPart and doThirdPart instead, needing the caller to call the three functions one after the other is perhaps misguided... About the customization, yes, it is overkill, but this is how I understood the question: In a more general problem, this is *one* way to provide customization. I'll think about a code example as soon as I am able to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:46:04.317",
"Id": "82120",
"Score": "0",
"body": "If these functions are there to solve subproblems, then why not? The `getLargestPrimeFactor` function does to the user exactly what is needed: It returns the largest prime factor of a number. If you mean `computePrimeFactors` then I would be on your side :) This one should actually call `computeFactors` inside and only get the number as input."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:32:51.533",
"Id": "46913",
"ParentId": "46906",
"Score": "2"
}
},
{
"body": "<p>Let me start off by general reviewing and end with your specific question:</p>\n\n<h1>Documentation</h1>\n\n<p>It is good that you thought about documenting with comments.\nHowever, the ones you made can be improved.</p>\n\n<p>Function comments document the function interface and as such should be located where the interface is declared (so at the beginning of your file).</p>\n\n<p>They also should not document the obvious (\"GET THE LARGEST PRIME FACTOR\" for <code>getLargestPrimeFactor</code>) or irrelevant (\"my magic\").</p>\n\n<p>They should state pre- and postconditions of the function and what the function does (if there is more to it than the function's name).</p>\n\n<p>Think about adopting the use of computer readable documentation systems like doxygen to let IDE's and other tools aid you with correct documentation.</p>\n\n<h1>Maximize constness</h1>\n\n<p>For example in <code>vector<llint> computePrimeFactors(vector<llint>& factorList)</code> you don't write to the <code>factorList</code> so it should really be defined as <code>const vector<llint>& factorList</code> to indicate that. This makes the code easier to reason about.</p>\n\n<h1>Readability</h1>\n\n<p>If it is possible try to use C++11 which gives some nice features that improve readability. For example this:</p>\n\n<pre><code>for(vector<llint>:: iterator i=factorList.begin();\n i<factorList.end();\n i++)\n {\n //check whether each of the element is prime\n if(isPrime(*i)) {\n prime.push_back(*i);\n }\n }\n</code></pre>\n\n<p>can become this in C++11:</p>\n\n<pre><code>for(auto const &i : factorList)\n{\n //check whether each of the element is prime\n if(isPrime(i)) {\n prime.push_back(i);\n }\n}\n</code></pre>\n\n<p>You can access the first and last element of most containers without using iterators by <code>front()</code> and <code>back()</code> so you could write:</p>\n\n<pre><code>return primeList.back();\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>vector<llint>::iterator i = primeList.end() - 1;\nreturn *i;\n</code></pre>\n\n<h1>Efficiency</h1>\n\n<p>At first you calculate some of the divisors (in <code>getFactors</code>) of the number and store them in a list. Then you process this list and pick out the primes with <code>isPrime</code> (in <code>getPrimeFactors</code>) by trying to divide them by all numbers below them.</p>\n\n<p>But actually you could have obtained all prime factors in the first function (<code>getFactors</code>) if you had divided as long as it was possible:</p>\n\n<pre><code>if(n % i == 0) {\n //if it does push it into the vector\n list.push_back(i);\n //remove this prime factor from the number\n while(n % i == 0)\n n /= i;\n}\n</code></pre>\n\n<p>Thereby you would avoid the necessity to later check if the factors are prime.</p>\n\n<h1>Naming</h1>\n\n<p>Your function <code>computePrimeFactors</code> is misnamed. Actually it should be called something like <code>filterPrimes</code> because it gets a list of numbers and returns the primes inside this list.\nThe better approach for this name would be to get the number as parameter and return the prime factors while internally calling <code>computeFactors</code>:</p>\n\n<pre><code>vector<llint> computePrimeFactors(llint n) {\n vector<llint> factors = computeFactors(n);\n vector<llint> primeFactors;\n // c++11!\n std::copy_if(factors.begin(), factors.end(),\n std::back_inserter(primeFactors), \n &isPrime);\n return prime;\n}\n</code></pre>\n\n<p>I have also replaced the copy code by a stdlib function, which reduces the risk of programming errors while (usually) increasing readability.</p>\n\n<h1>Your question</h1>\n\n<p>Finally I will answer your question:\nIn general it is good to break up logic units into functions that define clear boundaries and give a name to the unit. As such you would even further reduce the main function by making it's body another function that gets called from main. This allows reuse of the code later on.</p>\n\n<p>However, in your code it is unlikely to be needed again, so it is not necessary to do this. I would however state, that you should not put more into main.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T04:27:33.757",
"Id": "84254",
"Score": "0",
"body": "Great answer, but this code would be greatly simplified by not using a list. You seek the biggest factor that is prime. Either work your way up from 2, or down from sqrt n, but each time you find a factor, check if it's prime. I like the going down method myself. The first one you find that is prime, stop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T08:35:56.980",
"Id": "84269",
"Score": "1",
"body": "@Dov: My gut feeling tells me that this approach is slower, as you have to test for primeness very often, which is a very costly operation. It could be sped up by having a precomputed list of primes but then you would need a big one that includes the possible factors of the number you want to test. Reducing the number by division significantly improves the runtime of the more common case of non prime numbers (if you see each number as equally likely)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:33:41.080",
"Id": "46914",
"ParentId": "46906",
"Score": "12"
}
},
{
"body": "<ol>\n<li><p>As far as the methods you've created and are calling I see no problem with (as per your doubts). Functions calling functions is a good thing. Functions should pull all of their own weight, calling other functions when necessary, the coder shouldn't have to call those functions beforehand and pass in the parameters, unless of course there is a situation where you (the coder) do at times need to specify specific running values.</p></li>\n<li><p>Your main looks good, however as far as aesthetics of your code goes, I would add spaces between your operators and symbols...</p>\n\n<pre><code>//this\ncout<<\"The largest prime factor is : \"<<prime<<endl;\n\n//becomes\ncout << \"The largest prime factor is : \" << prime << endl;\n</code></pre>\n\n<p>This lack of spacing is in other parts of the code, but I'm not going to point out everywhere.</p></li>\n<li><p>Aesthetically this block of code could be re-factored a few different ways.</p>\n\n<pre><code>//Use one liners and no ugly brackets.\nif(list.size() == 2) \n return *(primeList.end());\nelse\n primeList = computePrimeFactors(list);\n\n//Take advantage of the fact that you don't need an else after a return.\nif(list.size() == 2) \n return *(primeList.end());\nprimeList = computePrimeFactors(list);\n</code></pre></li>\n<li><p>Use shortcut operators</p>\n\n<pre><code>n /= i;\n</code></pre></li>\n<li><p>Don't do extra work. There are two things to change about the code below.</p>\n\n<pre><code>if(count == 2) {\n return true;\n} else {\n return false;\n}\n</code></pre>\n\n<p>Kill the brackets as I did earlier. <strong>(opinion, and optional)</strong></p>\n\n<pre><code>if(count == 2)\n return true;\nelse \n return false;\n</code></pre>\n\n<p>Now that we can see this code clearly, we can realize what it is actually doing. <code>count == 2</code> yields a Boolean value which is then passed to the special <code>if function</code>, which then asks if the Boolean passed in was true, if so.. then return true, else false (oversimplification of what is happening on the low level, but you get the gist) <code>count == 2</code> is a Boolean, so instead of using that in an if... just return the Boolean you got from using that operator.</p>\n\n<pre><code>return count == 2;\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:46:52.747",
"Id": "82121",
"Score": "6",
"body": "\"Kill the brackets\" is against many guidelines (most?). Many reviews here would have said instead \"add brackets\" in case there weren't already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:50:57.853",
"Id": "82127",
"Score": "0",
"body": "@Morwenn it an opinion based and there is no definitive answer on that, however I highly recommend it, as it clears up the code from pointless fluff and allows you to more simply see what is going on. Most will agree that you shouldn't mix these two approaches within the context of a single if-else, so not to have brackets for half and not for the second, in this particular case, the brackets were serving one purpose... to get in the way of anyone trying to read the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:54:39.633",
"Id": "82130",
"Score": "2",
"body": "On the other hand, you can later add statements to the body of your `if` or `else` without risking to forget the braces, which is safer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:36:46.547",
"Id": "46916",
"ParentId": "46906",
"Score": "5"
}
},
{
"body": "<p>I think it's actually a really good habit to call functions from within functions. This is a very important concept in <a href=\"http://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow\">Object-Oriented Programming</a>. If you wrote this source code using OOP, you might structure it like this...</p>\n\n<ul>\n<li>Class Main\n<ul>\n<li>main()</li>\n</ul></li>\n<li>Class PrimeFactors\n<ul>\n<li>public getLargestPrimeFactor()</li>\n<li>private computeFactors()</li>\n<li>private computePrimeFactors()</li>\n<li>private isPrime()</li>\n</ul></li>\n</ul>\n\n<p>As you can see, in this class any method called from Main is declared as public, and any method only called from within the class is declared as private.</p>\n\n<p>Structuring this program as a class instead of a series of functions makes it easy to re-use the code. It makes Class PrimeFactors like a library that you can easily include into any main that you want.</p>\n\n<p>I agree with the others about commenting less. I was reading Clean Code by Robert C. Martin the other day, and he argues that comments should be minimal and pragmatic. Ideally you want to choose very succinct names for your variables and functions/methods, and you want to make as many chunks of code into functions/methods as possible. And what this does is it names everything, which helps to avoid you needing to make as many comments in the first place. I think you're already on the right track with this because you wrote multiple functions and you tried to give them all good names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T16:15:41.520",
"Id": "46938",
"ParentId": "46906",
"Score": "2"
}
},
{
"body": "<p>I know you already accepted an answer, but I think you asked the wrong question, so I will try to correct your other design mistakes.</p>\n\n<p>As I mentioned briefly in a comment, you are using a list when you should be doing a greedy loop. It doesn't matter how well structured your code is, if your algorithm is wildly overcomplicated, your code is by definition harder to read than it needs to be.</p>\n\n<p>So in a problem like this, your first concern should not be abstract object oriented concerns like coupling. You should be thinking about getting the algorithm right.</p>\n\n<p>Let's take a look at your isPrime function.\nThe comment should describe what it does. You could say \"return true if the number is prime\"\nwhich is fairly obvious, though not as useless as your current comment. But you could also describe how you are checking.</p>\n\n<p>\"Count how many factors are in the number. A prime has exactly 2\"</p>\n\n<p>That would at least explain your logic. But you should learn cleaner logic. This is the standard way:</p>\n\n<pre><code>bool isPrime(unsigned long long n) {\n for (unsigned long long i = 2; i < n; i++)\n if (n % i == 0)\n return false; // if it divides, it's not prime\n return true;\n}\n</code></pre>\n\n<p>That's the first level of brute force checking. It happens to be shorter, simpler, and considerably faster than yours. Why count how many divisors there are? The first one you get (except 1 which is a waste) you know you have a composite.</p>\n\n<p>If you want speed, you then have to start trading off some complexity for a faster answer.\nThere is no point in dividing by 4, 6, 8. If your number divides by 2, it is not prime, and if it does not, then it's odd. So:</p>\n\n<pre><code>bool isPrime(unsigned long long n) {\n if (n > 2 && n % 2 == 0) // special case, check if the number is even\n return false;\n const unsigned long long lim = sqrt(n);\n for (unsigned long long i = 3; i <= lim; i+=2) // not even, so only divide by odd\n if (n % i == 0)\n return false; // if it divides, it's not prime\n return true;\n}\n</code></pre>\n\n<p>This is much faster because you only go up to sqrt(n), not n, and do it by 2 to boot. For n= 10^12, that's the difference between 1 trillion iterations, and 500,000.</p>\n\n<p>If you are going to use a list in this problem, then it should be because you are implementing Eratosthenes' sieve (look it up on Wikipedia or here).</p>\n\n<p>As it stands, I would start at the square root of the number in question, working my way down. When I find a divisor, I check if it is prime. If it is bigger than the current maximum, store the number as maximum. If it is composite, break that one up and find its factors recursively. Because you have to keep splitting composites into primes, I would make a recursive function to do that, but there won't be any list, and you can stop splitting the moment your number is smaller than the maximum you found so far.</p>\n\n<p>If I were you, I would make a set of better and better isprime functions, because if you are going to keep tackling problems from project Euler you will need them.</p>\n\n<p>In the long run, all the advice you were given is pretty good. But on a problem like this, the best way to keep the code clean is to clean up your logic, not to use doxygen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T05:28:09.443",
"Id": "84256",
"Score": "0",
"body": "Thank you so much for your answer. It is very helpful. And I did the optimizations like returning false when number is evenly divisible by another in the loop and square root of n limit. And I thought about checking even divisibility first and then if it passes the test then proceeding further. But I was not sure whether its good practice or not. Thanks for clearing that up. And I implemented the sieve but the deletion of the elements from the list seems expensive. And I can't find a way to learn recursion properly. So I am stuck there. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T05:30:48.390",
"Id": "84257",
"Score": "0",
"body": "WHen they teach the sieve, they show all the numbers being struck out, but you have to think out of the box. Why create numbers in a list and then get rid of them? Just don't put them in the list in the first place! Post a new question if you don't understand. You should definitely write a sieve if you're going to keep solving project Euler problems, you will need it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T05:37:48.497",
"Id": "84258",
"Score": "0",
"body": "I was thinking about it. Obviously I will not strike out numbers from list. But I didn't try hard. I will try it and if I write the code, I will make a post for reviews. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T02:06:31.340",
"Id": "84406",
"Score": "0",
"body": "As long as you're interested in efficiency, pre-allocate the space you need. You know approximately how many prime numbers you want to store, so reserve that much space in the vector. Then fill it. Even faster than sieve is not even testing numbers, so try to skip multiples. Standard trick is to do multiples of 6+/-1, ie 5 and 7, 11 and 13, 17 and 19. Because anything that is divisible by 6 is obviously not prime, nor is anything that is 6 mod 2, 3, or 4. T"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T04:42:21.607",
"Id": "48024",
"ParentId": "46906",
"Score": "3"
}
},
{
"body": "<h2>Algorithm</h2>\n\n<p>I think you've gotten distracted by focusing on the wrong aspect of the problem.</p>\n\n<p>The challenge asks for the largest prime factor of <em>n</em> = 600851475143. There are three approaches you might consider in tackling this challenge:</p>\n\n<ol>\n<li><p><strong>Construct the list of all relevant prime numbers, then take the largest one that is a factor of <em>n</em>.</strong></p>\n\n<p>How high do we need consider? The largest candidate would be \\$\\frac{n}{3}\\$.</p>\n\n<p>What algorithm could we use? A good method to build a list of many prime numbers is the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\">Sieve of Eratosthenes</a>. That would require \\$\\frac{n}{3}\\$ bits of memory, or 23 GiB. Even if you had a machine with that much memory, just initializing that much memory to zero would be too slow to be reasonable as a Project Euler solution.</p>\n\n<p>Any other algorithm for building a list of primes would only be worse.</p>\n\n<p><em>You didn't choose Door #1. Good for you!</em></p></li>\n<li><p><strong>Test the largest candidate factors first.</strong></p>\n\n<p>Where would you start? The largest candidate would be \\$\\left\\lceil\\sqrt{n}\\right\\rceil\\$. You can test odd candidates in descending order, stopping as soon as you find an answer that is prime.</p>\n\n<p>How do you guarantee that the answer is prime? You have to check for primality. We've already ruled out the Sieve of Eratosthenes above, so you would have to use trial division or a fancier primality-testing algorithm.</p>\n\n<p>How long would we expect this to take? \\$\\left\\lceil\\sqrt{n}\\right\\rceil\\$ is 775147. We would have 387573 possible odd factors to test. There's no telling where we'll find numbers that are actually factors of \\$n\\$. Once we find a factor, we still have to verify whether it's prime.</p>\n\n<p>Food for thought: what would you do if \\$n\\$ were even?</p>\n\n<p><em>You didn't choose Door #2, even though some other users have advocated it. Good for you!</em></p></li>\n<li><p><strong>Test the smallest candidate factors first.</strong></p>\n\n<p>Suppose that I asked you to find the largest prime factor of 10241. How would you go about it? Would you start at \\$\\left\\lceil\\sqrt{10241}\\ \\right\\rceil\\$, trying 103, 101, 99, 97, 95, …?</p>\n\n<p>Chances are, you would prefer to do it the following way instead, and you could do it with just pencil and paper. (It's also easy to implement as one function.)</p>\n\n<ul>\n<li>10241 / 2 … no.</li>\n<li>10241 / 3 … no.</li>\n<li>10241 / 5 … no.</li>\n<li>10241 / 7 = 1463</li>\n<li>1463 / 7 = 209</li>\n<li>209 / 7 … no.</li>\n<li>209 / 9 … no.</li>\n<li>209 / 11 = 19</li>\n<li>19 / 11 … no.</li>\n<li>19 / 13 … no.</li>\n<li>19 / 15 … no.</li>\n<li>19 / 17 = no.</li>\n<li>19 / 19 = 1\ndone!</li>\n</ul>\n\n<p>As you can see, the big win comes when you find that 10241 is divisible by 7 — you immediately reduce the search space by a factor of 7. In just a few iterations, you've reduced the problem size from 10241 down to 209 — a much more manageable number.</p>\n\n<p>Bonus question: in the example above, do we still need to test 19 for primality? Why or why not?</p></li>\n</ol>\n\n<p>As it turns out, strategy 3 also works well for Project Euler Problem 3. In general, strategy 3 is a better bet than strategy 2, since <a href=\"http://en.wikipedia.org/wiki/Prime_number_theorem\">prime numbers tend to be more densely clustered closer to 0</a>.</p>\n\n<p>You've chosen an algorithm that is similar to strategy 3, which is good. However, it isn't the same solution. Your <code>computeFactors()</code> function very closely mimics the algorithm illustrated for strategy 3, but with a subtle and crucial difference. Can you spot it?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T08:50:00.947",
"Id": "84925",
"Score": "1",
"body": "I should have started earlier with writing about it. +1 one for the reference. Let me give one more point that I would have written about (which also is implicitly contained in your reasoning): Starting from the lower primes has on average the probability to find factors of a random number. Every second number has two as a factor, every third 3 and so on. This indicates that the probability distribution of finding a factor clearly leans towards the lower end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T07:55:27.617",
"Id": "125600",
"Score": "0",
"body": "70G is 600851475143/8, not sqrt(600851475143)/8, which is 180K."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T07:57:42.783",
"Id": "125601",
"Score": "1",
"body": "your 3rd is much more than just \"Test the smallest candidate factors first.\" It is also \"divide out the found factor\" and \"continue the search from the found factor\" (not restarting from 2 again)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T08:18:44.953",
"Id": "125603",
"Score": "0",
"body": "@WillNess You're right, I messed up the upper bound of method 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-04T09:43:36.020",
"Id": "125618",
"Score": "0",
"body": "yeah, me too. :) it's 100K, not 180."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:42:58.163",
"Id": "423121",
"Score": "0",
"body": "Hi. Could you please explain why \"The largest candidate would be √n\" for strategy 2? I considered it with these two examples: **Example 1:** For `n=8` then `√n = 2.8....` and the largest prime factor is `2 < √8`. **Example 2:** For `n = 110` then `√n = 10.488....` and the largest prime factor is `11 > √110`. So I wasn't able to conclude anything. Thanks in advance!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:48:39.687",
"Id": "423122",
"Score": "1",
"body": "@Eagle Factors always occur in pairs. For every factor that you find that is ≤ √n, you also automatically discover a corresponding factor that is ≥ √n."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T04:49:56.087",
"Id": "423123",
"Score": "0",
"body": "Oh yes. That makes sense. I thought it was about only the prime factors. Thanks a lot for your help."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T20:10:43.010",
"Id": "48185",
"ParentId": "46906",
"Score": "21"
}
}
] | {
"AcceptedAnswerId": "46914",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:08:32.500",
"Id": "46906",
"Score": "15",
"Tags": [
"c++",
"design-patterns",
"primes",
"programming-challenge"
],
"Title": "Project Euler #3 - largest prime factor"
} | 46906 |
<p>Imagine I have code like this in (it's about the concept; this is example code):</p>
<pre><code># models.py
from django.db import models
class Monster(models.Model):
x = models.FloatField()
y = models.FloatField()
def use_unique_ability(self, target):
''' different monsters types will implement this differently '''
def check_attack(self, player): # should I attack this player?
''' different monsters types will implement this differently '''
class Meta:
abstract = True
class SlimyMonster(Monster):
def __init__(self):
self.attack = 3
self.hit_points = 10
def use_unique_ability(self, target):
target.hit_points -= 2 * target.attack
def check_attack(self, player): # should I attack this player?
return player.hit_points < self.hit_points
class CaerbannogRabbit(Monster):
''' well, you get the idea '''
# many more monsters
</code></pre>
<p>Each monster has the same attributes and method names, but different values and implementation. <code>Monster</code> would probably be an interface in Java. Each monster type will override only some of the many methods.</p>
<p>This technically works, but it has some significant downsides:</p>
<ul>
<li>Each monster is a new database table with the same columns</li>
<li>Because of that, I need a lot of queries to check for all monsters</li>
<li>I need GenericForeignKey to reference individual monsters (instances of any of the model classes)</li>
</ul>
<p>The other extreme isn't exactly pretty either. This is based on <a href="https://stackoverflow.com/questions/8544983/dynamically-mixin-a-base-class-to-an-instance-in-python">dynamically mixin a base class to an instance</a> (+<a href="https://stackoverflow.com/questions/7320705/python-missing-class-attribute-module-when-using-type">this</a>) and <a href="https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path">how to import a module given the full path?</a>:</p>
<pre><code># models.py
from django.db import models
from os.path import join
from inspect import isclass
from imp import load_source
from settings import PATH_TO_MONSTER_FILES
class InconsistentMonsterError(Exception): pass
class MonsterClass(models.Model):
name = models.CharField(max_length = 32)
attack = models.PositiveIntegerField(default = 1)
defense = models.PositiveIntegerField(default = 10)
method_file = models.CharField(max_length = 128) # it's a source file, not media file, so I'm using CharField
def __init__(self, *args, **kwargs):
super(MonsterClass, self).__init__(*args, **kwargs)
try:
modul = load_source(self.method_file, join(PATH_TO_MONSTER_FILES, self.method_file))
except IOError:
raise InconsistentMonsterError('no file named %s' % join(PATH_TO_MONSTER_FILES, self.method_file))
classes = [cls for cls in [getattr(modul, x) for x in dir(modul)] if isclass(cls)]
if not len(classes):
raise InconsistentMonsterError('file %s doesn\'t contain classes' % join(PATH_TO_MONSTER_FILES, self.method_file))
bases = self.__class__.__bases__ + (classes[-1], )
self.__class__ = type('NewClassName', bases, {
'__module__': MonsterClass.__module__,
})
class MonsterInstance(models.Model):
cls = models.ForeignKey(MonsterClass)
x = models.FloatField()
y = models.FloatField()
</code></pre>
<p>and for each monster a file like this:</p>
<pre><code># slimy_monster.py
class SlimyMonster(): # not a Model
def use_unique_ability(self, target):
''' different monsters types will implement this differently '''
def check_attack(self, player): # should I attack this player?
''' different monsters types will implement this differently '''
</code></pre>
<ul>
<li>The code seems... inellegant. It's complex, and it's like using <code>eval</code> (execute code based on an 'external' string)</li>
<li>Every monster must be changed in two places: the database and a file (although I suppose I could define database values in the file)</li>
</ul>
<p>Given these two options, should I use one of them, or something in between? I tend towards the second option, but I'm not quite satisfied.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:50:30.127",
"Id": "82125",
"Score": "0",
"body": "I remove the notice about being off-topic. IMO, having two version of the same code tend to be opiniated, reviewing one version could be better (in fact you could probably have two questions). have you read the [faq] before posting ? This can help to decide if your question is on-topic or not. (I'm still hesitant to consider the on-topicness of the question)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:30:52.873",
"Id": "82142",
"Score": "0",
"body": "Well, it's best practise for specific code so that seems okay. Can't find the two different versions things. Splitting it in two questions seems wasteful though; the answers to each are just doing to complement each other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:37:36.297",
"Id": "82147",
"Score": "0",
"body": "The version things is my personal preference, nothing off-topic about it, just they have a tendency to being opinionated (again this is my opinion). I have difficulty to judge the topicness of v1 vs v2 questions. Indeed your question seems okay, there are no vote-to-close."
}
] | [
{
"body": "<p>What you want is inheritance as a <a href=\"https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models\" rel=\"nofollow\">proxy model</a>.</p>\n\n<p>In your subclasses, use the following Meta option:</p>\n\n<pre><code>class SlimyMonster(Monster):\n class Meta:\n proxy = True\n\n def some_method_to_override(self):\n ...\n</code></pre>\n\n<p>This way the subclassing has no effect on the database side, only on the Python side.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T09:24:21.390",
"Id": "47557",
"ParentId": "46907",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47557",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:18:25.010",
"Id": "46907",
"Score": "1",
"Tags": [
"python",
"django",
"import"
],
"Title": "Django models: different methods on each instance?"
} | 46907 |
<p>I am working on a price slider that is for a Java environment. It is working correctly but I would like to optimise it as much as possible. Any tips/advice?</p>
<pre><code><div class="wrap">
<div class="range"></div>
<div class="amount min-amount left"></div>
<div class="amount max-amount right"></div>
<form action="#" method="get" class="range-slider-form hidden">
<input type="hidden" class="slider_q" name="q" value="${searchPageData}" />
<input type="hidden" name="text" value="${searchPageData.freeTextSearch}" />
<input type="hidden" class="slider_step" value="1" />
<input type="hidden" class="slider_min" name="minSel" value="${min}" />
<input type="hidden" class="slider_max" name="maxSel" value="${max}" />
<input type="hidden" class="price_min" name="minSlider" value="${minSlider}" />
<input type="hidden" class="price_max" name="maxSlider" value="${maxSlider}" />
<input type="hidden" name="resultsForPage" value="${rs}" />
</form>
</div>
<script type="text/javascript">
var slider_step = $(".slider_step"),
price_min = $(".price_min"),
price_max = $(".price_max"),
slider_min = $(".slider_min"),
slider_max = $(".slider_max");
$( ".range" ).slider({
range: true,
min: parseInt(price_min.val()),
max: parseInt(price_max.val()),
step: parseInt(slider_step.val()),
values: [ parseInt(slider_min.val()), parseInt(slider_max.val()) ],
slide: function(event, ui){
//Sliding number
$('.ui-slider-handle:eq(0) .price-range-min').html('&pound;' + ui.values[0]);
$('.ui-slider-handle:eq(1) .price-range-max').html('&pound;' + ui.values[1]);
$('.price-range-both').html('<i>&pound;' + ui.values[0] + ' - </i>&pound;' + ui.values[1] );
if ( ui.values[0] == ui.values[1] ){
$('.price-range-both i').css('display', 'none');
} else{
$('.price-range-both i').css('display', 'inline');
}
if (collision($('.price-range-min'), $('.price-range-max')) == true){
$('.price-range-min, .price-range-max').css('opacity', '0');
$('.price-range-both').css('display', 'block');
} else{
$('.price-range-min, .price-range-max').css('opacity', '1');
$('.price-range-both').css('display', 'none');
}
},
change: function(event, ui){
/* update the values and submit the form */
slider_min.val(ui.values[0]);
slider_max.val(ui.values[1]);
// getting search query string from html
var q = $(".slider_q");
// create string from array and add priceValue and prices in required format.
var qrystr = q.val();
if (qrystr.indexOf("priceValue") == -1){
var r = qrystr+":priceValue:["+ui.values[0]+" TO "+ui.values[1]+"]";
}
else{
var a = qrystr.split(":");
a.splice(2,2);
var r = a.join(":")+":priceValue:["+ui.values[0]+" TO "+ui.values[1]+"]";
}
q.val(r);
// Submit the form
$(".range-slider-form").submit();
}
});
var minselected = parseInt($(".range").slider("values",0)),
maxselected = parseInt($(".range").slider("values",1));
$('.ui-slider-range').append('<span class="price-range-both value"><i>&pound;' + minselected + ' - </i>' + maxselected + '</span>');
$('.ui-slider-handle:eq(0)').append('<span class="price-range-min value">&pound;' + minselected + '</span>');
$('.ui-slider-handle:eq(1)').append('<span class="price-range-max value">&pound;' + maxselected + '</span>');
//Collison of Min/Max Price
function collision($div1, $div2){
var x1 = $div1.offset().left,
w1 = 40,
r1 = x1 + w1,
x2 = $div2.offset().left,
w2 = 40,
r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
</script>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T10:15:37.190",
"Id": "82300",
"Score": "0",
"body": "Can you put up a demo. I can't seem to get it working."
}
] | [
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li>You are assigning a class to hidden input elements, that does not make sense. Assign an <code>id</code> instead, selection on <code>id</code> is much faster.</li>\n<li><code>ui.values[0]</code> and <code>ui.values[1]</code> use magic sonstants, you should use named constants like <code>ui.values[SLIDER_MINIMUM]</code> and <code>ui.values[SLIDER_MAXIMUM]</code></li>\n<li>Do not disemvowel your variable too much , <code>qrystr</code> <- That's too much</li>\n<li>You declare <code>var r</code> more than once in <code>change</code>, don't do that</li>\n<li>The variable name in <code>collision</code> are terrible</li>\n<li>The magic <code>40</code> should be a properly named constant</li>\n<li>The one line of comment for <code>collision</code> is pretty useless, moar comments are needed</li>\n<li><p>This : </p>\n\n<pre><code>if (r1 < x2 || x1 > r2) return false;\nreturn true;`\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>return !(r1 < x2 || x1 > r2)\n</code></pre></li>\n</ul>\n\n<p>All in all, I think this code requires some polishing, but the basics are okay. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:37:26.633",
"Id": "47163",
"ParentId": "46915",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:36:08.957",
"Id": "46915",
"Score": "4",
"Tags": [
"javascript",
"optimization",
"jquery-ui"
],
"Title": "Price Slider using jQuery UI working in Java environment to be optimised"
} | 46915 |
<p>Let's compare the following code:</p>
<p>1)</p>
<pre><code>public class MyClass
{
private object syncRoot;
public MyClass()
{
this.syncRoot = new object();
}
...
}
</code></pre>
<p>2)</p>
<pre><code>public class MyClass
{
private object syncRoot = new object();
public MyClass()
{
}
...
}
</code></pre>
<p><strong>What do you prefer and what are the advantages/disadvantages of these solutions?</strong> To me I prefer the first one because its obvious seeing constructor what is getting intialized, however the second can be covering multiple constructors better. </p>
<p><strong>Edit</strong>:
I am pasting actual real code to make the question valid, adding some description: The class handles execution of powershell, there are some dependencies of class injected to constructor, and some fields initialized locally (syncRoot is used for thread-safety, logger is log4net for logging). </p>
<pre><code>/// <summary>
/// VCenter handler which creates the tasks and execute them
/// requirement: PowerCLI must be installed
/// </summary>
public class VCenterPowerCLI : IDisposable
{
/// <summary>log4net logger</summary>
private readonly ILog logger = LogManager.GetLogger(typeof(VCenterPowerCLI));
/// <summary>factory of powershell runtimes</summary>
private readonly IPowershellRuntimeFactory powershellRuntimeFactory;
/// <summary>vcenter handler configuration</summary>
private readonly VCenterConfiguration configuration;
/// <summary>Thread-safe sync</summary>
private object syncRoot = new object();
/// <summary>
/// Initializes a new instance of the VCenterPowerCLI class.
/// </summary>
/// <param name="configuration">vcenter handler configuration</param>
/// <param name="powershellRuntimeFactory">factory of powershell runtimes</param>
public VCenterPowerCLI(
VCenterConfiguration configuration,
IPowershellRuntimeFactory powershellRuntimeFactory)
{
this.configuration = configuration;
this.powershellRuntimeFactory = powershellRuntimeFactory;
}
/// <summary>
/// Immediate task - takes snapshot under the machine
/// </summary>
/// <param name="machineId">machine id</param>
/// <param name="snapshotName">snapshot name</param>
public void TakeSnapshot(string machineId, string snapshotName)
{
string task = this.CreateTakeSnapshotTask(machineId, snapshotName);
this.ExecuteTask(task);
}
/// <summary>
/// Creates take snapshot task to be executed in the pipeline later
/// </summary>
/// <param name="machineId">machine id</param>
/// <param name="snapshotName">snapshot name</param>
/// <returns>task to be executed</returns>
public string CreateTakeSnapshotTask(string machineId, string snapshotName)
{
StringBuilder code = new StringBuilder();
code.AppendLine("Add-PSSnapin \"VMware.VimAutomation.Core\" | Out-Null;");
code.AppendLine(string.Format("$global:Server = Connect-VIServer \"{0}\" -User \"{1}\" -Password \"{2}\"", this.configuration.Uri, this.configuration.User, this.configuration.Password));
code.AppendLine(string.Format("$cluster = Get-Cluster \"{0}\";", this.configuration.ClusterName));
code.AppendLine(string.Format("$vm = $cluster | Get-VM \"{0}\";", machineId));
code.AppendLine(string.Format("New-Snapshot -VM $vm -Name \"{0}\" -Quiesce -Memory | Out-Null", snapshotName));
code.AppendLine("Disconnect-VIServer -Server $global:Server -Confirm:$false");
return code.ToString();
}
/// <summary>
/// Executes the task - wait for finishing
/// </summary>
/// <param name="code">task to be executed</param>
public void ExecuteTask(string code)
{
lock (this.syncRoot)
{
using (IPowershellRuntime runtime = this.powershellRuntimeFactory.Create())
{
try
{
runtime.ExecuteCode(code);
}
catch (Exception e)
{
if (e.Message.Contains("Unsufficient permissions. You need 'System.Read' privileges to complete the requested operation"))
{
// skip, the operation with this exception is successfully done
}
else
{
throw;
}
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:53:07.000",
"Id": "82194",
"Score": "0",
"body": "That logger is not consistent with the other fields. Even if you don't inject it (which is a mistake!), since the others are initialized in the constructor, it should also be. `syncRoot` isn't as bad, because it has no data of any kind, but I'd still move it for consistency."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:12:53.923",
"Id": "82196",
"Score": "0",
"body": "Magus: Consistency is good point as mentioned by Jeroen, and as long as there are dependencies it seems that only way how to make it all consistent is to initialize all the locals in constructor as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:36:26.647",
"Id": "82203",
"Score": "1",
"body": "@TomasPanik Thanks for adding some real code. I have voted to reopen the question and I've also asked folks in the chat room to do so as well. Once again, welcome to Code Review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:48:51.033",
"Id": "82207",
"Score": "0",
"body": "`syncRoot` should be set to `readonly`. Bad things happen when the variable you are locking on starts referencing a new instance."
}
] | [
{
"body": "<p>There are no differences between your two options. There are a few remarks we can make about though:</p>\n\n<h1>Consistency</h1>\n\n<p>Keep everything consistent. There are a few reasons to change it up (for example: you can do inline initialization all the time and only initialize those in the constructor that take a constructor argument), but that's because these two situations have a significant difference.</p>\n\n<p>If there is no difference (for example: initializing a field to its default value) then you have to be consistent.</p>\n\n<h1>Multiple constructors</h1>\n\n<p>If you initialize your fields in your constructor and you add a second one, you might forget to chain them. </p>\n\n<hr>\n\n<p>All things considered, I believe inline initializing to be better. There is no functional difference but it doesn't have the possibility of the constructor chaining overlook.</p>\n\n<p>Aside from that, it also keeps the declaration and the initialization together which improves readability.</p>\n\n<h1>Comments</h1>\n\n<p>When I look at a variable called <code>IPowershellRuntimeFactory</code>, a comment that says <em>factory of powershell runtimes</em> doesn't add any value.</p>\n\n<p>Comments like this are a lot more important:</p>\n\n<pre><code>/// VCenter handler which creates the tasks and execute them\n/// requirement: PowerCLI must be installed\n</code></pre>\n\n<p>It is hard to deduct that PowerCLI must be installed if you omit it, so that's actually adding valuable information.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:22:51.527",
"Id": "46925",
"ParentId": "46918",
"Score": "8"
}
},
{
"body": "<p>I would not use any of them. Use <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow\">inversion of control</a> and <a href=\"http://en.wikipedia.org/wiki/Dependency_injection#Constructor_injection\" rel=\"nofollow\">constructor injection</a> instead:</p>\n\n<pre><code>public class MyClass\n{\n private readonly object syncRoot;\n\n public MyClass(object syncRoot)\n {\n this.syncRoot = syncRoot;\n }\n\n ...\n\n}\n</code></pre>\n\n<p>And once you understood that IoC and DI are good practices to follow, <a href=\"http://blog.vuscode.com/malovicn/archive/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx\" rel=\"nofollow\">Nikola Malovic's 4th law of IoC</a> becomes clear:</p>\n\n<blockquote>\n <p>Every constructor of a class being resolved should not have any\n implementation other then accepting a set of its own dependencies.</p>\n</blockquote>\n\n<p>In other words, <strong>do not do anything substantial in constructor</strong>. Creating an object is substantial.</p>\n\n<p><strong>UPDATE</strong> for guys fighting with locks:</p>\n\n<pre><code>public class MyClass\n{\n private readonly object syncRoot;\n\n /// <param name=\"syncRoot\">\n /// Just instantiated object, please\n /// \n /// And no locks, offcourse!\n /// </param>\n public MyClass(object syncRoot)\n {\n this.syncRoot = syncRoot;\n }\n}\n\npublic class MyClassFactory\n{\n MyClass Create()\n {\n return new MyClass(new object());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:50:33.480",
"Id": "82193",
"Score": "5",
"body": "This may be a slightly too strong point. I'd consider things like creating an empty list to be safe (and rather pointless to inject). If the object has some initial value though, sure. If it's really just a new `object`, it's messier to inject it. Nothing outside needs to know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:41:58.497",
"Id": "82204",
"Score": "5",
"body": "That unnecessarily exposes a private variable to meddling from others. For example, some other code could then take a lock on `syncRoot`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:31:58.877",
"Id": "82219",
"Score": "0",
"body": "@Magus Sometimes it's very useful to write own lists with own interfaces; at least you can have own interface, and wrap an usual list to think about it later. Passing correct arguments to the constructor is factories' job; empty object can be perfect correct argument, look at it's interface - it provides some useful values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:38:34.970",
"Id": "82221",
"Score": "0",
"body": "@200_success Document it: <please_no_locks_here />"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:48:14.857",
"Id": "82224",
"Score": "2",
"body": "`syncRoot` does not look like a dependency, therefore I would not use dependency injection on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:18:01.057",
"Id": "82229",
"Score": "0",
"body": "@Matthew In my code - yes, you're right. I missed original `...` dependency usage operator"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:19:53.237",
"Id": "82231",
"Score": "0",
"body": "Syncroot should not be injected as anything else that has a reference to it might also lock on it thus creating a deadlock. And if that 4th law really means what you claim, I'd say its bogus."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:22:54.477",
"Id": "82232",
"Score": "0",
"body": "new tag for @Andy: `<please_no_dead_locks_here />` or `<please_no_any_type_of_locks_here />`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:39:13.153",
"Id": "82238",
"Score": "0",
"body": "Just because you comment like that does not mean it will happen. Image two classes that need a sync root, how do you even know someone confined the container correctly so that the each get their own instance? you don't, and you'll only find out at runtime when you get hard to reproduce deadlocks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:47:23.000",
"Id": "82242",
"Score": "0",
"body": "@Andy Any module can't be sure that outside world will use it correctly. In the case of runtime deadlock you must search bugs starting from Composition Root - to be sure you're using your own system correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:49:34.417",
"Id": "82243",
"Score": "1",
"body": "Or you just new the syncLock object in the ctor and not waste hours of time debugging based on some unthinking religious belief, leaving you with one less problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:50:11.450",
"Id": "82244",
"Score": "0",
"body": "@Andy You can not protect any object from locking on it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:55:50.093",
"Id": "82246",
"Score": "0",
"body": "If its private a developer has to work hard to break things and cause a deadlock. Injecting the syncLock makes a deadlock that much easier to do by accident . DI is not a solution with zero drawbacks, and blindly following \"laws\" is just going to bite you in the ads."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:48:04.010",
"Id": "46931",
"ParentId": "46918",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": "46925",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:09:21.930",
"Id": "46918",
"Score": "7",
"Tags": [
"c#",
"constructor"
],
"Title": "What is the advantage/disadvantage of using default initializer for private fields?"
} | 46918 |
<p>I was having a hard time with bug <a href="https://logstash.jira.com/browse/LOGSTASH-665" rel="nofollow">logstash#665</a>. Hope they will fix it some day, but sparc/solaris support is probably not on top of their priority list. For further reference, original error is:</p>
<pre><code>NotImplementedError: stat.st_dev unsupported or native support failed to load dev_major at org/jruby/RubyFileStat.java:190
_discover_file at /tmp/aaaa/logstash-1.4.1.dev/vendor/bundle/jruby/1.9/gems/filewatch-0.5.1/lib/filewatch/watch.rb:140
</code></pre>
<p>After digging a lot I found out that the problem here is the usage of a native library which is not correclty retrieved on Solaris. So when ruby fails, it is trying a fallback to java, which fails as well. Now I have retrieved the original <a href="https://github.com/jordansissel/ruby-filewatch/blob/690206fd73a5a1b60122c4dca73c2381b55edbcd/lib/filewatch/watch.rb" rel="nofollow">watch.rb source file</a> and isolated the problematic function:</p>
<pre><code>private
def _discover_file(path, initial=false)
globbed_dirs = Dir.glob(path)
@logger.debug("_discover_file_glob: #{path}: glob is: #{globbed_dirs}")
if globbed_dirs.empty? && File.file?(path)
globbed_dirs = [path]
@logger.debug("_discover_file_glob: #{path}: glob is: #{globbed_dirs} because glob did not work")
end
globbed_dirs.each do |file|
next if @files.member?(file)
next unless File.file?(file)
@logger.debug("_discover_file: #{path}: new: #{file} (exclude is #{@exclude.inspect})")
skip = false
@exclude.each do |pattern|
if File.fnmatch?(pattern, File.basename(file))
@logger.debug("_discover_file: #{file}: skipping because it " +
"matches exclude #{pattern}")
skip = true
break
end
end
next if skip
stat = File::Stat.new(file)
@files[file] = {
:size => 0,
:inode => [stat.ino, stat.dev_major, stat.dev_minor],
:create_sent => false,
}
if initial
@files[file][:initial] = true
end
end
end # def _discover_file
</code></pre>
<p>More precisely, the bug was happening there:</p>
<pre><code> stat = File::Stat.new(file)
@files[file] = {
:size => 0,
:inode => [stat.ino, stat.dev_major, stat.dev_minor],
:create_sent => false,
}
</code></pre>
<p>So I a tried to understand what those two lines do and how to work them around to somehow have something which works. For reference, documentation says:</p>
<blockquote>
<p>dev_major() public</p>
<p>Returns the major part of File_Stat#dev or nil.</p>
</blockquote>
<p>After some experimentation, I concluded that since this function can return nil, I could just replace the call of the function by nil like this:</p>
<pre><code>stat = File::Stat.new(file)
@files[file] = {
:size => 0,
:inode => [stat.ino, nil, nil],
:create_sent => false,
}
</code></pre>
<p>Just replaced _stat.dev_major_ and _stat.dev_minor_ by <em>nil</em>, launched the program, and it worked. Now I did not test a lot but everything seems to work fine. </p>
<p>So I need your reviews for that last snippet of code which is of my own: The program seems to be bearing with it, but is it really safe to do this? </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T04:59:29.643",
"Id": "82701",
"Score": "0",
"body": "Just to be clear — the bug is that `File::Stat.new('/etc/hosts').dev_minor` would cause JRuby to crash with a `NotImplementedError`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:46:32.683",
"Id": "82719",
"Score": "0",
"body": "In my understanding, that part of the code should be used by a ruby equivalent of unix \"tail -F\" command (see [tail.rb](https://github.com/jordansissel/ruby-filewatch/blob/690206fd73a5a1b60122c4dca73c2381b55edbcd/lib/filewatch/tail.rb) from same source directory), so I would assume that the opened file is the followed one, eg /home/foo/nfsmounts/serverN/myapplication.log. The bug is that the system library containing actual implementation for dev_major/dev_minor is not found on Solaris (although it should exist)"
}
] | [
{
"body": "<p>In Unix filesystems, an inode is a number that uniquely identifies a file within the filesystem. (More strictly speaking, an inode is a data structure that holds metadata about a file within the filesystem; each inode is assigned an inode number, and the number is all you care about unless you're a kernel developer.)</p>\n\n<p>However, the inode number only uniquely identifies a file <em>within its filesystem</em>. If <code>/tmp</code> and <code>/usr</code> are separate filesystems, inode 3461 of the <code>/tmp</code> filesystem might be <code>/tmp/.ICE-unix</code> while inode 3461 on <code>/usr</code> might be <code>/usr/share/dict/words</code>. Therefore, to uniquely identify a file on the whole computer, a tuple of (inode number, device major number, device minor number) is needed.</p>\n\n<p>By ignoring the device number, you might end up acting on events on a file with a coincidentally equal inode number on a different filesystem — though the chance is miniscule.</p>\n\n<p>If you decide to keep this workaround, then I think you should make a corresponding change on <a href=\"https://github.com/jordansissel/ruby-filewatch/blob/690206fd73a5a1b60122c4dca73c2381b55edbcd/lib/filewatch/watch.rb#L71\" rel=\"nofollow\">line 71</a> as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T09:43:46.670",
"Id": "82723",
"Score": "0",
"body": "What about opening files remotely mounted through NFS? Is their inode the one of the remote file, or the inode of the symbolic link? Because I am considering opening around 30 of them.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:59:29.310",
"Id": "82743",
"Score": "0",
"body": "nvm, since it is a system related question, I [posted it](http://superuser.com/questions/741958/from-where-comes-the-inode-number-of-a-file-mounted-through-nfs) on _Super User_ Thanks for your help ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:04:38.287",
"Id": "47211",
"ParentId": "46922",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47211",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:18:43.200",
"Id": "46922",
"Score": "5",
"Tags": [
"ruby",
"file-system",
"solaris"
],
"Title": "Need reviews for impacts of dirty bug fix"
} | 46922 |
<p><a href="http://mochajs.org/" rel="nofollow">Mocha</a> is a feature-rich JavaScript test framework running on node.js and the browser. Mocha allows you to use any assertion library you want, if it throws an error, it will work! This means you can utilize libraries such as <a href="https://github.com/shouldjs/should.js" rel="nofollow">should.js</a>, <a href="http://nodejs.org/api/assert.html" rel="nofollow">node's regular assert module</a>, or others. The following is a list of known assertion libraries for node and/or the browser:</p>
<ul>
<li><a href="https://github.com/shouldjs/should.js" rel="nofollow">should.js</a> BDD style shown throughout these docs</li>
<li><a href="https://github.com/mjackson/expect" rel="nofollow">expect.js</a> expect() style assertions</li>
<li><a href="http://chaijs.com/" rel="nofollow">chai</a> expect(), assert() and should style assertions</li>
<li><a href="https://github.com/tj/better-assert" rel="nofollow">better-assert</a> c-style self-documenting assert()</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:19:39.327",
"Id": "46923",
"Score": "0",
"Tags": null,
"Title": null
} | 46923 |
<p>I'm experimenting with angular directives, and as a proof of concept I wanted to create a basic tab control. I'd like to know if anything can be changed to be more fluid, or if I'm doing things "right".</p>
<p>Live Example: <a href="http://jsfiddle.net/6wa2x/">http://jsfiddle.net/6wa2x/</a></p>
<p>HTML (with embedded angular templates):</p>
<pre><code><!doctype html>
<html ng-app="mainModule">
<body>
<tab-control id="MainTabControl" class="red">
<tab name="FirstTab" id="Tab1">
Tab 1 stuff
</tab>
<tab name="SecondTab" id="Tab2" selected>
Tab 2 stuff
</tab>
<tab name="ThirdTab" id="Tab3">
<strong>Tab 3</strong>
</tab>
</tab-control>
<div ng-controller="DynamicTabController">
<tab-control>
<tab ng-repeat="tab in tabs" name="{{tab.name}}" id="{{tab.id}}" selected="{{ $index == 1 }}">
{{tab.name}}
</tab>
</tab-control>
</div>
<script type="text/ng-template" id="tabControlTemplate">
<ul id="{{id}}" class="{{klass}} tab-control">
<li ng-repeat="tab in tabs" ng-class="{ selected: tab.selected }" class="tab" ng-click="selectTab(tab)">{{tab.name}}</li>
</ul>
<section ng-transclude>
</section>
</script>
<script type="text/ng-template" id="tabTemplate">
<article id="{{id}}" ng-class="{ selected: selected}" class="{{klass}} tab-content">
<header>
<h1>{{ name }}</h1>
</header>
<section ng-transclude>
</section>
</article>
</script>
</body>
</html>
</code></pre>
<p>Javascript:</p>
<pre><code>var mainModule = angular.module("mainModule", []);
mainModule.directive('tabControl', function() {
return {
restrict: 'E',
templateUrl: 'tabControlTemplate',
scope: {
id: '@id',
klass: '@class',
},
transclude: true,
controller: ['$scope', function($scope) {
$scope.tabs = []
this.addTab = function(tab){
$scope.tabs.push(tab);
}
$scope.selectTab = function(tab){
for(var i=0; i<$scope.tabs.length; i++){
if(tab.name != $scope.tabs[i].name){
$scope.tabs[i].selected = false;
}
else {
$scope.tabs[i].selected = true;
}
}
}
}]
};
});
mainModule.directive('tab', function(){
return {
restrict: 'E',
templateUrl: 'tabTemplate',
transclude: true,
replace: true,
scope: {
id: '@id',
name: '@name',
},
require: '^tabControl',
link: function(scope, element, attrs, ctrl) {
scope.selected = attrs.selected == "" || attrs.selected == true
ctrl.addTab(scope);
}
};
});
mainModule.controller("DynamicTabController", ['$scope', function($scope){
$scope.tabs = [
{ name: 'Tab1', id: 'Tab1'},
{ name: 'Tab2', id: 'Tab2'},
{ name: 'Tab3', id: 'Tab3'},
{ name: 'Tab4', id: 'Tab4'},
{ name: 'Tab5', id: 'Tab5'},
{ name: 'Tab6', id: 'Tab6'},
{ name: 'Tab7', id: 'Tab7'}
]
}]);
</code></pre>
<p>CSS:</p>
<pre><code>.tab-control {
list-style: none;
padding: 0;
margin: 5px;
}
.tab-control li {
display: inline;
padding: 5px 20px;
border: 1px solid grey;
border-bottom: 0;
border-radius: 5;
cursor: pointer;
}
.tab-control li.selected {
background-color: lightblue;
}
.tab-content header {
display : none;
}
.tab-content {
border: 1px solid black;
width: 100%;
height: 100%;
display: none;
}
.tab-content.selected {
display: block;
}
</code></pre>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>It seems both <code><tab name=\"FirstTab\" id=\"Tab1\"></code> and <code><tab ng-repeat=\"tab in tabs\" name=\"{{tab.name}}\" id=\"{{tab.id}}\" selected=\"{{ $index == 1 }}\"></code> will share the id <code>Tab1</code>, that's not good</p></li>\n<li><p>I am not sure what the point is of setting <code>name</code> in the elements, <code>id</code> should suffice</p></li>\n<li><p>I am not sure what the point is of <code>tab2ContentTemplate</code>, deleting it does not change functionality</p></li>\n<li><p>This : </p>\n\n<pre><code>if (tab.name != $scope.tabs[i].name) {\n $scope.tabs[i].selected = false;\n} else {\n $scope.tabs[i].selected = true;\n}\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>$scope.tabs[i].selected = ( tab.name == $scope.tabs[i].name );\n</code></pre></li>\n<li><p>There are some minor style issues you could find/solve by using jshint.com</p></li>\n</ul>\n\n<p>All in all, I find the HTML part very hard to follow, only after playing with it for a while did I really grasp what you are doing. You should carefully review the <code>id</code>'s you employ. For example: <code>tabTemplate</code> <- I would call this <code>articleTemplate</code> perhaps ?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T16:50:21.520",
"Id": "83228",
"Score": "0",
"body": "Yes, in this example your right, both FirstTab and the ng-repeated will end up with the same id, it was more an example using static tabs vs dynamically created tabs. Id can suffice, the difference was to allow id to be the tabs identifier, whereas the name is what's displayed on the tab itself. tab2Content template was removed, your right it wasn't used in the example (copy paste error). I don't agree to renaming tabTemplate to articleTemplate, the template is more about the tab content (using article in this case as an example.) maybe \"TabContentTemplate\". Thank you very much 4 the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T18:13:51.327",
"Id": "47380",
"ParentId": "46927",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:27:18.567",
"Id": "46927",
"Score": "7",
"Tags": [
"javascript",
"angular.js"
],
"Title": "AngularJS Tab Control"
} | 46927 |
<p>The purpose of the below code is to build a shape based on the user input, specifically:</p>
<ol>
<li>Prompt the user to enter a shape - either a triangle or a square</li>
<li>Determine which "texture" to use for the shape - currently set at <code>#</code>'s for squares, <code>*</code>'s for triangles</li>
<li>Build the shape based on the selected texture</li>
</ol>
<p>Sample output for "Square":</p>
<pre><code>#####
#####
#####
</code></pre>
<p>Sample output for "Triangle":</p>
<pre><code>*
**
***
****
*****
</code></pre>
<p>How can I completely redo the structure and flow of the program to better follow convention, especially in regards to the way the classes are structured? I still want use multiple classes however, as the main thing i'm trying to do here is work out how to use classes properly. Any other general refactoring welcome too. </p>
<p>Also sorry for the tab spacing. It's set to 2, but is a lot more when I paste it here.</p>
<pre><code># Shape Builder v0.1
class BuildShape
def buildShapeCheck
if @text == "square"
self.buildSquare
else
self.buildTriangle
end
end
def buildSquare
(1..3).each do
puts @texture*5
end
end
def buildTriangle
j = 1
(1..5).each do
puts @texture*j
j += 1
end
end
end
class Textures < BuildShape
def shapeCheck
@texture = ""
if @text == "square"
@texture = "#"
buildShapeCheck
else
@texture = "*"
buildShapeCheck
end
end
end
class UserInput < Textures
def initialize(text)
@text = text
end
def printInput
print "you entered: "
puts @text
self.testIfValid
end
def testIfValid
if @text == "square" || @text == "triangle"
puts "#{@text} is a valid shape."
shapeCheck
else
puts "#{@text} is not a valid shape, try again"
newUserInput = UserInput.new(gets.chomp.downcase)
newUserInput.testIfValid
end
end
end
puts "Enter either \"triangle\" or \"square\""
user_input = gets.chomp
newUserInput = UserInput.new(user_input.downcase)
newUserInput.printInput
</code></pre>
| [] | [
{
"body": "<p>Ok, so... there's <em>a lot</em> to talk about here. I've simply gone through it line by line, and added comments. So prepare for a pretty long review.</p>\n\n<p>As for the indentation, the reason it's different when you paste it here is probably that you're still using <em>tabs</em>. It should be <em>soft tabs</em>, i.e. just 2 space characters. Not 1 tab character set to be 2 characters wide, but actual spaces.</p>\n\n<p>Anyway, long review incoming.</p>\n\n<pre><code># BuildShape is a poor name for a class. Classes should generally be nouns,\n# but \"Build shape\" is an imperative. It's true that the class does build a\n# shape, but the class in itself is not \"the act of building\".\nclass BuildShape\n\n # This class has no \"initialize\" method, but because its parent\n # class (which is Object, when nothing else is specified) has one,\n # I can still call \"BuildShape.new.buildSquare\" (for instance). But\n # if I do, things will be weird, because @text and @texture haven't\n # been defined. And without an initialize method (or attribute\n # setters), there's no way to define them.\n\n\n # Don't duplicate the name of the class in the names of its methods.\n # There's simply no need to do that; you don't need to name a file\n # on your computer after the folder it's in.\n # Also, Ruby uses underscored method names, so if anything, it should\n # be called \"build_shape_check\"\n def buildShapeCheck\n if @text == \"square\"\n self.buildSquare # no need for \"self.\" here\n else\n self.buildTriangle # or here\n end\n end\n\n # This produces a 5x3 rectangle - not a square!\n # It looks like a square because of the font you use to\n # show it, but that's coincidental and may not hold true\n # in all situations. So either make the method produce a\n # real NxN square, or make it very clear in the comments\n # that \"by square, I do not actually mean a square\" (i.e.\n # admit the deceit and its reasons)\n def buildSquare\n (1..3).each do # you could also just use \"3.times do\"\n puts @texture*5\n end\n end\n\n # again: Underscore naming style\n def buildTriangle\n j = 1 # This is completely unnecessary...\n (1..5).each do # ...if you just add |j| as a block argument\n puts @texture*j\n j += 1 # And then this can go too\n end\n end\nend\n\n\n# When I said \"classes should be nouns\" I meant *singular* nouns.\n# The String class is not called \"Strings\" for instance.\n# If anything, this should be called \"Texture\"\n# But more importantly, this class doesn't make sense. You use\n# class inheritance because you have a generic class and want to\n# make a specialization of that class. E.g. you have a class called\n# \"Vehicle\", and you make a class called \"Car\" or \"Boat\". Those are\n# specializations of a common thing: a vehicle.\n# But here, you seem to be making a new class for a completely\n# different reason - a reason I can't quite figure out.\nclass Textures < BuildShape\n\n # Again, no initialize method...\n\n # Again you're kinda-sorta repeating the name of the class\n # in the method name, because - due to inheritance - this class\n # is a BuildShape. It'd be enough to call the method \"check\".\n # ... buuut, this method isn't checking anything, so it'd\n # still be a terrible name.\n def shapeCheck\n # This is unnecessary; @texture *will* be set to either \"#\"\n # or to \"*\" - there's no reason to set it to anything else\n # beforehand.\n @texture = \"\"\n\n # Another thing is that this method is pointless in many ways.\n # You can't set the @texture variable anywhere else, which means\n # @texture is 100% dependent on what @text is. Which, in turn,\n # means you can just figure out the right texture when you're\n # drawing the shape. You don't even need the @texture variable;\n # the methods that print the shape are already different depending\n # on whether you want a triangle or a square; they can just print\n # the correct character themselves.\n if @text == \"square\"\n @texture = \"#\"\n\n # Don't call this here, *and* in the else-block: Call it *after*\n # the if-else instead, since you want to call independent of\n # what the @text is\n buildShapeCheck\n else\n @texture = \"*\"\n buildShapeCheck # Again: Delete this\n end\n end\nend\n\n\n# Ok, this is a better name of a class. UserInput sounds like a\n# class name. But of course, your inheritance chain is saying that\n# \"UserInput is a kind of Textures, which is a kind of BuildShape\"\n# Do you see how that doesn't make sense?\n# It also highlights why the other classes are problematic: You\n# can't use them on their own. Only after 2 levels of inheritance\n# do you get the class that actually solves the task. The preceding\n# classes don't solve anything by themselves, you're simply\n# treating them as stepping stones to the class you actually want.\n# They're dependent on you extending them, which, to reuse the\n# analogy from earlier, is like saying that vehicles don't work\n# until someone builds a boat; it's backwards.\nclass UserInput < Textures\n\n # Yay! An initialize method!\n def initialize(text)\n @text = text\n end\n\n # Ok, it prints the input - but it also checks the input\n # and that's not at all obvious. Your methods should only\n # do what it says on the tin.\n def printInput\n print \"you entered: \" \n puts @text\n self.testIfValid\n end\n\n # Uh, no. The name of this method is again pretty wrong.\n # Does it mean \"it only does its test, if things are valid\"?\n # The Ruby-like name for this thing would be \"valid?\"\n # And again, the method isn't just testing; it's also\n # the method that actually produces the output! AND it\n # completely duplicating code from *outside* the class.\n # What's worse, it creates a instance of itself, within\n # itself, and... honestly, I don't know how to best explain\n # how weird this is. Sorry, but that the case.\n def testIfValid\n if @text == \"square\" || @text == \"triangle\"\n puts \"#{@text} is a valid shape.\"\n shapeCheck\n else\n puts \"#{@text} is not a valid shape, try again\"\n newUserInput = UserInput.new(gets.chomp.downcase)\n newUserInput.testIfValid\n end\n end\nend\n\n# If you just used single quotes, you wouldn't have to escape\n# the inner double quotes...\nputs \"Enter either \\\"triangle\\\" or \\\"square\\\"\"\n\n# Terrible naming: \"user_input\" is *not* a UserInput object;\n# that's \"newUserInput\"! Which, again, shouldn't be CamelCased\n# and just plain shouldn't be called that.\nuser_input = gets.chomp\nnewUserInput = UserInput.new(user_input.downcase)\n\n# So... when you say printInput, you actually mean\n# \"do everything and print the *output*\"?\nnewUserInput.printInput\n</code></pre>\n\n<p>Here's a different way of doing things:</p>\n\n<pre><code>def print_triangle(size = 5)\n size.times { |count| puts \"*\" * count }\nend\n\ndef print_square(size = 5)\n size.times { puts \"#\" * size }\nend\n\nwhile true # loop until further notice\n puts 'Please type either \"triangle\" or \"square\"'\n type = gets.chomp.downcase\n if %w(triangle square).include?(type) # did the user enter something valid?\n send(\"print_#{type}\") # call the proper method\n break # stop looping\n else\n puts \"Sorry, that didn't make sense. Try again.\"\n end\nend\n</code></pre>\n\n<p>And done. I know this doesn't use any class hierarchy or anything like that, but that's also to illustrate that it isn't always necessary. Just because you <em>can</em> doesn't mean you <em>should</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:13:44.690",
"Id": "82208",
"Score": "0",
"body": "`send` accepts string as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:57:41.793",
"Id": "82225",
"Score": "0",
"body": "@UriAgassi Derp, yep, editing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T06:51:22.687",
"Id": "82292",
"Score": "0",
"body": "Thanks, I definitely knew everything was written really badly, just started with Ruby a day or so ago, coming from casually playing around with C in the past. Appreciate the long and detailed answer. I knew I didn't have to use classes here either, I set the challenge arbitrarily to see if I could figure out how they work. The weird parts in the code that you mentioned are there because I was having issues getting the classes to talk with each other without using inheritance, and probably forgot to delete some parts later. Anyway, cheers for the response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:25:58.350",
"Id": "82323",
"Score": "0",
"body": "@user72364 No prob. I can certainly appreciate the wish to use inheritance and so forth, however, I'd pick a different task to really have a chance to do so. Although Uri's answer makes good use of classes, the task is still so simple that it may not be the best case-study for object-oriented design. (cont'd)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:31:25.187",
"Id": "82326",
"Score": "0",
"body": "@user72364 You could try something like the vehicle example I used in my answer, and make a little race where each vehicle type has a given speed. User inputs a number of minutes, and the program prints how far each vehicle got in that time. While the speed * time calculation is common for all vehicles, some have extra concerns: A plane needs to taxi before take-off, taking X minutes; a car will run out of gas after X minutes and needs to refuel (which takes some time); a ship is just slow but steady. So while they're all vehicles, they're still qualitatively different."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:49:51.723",
"Id": "46951",
"ParentId": "46928",
"Score": "4"
}
},
{
"body": "<p>You are interested in how to use classes properly, so let's talk about it.</p>\n\n<p><strong>Design your classes</strong><br>\nWhy did you choose to split the functionality as you did? Does you <code>BuildShape</code> have any stand alone value? Does it have any re-use value?<br>\nIn ruby it is very easy to arbitrarily break functionality into different classes, because you can call methods and members which are not there, and only in runtime they are checked.<br>\nThis does not mean you <em>should</em> arbitrarily break functionality into different classes - quite the opposite! It is the developers <em>responsibility</em> to design his classes well.</p>\n\n<p><strong>How should you design this?</strong><br>\nWhat are the <em>actors</em> in this exercise? </p>\n\n<ul>\n<li>We need to prompt the user to choose a shape</li>\n<li>We need to draw a shape</li>\n<li>We need to draw a square</li>\n<li>We need to draw a triangle</li>\n</ul>\n\n<p>So, we could break it down to 4 classes (with inheritance) - <code>ShapeFactory</code>, <code>Shape</code>, <code>Square < Shape</code>, <code>Triangle < Shape</code>.<br>\n<code>Shape</code> contains the functionality that is relevant to both <code>Square</code> and <code>Triangle</code> (like having texture), and the <code>ShapeFactory</code> is used to decide which shape to draw.</p>\n\n<pre><code>class Shape\n def initialize(texture, size)\n @texture = texture\n @size = size\n end\nend\n\nclass Triangle < Shape\n def draw\n @size.times { |i| puts @texture * i }\n end\nend\n\nclass Square < Shape\n def draw\n @size.times { puts @texture * @size }\n end\nend\n\nmodule ShapeFactory\n def self.create_shape(shape_name)\n case shape_name\n when 'square'\n Square.new('#', 5)\n when 'triangle'\n Triangle.new('*', 5)\n end\n end\nend\n</code></pre>\n\n<p>Now all you have to do is prompt the user:</p>\n\n<pre><code>puts 'Enter either \"triangle\" or \"square\"'\nshape_name = gets.chomp\nprint \"you entered: \" \nputs shape_name\nuntil shape = ShapeFactory.create_shape(shape_name)\n puts \"#{shape_name} is not a valid shape, try again\"\n shape_name = gets.chomp\nend\nputs \"#{shape_name} is a valid shape.\"\nshape.draw\n</code></pre>\n\n<p><strong>Some notes about the code</strong><br>\nThis is, of course a very elaborate design for a very simple assignment, and it is not optimal (<code>Shape</code> assumes that all you need is <code>@texture</code> and <code>@size</code>, which might not be true to a lot of other shapes, and hold very little merit on its own - but I wanted to show some inheritance). </p>\n\n<p>Note though that each method <em>does only what it is supposed to do</em>: <code>create_shape</code> just <em>creates a shape</em> - it does not prompt the user, and it does not print anything; <code>draw</code> only <em>draws the relevant shape</em>, etc. This makes the code more readable and maintainable. </p>\n\n<p>Note also, that the class I don't want anyone to instantiate, I wrote as a <code>module</code> rather than a <code>class</code>. A <code>module</code> cannot be instantiated, but can be <code>included</code> or <code>extended</code> in other classes. Also, its class methods (the ones starting with <code>self.</code>) can be called like class methods in classes, so it is an easy way to create singleton methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T06:55:15.043",
"Id": "82293",
"Score": "0",
"body": "Thanks, I knew the classes weren't needed at all, but this is a good overview of how to use inheritance correctly, which is one the things I was trying to figure out. Cheers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:45:21.313",
"Id": "46962",
"ParentId": "46928",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46951",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:28:27.763",
"Id": "46928",
"Score": "6",
"Tags": [
"beginner",
"ruby",
"formatting"
],
"Title": "Building shape based on user input"
} | 46928 |
<p>The following code achieves what I require, reading 10000 rows at a time:</p>
<pre><code>var query = repository.Subscribers.ToList().Skip(numberToSkip).Take(numberInBatch);
</code></pre>
<p>Is there an alternative which will make this faster?</p>
<p>Here's the full code:</p>
<pre><code>protected static string ContactUrl = BaseUrl + "/api/contact";
protected static int NumberInBatch = 10000;
protected static int NumberToSkip = 10000;
protected static int NumberToCountUpto = 100000;
public static string GetSubscribers(int numberToSkip, int numberInBatch)
{
using (var repository = new SubscriberEntities())
{
var index = 0;
string output = null;
var query = repository.Subscribers.ToList().Skip(numberToSkip).Take(numberInBatch);
foreach (var subscriber in query)
{
var telephone = ContactHelper.GetTelephoneFromEmail(subscriber.EmailAddress);
string requestCreateContact = RequestHelper.CreateContact(subscriber.EmailAddress, telephone);
if (index > 0) output = output + ",";
output = output + (requestCreateContact);
}
return output;
}
}
//Batch Create
public static void SendBatchCreate()
{
for (int i = NumberToSkip; i < NumberToCountUpto; i += NumberInBatch)
{
var requestCreateMultipleContacts = GetSubscribersAndCreateContacts(i, NumberInBatch);
RequestHelper.SubmitPostRequest(requestCreateMultipleContacts, ContactUrl);
}
Console.ReadKey();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:15:42.347",
"Id": "82280",
"Score": "0",
"body": "A simple way to speed up the `Skip().Take()` LINQ expression is to use `GetRange()` instead. I learnt that the hard way!"
}
] | [
{
"body": "<p>I would first suggest <a href=\"http://msdn.microsoft.com/en-US/data/dn469464\">logging the database operation</a> to see what SQL is executed. EF may not be running the SQL you think it is.</p>\n\n<p><strong>The red flag I see is that you call ToList before the Skip and Take.</strong> Generally in LINQ statements, ToList forces execution immediately.</p>\n\n<p>This suggests your EF code is pulling every record from the table up front, building a list, and <em>then</em> applying the Skip/Take to the list. If that's the case, the logged SQL should show a select statement without any filtering.</p>\n\n<p>I suspect what you really <em>want</em> to do is run the ToList after the Skip and Take. This should apply the filtering inside the executed SQL, but the logging will show you for sure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:01:39.113",
"Id": "82256",
"Score": "2",
"body": "Calling `ToList` will *definitely* materialize the query, and the rest of the chained LINQ calls operate with *Linq-to-Objects* in memory, on the client. A profiler will show something like `SELECT [all fields] FROM Subscribers`, embedded in an `sp_executesql` call."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:11:30.917",
"Id": "46943",
"ParentId": "46940",
"Score": "16"
}
},
{
"body": "<blockquote>\n<pre><code>var query = repository.Subscribers.ToList().Skip(numberToSkip).Take(numberInBatch);\n\nforeach (var subscriber in query)\n{\n var telephone = ContactHelper.GetTelephoneFromEmail(subscriber.EmailAddress);\n\n\n string requestCreateContact = RequestHelper.CreateContact(subscriber.EmailAddress, telephone);\n if (index > 0) output = output + \",\";\n output = output + (requestCreateContact);\n\n}\nreturn output;\n</code></pre>\n</blockquote>\n\n<p>The name <code>query</code> isn't appropriate here, because you've materialized the actual query with <code>ToList</code> and filtered it with <em>Linq-to-Objects</em>.</p>\n\n<p>This would do it:</p>\n\n<pre><code>var query = repository.Subscribers.Skip(numberToSkip).Take(numberInBatch);\n</code></pre>\n\n<p>Now the query hasn't executed yet, <em>because you haven't iterated it</em>. That's how <em>Linq-to-Entities</em> works (<em>Linq-to-SQL</em> works the same way), the materialization of the query is deferred to the very last possible moment, which enables you to return the <code>IQueryable<T></code> and keep adding to it (say, with a <code>Where</code> clause), all the while without hitting the database server.</p>\n\n<p>You don't <em>need</em> to call <code>ToList</code>: <em>iterating</em> it is enough.</p>\n\n<hr>\n\n<p>Another performance-related issue you have here, is that you're concatenating the <code>output</code> string in a loop. This is bad, because a <code>string</code> is an immutable object in .NET, so you're creating many, many, many objects here, without even noticing.</p>\n\n<p>The solution is to use a <code>StringBuilder</code> instead of straight concatenations. This code should run much faster with 10K rows:</p>\n\n<pre><code>var query = repository.Subscribers.Skip(numberToSkip).Take(numberInBatch);\nvar builder = new StringBuilder();\n\nforeach (var subscriber in query)\n{\n var telephone = ContactHelper.GetTelephoneFromEmail(subscriber.EmailAddress);\n var contact = RequestHelper.CreateContact(subscriber.EmailAddress, telephone);\n\n if (index > 0) // is this condition ever true?\n {\n builder.Append(\",\");\n }\n\n builder.Append(contact);\n}\n\nreturn builder.ToString();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:26:59.050",
"Id": "46973",
"ParentId": "46940",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T16:31:51.380",
"Id": "46940",
"Score": "6",
"Tags": [
"c#",
"performance",
"entity-framework"
],
"Title": "Entity Framework Skip and Take too slow"
} | 46940 |
<p>For full disclosure: this is an assignment for my programming class and I just want tips or advice on some of the code.</p>
<p>Assignment details just for background information purposes:</p>
<blockquote>
<p>Write a program that will read a number 1-100 from the user, and the
name of a data file, and will tell the user what word is in the file
and how many times the numbers shows up in the data file. Validate
input number (keep asking until valid) and validate the file was
successfully open.</p>
<p>text file contents: Darling 10 20 21 19 20</p>
</blockquote>
<hr>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // Needed for exit()
using namespace std;
int main()
{
ifstream inputFile;
string fileName;
int value;
cout << "Enter the file name: ";
getline(cin, fileName);
// Open the file
inputFile.open(fileName.c_str());
// Check for successful opening
if(inputFile.fail())
{
cerr << "Error Opening File" << endl;
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n";
cout << "Pick a number between 1 through 100. ";
cin >> value;
if (value >= 1 && value <= 100)
{
cout << value << " is in the acceptable range.\n";
}
else
{
cout << "Please enter a number from 1 to 100. ";
cin >> value;
}
string word;
int number;
int count = 0;
infile >> number;
// Read a file until you've reached the end
while (!inputFile.eof())
{
if (number == x)
{
sum1++
}
infile >> number;
}
cout << sum1;
while (!inputFile.eof())
{
inputFile >> word;
if (word == "input")
{
count++;
}
}
// Close the file
inputFile.close();
return 0;
}
</code></pre>
<p>Any tips or advice would be greatly appreciated since I'm lost when it comes to the fstream portion of this assignment right now.</p>
<p>UPDATED</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // Needed for exit()
using namespace std;
int main()
{
ifstream inputFile;
string fileName;
int value, x;
cout << "Enter the file name: ";
getline(cin, fileName);
// Open the file
inputFile.open(fileName.c_str());
// Check for successful opening
if(inputFile.fail())
{
cerr << "Error Opening File" << endl;
return(1);
}
cout << "Pick a number between 1 through 100. ";
cin >> value;
do
{
cout << "Pick a number between 1 through 100. ";
int value;
cin >> value;
} while (value < 1 || value > 100);
string word;
int number;
int count = 0;
infile >> number;
// Read a file until you've reached the end
while (!inputFile.eof())
{
if (number == x)
{
sum1++
}
inputFile >> number;
}
cout << sum1;
while (!inputFile.eof())
{
inputFile >> word;
if (word == "input")
{
count++;
}
}
// Close the file
inputFile.close();
return 0;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Despite what you may have been taught, you should not get into the habit of using <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>, especially when you start writing larger programs.</p></li>\n<li><p>Since you're in <code>main()</code>, you should just <code>return 1</code> instead of calling <code>exit(1)</code>. The latter is only necessary in other places from which you will need to terminate early.</p></li>\n<li><p>You don't need to display an output if the file was successfully opened. You'll know it failed if the program terminates after asking for a filename.</p></li>\n<li><p>Do not use <code>std::eof()</code> for detecting the end of the file. It will look for the eof bit <em>after</em> reading the end of the stream (and will not even consider errors in reading (i.e. bad bit)). Read <a href=\"https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong\">this</a> for more information.</p>\n\n<p>Instead, read from the file <em>and</em> check for the bad bit using <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a>:</p>\n\n<pre><code>while (std::getline(std::cin, line))\n{\n // ...\n}\n</code></pre></li>\n<li><p>You ask the user for input, but you only validate it once. If the user enters an invalid value a second time, the program will continue, causing problems. All of that should be in a loop that will terminate once the user provides valid input.</p>\n\n<pre><code>do\n{\n std::cout << \"Pick a number between 1 through 100. \";\n std::cin >> value;\n\n} while (value < 1 || value > 100);\n</code></pre></li>\n<li><p>You don't need <code>return 0</code> at the end of <code>main()</code>. Reaching the end already implies a successful termination, so the compiler will do this return for you.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:21:50.063",
"Id": "82200",
"Score": "0",
"body": "By changing the return 0 to return 1 in place of the exit() the loop would return a true value. Is that a correct conclusion from one of your bullet points?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:27:49.043",
"Id": "82202",
"Score": "0",
"body": "@jal3524: I mean changing the `exit(1)` to `return 1`. The former is for cases where you must exit from a different function (such as a `void` function). Other than that, you don't have any loops that return at the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:33:18.527",
"Id": "82284",
"Score": "1",
"body": "`do { std::cin >> value; } while (value < 1 || value > 100);` can/will loop indefinitely if the user enters something other than a digit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:36:39.853",
"Id": "82285",
"Score": "0",
"body": "@JerryCoffin: Yeah, I just gave a shorter example of this. I could've accounted for all input. I think Loki's answer is much better in regards to this anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:38:49.017",
"Id": "82288",
"Score": "2",
"body": "@Jamal: [You have chosen...wisely](https://www.youtube.com/watch?v=-_IlNbsILLE)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:57:30.367",
"Id": "46947",
"ParentId": "46946",
"Score": "5"
}
},
{
"body": "<p>Everything @Jamal said:</p>\n\n<p>When reading user input prefer not mix <code>getline()</code> with <code>operator>></code> as one reads and discards new line while the other does not and this can cause confusion as to where on the input stream you are.</p>\n\n<p>Secondly user input (when done manually) is usually line based (ie the input buffer is not flushed until they hit return). So it is best to read a whole line at a time then validate it.</p>\n\n<p>Remember scope:</p>\n\n<pre><code>int value; // This is the value being used in the while condition.\n\n// STUFF\n\ndo\n{\n cout << \"Pick a number between 1 through 100. \";\n\n int value; // This is the value you are\n // reading from user input and has nothing to \n // do with the variable value in the outer scope.\n\n // It is usually a bad idea to shadow variables\n // in the outer scope like this as it causes confusion.\n // so turn your compiler warning up so that the compiler\n // warns you about variable shadowing.\n\n // Then tell your compiler to treat all warnings as\n // errors (as all warnings are really logicall errors\n // in your code).\n\n cin >> value;\n\n // This while\n // is testing the variable `value` that is defined in the outer\n // scope (which is not what you want).\n} while (value < 1 || value > 100);\n</code></pre>\n\n<p>You must also check for invalid input.</p>\n\n<pre><code>int value;\nstd::cin >> value;\n</code></pre>\n\n<p>What happens if I type 'fred<enter>'?<br>\nPersonally I have forgotten if the variable is even changed (its in the standard somewhere). But the stream has its <code>bad</code> bit set. This means any further attempt to read from the stream will result in nothing happening so you can't even do it in a loop.</p>\n\n<pre><code>int value = 0; // make sure it has an initial value so\n // the while() test is valid even if the\n // user enters junk.\ndo\n{\n std::cout << \"Enter a value\\n\";\n std::cin >> value;\n}\nwhile (value < 1 || value > 100);\n</code></pre>\n\n<p>If I type 'fred' then this will enter an infinite loop (even if the user enters 10 next time around). Because the <code>bad</code> bit has been set and nothing will be read from the stream while this bit is set (its set because you are trying to read an int and you got fred (which is not an int)).</p>\n\n<p>Don't declare all your variables at the top of the function.</p>\n\n<pre><code>ifstream inputFile;\nstring fileName;\nint value, x;\n</code></pre>\n\n<p>Declare them as close to the point where you use them as possible (it makes reading the code easier). Also in C++ we sometimes (quite often) use the side affects of the constructor/destructor to do work. So you don't want those firing until you need them to fire.</p>\n\n<pre><code>std::cout << \"What is the file name?\\n\"; // Don't forget the '\\n'\nstd::string fileName;\nstd::getline(std::cin, fileName);\n</code></pre>\n\n<p>When testing a stream state best to use <code>bad</code> rather than any of the other states (as this catches all failures). Also note that when a stream is used in a boolean context (ie in an <code>if statements</code> condition) it converts itself into a value compatible with the context using the <code>bad()</code> method as a test.</p>\n\n<pre><code>std::ifstream file(fileName.c_str());\nif (!file) // don't need to call any functions.\n{ // This calls `bad()` and converts\n // the result into a value useful for a test\n // true if it is open and readable or false otherwise\n // so !file is only true if you can read the file.\n return 1;\n}\n</code></pre>\n\n<p>The same apples for <code>eof()</code> as it does <code>fail()</code>. Don't use it. Prefer <code>bad()</code>.</p>\n\n<pre><code>while (!inputFile.eof())\n// This will result in an infinite loop if the bad bit is set.\n</code></pre>\n\n<p>Also note that the stream operator <code>operator>></code> returns a reference to the stream. Which (as stated above) when used in a boolean context will convert itself to value that is useful using <code>bad()</code></p>\n\n<pre><code> while(file >> value)\n {\n // Loop is entered every time the read works.\n // This is because `file >> value` returns a reference to a stream.\n // When a stream is used in a boolean context like while(<stream>)\n // weill test itself using `bad()`\n }\n</code></pre>\n\n<h3>Conclusion:</h3>\n\n<pre><code>// Always use std::getline to read user input.\n// Always do the read and test in the same condition.\n// Always check for bad bit.\n\nstd::string line;\nint value;\nwhile(std::getline(std::cin, line))\n{\n // Successfully read a line.\n // If we did not enter the loop then we reached eof.\n\n // So now we want to check what the user entered was a number.\n // So convert the user input line into a stream and read a number\n // from it (or try).\n std::stringstream linestream(line);\n if (linestream >> value)\n {\n // You have successfully read a user value.\n // This means the read was good.\n // If there was text on the input then this would have failed.\n if (value >=1 && value <= 100)\n {\n break; // exit the loop\n }\n }\n\n // If we reach here the user either entered invalid data\n // Which caused the the `bad` bit in `linestream` to be set\n // or the value was out of range.\n // Either way we just tell him to retry.\n\n // Note: because we create a new linestream each attempt\n // this effectively resets the `bad` bit. If you want\n // mess around with the bit flags in the stream that \n // is fine but I usually find this easier.\n\n std::cout << \"Hey... Whats up dumb ass you can't read? Number between 1 and 100. Try again:\\n\"\n\n // The outer while loop will the try to get another value.\n\n}\n\nif (std::cin.eof())\n{\n // We failed to get a get a good value.\n // The loop above exited because std::getline() failed\n // This happens when we reach eof thus the value has\n // not been set correctly.\n\n\n return 1; // or exit(1) if appropriate.\n}\n\nstd::cout << \"The value was good: \" << value << \"\\n\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:53:29.700",
"Id": "46955",
"ParentId": "46946",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T17:41:35.527",
"Id": "46946",
"Score": "9",
"Tags": [
"c++",
"homework",
"file",
"stream"
],
"Title": "User input and reading contents of file"
} | 46946 |
<p>I tried making a class that handles my header and footer of my site. It looks like a mess, because I like to preserve the indentations as is.</p>
<p>But I'm wondering if there maybe is an even cleaner or better way of writing this class?</p>
<pre><code><?php
class HeadFoot {
protected $title,
$scripts;
public function __construct($title, $scripts) {
$this->title = $title;
$this->scripts = $scripts;
}
public function getHeader() {
if($this->title) {
$header = <<< EOD
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$this->title - Domain</title>
<link rel="shortcut icon" href="/favicon.ico">
<link rel="stylesheet" href="/stylesheets/init.css">
<link rel="stylesheet" href="/stylesheets/layout.css">
EOD;
if($this->scripts) {
foreach($this->scripts as $script) {
$header .= str_repeat(' ', 8) . $script . "\n";
}
}
$header .= <<< EOD
</head>
<body>
<div id="topbar"></div>
<div id="container">
<div id="header">
<div class="wrapper">
<h1 id="site-name"><a href="/">Domain</a></h1>
</div>
</div>
EOD;
$header .= Navigation::get();
$header .= str_repeat(' ', 12) . "\n";
return $header;
}
return false;
}
public function getFooter($ads = null) {
if($ads) {
return
' <div id="footer">
<p>Copyright © 2014 - Domain.net</p>
<p><a href="#" title="Terms of Service">Terms of Service</a> / <a href="#" title="Privacy Policy">Privacy Policy</a></p>
</div>
</div>
</body>
</html>';
}
return
' <div id="advertisement">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display: inline-block; width: 468px; height: 60px; vertical-align: top;"
data-ad-client="ca-pub-8849502800889803"
data-ad-slot="2598909127"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
</div>
<div id="footer">
<p>Copyright © 2014 - Domain.net</p>
<p><a href="#" title="Terms of Service">Terms of Service</a> / <a href="#" title="Privacy Policy">Privacy Policy</a></p>
</div>
</div>
</body>
</html>';
}
}
</code></pre>
| [] | [
{
"body": "<h1>Separation of Concerns</h1>\n\n<p>You should implement <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separation of Concerns</a>. In your case, don't mix logic with your view. Follow basic MVC, where M (model) is the data source, V (view) is where your HTML is, and C (controller), where all your logic is. In this case, put your HTML in one file, the logic in the other.</p>\n\n<h1>Templating</h1>\n\n<p>One thing that messes up development is when logic is mixed to the template. It makes the template messy and hard to maintain and visualize. I suggest you take a look at the <a href=\"https://github.com/bobthecow/mustache.php\" rel=\"nofollow\">PHP implementation of Mustache templates</a>. In your controller, simply make a function that loads the template to a variable, feeds it to Mustache, put some data in and done.</p>\n\n<h1>Inheritance</h1>\n\n<p>One use of inheritance is to hide utility functions. For instance, you can create a View class, where your future views inherit from. </p>\n\n<h1>End Result</h1>\n\n<p>You can simply do something as simple as this in the controller!</p>\n\n<pre><code>public function index(){\n $myView = new View('path/to/template'); // Create a view\n $myDataSource = new Model('MODEL_NAME'); // Create a model\n $theData = myDataSource->getData(); // Grab data\n $theResultHTML = myView->render($theData); // Render data to template and print\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:54:34.470",
"Id": "46956",
"ParentId": "46950",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46956",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:21:38.117",
"Id": "46950",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"html",
"php5"
],
"Title": "Class that handles header and footer includes looks like a mess"
} | 46950 |
<p>I've been reviewing my previous projects for the last few days. I've found that I never return an error from any of my methods. I always throw exceptions. I googled about exceptions vs errors and I feel like I should return an error if there's an error.</p>
<p>Please consider my service class from my previous project. We have online tutorials on our website and we send out a token (sort of a coupon) to users time to time. Users can redeem the token to get a full access to a certain tutorial on our website.</p>
<pre><code>class TutorialTokenRedeemptionService {
protected $memberRepository;
protected $tutorialRepository;
protected $tokenRepository;
public function __construct(
Repository\TutorialRepositoryInterface $tutorialRepository,
Repository\TokenRepositoryInterface $tokenRepository,
Repository\MemberRepositoryInterface $memberRepository
)
{
$this->memberRepository = $memberRepository;
$this->tutorialRepository = $tutorialRepository;
$this->tokenRepository = $tokenRepository;
}
public function redeem($tokenCode, Entity\MemberInterface $member)
{
// Let's see if we have the token in our system
$token = $this->tokenRepository->findByCode($token);
if( !$token ) {
throw new Exception\TokenNotFound($token);
}
// Let's see if we have the associated tutorial
$tutorial = $this->tutorialRepository->find($token->getBatch()->tutorial_id);
//
if( !$tutorial ) {
throw new Exception\TutorialNotFound($token);
}
$member->addPurchasedTutorial($tutorial);
$this->memberRepository->save($member);
$token->setActivatedBy($member->id);
$this->tokenRepository->save($token);
return new TutorialTokenRedeemptionServiceResult(StatusCodes::OK, $member, $tutorial, $token);
}
}
</code></pre>
<p>It might be considered an exception to users if the token he/she is trying to use is not in our system because users might have more than one token. Users can try other tokens. From the perspective of the <code>TutorialTokenRedeeptionService</code> and its client, it's an error because the service can't continue anymore. Am I going the right way?</p>
<p>What should be better? Throw exceptions all the time or throw exceptions and return errors depending on use cases?</p>
| [] | [
{
"body": "<p>Well, I'd say that, apart from one or two things, you're going about it in exactly the right way.<br>\nA class, and all of its methods process data. If the data supplied poses an exceptional problem (ie, the data is invalid), then an Exception has to be thrown back to the code that passed that data.</p>\n\n<p>The motto is: He who supplies the data, has to handle the errors.<Br>\nBy having methods simply <em>return</em> errors, your class is taking on too many responsibilities: Process data <em>and</em> error handling? No, that is in violation of the single most important SOLID principle: the SRP (Single Responsability Principle).</p>\n\n<p>Here's why I am prepared to defend my statements on throwing exceptions from classes:</p>\n\n<ul>\n<li>A class cannot check if the calling code is checking the return value of its method. You may return <code>false</code> or <code>ERROR</code>, but if the caller doesn't check it, you might aswell return a Shakespeare sonnet...</li>\n<li>If you receive bad data, don't <em>try</em> to make sense of it, or don't <em>try</em> to make it work: the calling code has a bug in it, and should be fixed. The best way to spot the troubled bit of code is to <code>throw new InvalidArgumentException</code> and look at the stack-trace. Like I said before: bad arguments received often means bad code is calling your method: FIX IT.</li>\n<li>If your class is well-tested, then it's safe to say that if ever it encounters a scenario where it can't do its job properly, something quite <em><code>Exception</code>-al has happened</em>, treat it accordingly.</li>\n<li>returning error-indicating values makes unit-testing harder, in a way. I, personally, like the odd <code>@expectedException</code> annotation, for example. If the test fails, it also yields more speceific output anyway.</li>\n<li>You don't know what code is going to handle the problem. Returning an error-indicator is all well and good, provided that return value is caught, and indeed returned all the way through to the code that will eventually deal with it. An exception just keeps going until it is caught. If not, the whole application just grinds to a halt. Either way, returning false is less pressing, there's no real <em>incentive</em> to do something. An exception, however, <em>must</em> be handled for the program to go on.</li>\n<li>You cannot register handlers for <code>return false;</code> or <code>return null;</code> statements, but you can register error and exception handlers. And you will do so in larger projects. This, certainly, is a huge advantage of exceptions.</li>\n<li>Returning errors depending on the usage of your class limits the context/use-cases, in which you can use the class. A class should be a self-contained, portable unit of code. It should, therefore, just process data, <strong>or</strong> handle exceptional cases, not both.</li>\n</ul>\n\n<p>Another quick hang-up of mine that I can't have go unmentioned: Please, <em>please</em>, <strong><em>please</em></strong> subscribe to the coding standards, as described by <a href=\"http://www.php-fig.org\" rel=\"nofollow\">PHP-FIG</a>.</p>\n\n<p>Other niggles I have, and I'm really nit-picking here:</p>\n\n<pre><code>throw new Exception\\TokenNotFound();\n</code></pre>\n\n<p>Ok, when I see this throw statement, I know that the <code>TokenNotFound</code> class is extending the <code>Exception</code> core-class (I hope), just like all other classes I might find in the <code>Exception</code> namespace. However, writing <code>namespace Exception;</code> at the top of a file could confuse PHP, if it doesn't already. Also, in files using the <code>use</code> keyword, the complementing <code>catch</code> statement just doesn't look right to me:</p>\n\n<pre><code>use Exception\\TokenNotFound;\ntry\n{\n //stuff\n}\nchatch(TokenNotFound $t)\n</code></pre>\n\n<p>Look at all <code>Exception</code> classes in common use: they all contain the word <code>Exception</code> (or <code>Fault</code> in SoapFault<code>).</code>TokenNotFound<code>could be anything from a mock object, to a handler for just such an exceptional case, when in fact it is the exception object itself. Just append</code>Exception` to the exception class names. You may find this redundant at first, but at some point in time people using your code, or even yourself, will thank you for it.</p>\n\n<pre><code>use Exception\\TokenNotFoundException;\ntry\n{\n //stuff\n}\nchatch(TokenNotFoundException $t)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:06:34.607",
"Id": "82628",
"Score": "0",
"body": "Thank you so much for the insight. I totally agree on the exception part!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T08:00:56.450",
"Id": "47131",
"ParentId": "46952",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:54:19.573",
"Id": "46952",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"exception",
"error-handling"
],
"Title": "Throw exception in favor of an error?"
} | 46952 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.