body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm learning C from the K.N. King book and just arrived at a question to reverse the words in a sentence.</p>
<p>Here is the output:</p>
<blockquote>
<p>Enter a sentence: you can cage a swallow can't you?</p>
<p>Reversal of sentence: you can't swallow a cage can you?</p>
</blockquote>
<p>Though I've done this and it runs correctly, I want to make my code shorter. I'm not asking for any other solution.</p>
<pre><code>#include <stdio.h>
#define N 100
int main(void) {
char ch[N], terminate;
int i, j, k, len;
printf("Enter a sentence: ");
for(i = 0; i < N; i++) {
ch[i] = getchar();
if(ch[i] == '?' || ch[i] == '.' || ch[i] == '!' || ch[i] == '\n') {
len = i; //Determine the length of the string
terminate = ch[i];
break;
}
}
int word_count = 0;
for(j = len - 1; j >= 0; j--) {
word_count++;
if(ch[j] == ' ') {
for(k = j+1; k < len; k++) {
printf("%c", ch[k]);
}
printf("%c", ch[j]); // print space character
len = len - word_count;
word_count = 0;
}
}
for(i = 0; i < len; i++) {
printf("%c", ch[i]);
if(ch[i] == ' ') {
break;
}
}
printf("%c", terminate);
return 0;
}
</code></pre>
<p>This can be done only with loops, arrays, <code>getchar()</code> and <code>putchar()</code> methoda using only <code><stdio.h></code> header and no extra header (restrict <code><string.h></code> header functions and methods). Also, no <code>puts()</code> and <code>gets()</code> functions. I guess this can be done only with two loops.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T22:07:33.743",
"Id": "35290",
"Score": "0",
"body": "Just a note - your reversal is incorrect; it should be \"you can't **swallow** a **cage** can you?\""
}
] |
[
{
"body": "<p>I'm not quite sure if you are aiming only for smaller length or also for better code/readability. Depending on the answer, you can take the following style comments into account (which are somehow pretty personal except for the last one):</p>\n\n<ul>\n<li>In C code, I find it easier to have bigger indentations</li>\n<li>I prefer having a whitespace after keywords such as <code>for</code> and <code>if</code>.</li>\n<li>It's usually recommended to define variables in the smallest possible scope. In your case, if you compile with the <code>-std=c99</code> flag or equivalent, you could define your variables containing indexes at the beginning of your <code>for</code> loops.</li>\n</ul>\n\n<p>This being said, three things I found :</p>\n\n<ul>\n<li><p>Because of the way you increment/update <code>word_count</code> and <code>len</code>, I had the feeling that we would always have the following property at the end of the loop : <code>len == word_count + j</code>. (I guess) you can prove/verify this using <a href=\"http://en.wikipedia.org/wiki/Loop_invariant\" rel=\"nofollow\">loop invariants</a>. This is true just before j gets decremented and this is also true just after word_count gets incremented. In order to be 100%, I used the following macro : <code>#define assert(c) if (!(c)) { printf (\"\" #c \"' is not true!\\n\"); return 0; }</code> and then I added <code>assert(len == word_count+j);</code> after incrementing word_count, after the k-look and at the end of the j-loop and the whole thing worked perfectly convincing me that my feeling was right.<br>\n<strong>TL;DR :</strong> The conclusion of this is that we don't need the <code>word_count</code> variable if you replace <code>len - word_count</code> by <code>j</code>.</p></li>\n<li><p>Because of the way j goes through the array, at the end of the j-loop, <code>len</code> is equal to the smallest index j leading to a space. Thus, we can easily deduce that for i in [0;len[, ch[i] is not a space. You can again verify this with the following assert : <code>assert(ch[i]!=' ');</code>.</p></li>\n<li><p>At this stage, the code is slightly shorter but still we have the same loop appearing twice : <code>for(k = j+1; k < len; k++) printf(...)</code> to print all the words but the last one and <code>for(i = 0; i < len; i++) printf(...)</code> to print the last word. Thus, my last trick was to make the j-loop go one step further (so that it reaches -1 which is pretty good because then your k-loop and your i-loop becomes equivalent as <code>j+1==0</code>) and print the last word. This comes at the cost of additional checks but it does work on your example.</p>\n\n<pre><code>int main(void) {\nchar ch[N], terminate;\nint len;\nprintf(\"Enter a sentence: \\n\");\nfor (int i = 0; i < N; i++) {\nch[i] = getchar();\nif (ch[i] == '?' || ch[i] == '.' || ch[i] == '!' || ch[i] == '\\n') {\n len = i;\n terminate = ch[i];\n break;\n}\n}\n\nfor (int j = len - 1; j >= -1; j--) {\nif (j<0 || ch[j] == ' ') {\n for (int k = j+1; k < len; k++) {\n printf(\"%c\",ch[k]);;\n }\n if (j>=0) {\n printf(\"%c\",ch[j]);;\n len = j;\n }\n}\n\n}\nprintf(\"%c\\n\", terminate);\n\nreturn 0;\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:48:57.147",
"Id": "22925",
"ParentId": "22914",
"Score": "2"
}
},
{
"body": "<p>I have a few comments.</p>\n\n<ol>\n<li><p><code>main</code> takes argc/argv normally. Also start the function with the opening\nbrace in colum 0</p></li>\n<li><p>Define one variable per line.</p></li>\n<li><p>Your request for input might be better printed to stderr so that it can be\nseparated from program output.</p></li>\n<li><p>Your initial loop should test for EOF. Currently it doesn't You can test\nthis in the *NIX shell with (<code>program</code> is your executable):</p>\n\n<pre><code>/bin/echo -n \"hello world\" | ./program\n</code></pre></li>\n<li><p><code>terminate</code> seems redundant</p></li>\n<li><p>You can and perhaps should define loop variables in the loop (as long as\nyou don't need the value outside the loop):</p>\n\n<pre><code>for (int i = 0; i < n; ++i) {\n</code></pre></li>\n<li><p>The second for-loop is a little messy. For a start it has a nested loop -\nmy advice is to avoid nested loops and extract the inner loop to a function.\nThis is not always practical, but more often than not it is useful. In this\ncase, you can write a little function (eg. <code>print_chars</code>) that prints a\nspecified number of characters.</p></li>\n<li><p>Your terminating loop can be replaced by a call to the <code>print_chars</code>\nfunction.</p></li>\n<li><p><code>putchar</code> is preferable to <code>printf(\"%c\", ...)</code></p></li>\n<li><p><code>while</code>, <code>for</code>, <code>if</code> etc should be followed by a space.</p></li>\n<li><p>Testing for ' ' might be better done using <code>isspace</code>, which will test for\nother space-like characters too.</p></li>\n</ol>\n\n<p>Here is my version, for what it is worth:</p>\n\n<pre><code>#include <stdio.h>\n#include <ctype.h>\n\n#define N 100\n\nstatic inline void print_chars(const char *s, long n)\n{\n for (int i = 0; i < n; ++i) {\n putchar(s[i]);\n }\n}\n\nint main(int argc, char **argv)\n{\n char line[N];\n int ch; /* note that ch is an int to allow it to hold 'EOF' */\n int len = 0;\n\n fprintf(stderr, \"Enter a sentence: \");\n\n while ((ch = getchar()) != EOF) {\n if (ch == '?' || ch == '.' || ch == '!' || ch == '\\n' || len >= N-1) {\n break;\n }\n line[len++] = (char) ch;\n }\n line[len] = '\\0';\n\n char *end = line + len;\n char *s = end;\n while (--s >= line) {\n if (isspace(*s)) {\n print_chars(s + 1, end - s - 1);\n putchar(*s);\n end = s;\n }\n }\n print_chars(line, end - line);\n if (ch != EOF) {\n putchar(ch);\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T17:53:16.253",
"Id": "35286",
"Score": "0",
"body": "Thanks for the answer, but I'm at chapter-8 of K.N. king book and upto this function like fprintf, pointers are not covered."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T15:29:57.570",
"Id": "22929",
"ParentId": "22914",
"Score": "4"
}
},
{
"body": "<p>The others have pointed out a lot so I will not repeat them.</p>\n\n<p>But part of programming is spotting code that can be split out into other functions for readability. You have a few places were functions would make the code more readable:</p>\n\n<pre><code>#include <stdio.h>\n\n#define N 100\n\nint endOfSentence(int x) {return x == '?' || x == '.' || x == '!' || x == '\\n';}\nchar* findWord(char* ch, int len)\n{\n if (len == 0)\n {return NULL;}\n\n while(len > 0 && ch[len-1] != ' ')\n {--len;}\n\n return ch+len;\n}\nvoid printWord(char* beg, char* end)\n{\n while(beg != end) {putchar(*beg);++beg;}\n}\n\nint main(void) {\n char ch[N];\n char terminate;\n int i = 0;\n int j, k;\n\n printf(\"Enter a sentence: \");\n while(i < N && !endOfSentence(ch[i] = getchar())) { ++i;}\n\n int len = i; //Determine the length of the string\n terminate = ch[i];\n\n char* word;\n while(len >= 0 && (word = findWord(ch, len)))\n {\n printWord(word, ch+len);\n len = word - ch - 1;\n if (len > 0)\n { putchar(' ');}\n }\n\n putchar(terminate);\n putchar('\\n');\n\n return 0;\n}\n</code></pre>\n\n<p>Fixed:</p>\n\n<pre><code>> gcc 22914.c\n> ./a.out \nEnter a sentence: you can cage a swallow can't you?\nyou can't swallow a cage can you?\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T01:52:14.863",
"Id": "35301",
"Score": "1",
"body": "Sorry, but that is not up to your usual high standard. Try compiling it. When you fix the errors, try running it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T19:00:59.380",
"Id": "35389",
"Score": "0",
"body": "Yes. C is much harder than C++"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:45:47.307",
"Id": "22933",
"ParentId": "22914",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22925",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:48:24.753",
"Id": "22914",
"Score": "4",
"Tags": [
"c",
"strings"
],
"Title": "Reverse a string without the <string.h> header"
}
|
22914
|
<p>I have written a lock free MPMC FIFO in C based on a ring buffer. It uses gcc's atomic built-ins to achieve thread safety. The queue is designed to return -1 if it's full on enqueue or empty on dequeue. </p>
<p>After some feedback, I've changed by design. I have tested this code to work, but testing multithreaded code is hardly enough to prove it's correct. </p>
<pre><code>struct queue
{
void** buf;
size_t num;
uint64_t writePos;
uint64_t readPos;
};
queue_t* createQueue(size_t num)
{
struct queue* new = xmalloc(sizeof(*new));
new->buf = xmalloc(sizeof(void*) * num);
memset(new->buf, 0, sizeof(void*)*num);
new->readPos = 0;
new->writePos = 0;
new->num = num;
return new;
}
void destroyQueue(queue_t* queue)
{
if(queue)
{
xfree(queue->buf);
xfree(queue);
}
}
int enqueue(queue_t* queue, void* item)
{
for(int i = 0; i < kNumTries; i++)
{
if(__sync_bool_compare_and_swap(&queue->buf[queue->writePos % queue->num], NULL, item))
{
__sync_fetch_and_add(&queue->writePos, 1);
return 0;
}
}
return -1;
}
void* dequeue(queue_t* queue)
{
for(int i = 0; i < kNumTries; i++)
{
void* value = queue->buf[queue->readPos % queue->num];
if(value && __sync_bool_compare_and_swap(&queue->buf[queue->readPos % queue->num], value, NULL))
{
__sync_fetch_and_add(&queue->readPos, 1);
return value;
}
}
return NULL;
}
</code></pre>
<p>(link to the <a href="http://pastebin.com/c82qqDsX" rel="nofollow">previous iteration</a>)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:54:29.420",
"Id": "73066",
"Score": "0",
"body": "Also check out Relacy for thread-safeness-testing. No guarantees on its accuracy -- http://www.1024cores.net/home/relacy-race-detector"
}
] |
[
{
"body": "<p>Did you test it? </p>\n\n<p>I think you have a problem if a thread calls <code>enqueue</code> and is interrupted\njust before the <code>memcpy</code>, having calculated <code>pos</code> to be slot-1. If another\nthread now calls <code>enqueue</code> and completes it will write to slot-2 and increment the <code>pendingRead</code> counter, leaving\nslot-1 still unwritten. If a third thread now reads before the first thread\ncan complete its write, the reader will read from the unwritten slot-1. This\nis becase the second thread correctly set the queue to say there is a pending\nread (slot-2) but <code>dequeue</code> assumes the data must be in the next available\nslot according to <code>readPos</code>. </p>\n\n<p>A few other comments:</p>\n\n<ol>\n<li><p><code>queue_t</code> is defined (elsewhere) as a pointer type. I prefer pointers to be\nexplicit.</p></li>\n<li><p>You have mixed use of <code>struct queue *</code> and <code>queue_t</code></p></li>\n<li><p>Return from <code>malloc</code> is not checked.</p></li>\n<li><p><code>buf</code> in <code>struct queue</code> should be <code>void*</code> not <code>char **</code></p></li>\n<li><p>Why are <code>writePos</code> and <code>readPos</code> of type <code>uint64_t</code> and not <code>size_t</code>?\nAfter all, <code>num</code> is <code>size_t</code>. Why the difference?</p></li>\n<li><p>Loss of precision assigning <code>num</code> in <code>createQueue</code></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T07:18:20.767",
"Id": "35324",
"Score": "0",
"body": "I rewrote the queue in an attempt to solve the problem you mentioned. `writePos` and `readPos` are uint64_t because even on 32 bit systems they need to be 64 bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T07:18:37.820",
"Id": "35325",
"Score": "0",
"body": "It would be nice if you could take a look at the new code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:26:37.887",
"Id": "35407",
"Score": "0",
"body": "In `dequeue`, You need to cache the value of `queue->readPos % queue->num` to protect against a change in `readPos` between assigning `value` and the following `if(...)`. In addition, you are using a busy-loop to wait for space/new-data; this is not usually considered a good idea but can sometimes be done - it depends upon your application (but personally I'd be suspicious of code like that if I met it in the wild). I don't see any other problem, but as you say, spotting race conditions is difficult; there might still be something wrong..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:27:59.013",
"Id": "22932",
"ParentId": "22915",
"Score": "4"
}
},
{
"body": "<p>It seems that your <code>enqueue()</code> does not guarantee progress by at least one thread, in case the thread that just enqueued into the <code>writePos</code>, before adjusting the index is being suspended by some interrupt or system scheduler. In such case all threads trying to <code>enqueue()</code> will wait until the first one wake up and increment the <code>writePos</code>.</p>\n\n<p>You might want to advance the <code>writePos</code> in case the CAS failed, and it is smaller than <code>readPos - 1</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-21T02:40:55.647",
"Id": "84626",
"ParentId": "22915",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>it seems that <code>enqueue()</code> can leave the queue with holes: <code>(readPos+1)%num == NULL</code> and <code>(readPos+1)%num != NULL</code>. I'll try to explain with an example.</p>\n\n<ul>\n<li>the system has 2 producers threads, <code>P1</code> and <code>P2</code> and one consumer thread, <code>C1</code>. <code>readPos == 0</code> and <code>writePos == 1</code>.</li>\n<li><code>P1</code> calls <code>enqueue()</code>, successfully executes <code>compare_and_swap</code> and gets preempted. <code>readPos == 0</code> and <code>writePos == 1</code>.</li>\n<li><code>C1</code> gets the CPU, dequeues 2 items, <code>buf[0]</code> and <code>buf[1]</code>, and gets preempted. <code>readPos == 2</code> and <code>writePos == 1</code>.</li>\n<li><code>P2</code> gets the CPU, enqueues 1 item in <code>buf[1]</code> and is preempted. <code>readPos == 2</code> and <code>writePos == 2</code>.</li>\n<li><code>P1</code> resumes, increments <code>writePos</code>. now <code>readPos == 2</code> and <code>writePos == 3</code>.</li>\n<li><code>P1</code> enqueues next item in <code>buf[3]</code>. <code>readPos == 2</code> and <code>writePos == 4</code>.</li>\n<li><code>C1</code> resumes. now <code>readPos == 2</code>, <code>writePos == 3</code> and the buffer has a hole (since <code>buf[2] == NULL</code>). <code>C1</code> is stuck at <code>readPos == 2</code>. it can not dequeue items from <code>buf[3]</code> onward.</li>\n</ul></li>\n</ol>\n\n<p>the system remains in this state till the producers wrap the buffer around and writes an item to <code>buf[2]</code>. replacing <code>fetch_and_add</code> with a <code>compare_and_swap</code> should help here.</p>\n\n<ol start=\"2\">\n<li>a particularly unlucky producer may fail the <code>compare_and_swap</code> all the <code>kNumTries</code> times and return <code>-1</code> from <code>enqueue()</code>, even though the <code>buf</code> is not full. you can perhaps introduce a variable such as <code>enqueue_in_progress</code> and busy wait on a <code>compare_and_swap(&enqueue_in_progress, 0, 1)</code> at the beginning of <code>enqueue()</code>. this will ensure only one producer can enter the body of <code>enqueue()</code> at a time.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-15T10:43:25.327",
"Id": "138746",
"ParentId": "22915",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T08:10:15.767",
"Id": "22915",
"Score": "4",
"Tags": [
"c",
"multithreading",
"thread-safety",
"circular-list"
],
"Title": "Lock free MPMC Ring buffer implementation in C"
}
|
22915
|
<p>I'm querying a MySQL database and displaying the info in order of timestamp (DESC). Essentially, I'm grabbing the last record in the database, displaying it's date and year as the header of it's section and then going backwards from there. I've put together these if and else if statements to display the appropriate month name according to the timestamp. It works fine but I know I could probably do this with an array or some sort of other loop. I'm still learning this type of coding so I was wondering if someone could help me find a way to make this code more efficient. Thanks!</p>
<pre><code>$sql = "SELECT * FROM user ORDER BY timestamp DESC LIMIT 1";
$result = $mysqli->query($sql);
$row_lastone = mysqli_fetch_array($result);
$timestamp_lastone = date_parse($row_lastone['timestamp']);
$month_lastone = $timestamp_lastone['month'];
$year_lastone = $timestamp_lastone['year'];
if ($month_lastone==1){
$lastone_month = "January";
}
else if ($month_lastone==2){
$lastone_month = "February";
}
else if ($month_lastone==3){
$lastone_month = "March";
}
else if ($month_lastone==4){
$lastone_month = "April";
}
else if ($month_lastone==5){
$lastone_month = "May";
}
else if ($month_lastone==6){
$lastone_month = "June";
}
else if ($month_lastone==7){
$lastone_month = "July";
}
else if ($month_lastone==8){
$lastone_month = "August";
}
else if ($month_lastone==9){
$lastone_month = "September";
}
else if ($month_lastone==10){
$lastone_month = "October";
}
else if ($month_lastone==11){
$lastone_month = "November";
}
else if ($month_lastone==12){
$lastone_month = "December";
}
echo "<h1>".$lastone_month." ".$year_lastone."</h1>";
</code></pre>
<p>Thanks for the help!</p>
|
[] |
[
{
"body": "<p>One possible solution would be to let your DB do the work. </p>\n\n<pre><code>SELECT DATE_FORMAT(´timestamp´, '%M') FROM user ORDER BY timestamp DESC LIMIT 1 \n</code></pre>\n\n<p>see <a href=\"http://dev.mysql.com/doc/refman/5.1/de/date-and-time-functions.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.1/de/date-and-time-functions.html</a></p>\n\n<p>Also i would suggest to not name your col 'timestamp', it may not be a reservered word but it could lead to confusion or forcing you to escape your col in your queries. </p>\n\n<p><strong>EDIT</strong></p>\n\n<p>if you want to stay in PHP or your DB does not support my suggested MySQL solution you could use DateTime to format your timestamp</p>\n\n<pre><code>$date = new DateTime();\n$date->setTimestamp($timestamp_lastone);\necho $date->format('F');\n</code></pre>\n\n<p>see <a href=\"http://www.php.net/manual/de/class.datetime.php\" rel=\"nofollow\">http://www.php.net/manual/de/class.datetime.php</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:05:15.250",
"Id": "22922",
"ParentId": "22917",
"Score": "1"
}
},
{
"body": "<p>Try something like this:</p>\n\n<pre><code>$sql = \"SELECT * FROM user ORDER BY timestamp DESC LIMIT 1\";\n$result = $mysqli->query($sql);\n$row_lastone = mysqli_fetch_array($result);\n\n$date = date(\"M Y\", strtotime($row_lastone['timestamp']));\n\necho \"<h1>\".$date.\"</h1>\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T01:04:26.000",
"Id": "23049",
"ParentId": "22917",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23049",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T08:48:08.000",
"Id": "22917",
"Score": "1",
"Tags": [
"php",
"mysql",
"array"
],
"Title": "Looking For a More Efficient/Elegant Way To Write a MySQL Query"
}
|
22917
|
<p>I thought about three (now four) different ways how to execute forks with PHP.
What is the faster, maybe better solution and why?</p>
<ol>
<li><p>PHP script included</p>
<pre><code>foreach($tasks as $task) {
$pid = pcntl_fork();
if($pid == -1) {
exit("Error forking...\n");
} else if($pid == 0) {
include 'worker.php';
exit();
}
}
while(pcntl_waitpid(0, $status) != -1);`
</code></pre></li>
<li><p>PHP script executed through exec()</p>
<pre><code>foreach($tasks as $task) {
$pid = pcntl_fork();
if($pid == -1) {
exit("Error forking...\n");
} else if($pid == 0) {
exec('php worker.php '.$task);
exit();
}
}
while(pcntl_waitpid(0, $status) != -1);
</code></pre></li>
<li><p>PHP script executed as background command</p>
<pre><code>foreach($tasks as $task) {
$workers[] = exec('php worker.php '.$task.' & echo $!');
}
do {
foreach($workers as $idx => $pid) {
if(!posix_getpgid($pid)) {
unset($workers[$idx]);
}
}
} while(!empty($workers));
</code></pre></li>
</ol>
<p>(additional) 4. Using <a href="http://gearman.org/" rel="nofollow noreferrer">Gearman</a></p>
<p><strong>worker.php</strong> can open database connections, files, etc ...</p>
<p>Any good explanation would be much appreciated.</p>
|
[] |
[
{
"body": "<p>you have an option to do forking using pcntl yourself, or by using something more robust like PHP-Daemon on GitHub.\nThere is also an option of background workers, which is the best option in my opinion (<a href=\"http://blog.anorgan.com/2013/02/22/dont-do-now-what-you-can-put-off-until-later/\" rel=\"nofollow\">http://blog.anorgan.com/2013/02/22/dont-do-now-what-you-can-put-off-until-later/</a>).</p>\n\n<p>For clean and easy solution, use Gearman together with supervisord. Or <a href=\"http://anorgan.github.com/QuTee/\" rel=\"nofollow\">http://anorgan.github.com/QuTee/</a> :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T10:16:16.857",
"Id": "35803",
"Score": "0",
"body": "Thanks Anorgan. I haven't tried yet, but I guess Gearman and Supervisord is the way to go :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T14:07:14.727",
"Id": "23162",
"ParentId": "22919",
"Score": "4"
}
},
{
"body": "<p><strong>5. All code embedded in a single PHP script.</strong> With explanation as requested.</p>\n\n<p>The statements before the fork is executed normally.</p>\n\n<p>After a succesful pcntl_fork(), the running process is cloned, complete with its current state (all variables, including process counter). So two identical processes continue from that point in code.\n<em>Almost</em> identical: the only difference is the return value<strong>s</strong> of pcntl_fork(), stored in both $pid'<strong>s</strong>.</p>\n\n<p>The cloned process is the parent, and receives the process_id of its clone.\nThe clone process is the child, and receives 0.\nDepending on this value, both processes go their separate ways, and continue until the hit an exit().\nIf parent- and child-code are <strong>not</strong> individually terminated by exit(), then both may continue executing the common code at the end, resulting <strong>both</strong> processes printing \"I am both\"!.\nTry for yourself, and inspect the output. Then uncomment the exit()'s and run it again. </p>\n\n<pre><code>$mypid = getmypid();\necho \"$mypid: I am the parent. I have no child yet.\\n\";\n\n// fork: a twin process is created\nif(($pid = pcntl_fork()) == -1) { exit(\"Error forking...\\n\"); }\n\nif($pid == 0) {\n // Child code goes here\n $mypid = getmypid();\n echo \"$mypid: I am the child. This is what I do.\\n\";\n // exit();\n}else{\n // Parent code goes here\n echo \"$mypid: I am still the parent. I have a child now: it's number is $pid.\\n\";\n // exit();\n}\n\n// Both parent and child execute this code unless\n// the exit's above are uncommented.\necho \"$mypid: we are both. The pid I know is: $pid\\n\";\n\nexit();\n</code></pre>\n\n<p>Output: of the script above. The $mypid at the beginning of the line is the process id of the printing process. The $pid on the right is the return-value of the fcntl_fork().</p>\n\n<pre><code>6346: I am the parent. I have no child yet.\n6347: I am the child. This is what I do.\n6346: I am still the parent. I have a child now: it's number is 6347.\n6346: we are both. The pid I know is: 6347\n6347: we are both. The pid I know is: 0\n</code></pre>\n\n<p>Note: after the fcntl_fork() both processes work independently. So one may go faster than the other; they may run on different processes, etc.\nThe order of the output may differ on your computer !\nYou can have them synchronized by making the parent wait for the childs exit.</p>\n\n<p>This was my attempt to give an explanation. Now the answer to your question, wich one is faster or better:</p>\n\n<p>Essentially they are all the same, as far as the fork goes. The differences are only in th extras.</p>\n\n<p>An <strong>include</strong> makes the 'compiler' translate the code all at once. And only once.\nAll variables set in the main program (<em>before</em> the fork ! ) are 'inherited' by the child.</p>\n\n<p>An <strong>exec</strong> cleans all process variables and starts a new program, just as you do from the command line. So this is overhead. And no information is shared from the parent to the child. (unless you ... well, there are possibilities).\nA new process in a clean memory also forces the child code to be compiled in the second process. So the compiler has to be started again; this to is overhead.</p>\n\n<p>So without exec is always better ? No. For example: if your co-worker changes his child-code, his typo's will make the compiler stop compiling your code if is is included.\nBut executing the other code will clearly show where the typo's are made. Programs are insulated much better this way. At some cost. Depends on how often you want the fork to be executed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-29T16:38:32.623",
"Id": "164475",
"ParentId": "22919",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "23162",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:44:12.320",
"Id": "22919",
"Score": "14",
"Tags": [
"php",
"comparative-review",
"child-process"
],
"Title": "Forking with PHP (4 different approaches)"
}
|
22919
|
<p>I have this set of functions - it works, but I'm concerned about the use of <code>let</code>s.</p>
<pre><code>(defn- create-counts [coll]
"Computes how many times did each 'next state' come from a 'previous state'.
The result type is {previous_state {next_state count}}."
(let [past coll
present (rest coll)
zipped (map vector past present)
sorted (sort zipped)
grouped (group-by first sorted)
seconds (map (fn [[key pairs]] [key (map second pairs)]) (seq grouped))
freqs (map (fn [[key secs]] [key (frequencies secs)]) seconds)]
(into {} freqs)))
</code></pre>
<p>I started learning functional programming in Haskell some time ago, and there, because of laziness, it's commonplace to use this equivalent of Clojure <code>let</code>, because what's not needed, isn't ever computed:</p>
<pre><code>asnwer = z
where
notused = map (^1000) [1000..10000]
x = [1..]
y = take 10 x
z = map (*2) y
</code></pre>
<ul>
<li><em>Is it okay to use Clojure <code>let</code> in this way?</em> Look for example at the <code>create-counts</code> fn definition - I use it quite heavily there.</li>
<li><em>Would it be better to just put it all inside one expression?</em></li>
<li><em>What's the best practice for this?</em></li>
</ul>
<p>I like how everything's named, but I don't know if there's not a performance penalty hidden somewhere.</p>
<p>When I try to match the Haskell example with Clojure code, it seems there's eager evaluation:</p>
<pre><code>(let [notused (do (Thread/sleep (rand 10000000)) :done)
x (iterate inc 1)
y (take 10 x)
z (map #(* 2 %) y)]
z)
;=> sleeps till the judgement day
</code></pre>
<p>I could imagine preventing this with futures or some clever let-like macro, but really it seems to me that I'm trying to do something Haskell-y (lazy) in Clojure. What's the idiomatic way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:36:50.830",
"Id": "35608",
"Score": "1",
"body": "Just a note that the Haskell equivalent of the clojure `let` is `let`. `where` is a different beast"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:44:32.283",
"Id": "35631",
"Score": "0",
"body": "Thanks, jozefg. Links with more info: http://www.haskell.org/tutorial/patterns.html#sect4.5 and http://www.haskell.org/haskellwiki/Let_vs._Where"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T13:57:43.807",
"Id": "35644",
"Score": "0",
"body": "I'm a clojure noob, but the documentation for map says it returns a lazy sequence. Group-by is not lazy. http://clojuredocs.org/clojure_core/clojure.core/map"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-03T03:14:08.763",
"Id": "201810",
"Score": "1",
"body": "Your Clojure example sleeps forever because \"do\" is an eager construct. Not everything is lazy in clojure. Look at the doc, and make sure you are working with lazy functions. I'm not sure what your notused map... code does in Haskell, but you can use map for it in Clojure also, and it'll be lazy."
}
] |
[
{
"body": "<p>First of all, you could use abstract structural binding (a.k.a. destructuring) to reduce the number of <code>let</code> bindings:</p>\n\n<pre><code>(defn- create-counts_org [[_ & present :as coll]]\n \"Computes how many times did each 'next state' come from a 'previous state'.\n The result type is {previous_state {next_state count}}.\"\n (let [zipped (map vector coll present)\n sorted (sort zipped)\n grouped (group-by first sorted)\n seconds (map (fn [[key pairs]] [key (map second pairs)]) (seq grouped))\n freqs (map (fn [[key secs]] [key (frequencies secs)]) seconds)]\n (into {} freqs)))\n</code></pre>\n\n<p>I think there's nothing wrong in using <code>let</code> bindings that are technically not necessary to improve readability and comprehensibility. </p>\n\n<p>But in your function, I think it is pretty clear what every step does: </p>\n\n<ul>\n<li><code>sorted</code> -> the first thing I see is the <code>sort</code> function</li>\n<li><code>grouped</code> -> the first thing I see is the <code>group-by</code> function</li>\n<li><code>seconds</code> / <code>freqs</code> -> I think these are also pretty clear, using <code>second</code> and <code>frequencies</code> </li>\n</ul>\n\n<p>And because each <code>let</code> binding just uses the previous binding once, I would probably use the <a href=\"http://clojuredocs.org/clojure_core/clojure.core/-%3E%3E\" rel=\"noreferrer\"><code>thread-last (->>)</code></a> macro:</p>\n\n<pre><code>(defn- create-counts [[_ & rest :as coll]]\n \"Computes how many times did each 'next state' come from a 'previous state'.\n The result type is {previous_state {next_state count}}.\"\n (->> (map vector coll rest)\n (sort)\n (group-by first)\n (map (fn [[key pairs]] [key (map second pairs)]))\n (map (fn [[key secs]] [key (frequencies secs)]))\n (into {})))\n</code></pre>\n\n<p>I think this also answers your <em>better to just put it all inside one expression</em> question. Also, even if there where a performance penalty in using <code>let</code> bindings, it would probably be negligible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T09:48:45.527",
"Id": "35865",
"Score": "0",
"body": "Thanks! I've seen the ->> macro before, but didn't think about it. Seems handy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T09:35:20.537",
"Id": "23256",
"ParentId": "22934",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23256",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:48:58.750",
"Id": "22934",
"Score": "7",
"Tags": [
"haskell",
"clojure"
],
"Title": "Excessive use of let a problem in Clojure?"
}
|
22934
|
<p>I'm creating a small extension to the JDBC API, with the hope of automating some common tasks and avoid boilerplate code.</p>
<p>One of its features will be a <em>basic</em> support for named parameters in prepared statements (that JDBC does not support natively).<br>
Since this is a vital part of the library, <strong>I would appreciate your opinions</strong> about the module that:</p>
<ol>
<li>Parses the prepared statement, by replacing named parameters with question marks</li>
<li>Creates a mapping between the name of the parameter and the index(es) of the resulting question mark(s)</li>
</ol>
<p>For example, you have:</p>
<pre><code>INSERT INTO customers (name, surname, age) VALUES (:name, :surname, :age)
</code></pre>
<p>The parse will produce this string (to be passed to JDBC standard APIs):</p>
<pre><code>INSERT INTO customers (name, surname, age) VALUES (?, ?, ?)
</code></pre>
<p>and will also create a mapping between the parameters and the corresponding placeholders, which is:</p>
<pre><code>name -> 1
surname -> 2
age -> 3
</code></pre>
<p>This is the whole parsing logic:</p>
<pre><code>import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class StatementParser {
private static final char PARAMETER_PLACEHOLDER = '?';
private static enum ParseStatus {
WAITING_FOR_IDENTIFIER, READING_IDENTIFIER
};
public static ParseResult parse(String sql, char marker) {
sql = sql + '\0'; // Insert null character at the end (for parsing)
ParseStatus status = ParseStatus.WAITING_FOR_IDENTIFIER;
Map<String, List<Integer>> parameters = new HashMap<String, List<Integer>>();
StringBuilder resultSql = new StringBuilder();
StringBuilder currentParameter = new StringBuilder();
int paramCount = 0;
for (int offset = 0; offset < sql.length(); offset++) {
char c = sql.charAt(offset);
switch (status) {
case WAITING_FOR_IDENTIFIER:
if (c == marker) {
status = ParseStatus.READING_IDENTIFIER;
} else {
resultSql.append(c);
}
break;
case READING_IDENTIFIER:
if (c == marker) {
throw new StatementParseError(
"Unexpected parameter marker at character " + offset);
} else if (Character.isLetterOrDigit(c)) {
currentParameter.append(c);
} else {
int paramNo = ++paramCount;
String paramName = currentParameter.toString();
if (paramName.isEmpty()) {
throw new StatementParseError(
"Error parsing parameter #" + paramNo);
}
if (parameters.containsKey(paramName)) {
parameters.get(paramName).add(paramNo);
} else {
List<Integer> list = new LinkedList<Integer>();
list.add(paramNo);
parameters.put(paramName, list);
}
resultSql.append(PARAMETER_PLACEHOLDER);
resultSql.append(c);
currentParameter.setLength(0); // reset buffer
status = ParseStatus.WAITING_FOR_IDENTIFIER;
}
break;
}
}
// Remove ending null character
resultSql.deleteCharAt(resultSql.length() - 1);
return new ParseResult(resultSql.toString(), parameters);
}
}
</code></pre>
<p>You can easily imagine what is the <code>ParseResult</code> class about, without me posting it here. <code>StatementParseError</code> is a <code>RuntimeException</code>.</p>
<p>My doubts are the following:</p>
<ol>
<li>If a SQL string constant contains the <code>marker</code> character, this parser will not ignore it - whereas it should. Example: <code>SELECT * FROM sometable WHERE foo = :param1 AND bar = 'a:b'</code>. I may try to improve my parser to consider also string delimiters (quotes) and ignore markers inside string constants, but each DBMS has it own rules when it comes, for example, to escape quotes inside strings. Do you think this shortcoming will seriously affect the robustness of my library, or I can just <strong>document it</strong> and suggest to use another marker as needed?</li>
<li>You may have noticed that I add a placeholder <code>\0</code> character at the end of the string, before parsing it. The reason is that if the input SQL string terminates with the last character of a named parameter identifier, then I need another iteration of the loop to find the end of the parameter identifier and store it in the <code>parameters</code> map. Is there a cleaner way?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T23:26:35.313",
"Id": "35292",
"Score": "1",
"body": "If possible, I would completely avoid dealing with raw String for SQL. This is error prone. There are some alternatives in the java world, like hibernate or method chaining (a quick google search reveals jooq). If we stick to your approach, I would get rid of this state machine. For this case, a split looks fine. Go over all elements from split, check if an element starts with identifier, do your work, finished. I am not sure at the moment if a complete answer is worth the work, so I started with this comment to see where it is going."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T23:30:47.713",
"Id": "35293",
"Score": "0",
"body": "Thank you for your advice. Well, this library is just for *slightly* improving my life when, for some reason, I cannot use an ORM or JOOQ. About the \"split\", how can I do it? Please note that an identifier can be immediately followed by some operand or parenthesis, can you provide me with an example? Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:34:33.023",
"Id": "35378",
"Score": "0",
"body": "I have extended the comment to a full answer. See below."
}
] |
[
{
"body": "<p>If possible, I would completely avoid dealing with raw String for SQL. This is error prone. There are some alternatives in the java world, like hibernate or method chaining (a quick google search reveals jooq). If we stick to your approach, I would get rid of this state machine.</p>\n\n<p>There are several ways to do it.<br>\nI will always use this method to handle the map:</p>\n\n<pre><code>private static void insertIntoMap(final Map<String, List<Integer>> mapNameToListPositons, final String name, final int position) {\n final List<Integer> listPositions = mapNameToListPositons.get(name);\n if (listPositions != null)\n listPositions.add(position);\n else\n mapNameToListPositons.put(name, new ArrayList<Integer>(Arrays.asList(position)));\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public static String parse2(final String sqlStatement, final String marker) {\n final Map<String, List<Integer>> mapNameToListPositons = new HashMap<String, List<Integer>>();\n //System.out.println(Arrays.toString(sqlStatement.split(\"[ (),]\")));\n //[INSERT, INTO, customers, , name, , surname, , age, , VALUES, , :name, , :surname, , :age]\n String returnStatement = sqlStatement;\n int parameterPosition = 1;\n for (final String sqlStatementSplitItem : sqlStatement.split(\"[ (),]\")) {\n if (sqlStatementSplitItem.startsWith(marker)) {\n insertIntoMap(mapNameToListPositons, sqlStatementSplitItem.substring(1), parameterPosition);\n ++parameterPosition;\n returnStatement = returnStatement.replace(sqlStatementSplitItem, \"?\");\n }\n }\n System.out.println(mapNameToListPositons);\n return returnStatement;\n}\n</code></pre>\n\n<p>Here, we use a split. We split for all the values which could be before or after the parametername. You can add more if needed, I took your example as input.<br>\nI have added <code>println</code> to make comparisons easier, because I do not know the implementation of your ParseResult class. You can easily change it.</p>\n\n<hr>\n\n<pre><code>public static String parse3(final String sqlStatement, final char marker) {\n final String regexp = \"(?<=\" + marker + \")\\\\p{Alnum}+\";\n final Map<String, List<Integer>> mapNameToListPositons = new HashMap<String, List<Integer>>();\n final Matcher matcher = Pattern.compile(regexp).matcher(sqlStatement);\n int parameterCount = 1;\n while (matcher.find()) {\n insertIntoMap(mapNameToListPositons, matcher.group(), parameterCount);\n ++parameterCount;\n }\n System.out.println(mapNameToListPositons);\n return sqlStatement.replaceAll(marker + \"\\\\p{Alnum}+\", \"?\");\n}\n</code></pre>\n\n<p>If we use split, we already used a pattern. We can even use a regular expression directly.</p>\n\n<p>But, I normally try to avoid regexp. They are indeed powerful, but nearly always completely unreadable.\nI do not know any good way to handle them in a readable and maintainable way.</p>\n\n<hr>\n\n<pre><code>public static String parse4(final String sqlStatement, final char marker) {\n final Map<String, List<Integer>> mapNameToListPositons = new HashMap<String, List<Integer>>();\n final StringBuilder resultSqlStatement = new StringBuilder();\n int parameterPosition = 1;\n\n for (int index = 0; index < sqlStatement.length(); index++) {\n if (sqlStatement.charAt(index) == marker) {\n ++index; //we do not care about the marker. The new index is the first char of the parameter name\n final int parameterStartIndex = index;\n while (Character.isLetterOrDigit(sqlStatement.charAt(index))) //lets search for the end\n ++index;\n insertIntoMap(mapNameToListPositons, sqlStatement.substring(parameterStartIndex, index), parameterPosition);\n ++parameterPosition;\n resultSqlStatement.append(PARAMETER_PLACEHOLDER);\n }\n resultSqlStatement.append(sqlStatement.charAt(index));\n }\n System.out.println(mapNameToListPositons);\n return resultSqlStatement.toString();\n}\n</code></pre>\n\n<p>Here we completely avoid regular expressions and use instead a submethod which is kind of inlined. You could very easily use recursion or a new method, too.</p>\n\n<hr>\n\n<p>All variants have their good and bad points. I would probably use the split or the last one.<br>\nPlease notice from comparison with your code, that I have added some small changes. I do not list them with quoted code, I will only name them:</p>\n\n<ul>\n<li>Speaking variable names, no uncommon abbreviations</li>\n<li>You should try to avoid modifying method parameters</li>\n<li>Really the only use case for a linked list is if you plan to do a lot of remove. In all other cases, use ArrayList (we are not talking about multithreading here)</li>\n<li>Try to avoid custom exceptions like <code>StatementParseError</code>. Use IllegalArgumentException, or here IllegalStateException.</li>\n<li>Write unit tests (I did only a basic one, you should add to enhance your confidence in your code</li>\n<li>You should avoid to use the \"setLength\" method for StringBuilder, instead create a new one. The meaning is not clear and the internals are unknown if they correspond to your expected behavior</li>\n</ul>\n\n<p>I hope, I got everything from my changes. If there are open points, just ask.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:33:58.317",
"Id": "22975",
"ParentId": "22935",
"Score": "5"
}
},
{
"body": "<p>Just a quick note: instead the following,</p>\n\n<pre><code>if (parameters.containsKey(paramName)) {\n parameters.get(paramName).add(paramNo);\n} else {\n List<Integer> list = new LinkedList<Integer>();\n list.add(paramNo);\n parameters.put(paramName, list);\n}\n</code></pre>\n\n<p>you could use a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html\" rel=\"nofollow\">Multimap</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T13:08:35.290",
"Id": "502878",
"Score": "0",
"body": "Rather use Map.compute(), computeIfAbsent() and computeIfPresent() in order to avoid using this badly modularized third party library."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:14:34.510",
"Id": "23036",
"ParentId": "22935",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22975",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T18:44:45.750",
"Id": "22935",
"Score": "4",
"Tags": [
"java",
"parsing"
],
"Title": "Custom parser for named parameters in prepared statement"
}
|
22935
|
<p>I had been working on a project for some time, and then it went on the way back burner after my daughter was born. I'm back to it, and now I discover that I'm best off using PDO over MySQLi. So, I'm working on the conversion, and I'd like to get some confirmation that I'm handling things well. Essentially: <strong>Does this code look secure and sound?</strong> [It's just my account activation php.]</p>
<pre><code><?php
require_once ('common.php');
$x = $y = FALSE;
if (isset($_GET['x']) && filter_var($_GET['x'], FILTER_VALIDATE_EMAIL)) {
$x = $_GET['x'];
}
if (isset($_GET['y']) && (strlen($_GET['y']) == 32 )) {
$y = $_GET['y'];
}
if ($x && $y) {
$query = "SELECT 1 FROM users WHERE (email=:email AND confirm IS NULL)";
$query_params = array( ':email' => $x );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$count = $stmt->rowCount();
if($count == 1) {
echo "<h3>Your account is already activated. No need to activate again. You may now log in.</h3>";
exit();
} else { // Not an active user
$query = "UPDATE users SET confirm=NULL WHERE (email=:email AND confirm=:confirm) LIMIT 1";
$query_params = array(
':email' => $x,
':confirm' => $y
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$count = $stmt->rowCount();
if($count == 1) {
echo "<h3>Your account is now active. You may now log in.</h3>";
exit();
} else {
echo '<p class="error">Your account could not be activated. Please re-check the link or contact the system administrator.</p>';
exit();
}
}
} else {
$url = BASE_URL . 'index.html';
ob_end_clean();
header("Location: $url");
exit();
}
?>
</code></pre>
<p>I am aware that the <code>$ex->getMessage()</code> needs to go before production.</p>
|
[] |
[
{
"body": "<p><strong>The Good</strong></p>\n\n<p>You use bound parameters. You handle errors.</p>\n\n<p><strong>The Bad</strong></p>\n\n<p>You filter the email address but then pass the unfiltered value to the select and update queries. What are you trying to achieve with the check of the filtered email?</p>\n\n<p>You are not checking the validity of the 'y' param (which I assume is an activation token). Isn't the point of this kind of activation to ensure that the real person at that email is doing the activation? The way you have it, an attacker could register an account using any email address. Here is how:</p>\n\n<p>1) Attacker goes to your registration page and enters someone else's email address (i.e. notme@example.com)</p>\n\n<p>2) Attacker crafts and visits the url: <code>yoursite.com/activation.php?x=notme@example.com&y=12345678901234567890123456789012</code> (where the y value is some random string, 32 chars in length)</p>\n\n<p>Attacker now has an activated account using an email they do not own, having never received the activation email.</p>\n\n<p><strong>The Ugly</strong></p>\n\n<p>Your logic and presentation are mixed together. Perhaps for this relatively simple script, it's not that big a deal. But, over time, these things have a habit of growing and getting very messy. Look into mvc.</p>\n\n<p>One try catch block should be all you need.</p>\n\n<p><strong>Example Rewrite</strong></p>\n\n<pre><code>try {\n //initialize and filter $x and $y\n if (!$x || !$y) {\n throw new Exception(\"$x or $y invalid\");\n }\n\n //run select query. It's where clause should be something like:\n $where = 'email = :email AND '\n . 'confirm = :token AND '\n . 'confirmExpiration <= :expiration AND '\n . 'activated = false';\n $params = array(\n ':email' => $x,\n ':token' => $y,\n ':expiration' => date('Ymd His'),\n );\n\n //check results of select query\n if (/* select was not successful */) {\n throw new Exception(\"Invalid request. x: $x y: $y\");\n }\n\n //Update the account so that it is now active\n\n //redirect to a success page\n} catch (Exception $e) {\n //if production, log it and redirect to a friendly error page\n //if development, redirect to some debug page\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T15:37:35.317",
"Id": "35647",
"Score": "0",
"body": "Rob, thank you very much for your answer. While I do actually check that the activation token matches the one stored in the database, you presented a much cleaner way of handling the whole process. I appreciate it. I don't know how I overlooked the email sanitization. Again, thank you; I really want to produce quality code, and your example will be seriously beneficial."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T15:34:07.530",
"Id": "23084",
"ParentId": "22938",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T20:31:12.627",
"Id": "22938",
"Score": "3",
"Tags": [
"php",
"mysql",
"security",
"pdo"
],
"Title": "Converting from MySQLi to PDO account activation"
}
|
22938
|
<p>Say I have this type of code I'd like to execute. There's some data encapsulated around a big Javascript object containing methods & properties that I'd like to extract based on comparing some other data in said object. The object includes associative (hash?) arrays where I don't know the array IDs at runtime so I have to do some iteration, this is the working code structure I came up with. But it's bloated and a bit messy to read. Was wondering it it can be optimized for efficiency and readability in general, to minimize iteration and conside the length of the object referencing.</p>
<p>I execute this code from Firebug console (or via Selenium WebDriver's execute javascript command, in which case console.log become "return" to return the desired value).</p>
<pre><code>for(x in MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry){
if (MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry[x].someObj.displayName == 'some value')
console.log(MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry[x].someObj.someId);
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>You should cache all methods calls - JS is interpreting language and\nthere is no optimizers to help you, therefore, each time you call\nmethod, get element from array etc, you are actually asking JS\nengine to DO this for you.</li>\n<li>Concluding that someObjArry is an array, should avoid using loops with \"in\" statements - use standard loops with indexes instead. \"in\" statement walks through all object's properties, not collection's elements, so it's just future maintenance \"watch-out\".</li>\n<li>Property \"displayName\" of object \"someObj\" seems like of a string type - try using strong type comparisons if possible (not an optimization, just a good practice)</li>\n<li>Cache as much as you can</li>\n</ol>\n\n<hr>\n\n<pre><code>var someArray = MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry, \n arrayElement;\n\nfor(var i=0, $length = someArray.length; i< $length; i++){\n arrayElement = someArray[i].someObj;\n\n if (arrayElement.displayName === 'some value'){\n console.log(arrayElement.someId);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T04:19:34.520",
"Id": "35307",
"Score": "2",
"body": "I'd love to see a demonstration in modern browsers where pre-grabbing the array length is a performance enhancing measure. Even if it does save some time, it adds quite a bit of noise. I'll grant that there may be some things returned by DOM functions (like getElementsByTagName) which return array \"like\" objects, and grabbing the length might make sense on them. Of course, there is also the native `forEach` which might prove faster (but not all browsers support it). And finally, JavaScript is generally compiled these days, but it is a good idea to use `someArray` as suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T11:09:09.980",
"Id": "35332",
"Score": "1",
"body": "@JayC also languages like CoffeeScript will do the all the caching (both the `someArray` and the `$length`) automatically when compiling to JavaScript, making the code somewhat cleaner without having to do these things (and also variable declarations) manually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:37:11.500",
"Id": "35383",
"Score": "0",
"body": "Thanks, I was lazy to break out the code with variable assignments. The suggested code is cleaner to read. I guess that's about as optimal as you can get with the code though?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T19:40:29.883",
"Id": "35393",
"Score": "0",
"body": "@JayC take a look at jsperf.com - plenty of tests of this sort of stuff. And you can make your own :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:48:23.160",
"Id": "35420",
"Score": "0",
"body": "@Flambino: Actually, I was kinda hoping Arthur P already had such a test or knew of such a test there. But the fact that a CoffeeScript compiles `(math.cube num for num in list)` to a for loop set up like Arthur's is rather convincing to me that there probably is something to caching the length and this observation also makes me reconsider if I shouldn't regularly be using some language that compiles to JavaScript or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T15:45:44.940",
"Id": "35510",
"Score": "0",
"body": "@JayC Googling a bit (jsperf's own search is not very useful, unfortunately), I found [this test](http://jsperf.com/caching-array-length/4) which covers a bit of ground. As for CoffeeScript, I can highly recommend it. By now it's almost weird for me to code regular JS (all those braces everywhere!) Optimizations aside, CoffeeScript is also just plain nice to code in. Takes a little getting used to, and get really idiomatically fluent, but it's well worth it, I think."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T03:51:41.343",
"Id": "22948",
"ParentId": "22947",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T02:38:29.710",
"Id": "22947",
"Score": "1",
"Tags": [
"javascript",
"json"
],
"Title": "Can this iterating javascript code be optimized?"
}
|
22947
|
<p>I realize that there is a surfeit of posts on SE/SO about optimizing one's R for() loops. I'm afraid, though, that I don't understand all of the guidance in the answers there, or how to apply their lessons to the loop I'm working on.</p>
<p>First, the code:</p>
<pre><code>HHCovarEvals <- data.frame()
for(k in 1:length(hhcovarmodels))
{
q.lm <- lm(as.formula(c("DeltaHHCGI~",hhcovarmodels[k])))
q.bptest <- bptest(q.lm)
HHCovarEvals[k,1] <- hhcovarmodels[k]
HHCovarEvals[k,2] <- length(split(seq(nchar(hhcovarmodels[k])),unlist(strsplit(hhcovarmodels[k],"")))[['+']])+2
HHCovarEvals[k,3] <- summary(q.lm)$r.squared
HHCovarEvals[k,4] <- summary(q.lm)$adj.r.squared
HHCovarEvals[k,5] <- AIC(q.lm)
HHCovarEvals[k,6] <- BIC(q.lm)
HHCovarEvals[k,7] <- NA
HHCovarEvals[k,8] <- max(colldiag(q.lm)$condindx)
if(HHCovarEvals[k,2]==2) HHCovarEvals[k,9]<-NA else
HHCovarEvals[k,9] <- max(vif(q.lm))
HHCovarEvals[k,10] <- q.bptest$statistic
HHCovarEvals[k,11] <- q.bptest$p.value
q.moran <- lm.morantest(q.lm,q.listw)
HHCovarEvals[k,12] <- q.moran$statistic[1,1]
HHCovarEvals[k,13] <- q.moran$p.value[1,1]
q.lagrange <- lm.LMtests(q.lm,q.listw,test=c("LMerr","RLMerr","LMlag","RLMlag","SARMA"))
HHCovarEvals[k,14] <- q.lagrange$LMerr$statistic
HHCovarEvals[k,15] <- q.lagrange$LMerr$p.value
HHCovarEvals[k,16] <- q.lagrange$RLMerr$statistic
HHCovarEvals[k,17] <- q.lagrange$RLMerr$p.value
HHCovarEvals[k,18] <- q.lagrange$LMlag$statistic
HHCovarEvals[k,19] <- q.lagrange$LMlag$p.value
HHCovarEvals[k,20] <- q.lagrange$RLMlag$statistic
HHCovarEvals[k,21] <- q.lagrange$RLMlag$p.value
HHCovarEvals[k,22] <- q.lagrange$SARMA$statistic
HHCovarEvals[k,23] <- q.lagrange$SARMA$p.value
q.err <- errorsarlm(formula=as.formula(c("DeltaHHCGI~",hhcovarmodels[k])),data=deltasnna,q.listw,tol.solve=1.0e-18)
HHCovarEvals[k,24] <- q.err$LL
HHCovarEvals[k,25] <- 2*(q.err$parameters-2)-2*q.err$LL
HHCovarEvals[k,26] <- -2*q.err$LL+(q.err$parameters-2)*log(nrow(deltasnna))
HHCovarEvals[k,27] <- summary(q.err)$Wald1$statistic
HHCovarEvals[k,28] <- summary(q.err)$LR1$statistic[1]
q.bptest <- bptest.sarlm(q.err)
HHCovarEvals[k,29] <- q.bptest$statistic
HHCovarEvals[k,30] <- q.bptest$p.value
q.durbin <- lagsarlm(formula=as.formula(c("DeltaHHCGI~",hhcovarmodels[k])),data=deltasnna,q.listw,tol.solve=1.0e-18,type="mixed")
durbin.test <- LR.sarlm(q.durbin,q.err)
HHCovarEvals[k,31] <- durbin.test$statistic
HHCovarEvals[k,32] <- 1-pchisq(durbin.test[[1]][1],q.lm$rank-1)
HHCovarEvals[k,33] <- (summary(q.err)$LR1$statistic)[1]
HHCovarEvals[k,34] <- (summary(q.err)$LR1$p.value)[1]
q.lmtest <- lm.LMtests(q.err$residuals,q.listw,test="LMerr")
HHCovarEvals[k,35] <- q.lmtest$LMerr$statistic[1,1]
HHCovarEvals[k,36] <- q.lmtest$LMerr$p.value[1,1]
}
</code></pre>
<p>This loop takes <code>hhcovarmodels</code>, a list of the right-hand side of 5000 linear models (as characters, e.g. <code>"Intercept + X + Y + Z"</code>, fits lm objects and writes some diagnostics to a data frame, and then fits <code>errorsarlm</code> objects (the Spatial Error Model) and writes some other diagnostics to the same data frame.</p>
<ol>
<li><p>One suggestion I've seen elsewhere is to instantiate the output data frame to its full size before running the loop, as opposed to growing it by accretion. Would this be properly accomplished with something like</p>
<p>HHCovarEvals <- data.frame(matrix(ncol=36,row=5000))</p></li>
</ol>
<p>?</p>
<ol>
<li><p>I've also seen it suggested that any code that can be vectorized should be vectorized. I'm afraid that I'm not sure what this means in my own example. Are there components that could clearly be vectorized?</p></li>
<li><p>Does my repeated use of <code>as.formula</code> to take a character-formatted definition of the right-hand side of these models and fit <code>lm</code> and <code>errorsarlm</code> slow things down?</p></li>
</ol>
<p>(For reference, with 5000 iterations, this operation takes about 3 hours.) </p>
<ol>
<li>I've also seen it suggested that it may be faster to write the results as a vector and then add that vector to the data frame. I understand how and why this might work if the result is a column that needs to be added to the output data frame. In this instance, though, my loop adds <em>rows</em> to the data frame, and I can't see how I would add to the data frame, except with <code>rbind</code>, which seems inefficient.</li>
</ol>
<p>My apologies if the code is so profoundly ugly that it causes you aesthetic or moral harm =) I'm a beginner.</p>
<p>Thanks in advance ...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T18:24:41.753",
"Id": "35308",
"Score": "0",
"body": "Tried to post a short answer here but, due to formatting issues, I'll post it as an answer. If you need help with it let me know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:03:38.353",
"Id": "35309",
"Score": "0",
"body": "You should learn to use the R profiling tools. At the moment with no data to work with you're just asking for guesses. My guess is that it is the calls to regression functions and summary() calls that are using most of the cycles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:11:13.493",
"Id": "35310",
"Score": "0",
"body": "Thanks @Dwin - the approach described at [this page](http://www.stat.berkeley.edu/~nolan/stat133/Fall05/lectures/profilingEx.html) is to use rprof([output file]) and rprof(NULL) around the code, and then consult the output file to see what's taking the most time. Are there other approaches you might recommend?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T08:26:23.020",
"Id": "35329",
"Score": "0",
"body": "Operations on data.frames (subsetting, assignment,...) are slow. If all the results are numeric, you should use a matrix to store them. And definitely pre-allocate the output data structure."
}
] |
[
{
"body": "<p>Instead of using a <code>for</code> loop you could write a function <code>fitModels</code> that executes all the tasks with any given model, and call it from</p>\n\n<pre><code>lapply(X=hhcovarmodels, FUN=fitModels)\n</code></pre>\n\n<p>Also, since it seems that each fit is independent of the rest, you could use a package that performs parallel computation, such as <code>foreach</code> via <code>plyr</code>:</p>\n\n<pre><code>library(package=plyr)\nldply(.data=hhcovarmodels, .fun=fitModels, .parallel=TRUE)\n</code></pre>\n\n<p>This way you can use more resources from the computer.</p>\n\n<hr>\n\n<p><strong>Explanation about suggesting plyr and parallelization</strong></p>\n\n<p>The way I see it, @dubhousing is basically fitting thousands of models and extracting the information from them. I am assuming this is what he should do, and since this is a question in stackoverflow and not in CrossValidated I am providing practical advice as how to go about doing it. I could bet that refining the model selection based on what is known about the data would reduce execution time (by cutting on model bulk), but that is not the issue at hand.</p>\n\n<p>That said, there is not much to optimize in his code other than what he already mentioned (<em>i.e.</em> pre-allocating the dataframe and avoiding an explicit for loop). The other things you could tweak are the model fitting functions, but that is neither advisable nor in the scope of this answer.</p>\n\n<p><em>So, issue at hand:</em> fit thousands of models independent of each other, possibly on a local dataset, assuming that the bulk of computation is due to the large number of models and not to model fitting itself. We can think of each iteration of the function as a relatively small operation, which we can distribute over an array of processing units (lets think some three or four processes per core, the model fitting being not very computationally demanding).</p>\n\n<p>Given that, in appearance, the code that would constitute <code>fitModels</code> is not further optimizeable, the next best alternative is parallel processing. Even if each run is non-optimal (or even arbitrarily slow), the serialized execution would be slower than a parallelized execution, since we assume that each run does not have a high overhead. even in the worst case (fitting only two models at a time, in parallel) would give speeds slightly larger than the serialized code.</p>\n\n<p>All of this, of course, would be useless if each fit consumes too many resources (huge dataset or very high overhead).</p>\n\n<p>This is where <code>plyr</code> comes into play. Although it increases overhead, it is a very convenient platform to provide the parallel backend with, as @DWin said, compact code.</p>\n\n<p>Not being provided with example data and models, this is as far as I will go.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:05:35.077",
"Id": "35311",
"Score": "0",
"body": "Suggestions to use `plyr` when the problem is speed seem dubious. It has serious advantages in compact expression, but rarely has it been a comptetitor in the speed department."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:13:24.020",
"Id": "35312",
"Score": "0",
"body": "Thanks for your reply Oscar. Is it a general principle that a function encompassing a single iteration, when used with lapply, is more efficient than a loop of all iterations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:14:41.523",
"Id": "35313",
"Score": "0",
"body": "@Dwin After reading [this post](http://librestats.com/2012/03/15/a-no-bs-guide-to-the-basics-of-parallelization-in-r/) at librestats, I'm wondering if `clusterapply` might be a good approach for me, since I'm running Windows. Do you think that would be a promising approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:21:27.830",
"Id": "35314",
"Score": "0",
"body": "To quote from that page: \"Just remember to try basic optimization before you jump to parallelization. Slow serial code produces slow parallel code.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:26:09.217",
"Id": "35315",
"Score": "0",
"body": "@DWin understood =) I will put one foot in front of another."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T20:17:20.640",
"Id": "35316",
"Score": "0",
"body": "@DWin yes, I myself have ended with longer execution times but compact code, just as you suggested. I'll elaborate in the post further about my suggestion of `plyr` and parallelization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T20:53:44.820",
"Id": "35317",
"Score": "0",
"body": "@dubhousing It's not a general principle. Mostly depends on what you are doing. In this example I would say that it does not improve the speed much on the looping side, but probably it would on the data collection side. A big advantage of `lapply` over `for` is in parallelization, with `plyr::ldply` given as a convenient example. Check [this post](http://stackoverflow.com/questions/2275896/is-rs-apply-family-more-than-syntactic-sugar) for a nice discussion on this subject. Also check [this other one](http://stackoverflow.com/questions/5533246/why-is-apply-method-slower-than-a-for-loop-in-r)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T18:27:46.217",
"Id": "22950",
"ParentId": "22949",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T18:09:49.943",
"Id": "22949",
"Score": "1",
"Tags": [
"r",
"optimization"
],
"Title": "Which components of this r loop are inefficient?"
}
|
22949
|
<p>Here I have some simple code that worries me, look at the second to last line of code, I have to return spam in order to change spam in the global space. Also is it bad to be writing code in this space and I should create a function or class to call from that space which contains most my code?</p>
<p>I found out very recently that I never even understood the differences between Python's identifiers compared to C or C++'s variables. This helps put into perspective why I always have so many errors in Python.</p>
<p>I do not want to continue writing code and get into a bad habit and this is why I want your opinion.</p>
<p>I also have a tendency to do things like <code>spam = fun()</code> because I do not know how to correctly make Python call a function which changes a variable in the scope of where the function was called. Instead I simply return things from the functions never learning how to correctly write code, I want to change that as soon as possible.</p>
<pre><code>import random
MAX = 20
def randomize_list(the_list, x=MAX):
for i in range(len(the_list)):
the_list[i] = random.randint(1, x)
def lengthen_list(the_list, desired_length, x=MAX):
if len(the_list) >= desired_length:
print "erroneous call to lengthen_list(), desired_length is too small"
return the_list
while(len(the_list) < desired_length):
the_list.append(random.randint(1, x))
# organize the_set
the_list = set(the_list)
the_list = list(the_list)
return the_list
spam = list(range(10))
randomize_list(spam, MAX)
print "the original list:"
print spam, '\n'
spam = set(spam)
spam = list(spam)
print "the set spam:"
print spam
print "the set spam with length 10"
spam = lengthen_list(spam, 10, MAX)
print spam
</code></pre>
<p>Please help me adopt a style which correctly fixes, in particular, the second to last line of code so that I do not need the function to do return things in order to work, if this is even possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:07:22.220",
"Id": "35318",
"Score": "0",
"body": "Well, I am not a python expert and this is more like my general convention than python convention. You should not reuse variable name. For example, set(spam) and list(spam) should not be assign to the same variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:14:50.947",
"Id": "35319",
"Score": "0",
"body": "@Tg. Yes I know what you mean. The point of the code I think you are talking about changes spam to a set and then back to a list. This is a quick and dirty way of removing repetitious values in the list and organizing them least to greatest in value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:28:26.850",
"Id": "35321",
"Score": "1",
"body": "Well, others already comment on most of your concern. For about your quick and dirty way, here is the better version.\n\nuniqSpam = list(set(spam))\n\nYou should avoid any one-time-use intermediate variable if it does not cluttering much on the right hand side."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-24T14:06:50.190",
"Id": "306783",
"Score": "0",
"body": "Since you wrote this question, our standards have been updated. Could you read [ask] and update your question to match what it is now?"
}
] |
[
{
"body": "<blockquote>\n <p>I also have a tendency to do things like spam = fun() because I do not\n know how to correctly make Python call a function which changes a\n variable in the scope of where the function was called.</p>\n</blockquote>\n\n<p>You can't. You cannot replace a variable in an outer scope. So in your case, you cannot replace the list with a new list, although you can modify the list. To make it clear</p>\n\n<pre><code>variable = expression\n</code></pre>\n\n<p>replaces a variable, whereas pretty much anything else:</p>\n\n<pre><code>variable[:] = expression\nvariable.append(expression)\ndel variable[:]\n</code></pre>\n\n<p>Modifies the object. The bottom three will take effect across all references to the object. Whereas the one before replaces the object with another one and won't affect any other references.</p>\n\n<p>Stylistically, it somestimes makes sense to have a function modify a list, and other times it makes sense for a function to return a whole new list. What makes sense depends on the situation. The one rule I'd pretty much always try to follow is to not do both. </p>\n\n<pre><code>def randomize_list(the_list, x=MAX):\n for i in range(len(the_list)):\n the_list[i] = random.randint(1, x)\n</code></pre>\n\n<p>This isn't a good place to use a modified list. The incoming list is ignored except for the length. It'd be more useful as a function that returns a a new list given a size something like:</p>\n\n<pre><code>def random_list(length, maximum = MAX):\n random_list = []\n for _ in range(length):\n random_list.append( random.randint(1, maximum) )\n return random_list\n\ndef lengthen_list(the_list, desired_length, x=MAX):\n if len(the_list) >= desired_length:\n print \"erroneous call to lengthen_list(), desired_length is too small\"\n</code></pre>\n\n<p>Don't report errors by print, raise an exception</p>\n\n<pre><code> raise Exception(\"erroneous call...\")\n\n\n return the_list\n while(len(the_list) < desired_length):\n the_list.append(random.randint(1, x))\n # organize the_set\n the_list = set(the_list)\n the_list = list(the_list)\n</code></pre>\n\n<p>That's not an efficient way to do that. You constantly convert back between a list and set. Instead do something like</p>\n\n<pre><code> new_value = random.randint(1, maximum)\n if new_value not in the_list:\n the_list.append(new_value)\n</code></pre>\n\n<p>That way you avoid the jumping back and forth, and it also modifies the original object rather then creating a new list.</p>\n\n<pre><code> return the_list\n</code></pre>\n\n<p>This particular function could go either way in terms of modifying or returning the list. Its a judgement call which way to go. </p>\n\n<blockquote>\n <p>Also is it bad to be writing code in this space and I should create a\n function or class to call from that space which contains most my code?</p>\n</blockquote>\n\n<p>Yes, you should really put everything in a function and not at the main level for all but the most trivial scripts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:21:29.633",
"Id": "35320",
"Score": "0",
"body": "I have not seen code like yours such as: `for _ in range(length):`, does the underscore just mean that we are not going to use some value from the range, we are instead going to do something `length` times?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T11:03:38.803",
"Id": "35331",
"Score": "0",
"body": "@Leonardo: yes, it's conventional to use `_` for a loop variable that's otherwise unused. See [here](http://stackoverflow.com/q/1739514/68063) or [here](http://stackoverflow.com/q/5893163/68063)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:16:23.067",
"Id": "22952",
"ParentId": "22951",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22952",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T04:57:04.963",
"Id": "22951",
"Score": "2",
"Tags": [
"python"
],
"Title": "What parts of my Python code are adopting a poor style and why?"
}
|
22951
|
<p>I needed short, unique, seemingly random URLs for a project I'm working on, so I put together the following after some research. I believe it's working as expected, but I want to know if there's a better or simpler way of doing this. Basically, it takes an integer and returns a string of the specified length using the character list. I'm new to Python, so help is much appreciated.</p>
<pre><code>def genkey(value, length=5, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', prime=694847539):
digits = []
base = len(chars)
seed = base ** (length - 1)
domain = (base ** length) - seed
num = ((((value - 1) + seed) * prime) % domain) + seed
while num:
digits.append(chars[num % base])
num /= base
return ''.join(reversed(digits))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T08:18:10.170",
"Id": "35328",
"Score": "1",
"body": "Without knowing your concrete requirements: What do you think about hashing your value and take the first x characters? Maybe you will need some additional checking for duplicates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:33:51.083",
"Id": "35366",
"Score": "0",
"body": "@mnhg I thought about that as well. This sort of became an exercise for its own sake at some point. How would you suggest handling duplicates?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T05:02:15.627",
"Id": "35444",
"Score": "0",
"body": "As this seems not performance critical, I would simple check the existing in the indexed database column that is storing the short url mapping. (Might also be a hashmap.) If I find a conflict I would a attached the current time/spaces/whatever and try it again or just rehash the hash once again."
}
] |
[
{
"body": "<p>The trouble with using a pseudo-random number generator to produce your shortened URLs is, <em>what do you do if there is a collision?</em> That is, what happens if there are values <code>v</code> and <code>w</code> such that <code>v != w</code> but <code>genkey(v) == genkey(w)</code>? Would this be a problem for your application, or would it be entirely fine?</p>\n\n<p>Anyway, if I didn't need to solve the collision problem, I would use Python's <a href=\"http://docs.python.org/2/library/random.html\" rel=\"nofollow\">built-in pseudo-random number generator</a> for this instead of writing my own. Also, I would add a docstring and some <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p>\n\n<pre><code>import random\nimport string\n\ndef genkey(value, length = 5, chars = string.ascii_letters + string.digits):\n \"\"\"\n Return a string of `length` characters chosen pseudo-randomly from\n `chars` using `value` as the seed.\n\n >>> ' '.join(genkey(i) for i in range(5))\n '0UAqF i0VpE 76dfZ oHwLM ogyje'\n \"\"\"\n random.seed(value)\n return ''.join(random.choice(chars) for _ in xrange(length))\n</code></pre>\n\n<p><strong>Update:</strong> you clarified in comments that you <em>do</em> need to avoid collisions, and moreover you know that <code>value</code> is a number between 1 and <code>domain</code> inclusive. In that case, you're right that your transformation is an injection, since <code>prime</code> is coprime to <code>domain</code>, so your method is fine, but there are several things that can be done to simplify it:</p>\n\n<ol>\n<li><p>As far as I can see, there's no need to subtract 1 from <code>value</code>.</p></li>\n<li><p>There's no need to use the value <code>seed</code> at all. You're using this to ensure that you have at least <code>length</code> digits in <code>num</code>, but it's easier just to generate exactly <code>length</code> digits. (This gives you a bigger domain in any case.)</p></li>\n<li><p>There's no need to call <code>reversed</code>: the reverse of a pseudo-random string is also a pseudo-random string.</p></li>\n</ol>\n\n<p>Applying all those simplifications yields the following:</p>\n\n<pre><code>def genkey(value, length=5, chars=string.ascii_letters + string.digits, prime=694847539):\n \"\"\"\n Return a string of `length` characters chosen pseudo-randomly from\n `chars` using `value` as the seed and `prime` as the multiplier.\n `value` must be a number between 1 and `len(chars) ** length`\n inclusive.\n\n >>> ' '.join(genkey(i) for i in range(1, 6))\n 'xKFbV UkbdG hVGer Evcgc 15HhX'\n \"\"\"\n base = len(chars)\n domain = base ** length\n assert(1 <= value <= domain)\n n = value * prime % domain\n digits = []\n for _ in xrange(length):\n n, c = divmod(n, base)\n digits.append(chars[c])\n return ''.join(digits)\n</code></pre>\n\n<p>A couple of things you might want to beware of:</p>\n\n<ol>\n<li><p>This pseudo-random scheme is not cryptographically strong: that is, it's fairly easy to go back from the URL to the value that produced it. This can be a problem in some applications.</p></li>\n<li><p>The random strings produced by this scheme may include real words or names in human languages. This could be unfortunate in some applications, if the resulting words were offensive or otherwise inappropriate.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:29:09.780",
"Id": "35365",
"Score": "0",
"body": "With the system I have in place now, collisions would be a problem. I'm under the impression that the code I wrote would not produce collisions for values within the `domain` (901,356,496 for length=5 and base=62). Do you know of any ways to test this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T20:44:47.753",
"Id": "35399",
"Score": "0",
"body": "Thanks for the great in-depth answer. How would you go about getting the initial value from the URL?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T20:49:18.643",
"Id": "35401",
"Score": "0",
"body": "[Extended Euclidean algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T11:25:57.170",
"Id": "22957",
"ParentId": "22954",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22957",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:51:44.350",
"Id": "22954",
"Score": "6",
"Tags": [
"python"
],
"Title": "Unique short string for URL"
}
|
22954
|
<p>I'm currently working on a system using WCF to communicate between a Windows Service and one or multiple clients. Service is required to answer clients calls, as well as notify them of certain events, which is why I implemented a callback feature using simplified subscriber model. Callback interface has methods with various signatures and I'd like to use a single method to invoke one of them for all subscribers (placing enumerating over them and exception handling in one place). At first I tried approach with an enum containing interface methods and a switch statement to invoke particular method.</p>
<pre><code>private enum CallbackFunc { Method1, Method2, Method3 }
private static void InvokeCallback(CallbackFunc callbackFunc, params object[] args)
{
foreach (var subscriber in subscribers)
{
try
{
switch (callbackFunc)
{
case CallbackFunc.Method1:
subscriber.Method1((int)args[0]);
break;
case CallbackFunc.Method2:
Foo foo = args[0] as Foo;
if (foo != null)
subscriber.Method2(foo , args.Length > 1 ? args[1] as List<Bar> : null);
break;
case CallbackFunc.Method3:
subscriber.Method3((Bar)args[0], (Baz)args[1]);
break;
}
}
catch
{
//error handling
}
}
}
</code></pre>
<p>This solution works, but I don't like it very much... it's missing finesse. I figured I could do it more universally using delegates, at which I failed because of different method signatures. Next step was to use reflection with the following result:</p>
<pre><code>private static void InvokeCallback(System.Reflection.MethodInfo func, params object[] args)
{
foreach (var subscriber in subscribers)
{
try
{
func.Invoke(subscriber, args);
}
catch
{
//error handling
}
}
}
</code></pre>
<p>As you can see the code is much nicer, but I began to doubt if this is actually a better solution (for example because of a little reflection overhead, less nice function call).</p>
<pre><code>public static void Method1(int a)
{
InvokeCallback(typeof(ICallback).GetMethod("Method1"), a);
InvokeCallback(CallbackFunc.Method1, a);
}
public static void Method2(Foo foo, List<Bar> bars)
{
InvokeCallback(typeof(ICallback).GetMethod("Method2"), foo, bars);
InvokeCallback(CallbackFunc.Method2, foo, bars);
}
public static void Method3(Bar bar, Baz baz)
{
InvokeCallback(typeof(ICallback).GetMethod("Method3"), bar, baz);
InvokeCallback(CallbackFunc.Method3, bar, baz);
}
</code></pre>
<p>I'd like to ask you which of these approaches is better or suggest a better solution. Any help will be much appreciated, thanks in advance. </p>
|
[] |
[
{
"body": "<p>Why not expose a lambda expression like this (assuming that <code>_subscribers</code> is a field of type <code>List<ICallback></code>):</p>\n\n<pre><code>private void InvokeCallbacks(Action<ICallback> callbackFunc)\n{\n _subscribers.ForEach(callbackFunc);\n}\n</code></pre>\n\n<p>and usage would be:</p>\n\n<pre><code>public void Method1(int a)\n{\n InvokeCallbacks(callback => callback.Method1(a));\n}\n\npublic void Method2(Foo foo, List<Bar> bars)\n{\n InvokeCallbacks(callback => callback.Method2(foo, bars));\n}\n\npublic void Method3(Bar bar, Baz baz)\n{\n InvokeCallbacks(callback => callback.Method3(bar, baz));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:25:44.210",
"Id": "35339",
"Score": "0",
"body": "Perfect! This is exactly what I was looking for. Thank you :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:03:09.543",
"Id": "22962",
"ParentId": "22958",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22962",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T12:22:28.473",
"Id": "22958",
"Score": "2",
"Tags": [
"c#",
"reflection"
],
"Title": "Multiple target method invocation wrapper"
}
|
22958
|
<p>This code loads the data for <a href="http://projecteuler.net/problem=18" rel="nofollow">Project Euler problem 18</a>, but I feel that there must be a better way of writing it. Maybe with a double list comprehension, but I couldn't figure out how I might do that. It is a lot more difficult since the rows to split up are not uniform in length.</p>
<pre><code>def organizeVar():
triangle = "\
75,\
95 64,\
17 47 82,\
18 35 87 10,\
20 04 82 47 65,\
19 01 23 75 03 34,\
88 02 77 73 07 63 67,\
99 65 04 28 06 16 70 92,\
41 41 26 56 83 40 80 70 33,\
41 48 72 33 47 32 37 16 94 29,\
53 71 44 65 25 43 91 52 97 51 14,\
70 11 33 28 77 73 17 78 39 68 17 57,\
91 71 52 38 17 14 91 43 58 50 27 29 48,\
63 66 04 68 89 53 67 30 73 16 69 87 40 31,\
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
triangle = [row for row in list(triangle.split(","))]
adjTriangle = []
for row in range(len(triangle)):
adjTriangle.append([int(pos) for pos in triangle[row].split(" ")])
return adjTriangle
</code></pre>
<p>The code converts this string into a list of lists of <code>int</code>s where the first list contains 75, the second list 95, 64, the third list 17, 47, 82, the fourth list 18, 35, 87, 10 and so on to the bottom row.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:28:28.237",
"Id": "35340",
"Score": "0",
"body": "Also there's no need to `list()` the `trianle.split(\",\")`, `split` will *always* return a list."
}
] |
[
{
"body": "<ol>\n<li><p>Avoid the need to escape the newlines by using Python's <a href=\"http://docs.python.org/2/reference/lexical_analysis.html#string-literals\" rel=\"nofollow\">triple-quoted strings</a> that can extend over multiple lines:</p>\n\n<pre><code>triangle = \"\"\"\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\"\"\"\n</code></pre></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.strip\" rel=\"nofollow\"><code>strip</code> method</a> to remove the whitespace at the beginning and end.</p></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.splitlines\" rel=\"nofollow\"><code>splitlines</code> method</a> to split the string into lines.</p></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.split\" rel=\"nofollow\"><code>split</code> method</a> to split each line into words.</p></li>\n<li><p>Use the built-in <a href=\"http://docs.python.org/2/library/functions.html#map\" rel=\"nofollow\"><code>map</code> function</a> to call <code>int</code> on each word.</p></li>\n</ol>\n\n<p>Putting that all together in a list comprehension:</p>\n\n<pre><code>>>> [map(int, line.split()) for line in triangle.strip().splitlines()]\n[[75],\n [95, 64],\n [17, 47, 82],\n [18, 35, 87, 10],\n [20, 4, 82, 47, 65],\n [19, 1, 23, 75, 3, 34],\n [88, 2, 77, 73, 7, 63, 67],\n [99, 65, 4, 28, 6, 16, 70, 92],\n [41, 41, 26, 56, 83, 40, 80, 70, 33],\n [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],\n [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],\n [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],\n [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],\n [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],\n [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]\n</code></pre>\n\n<p>In Python 3 <code>map</code> doesn't return a list, so you have to write</p>\n\n<pre><code>[list(map(int, line.split())) for line in triangle.strip().splitlines()]\n</code></pre>\n\n<p>instead. If you prefer a double list comprehension you can write it like this:</p>\n\n<pre><code>[[int(word) for word in line.split()] for line in triangle.strip().splitlines()]\n</code></pre>\n\n<p>but the version with <code>map</code> is shorter, and, I think, clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T12:51:38.207",
"Id": "35337",
"Score": "0",
"body": "Wow, that is awesome. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:46:43.270",
"Id": "35409",
"Score": "0",
"body": "Using Python 3.3 I haven't quite gotten this to work. The closest I get while trying to use the map form is:`[line.strip().split(' ') for line in triangle.strip().splitlines()]`. This returns everything correctly except ints. When I try to use map, as in `map(int, line.strip().split(' ')` or even just `map(int, line.split())` I get a bunch of these: `<map object at 0x0000000002F469E8>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:52:31.480",
"Id": "35410",
"Score": "0",
"body": "See revised answer. (Also, it's usually better to write `.split()` instead of `.split(\" \")` unless you really want `'a b'` to split into `['a', '', 'b']`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:03:15.463",
"Id": "35412",
"Score": "0",
"body": "I think also, if you try to put this into a function, you have to strip it twice; once for the two outside lines, and once for the indentation. If you don't, map will try to turn the extra space into ints, but will give an error when that happens... I didn't read your above comment in time. Alternatively I could just do that .split() to make it work. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:07:03.840",
"Id": "35414",
"Score": "0",
"body": "No, that's not necessary: `' a b '.split()` → `['a', 'b']`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T12:48:47.570",
"Id": "22960",
"ParentId": "22959",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T12:25:39.773",
"Id": "22959",
"Score": "2",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Organizing a long string into a list of lists"
}
|
22959
|
<p>In my Rails app I need to import some files from CSV and Excel files. I needed it in 2 models so I have written <code>lib/importable.rb</code>:</p>
<pre><code>module Importable
def self.included(base)
base.send :extend, ActAsMethods
end
module ActAsMethods
def act_as_importable(&block)
@import_block = block
send :extend, ImportableMethods
end
attr_reader :import_block
end
module ImportableMethods
def import_from(file, *args)
raise 'This model is not importable' if import_block.nil?
send(:before_import, *args) if respond_to? :before_import
sheet = open_spreadsheet(file)
header = sheet.row(1).map(&:to_sym)
(2..sheet.last_row).map do |i|
row = Hash[header.zip(sheet.row(i))]
import_block.call(row, *args)
end
end
private
def open_spreadsheet(file)
logger.info "Importing file #{file.original_filename}"
case File.extname(file.original_filename)
when '.csv' then Csv.new(file.path, nil, :ignore)
when '.xls' then Excel.new(file.path, nil, :ignore)
when '.xlsx' then Excelx.new(file.path, nil, :ignore)
when '.ods' then Openoffice.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
rescue
raise "Cannot open file: #{file.original_filename}"
end
end
end
class ActiveRecord::Base
include Importable
end
</code></pre>
<p>And in model I need to write, i.e.:</p>
<pre><code>class Invoice < ActiveRecord::Base
act_as_importable do |row, company|
invoice = company.invoices.find_or_initialize_by_name(row[:name].to_s)
vat_in = if row[:client].is_a? String
row[:client]
else
row[:client].to_i
end
client = company.clients.find_by_vat_in(vat_in.to_s)
invoice.client = client
invoice.pay_date = row[:pay_date]
invoice.full_amount = row[:full_amount].to_i
invoice.paid_amount = row[:paid_amount].to_i
invoice.save!
invoice
end
end
</code></pre>
<p>The importing in controller looks like:</p>
<pre><code> def save
file = params[:file]
logger.debug file.path
Invoice.transaction do
@invoices = Invoice.import_from(file, current_company)
@invoices.each(&:save)
end
rescue RuntimeError => error
logger.debug error
redirect_to import_company_clients_path, alert: I18n.t('invalid_file')
rescue ActiveRecord::RecordInvalid
redirect_to import_company_clients_path, alert: I18n.t('invalid_record')
else
respond_to do |format|
format.html
format.json { render json: @invoices }
end
end
</code></pre>
<p>But IMHO it's a little overbloated. Have you any suggedtions to make it more reagable and Gemified?</p>
|
[] |
[
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><p>Your code looks pretty good, but I personally wouldn't have written it as a mixable module, this code seemps completely independent from <code>ActiveRecord</code>. I'd write a <code>SpreadSheetReader</code> class and just use it from wherever you want (this way the code is more modular).</p></li>\n<li><p>Where is <code>import_from</code> called from? it seems some code is missing.</p></li>\n<li><p>This <code>vat_in</code> conditional seems too verbose. Which are the possible values of <code>row[:client]</code>?</p></li>\n</ul>\n\n<p>I'd write something like:</p>\n\n<pre><code>company = company_from_somewhere_i_dont_know\ncolumns = [:name, :client, <other columns>...]\n\nSpreadSheetReader.rows(:columns => columns).map do |row|\n invoice = company.invoices.find_or_initialize_by_name(row[:name].to_s)\n vat_in = row[:client].is_a?(String) ? row[:client] : row[:client].to_i.to_s\n client = company.clients.find_by_vat_in!(vat_in)\n invoice.update_attributes!({\n :pay_date => row[:pay_date],\n :full_amount => row[:full_amount].to_i,\n :paid_amount => row[:paid_amount].to_i,\n })\n invoice\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:18:42.573",
"Id": "22964",
"ParentId": "22961",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22964",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T12:58:43.320",
"Id": "22961",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Ruby ActiveRecord importing library"
}
|
22961
|
<pre><code>private String GetFacilityName(String facilityHexID) {
if (facilityHexID.equals(FACILITY_AIRCON_HEX_ID)) {
return FACILITY_AIRCON_NAME;
}
else if (facilityHexID.equals(FACILITY_FAN_HEX_ID)) {
return FACILITY_FAN_NAME;
}
return facilityHexID;
}
</code></pre>
<p>Or</p>
<pre><code>private String GetFacilityName(String facilityHexID) {
if (facilityHexID.equals(FACILITY_AIRCON_HEX_ID)) {
return FACILITY_AIRCON_NAME;
}
else if (facilityHexID.equals(FACILITY_FAN_HEX_ID)) {
return FACILITY_FAN_NAME;
}
else {
return facilityHexID;
}
}
</code></pre>
<p>They essentially do the same thing. I'm thinking first one is better from the standpoint of "Write more code only if you have to" and the second one is better from readability aspect.</p>
<p>I'd use a switch statement with default case but I'm using a old version of JDK.. so I can't use it on Strings.</p>
<p>Which one is better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:35:32.640",
"Id": "35380",
"Score": "2",
"body": "What about using a Map?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T10:46:18.973",
"Id": "35457",
"Score": "0",
"body": "How about using a `switch`? Java7 exists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:21:55.383",
"Id": "35516",
"Score": "0",
"body": "Is it possible to switch over to a custom Enum for your return string? It almost seems like it would best match up with this. I can't find the example on line that showed how to use the toValue version."
}
] |
[
{
"body": "<p>I'd remove both <code>else</code>s:</p>\n\n<pre><code>private String getFacilityName(String facilityHexId) {\n if (FACILITY_AIRCON_HEX_ID.equals(facilityHexId)) {\n return FACILITY_AIRCON_NAME;\n }\n if (FACILITY_FAN_HEX_ID.equals(facilityHexId)) {\n return FACILITY_FAN_NAME;\n }\n return facilityHexId;\n}\n</code></pre>\n\n<p>I think it's easier to follow. (It's called <a href=\"http://c2.com/cgi/wiki?GuardClause\">Guard Clause</a>.)</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p>I've switched the <code>equals</code> to <code>CONSTANT.equals(inputParameter)</code>. Now it handles <code>null</code> inputs too and does not throw <code>NullPointerException</code>.</p></li>\n<li><p>I've renamed the method to camelCase. It's more common in Java to start method names with small letters. (<a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a>)</p></li>\n<li><p>I've changed <code>ID</code> to <code>Id</code> in the variable names. I prefer camelCase here too because it's usually easier to read. From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T12:38:07.220",
"Id": "35642",
"Score": "1",
"body": "FWIW, Guard Clause is more about checking method invariants prior to logic execution. E.g. ``if (facilityHexId == null) return null;`` would be a Guard Clause."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T13:34:49.387",
"Id": "35643",
"Score": "1",
"body": "@ChrisKnight: I've thought the same when I wrote the answer but \"checks for trivial cases, and gets rid of them quickly\" (from the linked C2 wiki) seems appropriate here. http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html also reinforces that. What do you think?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T14:03:08.927",
"Id": "35645",
"Score": "1",
"body": "@palacsint: Well, to me, the name 'Guard Clause' implies its guarding against something which isn't the purpose of the if statements in the above code. In the refactoring.com link the line seems blurred between guarding against something and performing execution logic. Interesting link though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:37:43.160",
"Id": "22965",
"ParentId": "22963",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "22965",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:18:07.963",
"Id": "22963",
"Score": "3",
"Tags": [
"java"
],
"Title": "Which is a better style to write default return case in if-else"
}
|
22963
|
<p>I have a grid as </p>
<pre><code>>>> data = np.zeros((3, 5))
>>> data
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]]
</code></pre>
<p>i wrote a function in order to get the ID of each tile.</p>
<pre><code>array([[(0,0), (0,1), (0,2), (0,3), (0,4)],
[(1,0), (1,1), (1,2), (1,3), (1,4)],
[(2,0), (2,1), (2,2), (2,3), (2,4)]]
def get_IDgrid(nx,ny):
lstx = list()
lsty = list()
lstgrid = list()
for p in xrange(ny):
lstx.append([p]*nx)
for p in xrange(ny):
lsty.append(range(0,nx))
for p in xrange(ny):
lstgrid.extend(zip(lstx[p],lsty[p]))
return lstgrid
</code></pre>
<p>where nx is the number of columns and ny the number of rows</p>
<pre><code>test = get_IDgrid(5,3)
print test
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]
</code></pre>
<p>this function will be embed inside a class</p>
<pre><code>class Grid(object):
__slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell")
def __init__(self,xMin,yMax,nx,ny,xDist,yDist):
self.xMin = xMin
self.yMax = yMax
self.nx = nx
self.ny = ny
self.xDist = xDist
self.yDist= yDist
self.ncell = nx*ny
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:28:44.323",
"Id": "35382",
"Score": "2",
"body": "Good question. The only thing I'd suggest is actually having `get_IDgrid` in the class rather than saying that it will be embedded."
}
] |
[
{
"body": "<p>Numpy has built in functions for most simple tasks like this one. In your case, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html\" rel=\"nofollow\"><code>numpy.ndindex</code></a> should do the trick:</p>\n\n<pre><code>>>> import numpy as np\n>>> [j for j in np.ndindex(3, 5)]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p>You can get the same result in a similarly compact way using <a href=\"http://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> :</p>\n\n<pre><code>>>> import itertools\n>>> [j for j in itertools.product(xrange(3), xrange(5))]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p><strong>EDIT</strong> Note that the (now corrected) order of the parameters is reversed with respect to the OP's <code>get_IDgrid</code>.</p>\n\n<p>Both expressions above require a list comprehension, because what gets returned is a generator. You may want to consider whether you really need the whole list of index pairs, or if you could consume them one by one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:28:55.673",
"Id": "35374",
"Score": "0",
"body": "Thanks @jaime. Do you think insert the def of [j for j in np.ndindex(5, 3)] in the class can be correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:33:07.450",
"Id": "35376",
"Score": "0",
"body": "@Gianni It is kind of hard to tell without knowing what exactly you are trying to accomplish. I can't think of any situation in which I would want to store a list of all possible indices to a numpy array, but if you really do need it, then I guess it is OK."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:34:34.857",
"Id": "35379",
"Score": "0",
"body": "@jamie with [j for j in np.ndindex(5, 3)] return a different result respect my function and the Grid (see the example). Just invert the example :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:47:24.460",
"Id": "35381",
"Score": "1",
"body": "@Gianni I did notice that, it is now corrected. What `np.ndindex` does is what is known as [row major order](http://en.wikipedia.org/wiki/Row-major_order) arrays, which is the standard in C language, and the default in numpy. What your function is doing is column major order, which is the Fortran and Matlab way. If you are using numpy, it will probably make your life easier if you stick to row major."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:27:13.847",
"Id": "22973",
"ParentId": "22968",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22973",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:33:57.390",
"Id": "22968",
"Score": "1",
"Tags": [
"python",
"optimization",
"performance"
],
"Title": "python Improve a function in a elegant way"
}
|
22968
|
<p>Is there any point in wrapping this code in the self executing function declaring window and undefined? I've read that it improves performance etc... (NOTE I will be making use of the window at some point).</p>
<pre><code>(function (window, undefined) { // THIS BIT HERE!
var App = {
init: (function () {
$(document).ready(function () {
App.alertMessage('Hello world');
});
})(),
alertMessage: function (message) {
alert(message);
}
}
})(window); // end closure
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T19:25:59.710",
"Id": "35391",
"Score": "0",
"body": "If all you ask is why are those two arguments declared, then I think @dystroy's answer puts it simply. If you're also asking why the self-executing function in the first place: it prevents you from polluting the global object with variables you declare with `var`s."
}
] |
[
{
"body": "<p>There is only one positive result that I know : it lets minifiers replace <code>window</code> and <code>undefined</code> with shorter names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:50:36.127",
"Id": "22970",
"ParentId": "22969",
"Score": "0"
}
},
{
"body": "<h1>The IIFE/SEFE/closure/whatever</h1>\n\n<p>A quick discussion why we use \"closures\" for creating our code is that the purpose of the closure/IIFE/SEFE/whatever you want to call it, is to provide a scope where you are free to declare any variables for the internals to use, without polluting the global scope:</p>\n\n<pre><code>(function(ns){\n\n //I can declare tons of variables and functions here\n var a,b,c,d,e,f,g ...;\n\n //expose only foo to the namespace\n ns.foo = function(){\n //and foo can use them here\n }\n\n}(this.myNS = this.myNS || {}));\n\n//but out here, we call foo, use those variables\n//but none of those variables are visible\nmyNS.foo();\n\n//no a,b,c,d,e,f,g ... out here\n</code></pre>\n\n<h1><code>window</code></h1>\n\n<p>Now, in the case of <code>window</code>, the idea that they are passed into the function is to have a local reference of whatever was pointed by them. It's because of the usage of that IIFE/SEFE/closure and how the compiler works.</p>\n\n<pre><code>//-3-found \"a\" here\nvar a = 1\n(function(ns){\n //-2-no \"a\" here, going up\n ns.foo = function(){\n //-1-no \"a\" here, going up\n console.log(a);\n }\n}(this.myNS = this.myNS || {}));\n\nmyNS.foo();\n</code></pre>\n\n<p>A quick trip into the how the compiler works is that when it tries to look for a variable/function, it searches through the local function scope first. If that variable/function is not found, it will look for it in the outer/containing scope. This goes on until the compiler finds that value or when you reach the global scope and declares it as non-existent. </p>\n\n<p>In the code above, you crossed 2 scopes in order to find <code>a</code>. If <code>a</code> was declared lower into the scope, you could have minimized crossings. Now, wouldn't it be better if you provided window locally instead of having the compiler find it? YES, although:</p>\n\n<ul>\n<li>performance gain is almost negligible </li>\n<li>code structure might be more important than this minor optimization</li>\n</ul>\n\n<h1><code>undefined</code></h1>\n\n<p>For <code>undefined</code>, it's because <code>undefined</code> is mutable (it's not constant/final). Its value <em>can</em> be changed so that it would not be <code>undefined</code> anymore (but somewhat \"pseudo-defined\"). A quick code about that <a href=\"https://gist.github.com/easierbycode/1953667\" rel=\"nofollow\">can be found here</a>:</p>\n\n<pre><code>var a = {};\na.b === undefined; // true because property b is not set\nundefined = 42;\na.b === undefined; // false, because undefined is something else\n</code></pre>\n\n<p>So what they did to overcome this \"definable <code>undefined</code>\" was to pass nothing into the function, and by default, passing nothing to the function and naming it something in the function gives it the value of \"true <code>undefined</code>\".</p>\n\n<hr>\n\n<p>Personally, I don't pass in <code>window</code> and <code>undefined</code> into my closure for some reasons:</p>\n\n<ul>\n<li><p>I don't check potentially undefined values against <code>undefined</code>. Since undefined values are falsy, loose comparison will tell if it is undefined or more like \"unusable\":</p>\n\n<pre><code>//instead of this:\nif(potentiallyUndefined === undefined){...do stuff...}\nif(typeof potentiallyUndefined === 'undefined'){...do stuff...}\n\n//you can do this\nif(potentiallyUndefined){...do stuff...}\n</code></pre></li>\n<li><p>Like I said, it's a minor/negligible performance gain, so I don't pass in <code>window</code>. Besides, how much of my code uses <code>window</code> anyway? </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:42:22.440",
"Id": "35519",
"Score": "0",
"body": "Adding a little to your answer:\nhttp://stackoverflow.com/questions/14567055/immutable-undefined-in-self-invoking-functions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T01:54:13.280",
"Id": "22998",
"ParentId": "22969",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:46:42.093",
"Id": "22969",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Name-spaced JavaScript wrapped in self executing function"
}
|
22969
|
<p>I wrote function to generate nearly sorted numbers:</p>
<pre><code>def nearly_sorted_numbers(n):
if n >= 100:
x = (int)(n/10)
elif n >= 10:
x = 9
else:
x = 4
numbers = []
for i in range(1,n):
if i%x==0:
numbers.append(random.randint(0,n))
else:
numbers.append(i)
return numbers
</code></pre>
<p>Have you any idea how improve my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T19:58:55.010",
"Id": "35394",
"Score": "0",
"body": "What's the purpose of this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T20:26:58.053",
"Id": "35398",
"Score": "0",
"body": "I want to make performance test for sorting algorithms and this function should prepare input data according to x parameter (length of input data)."
}
] |
[
{
"body": "<pre><code>def nearly_sorted_numbers(n):\n if n >= 100:\n x = (int)(n/10)\n</code></pre>\n\n<p>Use <code>int(n//10)</code>, the <code>//</code> explicitly request integer division and python doesn't have casts</p>\n\n<pre><code> elif n >= 10:\n x = 9\n else:\n x = 4 \n</code></pre>\n\n<p>I wouldn't name the variable <code>x</code>, as it gives no hint as to what it means. I'd also wonder whether it wouldn't be better as a parameter to this function. It seems out of place to be deciding that here.</p>\n\n<pre><code> numbers = [] \n for i in range(1,n):\n if i%x==0: \n numbers.append(random.randint(0,n))\n else:\n numbers.append(i)\nreturn numbers\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T21:20:33.740",
"Id": "22982",
"ParentId": "22974",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22982",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:33:46.550",
"Id": "22974",
"Score": "2",
"Tags": [
"python"
],
"Title": "Function to generate nearly sorted numbers"
}
|
22974
|
<p>I have the following jQuery click functions:</p>
<pre><code>$childCheckbox.click(function(){
if(!$(this).hasClass('checked') && !$parentCheckbox.hasClass('checked')){
$(this).attr('checked', 'checked').addClass('checked');
$parentCheckbox.prop('indeterminate',true);
}
else if($(this).hasClass('checked')){
$(this).removeAttr('checked', 'checked').removeClass('checked');
$parentCheckbox.prop('indeterminate',false);
}
});
$subparentCheckbox.click(function(){
if(!$(this).hasClass('checked') && !$parentCheckbox.hasClass('checked')){
$(this).attr('checked', 'checked').addClass('checked');
$parentCheckbox.prop('indeterminate',true);
}
else if($(this).hasClass('checked')){
$(this).removeAttr('checked', 'checked').removeClass('checked');
$parentCheckbox.prop('indeterminate',false);
}
});
</code></pre>
<p>As you can see both are exactly the same with the exception of the "selector". Is there a good way to combine these to minimize code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T23:27:57.737",
"Id": "38919",
"Score": "0",
"body": "Tip: Store the result of `$(this)` in a temporary variable to avoid repeated calls to jQuery: `var $this = $(this);`"
}
] |
[
{
"body": "<p>Here are 3 - there are more, no doubt</p>\n\n<ol>\n<li><p>Give both checkboxes a class and use that as the selector </p>\n\n<pre><code>$(\".someClass\").click( ... )\n</code></pre></li>\n<li><p>Declare the event handler elsewhere, and use it anywhere: </p>\n\n<pre><code>function checkboxClick(event) {...}; \n\n$subparentCheckbox.click(checkboxClick); \n$childCheckbox.click(checkboxClick);\n</code></pre></li>\n<li><p>Use <code>.add</code> to combine the two checkboxes into one collection before calling <code>.click</code> like so </p>\n\n<pre><code>$subparentCheckbox.add($childCheckbox).click(...)`\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T17:04:19.307",
"Id": "35513",
"Score": "0",
"body": "You can call the .on() method straight away, since if you look in jQuery source, .click() refers right back to .on() anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T17:53:55.103",
"Id": "35514",
"Score": "1",
"body": "@JonnySooter True. I actually prefer using `.on()` in my own code even when there are aliasses like `.click()`. Keeps the code consistent."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T19:34:14.750",
"Id": "22980",
"ParentId": "22976",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22980",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:07:37.620",
"Id": "22976",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Two click functions doing the same thing with difference the selector"
}
|
22976
|
<p>first of all sorry for this easy question. I have a class</p>
<pre><code>class Grid(object):
__slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell","IDtiles")
def __init__(self,xMin,yMax,nx,ny,xDist,yDist):
self.xMin = xMin
self.yMax = yMax
self.nx = nx
self.ny = ny
self.xDist = xDist
self.yDist= yDist
self.ncell = nx*ny
self.IDtiles = [j for j in np.ndindex(ny, nx)]
if not isinstance(nx, int) or not isinstance(ny, int):
raise TypeError("an integer is required for nx and ny")
</code></pre>
<p>where</p>
<pre><code>xMin = minimum x coordinate (left border)
yMax = maximum y coordinate (top border)
nx = number of columns
ny = number of rows
xDist and yDist = resolution (e.g., 1 by 1)
</code></pre>
<p>nx and ny need to be an integer. I wish to ask where is the most elegant position for the TypeError. Before all self. or in the end?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:40:58.530",
"Id": "35384",
"Score": "0",
"body": "Ideally, you should write your whole Grid class and then show it to us. Then we'd suggest all the ways in which it could be improved rather then asking lots of specific questions."
}
] |
[
{
"body": "<pre><code>class Grid(object):\n __slots__= (\"xMin\",\"yMax\",\"nx\",\"ny\",\"xDist\",\"yDist\",\"ncell\",\"IDtiles\")\n def __init__(self,xMin,yMax,nx,ny,xDist,yDist):\n</code></pre>\n\n<p>Python convention says that argument should be lowercase_with_underscores</p>\n\n<pre><code> self.xMin = xMin\n self.yMax = yMax\n</code></pre>\n\n<p>The same convention holds for your object attributes</p>\n\n<pre><code> self.nx = nx\n self.ny = ny\n self.xDist = xDist\n self.yDist= yDist\n self.ncell = nx*ny\n self.IDtiles = [j for j in np.ndindex(ny, nx)]\n</code></pre>\n\n<p>This is the same as <code>self.IDtiles = list(np.ndindex(ny,nx))</code></p>\n\n<pre><code> if not isinstance(nx, int) or not isinstance(ny, int):\n raise TypeError(\"an integer is required for nx and ny\")\n</code></pre>\n\n<p>This would be more conventialy put at the top. But in python we prefer duck typing, and don't check types. You shouldn't really be checking the types are correct. Just trust that the user of the class will pass the right type or something close enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:45:17.073",
"Id": "35385",
"Score": "0",
"body": "Thanks @Winston Ewert. I didn't get about \"duck typing\". Do you suggest to avoid the \"TypeError\"? and the argument should be lowercase_with_underscores do you intend example self.__xMin = xMin?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:49:02.503",
"Id": "35386",
"Score": "1",
"body": "@Gianni, xMin should be x_min. There should be no capital letters in your names. Basically, only class names are named using capital letters. Re: duck typing. Just don't throw the TypeError. The python convention is to not check the types and just allow exceptions to be thrown when the type is used in an invalid manner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:58:11.073",
"Id": "35387",
"Score": "0",
"body": "Thank Winston really useful post for me. I have just the last question to clarify my doubts. inside a class if i have a function def get_distance_to_origin(xPoint,yPoint):\n#do some stuff (es euclidean distance). Do i need to write x_point and y_point in order to respect the style?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T19:00:47.677",
"Id": "35388",
"Score": "0",
"body": "@Gianni, yes, that is correct"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:40:14.643",
"Id": "22978",
"ParentId": "22977",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T18:17:04.027",
"Id": "22977",
"Score": "1",
"Tags": [
"python",
"optimization"
],
"Title": "Python right position for a Error message in a class"
}
|
22977
|
<p>I'm starting to learn Python and am trying to optimize this bisection search game.</p>
<pre><code>high = 100
low = 0
guess = (high + low)/2
print('Please think of a number between 0 and 100!')
guessing = True
while guessing:
print('Is your secret number ' + str(guess) + '?')
pointer = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if pointer == 'h':
high = guess
guess = (low + guess)/2
elif pointer == 'l':
low = guess
guess = (high + guess)/2
elif pointer == 'c':
guessing = False
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: ' + str(guess))
</code></pre>
|
[] |
[
{
"body": "<p>Some things I think would improve your code, which is quite correct:</p>\n\n<ul>\n<li>Having variables for <code>high</code> and <code>low</code>, you shouldn't hard code their values in the opening <code>print</code>.</li>\n<li>You should use <code>//</code> to make sure you are getting integer division.</li>\n<li>You can write <code>guess = (low + high) // 2</code> only once, if you place it as the first line inside the <code>while</code> loop.</li>\n<li>When checking for <code>pointer</code>, you may want to first convert it to lower case, to make sure both <code>h</code> and <code>H</code> are understood.</li>\n<li>Make your code conform to <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> on things like maximum line length.</li>\n<li>Using the <code>format</code> method of <code>str</code> can make more clear what you are printing.</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>high, low = 100, 0\n\nprint('Please think of a number between {0} and {1}!'.format(low, high))\n\nguessing = True\nwhile guessing:\n guess = (low + high) // 2\n print('Is your secret number {0}?'.format(guess))\n pointer = raw_input(\"Enter 'h' to indicate the guess is too high. \"\n \"Enter 'l' to indicate the guess is too low. \"\n \"Enter 'c' to indicate I guessed correctly.\").lower()\n if pointer == 'h' :\n high = guess\n elif pointer == 'l' :\n low = guess\n elif pointer == 'c':\n guessing = False\n else:\n print('Sorry, I did not understand your input.')\n\nprint('Game over. Your secret number was {0}.'.format(guess))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T00:44:11.667",
"Id": "22992",
"ParentId": "22984",
"Score": "8"
}
},
{
"body": "<p>In addition to Jaime's points.</p>\n\n<ol>\n<li><p>Get rid of the <code>guessing</code> flag, and just have an infinite loop with a break statement. </p></li>\n<li><p><code>pointer</code> is a really wierd name for that variable especially as it means something else in other programming languages.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T16:15:21.487",
"Id": "23029",
"ParentId": "22984",
"Score": "6"
}
},
{
"body": "<p>Completing the reply given by Jamie, with a remark:</p>\n\n<p>When you type <code>'c'</code> , even if the number is not the one you think of, always prints this part of code <code>print('Game over. Your secret number was {0}.'</code></p>\n\n<p>So, to avoid that, you must test also <code>(str(numbers) == str(guess))</code> on the branch of <code>(response == 'c')</code>:</p>\n\n<pre><code>high, low = 100, 0\nguess = (low + high) // 2\n\nnumbers = raw_input('Please think of a number between {0} and {1}!'.format(low, high))\n\nguessing = True\nwhile guessing:\n\n print('Is your secret number {0}?'.format(guess))\n response = raw_input(\"Enter 'h' to indicate the guess is too high. \"\n \"Enter 'l' to indicate the guess is too low. \"\n \"Enter 'c' to indicate I guessed correctly.\").lower()\n if response == 'h' :\n high = guess\n elif response == 'l' :\n low = guess\n elif (response == 'c') and (str(numbers) == str(guess)) : \n print('Game over. Your secret number was {0}.'.format(guess))\n break\n else:\n print('Sorry, I did not understand your input.')\n guess = (low + high) // 2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-16T05:04:20.793",
"Id": "315843",
"Score": "0",
"body": "The point of this guessing game is that the user never inputs the actual number since that is a _secret_."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-07T10:31:15.713",
"Id": "104018",
"ParentId": "22984",
"Score": "1"
}
},
{
"body": "<p>In addition to the other answers: when I choose the number 100 as my secret, the code will run into and endless loop, repeatedly asking me how it compares to 99. You can restrict the range more after you get an answer from the user.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-16T05:11:23.190",
"Id": "165923",
"ParentId": "22984",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:01:04.830",
"Id": "22984",
"Score": "6",
"Tags": [
"python",
"beginner",
"number-guessing-game"
],
"Title": "Bisection search game"
}
|
22984
|
<p>Often I need to clean a file name using <code>Path.GetInvalidFileNameChars()</code>, however I do not know of a way to search for any of the invalid letters (except by using Regex) in one pass.</p>
<pre><code>public string LoopMethod()
{
StringBuilder sb = new StringBuilder(fileName);
foreach(var invalidChar in Path.GetInvalidFileNameChars())
{
sb.Replace(invalidChar, '_');
}
return sb.ToString();
}
Regex invalidCharsRegex;
public void RegexMethodInit()
{
var invalidChars = Path.GetInvalidPathChars().Select(c => Regex.Escape(c.ToString())).ToString();
invalidCharsRegex = new Regex(string.Join("|", invalidChars));
}
public string RegexMethod(string fileName)
{
return invalidCharsRegex.Replace(fileName, "_");
}
</code></pre>
<p>Is one of those ways the "correct" way to to this or is there a better function I am missing?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:28:16.723",
"Id": "35416",
"Score": "0",
"body": "Related: http://forums.asp.net/t/1185961.aspx/1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T00:11:01.787",
"Id": "35423",
"Score": "0",
"body": "@Leonid [Path.GetInvalidPathChars()](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx) returns a `char[]` of characters that are illegal in a file name. What I wanted to know is what is the proper way to clean a filename from the returned `char[]`, is it to just loop like in my example, or is there a function that can take in a char[] and replace on a string in one operation?"
}
] |
[
{
"body": "<pre><code>foreach(var c in Path.GetInvalidPathChars())\n path = path.replace(c, '_')\n</code></pre>\n\n<p>That's a bit inefficient as it can allocate a string on every itteration, but usually not a problem. Alternative:</p>\n\n<pre><code>var chars = Path.GetInvalidPathChars()\npath = new string(path.Select(c => chars.Contains(c) ? '_' : c).ToArray())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:15:31.330",
"Id": "35530",
"Score": "0",
"body": "Ah, your answer is better, except that you are not using a set. Using a set may speed things up or slow them down depending on the size of the array. Either way this function should run fast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T10:50:51.107",
"Id": "35546",
"Score": "3",
"body": "Come to think of it, this code is doing File IO, any of these solutions is fine. They'll all be several levels of magnitude faster than doing File IO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T02:29:53.720",
"Id": "22999",
"ParentId": "22986",
"Score": "4"
}
},
{
"body": "<p>You can just make a regex of the <code>\"[abcdef]\"</code> type; it'll match all characters inside the brackets. No need to join them with <code>|</code>.</p>\n\n<p>I use this function, which uses the above regex type, and utilizes the fact you can simply make a string from a character array. Since it was written for converting a document title to a file name it uses spaces as replace characters, and somewhat trims the final result by collapsing any double spaces.</p>\n\n<pre><code>public static String MakeSafeFileName(String input)\n{\n // make regex of illegal characters list\n String illegalChars = \"[\"+ Regex.Escape(new String(Path.GetInvalidFileNameChars())) + \"]\";\n // replace characters by space\n input = Regex.Replace(input, illegalChars, \" \");\n // replace double spaces by a single space\n input = Regex.Replace(input, \"\\\\s\\\\s+\", \" \");\n return input;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-09T10:45:31.460",
"Id": "100400",
"ParentId": "22986",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22999",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:18:59.657",
"Id": "22986",
"Score": "4",
"Tags": [
"c#",
"strings"
],
"Title": "Replacing from a list chars in a string"
}
|
22986
|
<pre><code>CREATE PROCEDURE dbo.foo
AS
BEGIN
DECLARE @true BIT, @false BIT;
SET @true = 1;
SET @false = 0;
IF (some condition)
Select @true;
ELSE
Select @false;
END
</code></pre>
<p>SQL is not the language that I'm strongest in now, but the above stored procedure seems to be produce the desired functioning: returning the truth value of <code>some condition</code>.</p>
<p>Is there a better way to define this stored procedure? By the way, it runs on MS SQL 2008.</p>
|
[] |
[
{
"body": "<p>Since SQL Server has no Boolean data type, and since the bit values 1 and 0 are widely used and understood to represent true and false in many programming languages, I would simply return <code>0x1</code> or <code>0x0</code> as appropriate. I don't think that actually declaring <code>@true</code> and <code>@false</code> variables adds anything to the code.</p>\n\n<p>What might add something would be to return the value in an <a href=\"http://msdn.microsoft.com/en-us/library/ms187004%28v=sql.105%29.aspx\">output parameter</a> with a useful name:</p>\n\n<pre><code>CREATE PROCEDURE dbo.foo\n @IsTrue BIT OUTPUT\nAS\nBEGIN \n\nIF (condition)\n SET @IsTrue = 0x1\nELSE\n SET @IsTrue = 0x0\nEND\n</code></pre>\n\n<p>Especially if your procedure is called from other TSQL code, it is much easier to use an output parameter in the calling code than a result set. But if you're calling it from some other language then you can make that decision based on the calling language and framework. An output parameter is the preferred way to return scalar values from a procedure: use <code>SELECT</code> for returning result sets and <code>RETURN</code> for indicating the status of the procedure execution itself (succeeded, failed, failed with reason X etc.).</p>\n\n<p>And by 'useful name' I mean a name that indicates that the purpose of the variable is to store a true/false condition. Names starting with <code>Is</code> or <code>Has</code> are usually good. But please do not use a double-negative name: something like <code>if @IsNotEnabled = 0x0</code> is extremely difficult to parse mentally without interrupting your thoughts. <code>IsEnabled = 0x1</code> is far better.</p>\n\n<p>And depending on your condition, you might be able to use <code>CASE</code>:</p>\n\n<pre><code>SET @result = CASE WHEN (condition) THEN 0x1\n ELSE 0x0\n END \n</code></pre>\n\n<p>Whether or not that's preferable in this specific case is probably a question of taste, but <code>CASE</code> seems more 'SQL-like' to me. But <code>IF</code> and <code>CASE</code> do different things so you can't always substitute one for the other.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T13:44:57.353",
"Id": "23055",
"ParentId": "22989",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:25:26.223",
"Id": "22989",
"Score": "3",
"Tags": [
"sql",
"sql-server"
],
"Title": "SQL stored procedure that returns a boolean value?"
}
|
22989
|
<p>I have developed a jQuery slider and I want to implement it in WordPress (it will be a Featured Posts slider).</p>
<p>This is my slider logic:</p>
<ul>
<li>If there are 1 or 3 posts, show them but hide the <strong>prev</strong> and <strong>next</strong> buttons.</li>
<li>If there are more than 3 posts but <strong>less than or equal to</strong> 6, or <strong>more</strong> than 6, show navigation.</li>
<li>If there are <strong>more</strong> than 6 posts, show navigation.</li>
<li>After the animation is finished, hide the <strong>next</strong> button.</li>
</ul>
<p>In my code, there are a lot of <code>if</code> <code>else</code> statement. Is there a better way to write my slider?</p>
<p>You can look at <a href="http://jsfiddle.net/2pNZV/" rel="nofollow noreferrer">the Fiddle</a> and try to delete <code>div</code>s from <code>container</code> (slider and its navigation will remain functional...) </p>
<p>jQuery:</p>
<pre><code>$(document).ready(function () {
//If less than four divs Hide next button
if ($('.container div').length < 4) {
$('.next').hide();
}
//Also hide prev button
$('.prev').hide();
i = 0; //Click counter...
$('.next').click(function () {
//Prevent animation to mess up...
if ($('.container').is(':animated')) {
return false;
}
//Animate next click...
$('.container').animate({
marginLeft: '-=300'
}, 1000, function () {
i++; //Increase Var by One...
// Animation Callback If there are LESS than 6 divs
//hide next button
if ($('.container div').length <= 6) {
$('.next').hide();
}
// Else if there are more than 6 divs
//show next button
else if ($('.container div').length >= 6) {
$('.next').show();
}
//If first click exists show prev button
if (i == 1) {
$('.prev').show();
}
//If second click exists hide next button
else if (i == 2) {
$('.next').hide();
}
});
});
//on prev button click
$('.prev').click(function () {
//Prevent animation to mess up...
if ($('.container').is(':animated')) {
return false;
}
//Run animation...
$('.container').animate({
marginLeft: '+=300'
}, 1000, function () {
i--; //Decrase number of clicks
//If on prev click counter===0 hide prev button
//and show next button
if (i == 0) {
$('.prev').hide();
$('.next').show();
}
//Else if click===1 or click===0
//Show next button
else if (i == 1 || i == 0) {
$('.next').show();
}
});
});
});
</code></pre>
<p>HTML:</p>
<pre><code><div class="wrapper">
<div class="container">//If you delete those guys below //Slider and navigation will still work!!
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
<div class="seven"></div>
<div class="eight"></div>
<div class="nine"></div>
</div>
</div>
<!--/wrapper-->
<div class="nav_wrapper">
<div class="next">Next</div>
<div class="prev">Prev</div>
</div>
<!--/nav_wrapper-->
</code></pre>
|
[] |
[
{
"body": "<p>Here's how I would have written the slider. For a small project like this, you probably don't need to use <a href=\"http://msdn.microsoft.com/en-us/magazine/ff852808.aspx\" rel=\"nofollow noreferrer\">Prototypal Inheritance</a>. However, if you wanted to scale or add new functionality it would be a walk in the park. As you dive into larger projects, taking time to plan how you're going to structure your code will greatly improve your ability to write the same. Keep in mind if any part of this is confusing or unclear, I'll be happy to walk you through it. I've included the code in <a href=\"http://jsfiddle.net/4PUeY/1/\" rel=\"nofollow noreferrer\">this fiddle</a>, but I'll do most of the explaining in the commented code below.</p>\n<p>Now onto the fun stuff. You can place the following code in a separate .js file.</p>\n<pre><code>function Slider ( container, nav ) {\n //Get the elements passed in\n this.container = container;\n this.nav = nav;\n\n this.divs = this.container.find('div'); //Select the divs in the container\n this.divWidth = this.divs.width(); //Width of each div\n this.divsLen = this.divs.length; //Count how many divs there are\n\n this.current = 0; //Set the counter to the first div\n};\n\n//This function does all the animation\nSlider.prototype.transition = function( speed ) {\n this.container.animate({\n //Set the margin to a negative, hence the "-" in front.\n //Get the current div, multiply by its width, and multiply by 3.\n //This makes the animation move three divs at a time.\n //If you changed the width in the CSS, this code would work just fine.\n 'margin-left': -( this.current * this.divWidth * 3 )\n }, speed); //Here I get the speed from the click event set up in your html file.\n};\n\n//Here is where it might get tricky. \n//This function controls the current set of divs being displayed.\nSlider.prototype.setCurrent = function( dir ) {\n var pos = this.current; //Cache the current div\n\n //Okay. Take a breather right here :)\n //Get the current div and add to it depending on what is returned.\n //We test to see if the clicked button was 'next'.\n //If true, it returns '1' and adds that to 'pos'.\n //If false, that means you clicked 'prev'. It then returns a '-1' and adds to 'pos'.\n pos += ( ~~( dir === 'next' ) || -1 );\n\n //Now if we kept clicking 'prev', we would end up with a negative number after a while.\n //This tests to see if 'pos < 0'.\n //If yes, take the total divs, divide by 3, and subtract one.\n //This will make it display the last three divs. It kinda goes 'backwards'.\n //If pos isn't < 0, then take modulus of pos and the total / 3\n //Modulus is a math operator and if you're not clear on it, there's a link in the bottom.\n this.current = ( pos < 0 ) ? (this.divsLen / 3) - 1 : pos % (this.divsLen / 3);\n\n return pos;\n};\n</code></pre>\n<p>This part comes after your script in the previous .js file. It can be in your html page at the bottom. I set up the previous piece of code so that we can refrain from referencing any DOM elements or specific values, keeping the logic separate. This part now sets all the configurations we and values to be sent to the slider.</p>\n<pre><code>//First off, if your user doesn't have JS on, your plugin will fail.\n//I've set the wrapper overflow to scroll in the CSS, so if there is no JS, the\n//user can still scroll and see all the divs.\n//Here we set the overflow to hidden and select our container element.\nvar container = $('.wrapper').css('overflow', 'hidden').children('.container');\n\n//Set up the Slider constructor function, and pass in the elements we want.\nvar slider = new Slider( container, $(".nav_wrapper") );\n\n\n//Again, if there's no JS, there's no point in having buttons.\n//The buttons are hidden in the CSS, and here we display then with .show().\n//Then we select and set up the click event on the actual div button.\nslider.nav.show().find('div').on('click', function() {\n //When clicked, we call the functions from our previous code, passing in our configurations.\n //By doing this, if we want to change anything, it can be done here and only done once.\n //Calls setCurrent and passes the clicked div class. It's either 'prev' or 'next'.\n slider.setCurrent( $(this).attr('class') );\n\n //After the current div is all figured out, we just animate.\n //Call transition and pass in the speed we want.\n slider.transition( 1000 );\n});\n</code></pre>\n<p>Hopefully this all made sense to you. If you're a beginner in JS, this might be a little over your head, but that's perfectly ok! Try reading as many articles as you can find on the subjects here and you'll catch on soon.</p>\n<p>Article explaining modulus: <a href=\"http://mathforum.org/library/drmath/view/54363.html\" rel=\"nofollow noreferrer\">http://mathforum.org/library/drmath/view/54363.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:12:23.303",
"Id": "23035",
"ParentId": "22990",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23035",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:30:19.160",
"Id": "22990",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "jQuery slider for WordPress"
}
|
22990
|
<p>I wrote some Java code for Spotify's <a href="https://www.spotify.com/us/jobs/tech/reversed-binary/" rel="nofollow" title="Reversed Binary Numbers">Reversed Binary Numbers</a> puzzle and I tested it on my machine and I am almost positive that it behaves as expected. However, when I send it to puzzle AT spotify.com it kicks it back saying I have the "wrong answer", and nothing else.</p>
<p>Frustrating as this is, I can't for the life of me seem to figure out why the code I have wouldn't work. I even went so far as to remove all error messages that result from bad input, thinking that maybe that was causing it to fail. I was wondering if anyone here with a keener eye than my own could possibly help me hunt down the bug? </p>
<p>Here is a snippet of the most relevant portion of the code:</p>
<pre><code>/**
* Reverse the bits of an integer between 1 ≤ n ≤ 1000000000.
* i.e. 11 (1011) becomes 13 (1101)
*
* @param n The integer to reverse.
* @return The reversed integer.
*/
public static int reverseBits(int n) {
// 1-indexed MSB Position
int msbPosition = findMSBPosition(n);
int reversed = 0;
for (int i = 0; i < msbPosition; i++) {
int mask = 1 << i;
int bit = (n & mask) >> i;
reversed |= (bit << (msbPosition - i - 1));
}
return reversed;
}
/**
* Find the 1-indexed position of the MSB of a number.
* i.e. For the number 11 (1011), findMSBPosition() would return 4.
*
* @param n The number to find the MSB for.
* @return The 1-indexed position of the MSB.
* @protected
*/
protected static int findMSBPosition(int n) {
int msbPos = 0;
int testNum = 1;
while (testNum <= n) {
msbPos++;
testNum <<= 1;
}
return msbPos;
}
</code></pre>
<p><strong>The full code can be found <a href="https://gist.github.com/traviskaufman/5009448" rel="nofollow">in this gist</a>.</strong></p>
<p>As a caveat and as information I am NOT APPLYING TO SPOTIFY NOR HAVE ANY INTENTION TO. I'm just doing this to stay sharp and since "wrong answer" is less than helpful output I'd love to know where I messed up. Thank you so much.</p>
|
[] |
[
{
"body": "<p>I do not see any problems inside the given range. I would have used already existing methods:</p>\n\n<pre><code>public static int reverse2(final int n) {\n return Integer.valueOf(new StringBuilder(Integer.toBinaryString(n)).reverse().toString(), 2);\n}\n</code></pre>\n\n<p>Which is probably to best readable version.</p>\n\n<hr>\n\n<p>If we want to do it by ourself and do not want to create a string and stringbuilder:</p>\n\n<p>With recursion:</p>\n\n<pre><code>public static int reverse3(final int newNumber, final int number) {\n if (number == 0)\n return newNumber;\n return reverse3((newNumber << 1) | (number & 1), number >> 1);\n}\n</code></pre>\n\n<p>Without recursion:</p>\n\n<pre><code>public static int reverse4(int number) {\n int newNumber = 0;\n while (number != 0) {\n newNumber = (newNumber << 1) | (number & 1);\n number >>= 1;\n }\n return newNumber;\n}\n</code></pre>\n\n<hr>\n\n<p>Hint: I have only considered the given range. I did not think about negative numbers.</p>\n\n<hr>\n\n<p>You could try to avoid Scanner and use Integer.parseInt inside a try/catch. Who knows what they throw at you at the command line. The nextInt from Scanner does a Integer.parseInt, but it also tries to match tokens.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T11:44:01.113",
"Id": "35460",
"Score": "1",
"body": "+1 for both the Java-esque `toBinaryString()` version and the I-can-do-it-myself-Dad-look-no-hands version. The latter is more appropriate for an interview answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T20:18:52.977",
"Id": "35525",
"Score": "0",
"body": "The existing methods would definitely be the way to go for most cases. However as @RossPatterson pointed out I was coming at it from an interview standpoint. Furthermore I was trying to keep the code as lean and mean as possible, maximizing throughput and minimizing stack space so I tried to keep it mostly to bitwise operations on primitives. However the recursive and dynamic solutions provided are definitely very interesting and could definitely be implemented as improvements. Thanks so much for your insight!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T10:35:10.513",
"Id": "23011",
"ParentId": "22991",
"Score": "3"
}
},
{
"body": "<p>The code (on the gist) currently handles only command line parameter inputs instead of stdin. From <a href=\"https://www.spotify.com/us/jobs/tech/reversed-binary/\" rel=\"nofollow\">https://www.spotify.com/us/jobs/tech/reversed-binary/</a>:</p>\n\n<blockquote>\n <p>Input is read from stdin.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T20:20:11.467",
"Id": "35526",
"Score": "1",
"body": "oh wow -_- that happened to be the issue. Making that one tweak solved the problem. It definitely pays not to glaze over **any portion** of a problem description, and make sure I always have a thorough knowledge of the problem domain. Thanks so much for your sharp eyes and for helping me with this!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T17:27:13.300",
"Id": "23032",
"ParentId": "22991",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23032",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:34:52.637",
"Id": "22991",
"Score": "0",
"Tags": [
"java",
"integer",
"bitwise",
"contest-problem"
],
"Title": "Spotify's \"Reversed Binary Numbers\" Problem"
}
|
22991
|
<p>I'm trying to become more proficient in Python and have decided to run through the Project Euler problems. </p>
<p>In any case, the problem that I'm on (<a href="http://projecteuler.net/problem=17" rel="nofollow">17</a>) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.</p>
<p>I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.</p>
<p>I have a function (<code>num2eng</code>) which translates the given integer into English words but does not include the word "and". </p>
<pre><code>for i in range (1, COUNTTO + 1):
container = num2eng(i)
container = container.replace(' ', '')
print container
if i > 100:
if not i % 100 == 0:
length = length + container.__len__() + 3 # account for 'and' in numbers over 100
else:
length = length + container.__len__()
else:
length = length + container.__len__()
print length
</code></pre>
<p>There is some repetition in my code and some nesting, both of which seem un-pythonic.</p>
<p>I'm specifically looking for ways to make the script shorter and with simpler loops; I think that's my biggest weakness in general.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:36:38.837",
"Id": "35424",
"Score": "0",
"body": "Your question isn't very specific; it's pretty open ended. We like specific programming questions here with a clear answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:39:51.883",
"Id": "35425",
"Score": "5",
"body": "Don’t call magic methods directly, just use `len(container)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:07:05.217",
"Id": "35426",
"Score": "0",
"body": "I know it doesn't relate to the programming question, but integers should never be written out or spoken with \"and.\" \"And\" is used only for fractions. 1234 is \"one thousand twenty-four\" with no \"and\", but 23.5 is twenty-three and one half."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T00:56:28.790",
"Id": "35432",
"Score": "0",
"body": "@askewchan: that's far from a universal standard, and I definitely don't think it rises to the level of \"should never be\". Even Americans, I believe, tend to include the \"and\" when writing on cheques. Unfortunately continued discussion would be off-topic, but for my part, let a thousand (and one) flowers bloom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T05:23:31.840",
"Id": "35446",
"Score": "0",
"body": "@Hiroto Edited to make more specific, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T08:31:18.670",
"Id": "35452",
"Score": "0",
"body": "If you _have_ to ask, then yes it _can_."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:21:01.390",
"Id": "35515",
"Score": "0",
"body": "I think my question should have been \"how can\", since I believe virtually any code \"can\" be improved. Changed to reflect that, thanks!"
}
] |
[
{
"body": "<p>The more pythonic version:</p>\n\n<pre><code>for i in range(1, COUNTTO + 1):\n container = num2eng(i).replace(' ', '')\n length += len(container)\n if i % 100:\n length += 3 # account for 'and' in numbers over 100\n\nprint length\n</code></pre>\n\n<p>code golf:</p>\n\n<pre><code>print sum(len(num2eng(i).replace(' ', '')) + bool(i > 100 and i % 100) * 3\n for i in range(1, COUNTTO + 1))\n</code></pre>\n\n<p>:)</p>\n\n<p>Don't do that in real code, of course.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:40:25.177",
"Id": "22994",
"ParentId": "22993",
"Score": "1"
}
},
{
"body": "<p>You can make it a bit shorter</p>\n\n<pre><code>length += len(container) + 3 if (i > 100 and i % 100) else 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:46:18.427",
"Id": "35427",
"Score": "0",
"body": "`i % 100` can't be `0` for `1 <= i <= 100`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:47:22.703",
"Id": "35428",
"Score": "0",
"body": "but for 1 <= i <= 100 there's no 'and' in the word"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:49:52.820",
"Id": "35429",
"Score": "0",
"body": "Ah yes. Excuse me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:42:15.373",
"Id": "22995",
"ParentId": "22993",
"Score": "0"
}
},
{
"body": "<p>Here are a few things:</p>\n\n<ul>\n<li><code>container.__len__()</code> – You should never call magic methods directly. Just use <code>len(container)</code>.</li>\n<li><p>As you don’t know to what amount you need to increment (i.e. your <code>COUNTTO</code>), it would make more sense to have a while loop that keeps iterating until you reach your final length result:</p>\n\n<pre><code>while length < 1000:\n # do stuff with i\n length += # update length\n i += 1\n</code></pre></li>\n<li><p>You could also make use of <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow\"><code>itertools.count</code></a>:</p>\n\n<pre><code>length = 0\nfor i in itertools.count(1):\n length += # update length\n if length > 1000:\n break\n</code></pre></li>\n<li><code>not i % 100 == 0</code> – When you already have a operator (<code>==</code>) then don’t use <code>not</code> to invert the whole condition, but just use the inverted operator: <code>i % 100 != 0</code></li>\n<li><p>Also having additional counting logic outside of your <code>num2eng</code> does not seem to be appropriate. What does that function do exactly? Shouldn’t it rather produce a real number using a complete logic? Ideally, it should be as simple as this:</p>\n\n<pre><code>length = 0\nfor i in itertools.count(1):\n length += len(num2eng(i))\n if length > 1000:\n break\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:10:16.997",
"Id": "35430",
"Score": "0",
"body": "I think the reason to have some logic outside of `num2eng` is to avoid counting the letters in `'hundred'` and `'thousand'` so many times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T23:13:58.527",
"Id": "35431",
"Score": "0",
"body": "@askewchan Huh? That doesn’t make much sense to me, as you still do that. Also I’d expect a function `num2eng` to return a complete written English representation of the number I pass in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T05:19:16.370",
"Id": "35445",
"Score": "0",
"body": "You're correct. The function num2eng returns the English representation of the numbers provided. For instance, 102 becomes one hundred two. It's doesn't include \"and\" though and the scope of the challenge required \"and\" to be included (e.g., one hundred and two), hence the addition. But it would makes sense to modify num2eng instead of making up for it here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T05:25:41.577",
"Id": "35448",
"Score": "0",
"body": "Thank you so much for this feedback, this is exactly what I was looking for!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:44:02.690",
"Id": "22996",
"ParentId": "22993",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22996",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T22:34:46.893",
"Id": "22993",
"Score": "1",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Number letter counts"
}
|
22993
|
<p>Write a method to compute the difference between two ranges. A range is defined by an integer low and an integer high. A - B (A “minus” B) is “everything in A that is not in B”.</p>
<p>This is an interview question and here is my code: </p>
<pre><code>void findDiff(int a1,int a2, int a3, int a4)
{
cout<<"("<<a1<<","<<a2<<") - ("<<a3<<","<<a4<<") = \n";
if(a1 < a3)
{
int end = (a2<a3) ? a2: a3-1;
for(int i=a1; i<=end; i++) cout<<i<<"\t";
}
if(a4 < a2)
{
int start = (a1>a4) ? a1 : (a4+1);
for(int i=start; i<=a2; i++) cout<<i<<"\t";
}
cout<<"\n";
}
</code></pre>
<p>Please look at the code and tell me if it correct and if I'm missing any case. Thanks a lot in advance :)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T06:00:33.610",
"Id": "35449",
"Score": "0",
"body": "You flaged this with unit testing, so where are they? (Don't post all, just your inputs for `a` that you have tested.)"
}
] |
[
{
"body": "<p>Make sure this is the signature they want. e.g. they do not expect the function to return vector, iterator or sthg. Also make sure they do not expect you to validate input. e.g. a1 <= a2 etc... after that you can remove redundant conditionals, they are already present in the for loops. And you can replace ternary operators with std::min/max for a more idiomatic c++. otherwise I could not find any missed case or off-by-one bugs.</p>\n\n<pre><code>void findDiff(int a1,int a2, int a3, int a4)\n{\n cout<<\"(\"<<a1<<\",\"<<a2<<\") - (\"<<a3<<\",\"<<a4<<\") = \\n\";\n\n for(int i=a1; i<=std::min(a2, (a3-1)); i++) cout<<i<<\"\\t\";\n\n for(int i=std::max(a1, (a4+1)); i<=a2; i++) cout<<i<<\"\\t\";\n\n cout<<\"\\n\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T12:28:43.660",
"Id": "23013",
"ParentId": "22997",
"Score": "2"
}
},
{
"body": "<p>Seems like you don't need two loops. Also your function and parameter names are badly chosen.</p>\n\n<pre><code>#include <iostream>\n\nvoid range_diff(int a_lo, int a_hi, int b_lo, int b_hi)\n{\n if (b_lo > b_hi) {\n return;\n }\n for (int i = a_lo; i <= a_hi; ++i) {\n if (i < b_lo || i > b_hi) {\n std::cout << i << \" \";\n }\n }\n std::cout << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:40:39.333",
"Id": "35535",
"Score": "0",
"body": "Thanks..It was a practice question so didn't bother much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:05:31.100",
"Id": "23046",
"ParentId": "22997",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T01:44:16.953",
"Id": "22997",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"interview-questions"
],
"Title": "Calculate difference of two ranges given"
}
|
22997
|
<p>I've been learning C#/XNA in an attempt to make a game for the past few weeks so maybe this is an obvious newbie thing, but here goes:</p>
<p>I've been making a fairly simple 2D game, so I have a list of ~1000 objects (NPC's), and I'm iterating through them extremely frequently to do distance checking on each one. The problem is when I increase the distances, everything slows down considerably to the point where the game is unplayable, and I don't really understand why. </p>
<p>It works fine when the distances are short (if all objects are within one 800x480 world size), but when they are increased (say, an 8000x4800 world size), my performance tanks.</p>
<p>Here is some relevant code (not all of it, obviously, since that would be too much stuff, but this is the gist of what's happening):</p>
<pre><code>List<Human> humans;
List<Enemy> enemies;
public void Update(City city, float gameTime)
{
humans = city.GetHumans();
enemies = city.GetEnemies();
for (int h = 0; h < humans.Count; h++)
{
Vector2 human_position = humans[h].position;
Vector2 nearestEnemyPosition = Vector2.Zero;
for (int e = 0; e < enemies.Count; e++)
{
Vector2 enemy_position = enemies[e].position;
float distanceToEnemy = Vector2.DistanceSquared(human_position, enemy_position);
if (distanceToEnemy < distanceToNearestEnemy)
{
distanceToNearestEnemy = distanceToEnemy;
nearestEnemyPosition = enemy_position;
}
if (distanceToNearestEnemy < 2500f)
{
logic code here (very little performance impact)
}
}
for (int hh = 0; hh < humans.Count; hh++)
{
if (h == hh)
{
continue;
}
if (humanMoved == true)
{
continue;
}
Vector2 other_human_position = humans[hh].position;
if (Vector2.DistanceSquared(human_position, other_human_position) < 100f)
{
do more stuff here (movement code, no performance impact)
}
</code></pre>
<p>I also have almost identical loops for the enemy list.</p>
<p>The code to make them is here:</p>
<pre><code>foreach (Human human in this.humans)
{
Vector2 position = new Vector2(random.Next(800), random.Next(480));
human.Spawn(position);
}
</code></pre>
<p>This works fine. I get 60FPS and it's totally smooth & everything runs perfectly. However, if I do this:</p>
<pre><code>foreach (Human human in this.humans)
{
Vector2 position = new Vector2(random.Next(8000), random.Next(4800));
human.Spawn(position);
}
</code></pre>
<p>Everything tanks and I get 1FPS. I tried normalizing the vectors, which solved the performance issue, but whenever I checked to find the closest object it gave me inaccurate results.</p>
<p>Is there any way to accurately check for the distance of two objects that have been normalized with <code>Vector2.Normalize()</code>? Am I even asking the right question?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T10:08:15.020",
"Id": "35456",
"Score": "2",
"body": "Hello, and thanks for your detailed question. :) Did you profile your code to see where the time is spent? The issue is surprising, so you might be surprised by the reason too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T03:10:53.657",
"Id": "35542",
"Score": "0",
"body": "Yes, I did profiling. The vast majority of time (90%+) is spent in the DistanceSquared method. This time drops dramatically (30-40%) with normalized vectors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T23:57:27.067",
"Id": "35776",
"Score": "1",
"body": "What is the maximum visibility/sensibility range of a unit? You could split your world into squares (a dictionary of (X,Y) => set(player), set(enemy)). Now, whenever a player/enemy moves, they will potentially jump from one square to the next. With the right size of the square, you will need to consider only up to 9 squares total and not the whole board for every unit in that square. This way you can do all players and all enemies in that one square. Your dictionary will have as many keys as there are occupied squares."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T01:12:01.960",
"Id": "35777",
"Score": "0",
"body": "By the way, this type of problem seems to be \"map-reducible\". Are you looking to employ multithreading?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T16:00:45.323",
"Id": "36147",
"Score": "0",
"body": "My best guess is that you have code in either or both of the `if (distanceToNearestEnemy < 2500f) {}` or the `if (Vector2.DistanceSquared(human_position, other_human_position) < 100f) {}` code blocks that breaks out of the loop. I would recommend what Leonid is recommending. Look up info on space partitioning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T21:43:15.263",
"Id": "57546",
"Score": "0",
"body": "This question appears to be off-topic because it seems to be asking for resolving a specific performance issue which, in spite of posted answer, isn't reproductible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T06:07:40.230",
"Id": "57591",
"Score": "0",
"body": "this Question is off-topic because you're asking how to make the game, and you have something that is broken. meaning this is non working code, this would be better suited for [Game Development](http://gamedev.stackexchange.com/), be prepared, they will tell you that XNA is dying, and will no longer be supported."
}
] |
[
{
"body": "<p>Let me start by agreeing with the comments that have been posted. It is really strange that you're getting this behavior. In fact, it seems like it should be the opposite.</p>\n\n<h2>I Could Not Reproduce the Performance Delay</h2>\n\n<p>I started off by trying to recreate the problem you're describing. I first attempted by starting from the code you've given. I could measure no performance difference (using the <code>Stopwatch</code> class) when selecting between the small 800x480 size and the larger 8000x4800 size.</p>\n\n<p>The next thing I tried was to strip the example down to just simply <code>Vector2</code> objects, leaving out all of your <code>Human</code>, <code>Enemy</code>, and <code>City</code> types. I used the following code:</p>\n\n<p>private static Random random = new Random();</p>\n\n<pre><code>protected override void Update(GameTime gameTime)\n{\n // Generate initial list of vectors.\n List<Vector2> vectors = new List<Vector2>();\n for (int index = 0; index < 1000; index++)\n {\n vectors.Add(new Vector2(random.Next(800), random.Next(480)));\n }\n\n double sumOfSquares = 0;\n\n // Start timing.\n Stopwatch stopwatch = new Stopwatch();\n stopwatch.Start();\n\n // Add up the \n foreach(Vector2 a in vectors)\n {\n foreach(Vector2 b in vectors)\n {\n sumOfSquares += Vector2.DistanceSquared(a, b);\n }\n }\n\n // End timing and print results.\n stopwatch.Stop();\n Console.WriteLine(stopwatch.ElapsedMilliseconds);\n}\n</code></pre>\n\n<p><strong>In both cases, there were no measurable differences. The size of the vectors does not have an impact on the performance.</strong></p>\n\n<p>I think this jives with what people would usually expect, hence the comments indicating it was a surprise. Regardless of the size of the values contained in the variables, the code should produce the same IL code, and ultimately the same machine instructions. It should be running the exact same code.</p>\n\n<h2>Looking for Other Problems</h2>\n\n<p>I think at this point, you should turn your attention elsewhere in your code. (You probably already did. This question is six months old now.)</p>\n\n<p>One thing that strikes me as a possibility is if all you do is essentially change the size of your world (800x480 to 8000x4800), you potentially need to change a number of other variables as well, if you're making the change to create a higher resolution world, instead of just simply a larger world. In particular, the number you're using as the minimum distance between a human and an enemy, and a human and another human. Without changing these appropriately, you'll get different percentages of breakdowns in how often it gets into each of these if-statements. </p>\n\n<p>What's still odd to me is that it seems backwards. If you increase the size of the world without increasing the number of objects in it, they'll be less dense. You should be hitting the inside of those if-statements less frequently. In theory, it should <em>increase</em> the performance to use a bigger world.</p>\n\n<p>So in the end, you'll probably want to reconsider what the code inside of those if-statements actually do. There's a much better chance that that is causing the lag, not the actual size of the world. If you've got <code>break</code> or <code>continue</code>, you'll want to take an especially close look at how these behave, because these could be short circuiting your loop.</p>\n\n<h2>The Difference in Performance is Not Caused by Not Having Space Partitioning</h2>\n\n<p>One thing I don't agree with, as far as the comments go, is that this case warrants looking into space partitioning. It's possible that you'll want it in the end, but your underlying performance problem isn't necessarily tied to the spatial arrangement of your objects. There is something else strange going on here, and you'll want to figure that out first.</p>\n\n<p>If both of your cases had the same performance, you felt like it was too slow, and the performance delay was clearly and measurably caused by the distance comparisons (i.e., profiling) <em>that's</em> when you'd look into some form of partitioning.</p>\n\n<h2>Vector Normalization</h2>\n\n<p>You mentioned that you normalized the vectors, and that solved your issue. Vector normalization takes a vector and turns it into one that points in the same direction, but has a length of 1. If a <code>Vector2</code> object represents a velocity, an acceleration, or a vector from one point to another, vector normalization can be used to tell you the direction of that vector.</p>\n\n<p>But if your vector is being used to represent a point in 2D space (or 3D space) normalizing it will just tell you the direction that the point lies from the origin of your world. <strong>It loses its meaning, as far as determining how far away two points are from each other.</strong> So that's why you're no longer getting correct results when you do this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-08T14:27:00.567",
"Id": "30956",
"ParentId": "23001",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30956",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T03:23:57.943",
"Id": "23001",
"Score": "4",
"Tags": [
"c#",
"performance",
"xna"
],
"Title": "Distance checking of normalized vectors?"
}
|
23001
|
<p>I've been working on a project where I am importing a large document of documents and tokenizing each document. I then make a hashset of the tokens I have, and for each of these unique tokens I am looking to find their frequency in each of the documents I have. There are about 130000 documents total.</p>
<p>I've run the code and unfortunately, it's taking 150 hrs to run. Do you have any suggestions on improving my code?</p>
<p>This is my <code>Tokenizer()</code> function, which surprisingly works okay:</p>
<pre><code>static private IEnumerable<string> Tokenizer(ref StreamReader sr, ref List<string> tokenz, ref List<string> stopwords)//function for tokenizing
{
string line;
var comparer = StringComparer.InvariantCultureIgnoreCase;
var StopWordSet = new HashSet<string>(stopwords, comparer);
List<string> tokens = new List<string>();//list of strings called tokens
while ((line = sr.ReadLine()) != null)//as long as the streamreader has something
{
foreach (string item in line.Split(' '))//split amongst strings
{
if (item.StartsWith("<") & item.EndsWith(">"))
{
item.Trim();//trims the item of spaces
if (item == "</DOC>")
{
//return item;
tokenz.Add(item);//adds the doc tags for later separation use
}
}
else
{
string newitem;
item.Trim();//trims the item of spaces
if (item != "")//ensures item is not blank
{
newitem = Regex.Replace(item, @"[^A-Za-z0-9]+", "", RegexOptions.IgnoreCase);//regex allows us to ignore case and remove any special characters
string newitem2 = newitem.ToLower();
{
if (StopWordSet.Contains(newitem2))
{
}
else
{
tokenz.Add(newitem2);
}
//tokens.Add(newitem.ToLower());//makes all lower case
}
}
}
}
}
return tokens;
}
</code></pre>
<p>The real issue is here:</p>
<pre><code>static public void AddToDictionaryAndCount(ref int doccounter2, ref HashSet<string> MyLexicon, ref List<string> tokens, ref Dictionary<int, int> DocFreqCounter, ref Dictionary<string, Dictionary<int, int>> MyDictionary, ref Dictionary<int, int> DocWordCounter)
{
foreach (string item in MyLexicon)
{
int counter = 0;
int secondcounter = 0;
int doccounter = 1;
int termcounter = 0;
while (counter <= tokens.LastIndexOf("</DOC>"))
{
if (tokens[counter] == "</DOC>")
{
DocFreqCounter.Add(doccounter, termcounter);
if (doccounter2 < doccounter)
{
DocWordCounter.Add(doccounter, (counter - secondcounter));
doccounter2++;
}
termcounter = 0;
secondcounter = counter;
doccounter++;
}
if (tokens[counter] == item)
{
termcounter++;
//words.termCount = termcounter;
}
counter++;
}
MyDictionary.Add(item, new Dictionary<int, int>(DocFreqCounter));
DocFreqCounter.Clear();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T11:34:24.947",
"Id": "35458",
"Score": "5",
"body": "Have you profiled your code? This should _always_ be the first step when optimising."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T12:14:04.433",
"Id": "35462",
"Score": "0",
"body": "Are you sure this is a CPU bound performance issue?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T12:40:07.007",
"Id": "35463",
"Score": "1",
"body": "@user2094139, in addition to profiling and identifying the problem, do go through suggestions provided by [almaz](http://codereview.stackexchange.com/a/23010/22425). Not all of them may help improve performance, but would definitely help improve readability and maintainability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T14:28:06.290",
"Id": "35548",
"Score": "0",
"body": "This smells like a high-memory-activity application. I wouldn't be surprised to find that your data structures are huge and that the paging subsystem is thrashing. Profiling is important to optimization."
}
] |
[
{
"body": "<p>Since the tokens array doesn't change in the while loop, you can pull out the check for LastIndexOf so that it doesn't get called on every loop.</p>\n\n<p>The only other thing I can suggest is grab a copy of dottrace performance (or ANTS performance) and see exactly where you have a problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T03:53:20.613",
"Id": "35435",
"Score": "0",
"body": "Hey Robert, thanks for the reply. I'm not sure what you mean by actually pulling out the check, do you mean by storing the position where lastindexof</DOC> is and then substituting that in instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T03:53:56.580",
"Id": "35436",
"Score": "0",
"body": "Yes that's what I meant: var loopTill = tokens.LastIndexOf(\"</DOC>\")l; while (counter <= loopTill)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T03:58:34.757",
"Id": "35437",
"Score": "0",
"body": "Thanks a lot! I'll use that for now, let me know if you possibly know of any other ways to optimize the code. \nI'll also look up the dottrace/ANTS performance programs you suggested and try that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T04:00:41.733",
"Id": "35438",
"Score": "0",
"body": "Just a heads up, WOW. I am thoroughly impressed at the speed that you just saved me, already. I tested it once and you already cut down around 3 seconds of time per addition to the dictionary. Thanks so much already!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T04:01:00.113",
"Id": "35439",
"Score": "2",
"body": "As a side note, I think you misunderstand how the \"ref\" keyword works. You don't need them as you are not assigning new instances to the parameters"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T04:02:04.857",
"Id": "35440",
"Score": "0",
"body": "Nice :). Add it back in and have a look in one of the perf profilers at that line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T04:02:28.960",
"Id": "35441",
"Score": "0",
"body": "Ah I see, thanks again for your help. Does removing them improve efficiency?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T04:04:16.147",
"Id": "35442",
"Score": "0",
"body": "No it would not"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T03:40:14.773",
"Id": "23003",
"ParentId": "23002",
"Score": "3"
}
},
{
"body": "<p><code>Tokenizer</code> method:</p>\n\n<ul>\n<li>You use <code>ref</code> incorrectly, all reference types are always passed by reference, please read the MSDN or any other online resource to understand the <code>ref</code></li>\n<li>Your code doesn't follow naming conventions: local variables, parameters should be camelCased (e.g. <code>StopWordSet</code>)</li>\n<li>use <code>string.Split(new char[0], StringSplitOptions.RemoveEmptyEntries)</code> overload to split on all whitespace characters and remove empty strings during tokenizing, rather than trimming result</li>\n<li>strings are immutable, so the statement <code>item.Trim()</code> is useless unless you assign it to something</li>\n<li><code>Tokenizer</code> method always returns an empty list since <code>tokens</code> (not <code>tokenz</code>) is only intialized and not used. It looks like <code>tokenz</code> parameter is redundant and <code>tokens</code> variable should be used instead</li>\n<li><p>To improve performance it might be better to change the type of <code>stopwords</code> parameter to <code>ISet<string></code> and use it for matching, rather than create a new <code>StopWordSet</code> each time\nAs a result you'll get a cleaner version of <code>Tokenizer</code>: </p>\n\n<pre><code>private static IEnumerable<string> Tokenizer(StreamReader sr, ISet<string> stopwords)//function for tokenizing\n{\n string line;\n List<string> tokens = new List<string>();//list of strings called tokens\n\n while ((line = sr.ReadLine()) != null)//as long as the streamreader has something\n {\n foreach (string item in line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries))//split amongst strings\n {\n if (item.StartsWith(\"<\") & item.EndsWith(\">\"))\n {\n if (item == \"</DOC>\")\n tokens.Add(item); //adds the doc tags for later separation use\n }\n else\n {\n string newitem = Regex.Replace(item, @\"[^A-Za-z0-9]+\", \"\", RegexOptions.IgnoreCase).ToLower();\n if (!stopwords.Contains(newitem))\n tokens.Add(newitem);\n }\n }\n }\n return tokens;\n}\n</code></pre></li>\n</ul>\n\n<p>Now let's look at the <code>AddToDictionaryAndCount</code> method:</p>\n\n<ul>\n<li>naming conventions - do name your variables/parameters properly, it's absolutely not clear what is the difference between <code>doccounter2</code> parameter, <code>doccounter</code> and <code>secondcounter</code> variables. Rename them to smth. like <code>documentIndex</code>, <code>numberOfTermOccurances</code> etc. </li>\n<li><code>while (counter <= tokens.LastIndexOf(\"</DOC>\"))</code> is the killer, you're looking for <code>\"</DOC>\"</code> entry on each iteration. Cache the calculated value instead.</li>\n<li>since you know the number of iterations and you always increment the index it's better to use <code>for</code> instead of <code>while</code></li>\n<li>not sure why you pass <code>docFreqCounter</code> as parameter, it looks like is being used as a local variable.</li>\n</ul>\n\n<p>As to performance improvements (other than caching <code>LastIndexOf</code>) - currently you scan the through the <code>tokens</code> list for each and every item in <code>myLexicon</code>. Assuming that lexicon is built from <code>tokens</code> it would be much better to scan the <code>tokens</code> list only once, tracking which items you've already counted and where are the doc boundaries. Since you haven't provided the meaning of all parameters participating in this method it's hard to suggest a proper solution, but here is the first approximation:</p>\n\n<pre><code>public static Dictionary<string, Dictionary<int, int>> AddToDictionaryAndCount(List<string> tokens)\n{\n var result = new Dictionary<string, Dictionary<int,int>>();\n var documentIndex = 0; //tracks the current document index\n\n var lastDocumentIndex = tokens.LastIndexOf(\"</DOC>\");\n for (int i = 0; i <= lastDocumentIndex; i++)\n {\n var token = tokens[i];\n if (token == \"</DOC>\")\n {\n //finalize stats for the document. not sure what goes here.\n //add the logic corresponding to \"doccounter2 < doccounter\"\n documentIndex++;\n continue;\n }\n\n Dictionary<int, int> documentStats;\n if (!result.TryGetValue(token, out documentStats))\n documentStats = result[token] = new Dictionary<int, int>();\n\n documentStats[documentIndex]++;\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T05:11:30.780",
"Id": "35581",
"Score": "0",
"body": "Thanks so much for the help almaz! I really appreciate it! :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T09:37:07.490",
"Id": "23010",
"ParentId": "23002",
"Score": "9"
}
},
{
"body": "<p>In addition to the <a href=\"https://codereview.stackexchange.com/a/23010/6172\">great</a> <a href=\"https://codereview.stackexchange.com/a/23003/6172\">answers</a> from <a href=\"https://codereview.stackexchange.com/users/19473/almaz\">almaz</a> and <a href=\"https://codereview.stackexchange.com/users/22411/robert-wagner\">Robert Wagner</a>, I would do one more thing: make the Regex compiled and pull it out of the loop. So your original code looks like:</p>\n\n<pre><code>newitem = Regex.Replace(item, @\"[^A-Za-z0-9]+\", \"\", RegexOptions.IgnoreCase);//regex allows us to ignore case and remove any special characters\nstring newitem2 = newitem.ToLower();\n</code></pre>\n\n<p>and the modified code would look like:</p>\n\n<pre><code>private static readonly Regex replacer = new Regex(@\"[^A-Za-z0-9]+\", RegexOptions.Compiled | RegexOptions.IgnoreCase);\n\nprivate static IEnumerable<string> Tokenizer(TextReader sr, ICollection<string> stopwords)\n{\n // original codestuffs\n var newitem = replacer.Replace(item, string.Empty).ToLower();\n // more original codestuffs\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T16:01:00.047",
"Id": "23028",
"ParentId": "23002",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T03:28:35.293",
"Id": "23002",
"Score": "4",
"Tags": [
"c#",
"performance",
"parsing"
],
"Title": "Tokenizing each document in a large document of documents"
}
|
23002
|
<p>I have a function that needs to return the call to another function that have some parameters. Let's say, for example, the following:</p>
<pre><code>def some_func():
iss = do_something()
example = do_something_else()
return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'})
</code></pre>
<p>I want to adjust it so it will comply with PEP 8. I tried:</p>
<pre><code>def some_func():
iss = do_something()
example = do_something_else()
return some_long_name('maybe long string', {'this': iss,
'an': example,
'dictionary': 'wich is very long'})
</code></pre>
<p>But it still goes way beyond 80 characters. So I did a two step 'line continuation', but don't know if it's how it's done.</p>
<pre><code>def some_func():
iss = do_something()
example = do_something_else()
return some_long_name('maybe long string',
{
'this': iss,
'an': example,
'dictionary': 'wich is very long'
})
</code></pre>
<p>Or should it be something like:</p>
<pre><code>def some_func():
iss = do_something()
example = do_something_else()
return some_long_name('maybe long string',
{'this': iss,
'an': example,
'dictionary': 'wich is very long'})
</code></pre>
<p>I would appreciate some insight so I can maintain a better code because PEP8 doesn't explain it very well.</p>
|
[] |
[
{
"body": "<p>PEP-0008 suggests this approach (see the first example group there):</p>\n\n<pre><code>return some_long_name(\n 'maybe long string',\n {'this': iss,\n 'an': example,\n 'dictionary': 'wich is very long'})\n</code></pre>\n\n<p>As for the dict formatting style, in my opinion, not having lines with only braces on them is more readable, navigatable and editable. The PEP does not mention any specific style for dict formatting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T08:29:15.013",
"Id": "23007",
"ParentId": "23006",
"Score": "1"
}
},
{
"body": "<p>In my opinion, use Explaining Variables or Summary Variables express the dict. I like this coding style as follows.</p>\n\n<pre><code>keyword = {\n 'this': iss,\n 'an': example,\n 'dictionary': 'wich is very long',\n}\nreturn some_long_name('maybe long string', keyword)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T12:52:08.637",
"Id": "23014",
"ParentId": "23006",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23014",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T07:05:59.650",
"Id": "23006",
"Score": "1",
"Tags": [
"python"
],
"Title": "Python Line continuation dictionary"
}
|
23006
|
<p>This function takes in a number and returns all divisors for that number. <code>list_to_number()</code> is a function used to retrieve a list of prime numbers up to a limit, but I am not concerned over the code of that function right now, only this divisor code. I am planning on reusing it when solving various Project Euler problems.</p>
<pre><code>def list_divisors(num):
''' Creates a list of all divisors of num
'''
orig_num = num
prime_list = list_to_number(int(num / 2) + 1)
divisors = [1, num]
for i in prime_list:
num = orig_num
while not num % i:
divisors.append(i)
num = int(num / i)
for i in range(len(divisors) - 2):
for j in range(i + 1, len(divisors) - 1):
if i and j and j != num and not orig_num % (i * j):
divisors.append(i * j)
divisors = list(set(divisors))
divisors.sort()
return divisors
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T09:38:25.387",
"Id": "35455",
"Score": "0",
"body": "I've changed the bottom for loop to be `for i in range(1, len(divisors) - 2):\n for j in range(i + 1, len(divisors) - 1):\n if not orig_num % (i * j):\n divisors.append(i * j)` but it doesn't read well here."
}
] |
[
{
"body": "<p><code>num/2</code> should be <code>sqrt(num)</code>. And this should also be recalculated in your loop, or at least check to leave the for earlier.</p>\n\n<p>A better prime candidates algorithms might also improve overall performance.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/171765/what-is-the-best-way-to-get-all-the-divisors-of-a-number\">What is the best way to get all the divisors of a number?</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T09:32:41.257",
"Id": "23009",
"ParentId": "23008",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Don't reset <code>num</code> to <code>orig_num</code> (to fasten division/modulo) </li>\n<li>Think functionnaly :\n<ul>\n<li>From your prime factors, if you generate a <em>new</em> collection with all possible combinations, no need to check your products.</li>\n<li>It makes harder to introduce bugs. Your code is indeed broken and won't output 20 or 25 (...) as divisors of 100.</li>\n<li>You can re-use existing (iter)tools.</li>\n</ul></li>\n<li>Avoid unnecessary convertions (<code>sorted</code> can take any iterable)</li>\n<li>Compute primes as you need them (eg, for 10**6, only 2 and 5 will suffice). Ie, use a generator.</li>\n</ul>\n\n<p>This leads to :</p>\n\n<pre><code>from prime_sieve import gen_primes\nfrom itertools import combinations, chain\nimport operator\n\ndef prod(l):\n return reduce(operator.mul, l, 1)\n\ndef powerset(lst):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n return chain.from_iterable(combinations(lst, r) for r in range(len(lst)+1))\n\ndef list_divisors(num):\n ''' Creates a list of all divisors of num\n '''\n primes = gen_primes()\n prime_divisors = []\n while num>1:\n p = primes.next()\n while not num % p:\n prime_divisors.append(p)\n num = int(num / p)\n\n return sorted(set(prod(fs) for fs in powerset(prime_divisors)))\n</code></pre>\n\n<p>Now, the \"factor & multiplicity\" approach like in suggested link is really more efficient.\nHere is my take on it :</p>\n\n<pre><code>from prime_sieve import gen_primes\nfrom itertools import product\nfrom collections import Counter\nimport operator\n\ndef prime_factors(num):\n \"\"\"Get prime divisors with multiplicity\"\"\"\n\n pf = Counter()\n primes = gen_primes()\n while num>1:\n p = primes.next()\n m = 0\n while m == 0 :\n d,m = divmod(num,p)\n if m == 0 :\n pf[p] += 1\n num = d\n return pf\n\ndef prod(l):\n return reduce(operator.mul, l, 1)\n\ndef powered(factors, powers):\n return prod(f**p for (f,p) in zip(factors, powers))\n\n\ndef divisors(num) :\n\n pf = prime_factors(num)\n primes = pf.keys()\n #For each prime, possible exponents\n exponents = [range(i+1) for i in pf.values()]\n return sorted([powered(primes,es) for es in product(*exponents)])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T13:06:57.343",
"Id": "23015",
"ParentId": "23008",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23015",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T08:55:46.097",
"Id": "23008",
"Score": "4",
"Tags": [
"python",
"primes"
],
"Title": "Returning a list of divisors for a number"
}
|
23008
|
<p>Im using Foundation by Zurb as a front-end framework. Below is the SCSS used to generate the basic layout of the homepage using the Semantic Grid Mixins Foundation supplies (<a href="http://foundation.zurb.com/docs/sass-mixins.php" rel="nofollow">http://foundation.zurb.com/docs/sass-mixins.php</a>). </p>
<p>The problem I am having is that it is creating massive selectors when I view them in the inspector in Chrome.</p>
<pre><code>body.homepage div[role="main"] {
header {
@include outerRow();
margin-bottom: 60px!important;
h1 { @include column(12); }
}
& > section {
margin-bottom: 120px!important;
}
.hero_container {
@include outerRow();
.video_holder {
@include column(5);
@include mobileColumn(4);
}
form {
@include column(7);
@include mobileColumn(4);
legend { }
.personal_details {
@include innerRow();
label {
@include column(6);
}
}
.form_actions {
@include innerRow();
label { @include column(6); }
.input_action { @include column(6); }
}
}
}
.reasons {
@include outerRow();
ul {
list-style: none;
li {
@include column(4);
@include mobileColumn(2);
margin-bottom: $halfColumnGutter;
p {
padding: 12px;
border: 1px solid #eee;
background: #efefef;
}
}
}
}
.testimonials {
@include outerRow();
h4 { @include column(12); }
ul {
list-style: none;
blockquote { @include column(3); @include mobileColumn(2); border-left: none; }
p {
padding: 12px;
border: 1px solid #eee;
background: #efefef;
}
}
}
.register {
@include outerRow();
form {
@include column(12);
.personal_details {
@include innerRow();
margin-bottom: $halfColumnGutter;
label {
@include column(4);
}
}
.extra_info {
@include innerRow();
margin-bottom: $halfColumnGutter;
label {
@include column(4);
}
}
.form_actions {
@include innerRow();
label { @include column(4); }
.input_action { @include offsetBy(4); @include column(2); }
}
}
}
}
body.homepage.mobile div[role="main"] {
.hero_container {
form { margin-top: $halfColumnGutter; }
}
}
</code></pre>
<p>Below is the output from the Chrome inspector when viewing the <code>label</code> in <code>.personal_details</code></p>
<pre><code>.top_bar .information_for_agencies, .top_bar .registration, header[role="banner"] .branding, header[role="banner"] .branding .logo, header[role="banner"] .branding .tagline, header[role="banner"] div[role="navigation"], footer[role="contentinfo"] section, body.full_width div[role="main"] article[role="article"], body.full_width div[role="main"] article[role="article"] header img.top_masthead, body.full_width div[role="main"] article[role="article"] div.content img.top_left, body.full_width div[role="main"] article[role="article"] div.content img.top_right, body.full_width div[role="main"] article[role="article"] div.content figure.left_align, body.full_width div[role="main"] article[role="article"] div.content figure.right_align, body.full_width div[role="main"] article[role="article"] div.content figure.full_width, body.full_width div[role="main"] article[role="article"] footer img.bottom_masthead, body.two_columns div[role="main"] article[role="article"], body.two_columns div[role="main"] article[role="article"] header img.top_masthead, body.two_columns div[role="main"] article[role="article"] div.content img.top_left, body.two_columns div[role="main"] article[role="article"] div.content img.top_right, body.two_columns div[role="main"] article[role="article"] div.content figure.left_align, body.two_columns div[role="main"] article[role="article"] div.content figure.right_align, body.two_columns div[role="main"] article[role="article"] div.content figure.full_width, body.two_columns div[role="main"] article[role="article"] footer img.bottom_masthead, body.two_columns div[role="main"] aside[role="complementary"], body.three_columns div[role="main"] section.adverts, body.three_columns div[role="main"] article[role="article"], body.three_columns div[role="main"] article[role="article"] header img.top_masthead, body.three_columns div[role="main"] article[role="article"] div.content img.top_left, body.three_columns div[role="main"] article[role="article"] div.content img.top_right, body.three_columns div[role="main"] article[role="article"] div.content figure.left_align, body.three_columns div[role="main"] article[role="article"] div.content figure.right_align, body.three_columns div[role="main"] article[role="article"] div.content figure.full_width, body.three_columns div[role="main"] article[role="article"] footer img.bottom_masthead, body.three_columns div[role="main"] aside[role="complementary"], body.homepage div[role="main"] header h1, body.homepage div[role="main"] .hero_container .video_holder, body.homepage div[role="main"] .hero_container form, body.homepage div[role="main"] .hero_container form .personal_details label, body.homepage div[role="main"] .hero_container form .form_actions label, body.homepage div[role="main"] .hero_container form .form_actions .input_action, body.homepage div[role="main"] .reasons ul li, body.homepage div[role="main"] .testimonials h4, body.homepage div[role="main"] .testimonials ul blockquote, body.homepage div[role="main"] .register form, body.homepage div[role="main"] .register form .personal_details label, body.homepage div[role="main"] .register form .extra_info label, body.homepage div[role="main"] .register form .form_actions label, body.homepage div[role="main"] .register form .form_actions .input_action
{
position: relative;
min-height: 1px;
padding: 0 15px;
}
</code></pre>
<p>The guidelines for scss say not to go more than five levels deep, which I haven't. Is it something I am doing wrong? how can I write it more efficiently? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T07:11:35.777",
"Id": "67461",
"Score": "0",
"body": "I suggest not selecting `div[role=\"main\"]`, you simply could use a class like `.site-content` instead. Also using `body.homepage` is overqualified. `.homepage` is enough."
}
] |
[
{
"body": "<p>The CSS that was created (i.e. the position, min-height, and padding) is not anything you have specified in your SCSS. So it must be boilerplate generated by the mixins you're using, e.g. innerRow() and column(). I expect if you look at the Foundation source SCSS for those mixins you will see they'll be using @extend internally and hence generating the large selectors. Either that or there's a bug in Foundation. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-19T16:18:31.390",
"Id": "24108",
"ParentId": "23012",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T11:51:17.170",
"Id": "23012",
"Score": "4",
"Tags": [
"css",
"sass"
],
"Title": "Innefficient scss selectors being generated"
}
|
23012
|
<p>Python doesn't remove the variables once a scope is closed (if there's such a thing as scope in Python, I'm not sure). I mean, once I finish a <code>for variable in range(1, 100)</code>, the <code>variable</code> is still there, with a value (<code>99</code> in this case).</p>
<p>Now I usually indent a whole block when I use the <code>with ... as</code> statement. But should I close the file and end the indentation as soon as I'm done with it? I mean, should I write:</p>
<pre><code>with open('somefile', 'r') as f:
newvar = f.read()
newvar.replace('a', 'b') # and etc
</code></pre>
<p>Instead of:</p>
<pre><code>with open('somefile', 'r') as f:
newvar = f.read()
newvar.replace('a', 'b') # and etc
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T15:25:34.500",
"Id": "35470",
"Score": "0",
"body": "Do you have a more real concrete example? That's a trivial (and unrealistic) example. The motivations for choosing one approach over the other may be different depending on what is being done in the blocks."
}
] |
[
{
"body": "<p>Yes, ideally, you close the <code>with</code> block as soon as possible, that way the file gets closed quickly - which means you are not (potentially) blocking access to it, having less file handles in use, etc...</p>\n\n<p>Python does have scoping, it just doesn't make new scopes very often - only for functions and classes (and some other smaller cases, like list comprehensions and cousins in 3.x and above).</p>\n\n<p>Unlike in Java, Python doesn't take the approach that every block is a scope, therefore loops, as you say in your question, don't introduce a new one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T19:39:24.167",
"Id": "35522",
"Score": "0",
"body": "thanks for making scopes clearer as well as answering the question :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T15:12:55.970",
"Id": "23019",
"ParentId": "23016",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23019",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T13:36:28.633",
"Id": "23016",
"Score": "0",
"Tags": [
"python"
],
"Title": "Pythonic indenting `with` statement blocks"
}
|
23016
|
<p><strong>Background</strong></p>
<p>I like to code JavaScript in a typical style with "classes" and inheritance. My goal was to create an easy way to make inheritance available and keep classes that inherits from others clean. Also I like to use the module pattern and uses its look and feel.</p>
<p><strong>My solution</strong></p>
<p>I hope the code is self-explanatory. I'm using it in all my newer projects and it seems to work fine.</p>
<pre><code> if(typeof(SimpleJSLib)==='undefined'){
var SimpleJSLib = {}; // define namespace
}
SimpleJSLib.BaseObject = function(){
// returns an object you wether can inherit from or instantiate it
var createInheritObject = function(inheritFunctions){
return {
// instantiate the current class
// iterates through all functions which the class inherits from and calls them
construct : function(){
var me = {}, _protected = {};
for(var i = 0; i < inheritFunctions.length; i++){
me = inheritFunctions[i].call(me, me, _protected);
if(typeof(me)==='undefined'){
throw 'Inherit function did not return "me"';
}
}
// if a constructor is defined we call them and deliver the arguments this function was called with
if(typeof(_protected.construct)!=='undefined'){
_protected.construct.call(me, arguments);
}
return me;
},
// clones the pointers to the functions you inherit from
// and returns another object you can instantiate or inherit from
inherit : function(inheritFunction){
var _inheritFunctions = inheritFunctions.slice(0); // clone
_inheritFunctions.push(inheritFunction);
return createInheritObject.call(window, _inheritFunctions);
}
};
};
return {
// allows you to inherit directly from BaseObject
inherit : function(inheritFunction){
// this is the first call of the function, so the the inheritFunctions array just contains one function
return createInheritObject.call(window, [inheritFunction]);
}
}
}();
</code></pre>
<p><strong>Questions</strong></p>
<p>Is there any good argument why I shouldn't use this code snippet?
How about performance? Is there anything I could make better?</p>
<p><strong>Examples</strong></p>
<p>Just a few simple ones.</p>
<pre><code>var MyClass = SimpleJSLib.BaseObject.inherit(function(me, _protected){
// protected
_protected.myValue = 'value';
_protected.doSomething = function(){
console.log('something')
};
// public
me.getMyValue = function(){
return _protected.myValue;
}
return me;
});
var MySubClass = MyClass.inherit(function(me, _protected){
me.anotherFunction = function(){
_protected.doSomething();
}
return me;
});
var myClassInstance = MyClass.construct();
console.log(myClassInstance.getMyValue());
var mySubClassInstance = MySubClass.construct();
console.log(mySubClassInstance.anotherFunction());
</code></pre>
<p>Using the constructor</p>
<pre><code>var MyClass = SimpleJSLib.BaseObject.inherit(function(me, _protected){
_protected.valueOne = null;
_protected.valueTwo = null;
_protected.construct = function(parameters){
_protected.valueOne = parameters[0];
_protected.valueTwo = parameters[1];
};
return me;
});
var myClassInstance = MyClass.construct('valueOne', 'valueTwo');
</code></pre>
<p>Singelton</p>
<pre><code>var Singelton = SimpleJSLib.BaseObject.inherit(function(me, _protected){
return me;
}).construct(); // mention the construct!
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T13:56:02.067",
"Id": "35466",
"Score": "1",
"body": "Reinventing the wheel. jQuery and underscore for example both have .extend methods that take care of inheritance see how those are implemented. Also, look at how TypeScript handles it. Also, look at Douglas Crockford's blog posts on how to simulate classical inheritance. Also, classical inheritance in javascript is rarely used because prototypical inheritance is generally better (share functionality)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T14:14:59.323",
"Id": "35467",
"Score": "0",
"body": "jQuery.extend do not support a protected scope as far as I know. I haven't looked at the other frameworks. \"Also, classical inheritance in javascript is rarely used because prototypical inheritance is generally better (share functionality)\". What do you mean with \"share functionality\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T14:42:46.470",
"Id": "35468",
"Score": "0",
"body": "_Why_ is inheritance so useful? You generally use inheritance to indicate different objects are similar, ie that one object is a superset of another object. To use a classic example every Dog is an Animal. Inheritance lets you share functionality between Dog and Animal, and to treat Dogs like Animals (Polymorphism), since javascript is a dynamic language the second advantage is no longer a concern, I can treat any object whichever way I'd like. Since functions are objects in js I can also apply Animal functionality on Dog without having to be explicit about it Animal.doAnimalStuff.apply(dog))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T14:58:04.040",
"Id": "35469",
"Score": "0",
"body": "Yes, sure. But inheritance also allows you to reuse functionalities from your parents. To treat an dog like an animal is possible in my implementation. Have a look in example one. You could call _mySubClassInstance.getMyValue();_.\n\n(Oh, there was a bug in the example that might explains the misunderstanding. var mySubClassInstance = MySubClass.construct() is the correct call)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T15:59:30.150",
"Id": "35511",
"Score": "0",
"body": "So does prototypical inheritance, methods of your parents are accessible to you. This is really not a subject for discussion in comments, you're more to the stackoverflow javascript chat where we can discuss this: http://chat.stackoverflow.com/rooms/17/javascript"
}
] |
[
{
"body": "<p>From some staring at your code:</p>\n\n<ul>\n<li><p>Do not declare <code>var</code> in an <code>if</code> block, it gives the wrong impression. I would just declare it on top, something like this:</p>\n\n<pre><code>//Define namespace\nvar SimpleJSLib;\nSimpleJSLib = SimpleJSLib || {}; \n</code></pre>\n\n<p>As far as naming, since <code>SimpleJSLib</code> is not a constructor, it should not start with capital S. The name <code>JSLib</code> is not very informative beyond what language it is writen in..</p></li>\n<li>I know that for some <code>_</code> in <code>_protected</code> means \"private\", but I agree with Crockford that this convention should be avoided</li>\n<li>Now a big one: you broke support for <code>instanceof</code> operator, that's just wrong</li>\n<li>Furthermore, you kind of broke support for <code>prototype</code>, you are also not using <code>hasOwnProperty</code> anywhere when you construct objects</li>\n<li>And, JS has a perfectly valid <code>constructor</code>, but you decided to have your own <code>construct</code></li>\n<li>Finally, this will be messy once you want to start serializing with <code>JSON</code></li>\n</ul>\n\n<p>Honestly, read this: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript</a> and abandon your code. I would not want to maintain code that relies on this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:25:59.583",
"Id": "43750",
"ParentId": "23017",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T13:38:50.707",
"Id": "23017",
"Score": "1",
"Tags": [
"javascript",
"inheritance"
],
"Title": "Inheritance selfmade or reinventing wheel"
}
|
23017
|
<p>My user defined comparison compare function is defined with an array:</p>
<pre><code>$boardkey_to_values=Array(19=>2601248,23=>2601248,39=>2603445,
43=>2256319,47=>2632006,59=>2603445,63=>2232152,67=>2260713,71=>2632006,...)
</code></pre>
<p>so <code>23>19</code> EDIT:<code>23=19</code>, <code>39>19</code>, <code>39<23</code>,...</p>
<p>I have an array of values <code>$board_id</code>, and I want to get the array of all the keys for the minimum values.</p>
<p>Here's my solution, but I don't think it is really intuitive.</p>
<pre><code>$min_key=Array(0);
foreach ($board_id as $key => $value) {
if ($boardkey_to_values[$board_id[$min_key[0]]]>$boardkey_to_values[$value])
$min_key=Array($key);
if ($boardkey_to_values[$board_id[$min_key[0]]]==$boardkey_to_values[$value] && $min_key[0]!=$key)
$min_key[]=$key;
}
</code></pre>
<p>Here is an example to show how this should behave:</p>
<p>say <code>$board_id = [19,23,39,47,71]</code></p>
<p>it will look at the values corresponding to this numbers <code>[2601248,2601248,2603445,2632006,2632006]</code></p>
<p>it looks for the smallest value: <code>2601248</code></p>
<p>so the result (<code>$min_key</code> should be <code>[19,23]</code>)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-26T22:00:49.350",
"Id": "37670",
"Score": "0",
"body": "Why is 23 > 19 when they both map to the same value? Shouldn't they be equal?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T07:16:26.757",
"Id": "37674",
"Score": "0",
"body": "Yes you're right 23=19, I have edited my question"
}
] |
[
{
"body": "<p>You could try doing it this way:</p>\n\n<pre><code>$min_key = null;\nasort($boardkey_to_values);\n\nforeach(array_count_values($boardkey_to_values) as $val) {\n $min_key = array_slice( array_keys($boardkey_to_values), $val );\n break;\n}\n</code></pre>\n\n<p>I believe that would accomplish what you're trying to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T21:29:07.880",
"Id": "35604",
"Score": "0",
"body": "Your function is very slow compared to mine, because array_slice is slow given the size of the `$boardkey_to_values` (more than 40 000 entries). And it isn't exactly what I meant (cf edit for the example)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T21:04:43.887",
"Id": "23041",
"ParentId": "23018",
"Score": "0"
}
},
{
"body": "<p>This should be <em>O(n)</em>* where <em>n</em> is <code>count($board_id)</code>.</p>\n\n<pre><code>$mapped = array_map(function ($id) use ($boardkey_to_values) {\n return array($boardkey_to_values[$id], $id);\n}, $board_id);\nasort($mapped);\nlist($min_value, $id) = reset($mapped);\n$min_ids = array($id);\nwhile (list($value, $id) = next($mapped)) {\n if ($value == $min_value) {\n $min_ids[] = $id;\n }\n else {\n break;\n }\n}\n</code></pre>\n\n<p>* ignoring the call to <code>asort</code> which is probably <em>O(n log n)</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T07:27:06.457",
"Id": "37676",
"Score": "0",
"body": "What exactly does the `use` keyword do after the parameters of an anonymous function ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T07:55:10.763",
"Id": "37677",
"Score": "1",
"body": "It allows the anonymous function to access the named variable. Without it the function can only access the local variables and arguments it declares."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-26T22:15:17.567",
"Id": "24400",
"ParentId": "23018",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24400",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T14:28:05.140",
"Id": "23018",
"Score": "5",
"Tags": [
"php",
"array"
],
"Title": "Array find min value with user-defined comparison compare function"
}
|
23018
|
<p>I have the async code that implements cancellation token. It's working but Im not pretty sure if this is the right way to do it so I just want feedback about it.</p>
<p>Here is the actual code:</p>
<pre><code>/// <summary>
///
/// </summary>
private async void SaveData() {
if (GetActiveServiceRequest() != null)
{
var tokenSource = new System.Threading.CancellationTokenSource();
this.ShowWizardPleaseWait("Saving data...");
var someTask = System.Threading.Tasks.Task<bool>.Factory.StartNew(() =>
{
bool returnVal = false;
// Set sleep of 7 seconds to test the 5 seconds timeout.
System.Threading.Thread.Sleep(7000);
if (!tokenSource.IsCancellationRequested)
{
// if not cancelled then save data
App.Data.EmployeeWCF ws = new App.Data.EmployeeWCF ();
returnVal = ws.UpdateData(_employee.Data);
ws.Dispose();
}
return returnVal;
}, tokenSource.Token);
if (await System.Threading.Tasks.Task.WhenAny(someTask, System.Threading.Tasks.Task.Delay(5000)) == someTask)
{
// Completed
this.HideWizardPleaseWait();
if (someTask.Result)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
else
{
this.DialogResult = System.Windows.Forms.DialogResult.Abort;
}
btnOK.Enabled = true;
this.Close();
}
else
{
tokenSource.Cancel();
// Timeout logic
this.HideWizardPleaseWait();
MessageBox.Show("Timeout. Please try again.")
}
}
}
</code></pre>
<p>Does async / await / cancellation code is well implemented?</p>
|
[] |
[
{
"body": "<p>It's better to use <a href=\"http://msdn.microsoft.com/en-us/library/hh139229.aspx\" rel=\"nofollow\"><code>CancellationTokenSource(TimeSpan)</code></a> constructor to set the cancellation after 5 seconds.</p>\n\n<p>Also, <code>Task.Run</code> method is a recommended way to run compute-bound tasks (see remark <a href=\"http://msdn.microsoft.com/en-us/library/dd321421.aspx\" rel=\"nofollow\">here</a>).</p>\n\n<p>Other issues worth noting:</p>\n\n<ul>\n<li>by conventions asynchronous methods should have a suffix <code>Async</code></li>\n<li><code>using</code> keyword is a recommended way to correctly dispose <code>IDisposable</code> objects</li>\n<li><p>if a task to be cancelled cannot return correct results (according to business requirements) it's recommended to throw <code>OperationCanceledException</code> by calling <code>token.ThrowIfCancellationRequested()</code> method.</p>\n\n<pre><code>private async void SaveDataAsync() \n{\n if (GetActiveServiceRequest() == null)\n return;\n\n var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token;\n this.ShowWizardPleaseWait(\"Saving data...\");\n\n var someTask = Task.Run<bool>(() =>\n {\n // Set sleep of 7 seconds to test the 5 seconds timeout.\n System.Threading.Thread.Sleep(7000);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n // if not cancelled then save data\n using (App.Data.EmployeeWCF ws = new App.Data.EmployeeWCF())\n {\n return ws.UpdateData(_employee.Data);\n }\n }, cancellationToken);\n\n try\n {\n this.DialogResult = await someTask\n ? DialogResult.OK\n : DialogResult.Abort;\n\n btnOK.Enabled = true;\n this.Close();\n }\n catch(OperationCanceledException)\n {\n MessageBox.Show(\"Timeout. Please try again.\")\n }\n finally\n {\n this.HideWizardPleaseWait();\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-08T09:16:37.457",
"Id": "107228",
"Score": "0",
"body": "I had been pulling my hair out using the `Task.Delay()` method in the question where tasks would `RunToCompletion` regardless of a call to `CancellationTokenSource.Cancel()`. Refactored my `Task` manager to use this method and it all just works. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T22:24:42.240",
"Id": "23067",
"ParentId": "23020",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T15:39:22.107",
"Id": "23020",
"Score": "8",
"Tags": [
"c#",
"task-parallel-library",
"async-await"
],
"Title": "C# 5 Async Await .Task.Factory.StartNew cancellation"
}
|
23020
|
<p>This was a homework assignment that I'm now done with - I submitted it as is. However the fact that I needed to use the same code twice bugged me... The double code is:</p>
<pre><code>printf("Enter a distance in inches (0 to quit): ");
scanf("%f",&input);
</code></pre>
<p>Is there a better way to do the same thing in my loop instead of the double <code>scanf</code>/<code>printf</code>? It does need to quit the program immediately if a 0 is entered.</p>
<pre><code>#include <stdio.h>
int main()
{
float distance, floatFeet, input;
int feet;
printf("Enter a distance in inches (0 to quit): ");
scanf("%f", &input);
while (input != 0)
{
feet = input/12;
distance = (input-feet*12);
floatFeet = input/12;
printf("%d feet and %f inches or %f feet \n\n", feet, distance, floatFeet);
printf("Enter a distance in inches (0 to quit): ");
scanf("%f", &input);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:29:48.757",
"Id": "35471",
"Score": "13",
"body": "there is a codereview.SO where questions like are better suited"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T15:41:33.333",
"Id": "35472",
"Score": "1",
"body": "And off we go..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T09:10:28.753",
"Id": "35715",
"Score": "0",
"body": "I would flush the output before reading for the input.."
}
] |
[
{
"body": "<p>Use <code>do-while</code> instead <code>while</code>.</p>\n\n<pre><code>#include <stdio.h>\nint main()\n{\n float inches, floatFeet, input;\n int feet;\n\n do\n {\n printf(\"Enter a distance in inches (0 to quit): \");\n scanf(\"%f\",&input);\n if (input == 0) break;\n feet = input/12;\n inches = (input-feet*12);\n floatFeet = input/12; \n printf(\"%d feet and %f inches or %f feet \\n\\n\",feet,inches,floatFeet); \n }\n while (input != 0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:49:12.973",
"Id": "35475",
"Score": "0",
"body": "\"It does need to quit the program immediately if a 0 is entered.\" This would print \"0 feet and 0 inches or 0 feet\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:50:13.517",
"Id": "35477",
"Score": "0",
"body": "That depends on what you mean by immediately. Since the code executed before quitting has no side effects, it shouldn't matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:50:34.127",
"Id": "35478",
"Score": "1",
"body": "@Antimony The side effect is printing a line. I don't think that \"shouldn't matter\"...the code as edited will work though (although there is an extra comparison every time the loop loops)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:51:26.167",
"Id": "35479",
"Score": "0",
"body": "@Lc Oh I didn't notice that. Ok I see the problem now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:51:59.770",
"Id": "35480",
"Score": "4",
"body": "Also, if you're breaking out explicitly, there's no point in a do loop. Just make it while(1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:05:40.087",
"Id": "35481",
"Score": "1",
"body": "@Antimony The two methods may be functionally equivalent; but the do-while construct makes it explicit that it's not intended to be an infinite loop. That said, I'd probably replace the `if (input == 0) break;` construct with `if(input !=0) { ...}`and put the rest of the loop inside the {}'s to eliminate the second exit point from the loop as well."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:47:44.497",
"Id": "23022",
"ParentId": "23021",
"Score": "5"
}
},
{
"body": "<p>You can use a <code>do while</code> loop, which will always execute once and check the condition at the end of the loop.</p>\n\n<p>If you need the program to exit immediately without printing when a 0 is entered, you could just put the calculation and printing code in an if statement within the loop:</p>\n\n<pre><code>do {\n printf(\"Enter a distance in inches (0 to quit): \");\n scanf(\"%f\",&input);\n if( input != 0 ) {\n feet = input/12;\n inches = (input-feet*12);\n floatFeet = input/12; \n printf(\"%d feet and %f inches or %f feet \\n\\n\",feet,inches,floatFeet);\n } \n} while (input != 0)\n</code></pre>\n\n<p>Or, to avoid repeating anything:</p>\n\n<pre><code>while(true) {\n printf(\"Enter a distance in inches (0 to quit): \");\n scanf(\"%f\",&input);\n if( input == 0 ) {\n break;\n }\n feet = input/12;\n inches = (input-feet*12);\n floatFeet = input/12; \n printf(\"%d feet and %f inches or %f feet \\n\\n\",feet,inches,floatFeet);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:47:55.410",
"Id": "23023",
"ParentId": "23021",
"Score": "10"
}
},
{
"body": "<p>In general, you would need to insert an explicit conditional somewhere in order to distinguish between the first iteration (when no results should be displayed before the prompt) and any subsequent ones. That's because the \"do not display output\" condition is different from the \"exit program\" condition, so you can't just shove both into the loop condition.</p>\n\n<p>Since you are going to insert an <code>if</code> no matter what, you might as well make it break out of the loop and make the loop infinite:</p>\n\n<pre><code>while (1)\n{\n printf(\"Enter a distance in inches (0 to quit): \");\n scanf(\"%f\",&input);\n\n if (input == 0) break;\n\n feet = input/12;\n inches = (input-feet*12);\n floatFeet = input/12; \n printf(\"%d feet and %f inches or %f feet \\n\\n\",feet,inches,floatFeet);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:52:40.533",
"Id": "35484",
"Score": "2",
"body": "In C, you'd probably want while(1), not while(true)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:53:37.037",
"Id": "35485",
"Score": "3",
"body": "@Antimony: So true, thanks (no pun intended). I 've blown my cover! ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:57:02.523",
"Id": "35486",
"Score": "0",
"body": "while (true) throws an 'undeclared' error at me, should I just use while (1)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:57:33.897",
"Id": "35487",
"Score": "0",
"body": "ah okay thanks antimony, comments didn't refresh right away :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T01:56:28.807",
"Id": "35488",
"Score": "1",
"body": "In C, the idiom for \"infinite loop\" is `for(;;) { .... }`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:48:01.970",
"Id": "23024",
"ParentId": "23021",
"Score": "19"
}
},
{
"body": "<p>You can replace this loop with a \"forever\" loop that exits from the middle of its body, like this:</p>\n\n<pre><code>for (;;) {\n printf(\"Enter a distance in inches (0 to quit): \");\n scanf(\"%f\",&input);\n if (input == 0) break;\n feet = input/12;\n inches = (input-feet*12);\n floatFeet = input/12; \n printf(\"%d feet and %f inches or %f feet \\n\\n\",feet,inches,floatFeet);\n}\n</code></pre>\n\n<p>There are multiple ways to do a \"forever\" loop; this one is borrowed from K&R's book.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:55:39.327",
"Id": "35489",
"Score": "0",
"body": "Any reason to use a for loop instead of a while loop when making a 'forever' loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:57:29.233",
"Id": "35490",
"Score": "3",
"body": "@Symon I use `for(;;)` because it is a very common idiom popularized by [\"the\" book](http://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628) on the C language. Other than that, there is no reason to go one way or the other: the compiler will generate identical binary code for both loops."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:58:23.583",
"Id": "35491",
"Score": "3",
"body": "Some people even define: `#define ever (;;)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:59:36.160",
"Id": "35492",
"Score": "7",
"body": "@mouviciel: People who have just not learned to *leave the preprocessor alone if at all possible*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T15:06:05.293",
"Id": "35493",
"Score": "2",
"body": "@Symon In a compiler which does not optimize at all, `while (1)` might generate a comparison to a constant which is omitted in `for (;;)`. However, all normal compilers would optimize that comparison away."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:48:36.680",
"Id": "23025",
"ParentId": "23021",
"Score": "7"
}
},
{
"body": "<p>You could move the duplicated lines into a function, something like this should work:</p>\n\n<pre><code>#include <stdio.h>\n\nfloat get_input(void)\n{\n float input;\n\n printf(\"Enter a distance in inches (0 to quit): \");\n scanf(\"%f\", &input);\n\n return input;\n}\n\nint main()\n{\n float inches, floatFeet, input;\n int feet;\n\n while (input = get_input())\n {\n feet = input/12;\n inches = (input-feet*12);\n floatFeet = input/12;\n printf(\"%d feet and %f inches or %f feet \\n\\n\",feet,inches,floatFeet);\n }\n\n printf(\"Goodbye!\\n\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:37:26.533",
"Id": "35498",
"Score": "1",
"body": "@mskfisher, thanks! Maybe out of scope though, if the OP has not learned about functions and such yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:39:47.487",
"Id": "35499",
"Score": "0",
"body": "+1, because it's more elegant than all the other solutions. However, I would extract the first 3 lines from the while block also into a method (calculate_output or something like that). Also, the answer lacks the check for 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:43:06.970",
"Id": "35500",
"Score": "0",
"body": "I would too, but restricted my answer to just what the OP was asking about. The 0 is checked by `while`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:43:15.283",
"Id": "35501",
"Score": "1",
"body": "@Marton `while(input = get_input())` checks whether `input` is 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:52:13.233",
"Id": "35502",
"Score": "0",
"body": "@DanielFischer Oops, sorry, I just never use `while(0)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:56:13.857",
"Id": "35503",
"Score": "1",
"body": "@Marton It's not `while(0)`, it's `while(input)` - except that `input` also gets assigned when the loop condition is evaluated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T15:00:29.767",
"Id": "35504",
"Score": "0",
"body": "+1, however I would move variable declaration to the first place they are used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T15:13:13.413",
"Id": "35505",
"Score": "1",
"body": "@marco-fiset This is possible in C99 but not in classic C. C99 doesn't really seem to have set off yet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T15:16:18.010",
"Id": "35506",
"Score": "0",
"body": "@FelixDombek: True, I have not programmed in C for a really long time! Did not remember that one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T15:34:11.080",
"Id": "35507",
"Score": "0",
"body": "Sorry but this is not elegant! `while (input = get_input())` will cause confusion for any beginning C programmer. Marton's comment shows that even experienced ones will fall for that trap!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:26:37.813",
"Id": "35508",
"Score": "0",
"body": "Yes it can confuse the beginning C programmer, but nevertheless it's an elegant solution, using the given assumption (using the 0 as stop sign)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T20:41:22.323",
"Id": "35509",
"Score": "0",
"body": "@Alexander Thanks, programming has been my job for several years now, but I never used (and will never use) while like this. Exactly because it's confusing. But I learned something new today :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T16:31:30.133",
"Id": "35512",
"Score": "1",
"body": "Better would be `while ((input = get_input()) != 0)` which won't give a compiler warning and doesn't confuse the assignment with a boolean."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:52:26.550",
"Id": "23027",
"ParentId": "23021",
"Score": "30"
}
},
{
"body": "<p>Symon, here is another alternative. Notice the following things: </p>\n\n<ol>\n<li><p>I have separated getting input into a function, <code>get_input</code>. The function takes a pointer to a variable to accept the input value and checks whether <code>scanf</code> actually reads a value from the user input. It returns an integer value that is non-zero (true) if <code>scanf</code> really did read a value. The exit condition has changed to <code>ctrl-d</code> which is the standard UNIX way of indicating end-of-input. Equally, typing a non-numeric will also cause <code>scanf</code> to return 0.</p></li>\n<li><p>The <code>while</code> loop now exits on failure of the input function.</p></li>\n<li><p>The variables are defined at the point of use. This is better practice as it reduces the scope of the variable (ie. the amount of the code where it is valid). </p></li>\n<li><p><code>distance</code> is renamed <code>inches</code>, which seems more appropriate. </p></li>\n<li><p>The division is done only once and there is a cast (int) to avoid a conversion compiler warning (turn many warnings ON in your compiler).</p></li>\n<li><p>A new-line is printed on exit to be nice to the user.</p>\n\n<pre><code>#include <stdio.h>\n\nstatic inline int get_input(float *input)\n{\n printf(\"\\nEnter a distance in inches (ctrl-d to quit): \");\n return scanf(\"%f\", input) == 1;\n}\n\nint main(void)\n{\n float input;\n\n while (get_input(&input) != 0) {\n\n float float_feet = input / 12;\n int feet = (int) float_feet;\n float inches = input - (feet * 12);\n\n printf(\"%d feet, %f inches or %f feet \\n\", feet, inches, float_feet);\n }\n putchar('\\n');\n return 0;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T16:57:13.030",
"Id": "23031",
"ParentId": "23021",
"Score": "0"
}
},
{
"body": "<p>This is exactly where you use the:</p>\n\n<pre><code>do {\n //stuff\n} while (condition)\n</code></pre>\n\n<p>... where you need to do something once, at least, but conditionally repeat the same task...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T07:56:45.897",
"Id": "23150",
"ParentId": "23021",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23024",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T13:44:23.900",
"Id": "23021",
"Score": "18",
"Tags": [
"c"
],
"Title": "Converting inches to feet"
}
|
23021
|
<p>I'm reading the awesome Head First Design Patterns book. As an exercise I converted first example (or rather a subset of it) to Python. The code I got is rather too simple, i.e. there is no abstract nor interface declarations, it's all just 'classes'. Is that the right way to do it in Python? My code is below, original Java code and problem statement can be found at <a href="http://books.google.com/books?id=LjJcCnNf92kC&pg=PA18">http://books.google.com/books?id=LjJcCnNf92kC&pg=PA18</a></p>
<pre><code>class QuackBehavior():
def __init__(self):
pass
def quack(self):
pass
class Quack(QuackBehavior):
def quack(self):
print "Quack!"
class QuackNot(QuackBehavior):
def quack(self):
print "..."
class Squeack(QuackBehavior):
def quack(self):
print "Squeack!"
class FlyBehavior():
def fly(self):
pass
class Fly():
def fly(self):
print "I'm flying!"
class FlyNot():
def fly(self):
print "Can't fly..."
class Duck():
def display(self):
print this.name
def performQuack(self):
self.quackBehavior.quack()
def performFly(self):
self.flyBehavior.fly()
class MallardDuck(Duck):
def __init__(self):
self.quackBehavior = Quack()
self.flyBehavior = Fly()
if __name__ == "__main__":
mallard = MallardDuck()
mallard.performQuack()
mallard.performFly()
mallard.flyBehavior = FlyNot()
mallard.performFly()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T20:04:40.450",
"Id": "35602",
"Score": "0",
"body": "This looked [very familiar](http://codereview.stackexchange.com/questions/20718/the-strategy-design-pattern-for-python-in-a-more-pythonic-way/20719#20719) - you might want to take a look at my answer to that question."
}
] |
[
{
"body": "<pre><code>class QuackBehavior():\n</code></pre>\n\n<p>Don't put <code>()</code> after classes, either skip it, or put <code>object</code> in there</p>\n\n<pre><code> def __init__(self):\n pass\n</code></pre>\n\n<p>There's no reason to define a constructor if you aren't going to do anything, so just skip it</p>\n\n<pre><code> def quack(self):\n pass\n</code></pre>\n\n<p>You should probably at least <code>raise NotImplementedError()</code>, so that if anyone tries to call this it'll complain. That'll also make it clear what this class is doing.</p>\n\n<p>You don't really need this class at all. The only reason to provide classes like this in python is documentation purposes. Whether or not you think that's useful enough is up to you.</p>\n\n<pre><code>class Quack(QuackBehavior):\n def quack(self):\n print \"Quack!\"\n\nclass QuackNot(QuackBehavior):\n def quack(self):\n print \"...\"\n\nclass Squeack(QuackBehavior):\n def quack(self):\n print \"Squeack!\"\n\nclass FlyBehavior():\n def fly(self):\n pass\n\nclass Fly():\n</code></pre>\n\n<p>If you are going to defined FlyBehavior, you should really inherit from it. It just makes it a litle more clear what you are doing.</p>\n\n<pre><code> def fly(self):\n print \"I'm flying!\"\n\nclass FlyNot():\n def fly(self):\n print \"Can't fly...\"\n\nclass Duck():\n</code></pre>\n\n<p>I'd define a constructor taking the quack and fly behavior here.</p>\n\n<pre><code> def display(self):\n print this.name\n\n def performQuack(self):\n self.quackBehavior.quack()\n\n def performFly(self):\n self.flyBehavior.fly()\n\nclass MallardDuck(Duck):\n def __init__(self):\n self.quackBehavior = Quack()\n self.flyBehavior = Fly()\n</code></pre>\n\n<p>There's not really a reason for this to be a class. I'd make a function that sets up the Duck and returns it. </p>\n\n<pre><code>if __name__ == \"__main__\":\n mallard = MallardDuck()\n mallard.performQuack()\n mallard.performFly()\n mallard.flyBehavior = FlyNot()\n mallard.performFly()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:35:43.547",
"Id": "23038",
"ParentId": "23033",
"Score": "7"
}
},
{
"body": "<p>In Python, you can pass functions as argument. This simplifies the \"Strategy\" Design pattern, as you don't need to create classes just for one method or behavior. See this <a href=\"https://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia\">question</a> for more info.</p>\n\n<pre><code>def quack():\n print \"Quack!\"\n\ndef quack_not():\n print \"...\"\n\ndef squeack():\n print \"Squeack!\"\n\ndef fly():\n print \"I'm flying!\"\n\ndef fly_not():\n print \"Can't fly...\"\n\n\nclass Duck:\n def display(self):\n print this.name\n\n def __init__(self, quack_behavior, fly_behavior):\n self.performQuack = quack_behavior\n self.performFly = fly_behavior\n\nclass MallardDuck(Duck):\n def __init__(self):\n Duck.__init__(self, quack, fly)\n\nif __name__ == \"__main__\":\n duck = Duck(quack_not, fly_not)\n duck.performQuack()\n mallard = MallardDuck()\n mallard.performQuack()\n mallard.performFly()\n mallard.performFly = fly_not\n mallard.performFly()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>...\nQuack!\nI'm flying!\nCan't fly...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T15:08:54.087",
"Id": "35550",
"Score": "0",
"body": "I picked this answer because it actually shows what @WinstonEwert's only proposed. However, this code lets you create a generic Duck, which was not possible in original Java example (that class is abstract). I assumed not having \\_\\_init__ in Duck() would make it kind-of-abstract in Python... Is that a correct assumption?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T23:27:35.507",
"Id": "35677",
"Score": "0",
"body": "Yes, here's some more info on that: http://fw-geekycoder.blogspot.com/2011/02/creating-abstract-class-in-python.html\nThe reason I had the `__init__` was for my own reasons of testing the script."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T23:35:22.530",
"Id": "23044",
"ParentId": "23033",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23044",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T17:46:59.227",
"Id": "23033",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"design-patterns"
],
"Title": "Strategy Design Pattern in Python"
}
|
23033
|
<p>I have a Swing application with no real design pattern. I want to start learning to design Swing or any types of application properly. Here is the main <code>JFrame</code> class.</p>
<pre><code> import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import org.text.gui.components.tabs.*;
public class TextFrame extends JFrame {
private static final long serialVersionUID = 1289484372051624149L;
public static final String INBOX = "Inbox";
public static final String CONTACT = "Contact";
public static final String SEND = "Send";
private JTabbedPane pane;
public TextFrame() {
initComponents();
layoutComponents();
pack();
setLocationByPlatform(true);
setVisible(true);
}
public Component getTab(String title) {
return pane.getComponentAt(pane.indexOfTab(title));
}
public void setSelectedTab(String title) {
pane.setSelectedComponent(getTab(title));
}
private void initComponents() {
setTitle("Text");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane = new JTabbedPane();
pane.setPreferredSize(new Dimension(225, 300));
pane.addTab(INBOX, new InboxTab(this));
pane.addTab(CONTACT, new ContactTab(this));
pane.addTab(SEND, new SendTab());
}
private void layoutComponents() {
add(pane);
}
}
</code></pre>
<p>The tabs are <code>JPanel</code>s with some logic in them. Any advice on a design pattern to implement or examples or anything would be greatly appreciated. I hope I included enough information.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T03:03:15.890",
"Id": "35614",
"Score": "1",
"body": "This appears to be a pretty clean implementation of the top frame. Seeing the code for the tabs (Inbox/Contact/etc) would shed more light on what's going on here and maybe more opportunity for review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T17:32:00.457",
"Id": "35810",
"Score": "1",
"body": "One thing which could be discussed, if it is a better way to extend JFrame or to have a private member of type JFrame. I prefer the second. Other than that I would agree to @E-Man"
}
] |
[
{
"body": "<p>One thing would be to separate view from functionality (you may even make the business logic invocation asynchronous). You can also make your code cleaner and smaller by creating widgets that support templating and using them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T14:46:45.293",
"Id": "24500",
"ParentId": "23042",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T22:48:53.337",
"Id": "23042",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"swing"
],
"Title": "Design Pattern for Swing application"
}
|
23042
|
<p>I want to know if there is a way to improve my code. It finds the two highest values in an array, and these numbers need to be distinct.</p>
<p>I don't want to sort the values; I just want to find them.</p>
<p>My idea is to create a new array if the length is even and compare the pair of values to find the minimum and maximum values.</p>
<p>So, later, I find the second highest value.</p>
<pre><code>package doze;
public class Elementos {
public int maxValue(int array[], int arrayLength) {
arrayLength = array.length;
if ((arrayLength % 2) > 0) {
arrayLength++;
int aux[] = array;
array = new int[arrayLength];
for (int i = 0; i < aux.length; i++) {
array[i] = aux[i];
}
array[(arrayLength - 1)] = aux[(arrayLength - 2)];
}
int maxValue = array[0];
int minValue = array[0];
int i = 0;
while (i != arrayLength) {
if (array[i] > array[i + 1]) {
if (array[i] > maxValue) {
maxValue = array[i];
}
if (array[i + 1] < minValue) {
minValue = array[i + 1];
}
} else {
if (array[i + 1] > maxValue) {
maxValue = array[i + 1];
}
if (array[i] < minValue) {
minValue = array[i];
}
}
i += 2;
}
int secondMaxValue = minValue;
i = 0;
while (i != arrayLength) {
if ((array[i] > minValue) && (array[i] < maxValue)) {
minValue = array[i];
secondMaxValue = minValue;
}
i += 1;
}
return maxValue;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-22T22:41:17.957",
"Id": "266524",
"Score": "0",
"body": "You present uncommented code - I, for one, am neither going to guess how it is supposed to work, nor even read it in earnest. If you determine the highest value _H_ \"tournament style\", the second highest will be among its \"opponents\" - which not only may all equal _H_: for each identical value, the respective opponents would have to be inspected to find the highest with lower value - worst case much the same order of growth as the approach discussed in the answers below."
}
] |
[
{
"body": "<p>I'd be somewhat surprised if the code is correct, but even if it is, it has a lot of pointless stuff - comparing in pairs, aux array, minValue. A much better way is to find the max value, and the max value that's smaller than the first max. The naive way is to iterate through the array twice, but it can actually be done by iterating only once and updating both variables. One important question (to the initial problem) is what to do if the array does not contain 2 different values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:14:04.973",
"Id": "35529",
"Score": "0",
"body": "Thanks for your reply, i did this code running problably like you suggest with one \"for\" and comparing, if the number < vector, i update the second element and update also the max value...but if the first number is the higher valeu i can get the second max value...\n\nmy code is running correct, i´ve tried to test with a array, ordened, unoderned and sorted"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:29:04.127",
"Id": "35531",
"Score": "0",
"body": "@DiegoMacario are you saying that you have another version of the program, with a single \"for\"? If so, I'd like to see it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:36:27.843",
"Id": "35532",
"Score": "0",
"body": "something like this...\n\n public void findElements(int[] array) {\n\n int maxValue = array[0];\n int secondMaxValue = array[0];\n\n for (int i = 0; i < array.length; i++) {\n\n if (array[i] > maxValue) {\n secondMaxValue = maxValue;\n maxValue = array[i];\n }\n\n }\n\n }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:39:16.663",
"Id": "35534",
"Score": "1",
"body": "That's a very good start, except you're not handling one situation: what if array[i] is between the secondMaxValue and the maxValue?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:41:15.943",
"Id": "35536",
"Score": "0",
"body": "i imagine if the array contains the same values will not have distinct values"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:44:18.427",
"Id": "35537",
"Score": "1",
"body": "One example is: 2, 5, 3. Your code would find 5 and 2."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:46:41.460",
"Id": "35538",
"Score": "0",
"body": "rigth, but how can i handle this?\ni tryed to make my code improve, but i dont know"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:50:05.163",
"Id": "35539",
"Score": "0",
"body": "First you need to understand what the program needs to do when it finds 3 - what to update and why. I could give you the answer but it would be much better for you to figure it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:57:05.707",
"Id": "35540",
"Score": "0",
"body": "yes of course, the first code i tougth for 2 days, and i haver other"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T01:01:20.300",
"Id": "35541",
"Score": "0",
"body": "i dont if this can works but compare also if the number is different of the max...."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T00:08:28.457",
"Id": "23047",
"ParentId": "23045",
"Score": "4"
}
},
{
"body": "<p>Aside from corner case testing like no two distinct max values. If you assume an array size of at least two, and this might be more valid C# than java but....</p>\n\n<pre><code>int max1 = Math.Max(array[0], array[1]);\nint max2 = Math.Min(array[0], array[1]);\nif(max1 == max2) max2 = Int.MinValue;\n\n//for loop 2...array length\n\nint curr = array[idx];\nif(curr > max1) { \n max2 = max1; max1 = curr;\n}\nelse if(curr > max2 && curr != max1) {\n max2 = curr;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T21:09:37.810",
"Id": "35572",
"Score": "0",
"body": "Something is weird. max1 and max2 are guaranteed to be the same at line 3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T19:11:22.677",
"Id": "35599",
"Score": "2",
"body": "I would move the test `max1 == max2` to the end. Like this would detect the case where the whole array does not contain two distinct values."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:43:32.440",
"Id": "23062",
"ParentId": "23045",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>I don't want to sort the values.</p>\n</blockquote>\n\n<p>Are you saying this because you don't realize how easy it is?</p>\n\n<p><strong>Sorting</strong> is the key insight to greatly simplify the code.</p>\n\n<p>Implement, or override, the Java version of <code>IComparible</code>. The language automatically uses this to know how to sort. <strong>Search Java documentation</strong> and see if the Array class has a way to pass in a method that tells it how to sort. If not then make a custom class.</p>\n\n<p>Then write methods that take advantage of the fact that it's dealing with a sorted array.</p>\n\n<p>Consider the following as pseudo code, in C#</p>\n\n<pre><code>// a custom List of integers\npublic class MyList : List, IComparable {\n\n // IComparible implementation\n public int Compare (int thisValue, int otherValue) {\n if(thisValue > otherValue) return 1;\n if(thisValue < otherValue) return -1;\n if(thisValue == otherValue) return 0;\n }\n\n public int getLargestValue() {\n this.Sort();\n return this[0];\n }\n\n public int getSecondLargestValue() {\n int largest = this.getLargestValue();\n int nextLargest; //defaults to zero\n\n foreach (int nextNum in this) {\n nextLargest = nextNum;\n if (nextLargest != largest) break; \n }\n\n return nextLargest;\n }\n}\n\n// client code...\n\nMyList integers = new MyList();\n// fill it up with numbers here\n\nint largest = integers.getLargestValue();\nint nextLargest = integers.getSecondLargestValue();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T21:11:43.203",
"Id": "35573",
"Score": "2",
"body": "Well, sorting is `O(n*logn)`, so iterating over the entire array twice will generally be faster than sorting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T04:45:09.347",
"Id": "35580",
"Score": "2",
"body": "Too bad we can't calculate big-O for the time to write, debug, extend, and simply comprehend code. The original code's problem is it's totally unnecessary size, complexity, and incomprehensibility. Once we bring some sanity to it then we can worry about performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T14:21:39.900",
"Id": "35593",
"Score": "0",
"body": "Well, if it was just an array of primitives, `Arrays.sort()` would do the trick, then just walk back from the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T19:00:09.227",
"Id": "35762",
"Score": "0",
"body": "I don´t wanna use api Java, just code...like in c++"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T18:56:27.927",
"Id": "23065",
"ParentId": "23045",
"Score": "1"
}
},
{
"body": "<p>Here's a simple implementation which will return the max (first index in return array) and second distinct max (second index in return array) value as an array. If the list is size zero or there is no distinct max value, then Integer.MIN_VALUE is returned.</p>\n\n<pre><code>/**\n * @param integer array\n * @return an array comprising the highest distinct value (index 0) and second highest distinct\n * value (index 1), or Integer.MIN_VALUE if there is no value.\n */\npublic int[] findTwoHighestDistinctValues(int[] array)\n{\n int max = Integer.MIN_VALUE;\n int secondMax = Integer.MIN_VALUE;\n\n for (int value:array)\n {\n if (value > max)\n {\n secondMax = max;\n max = value;\n }\n else if (value > secondMax && value < max)\n {\n secondMax = value;\n }\n }\n return new int[] { max, secondMax };\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T11:46:38.790",
"Id": "35635",
"Score": "0",
"body": "+1: looks like the simplest solution. You may add a comment to explain that the second if also guarantees that max won't be equal to secondMax."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T17:25:53.447",
"Id": "35809",
"Score": "0",
"body": "Some small enhancements: You could use a foreach loop, which would make it a bit more readable. The second branch condition could be `secondMax < array[i] && array[i] < max` which helps to see the effect. And I would add some JavaDoc, at least to document the return value. The rest is fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T23:39:35.147",
"Id": "35844",
"Score": "0",
"body": "@tb - nice suggestions. Code updated accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-22T22:46:15.880",
"Id": "266526",
"Score": "0",
"body": "Comparing to `secondMax` first should allow to skip many comparisons with `max`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T21:56:10.760",
"Id": "23066",
"ParentId": "23045",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T23:56:58.530",
"Id": "23045",
"Score": "6",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Find the 2 distinct highest values in an array"
}
|
23045
|
<p>This code takes text from the standard input, maps it to a struct (if possible), and creates a JSON string from that.</p>
<p>I'm using a barcode scanner for the input, and I've attempted to use goroutines to ensure that <strong>if something goes wrong with the parsing or JSON-marshalling, the program will continue to receive and process input from the scanner.</strong></p>
<p>Am I doing this correctly, and am I doing it in the most effective, efficient, or idiomatic way?</p>
<p>Because all I care about for this post is the concurrency, I've left out all code that parses the input and creates JSON. Additionally, the only thing I do with the JSON right now is print it back out.</p>
<p>Thanks for taking a look at this.</p>
<pre><code>package main
import (
"fmt"
"status2/shoporder"
)
func main() {
var input string
for input != "exit" {
fmt.Scanln(&input)
ch := make(chan string)
quit := make(chan bool)
go parseInput(input, ch, quit)
go sendJson(ch, quit)
}
}
// Take the input and generate some JSON, then return it along a channel.
func parseInput(input string, ch chan string, quit chan bool) {
// shoporder.Parse() uses regexp to validate the input, and returns a JSON string.
son, ok := shoporder.Parse(input)
if !ok {
// If the input could not be parsed into JSON, then ignore and shut down
// both goroutines.
quit <- true
return
}
ch <- son
}
// This will eventually send the JSON using websockets, but for now I just
// print it back out.
func sendJson(ch chan string, quit chan bool) {
select {
case json := <-ch:
// For now I just print the JSON.
fmt.Println(json)
case <-quit:
// I make sure to quit the goroutine, because I'm worried about creating a
// bunch that never end and just hang around. Do I need to do this?
return
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It seems reasonable to start a goroutine for each input, but I'm not sure you need separate goroutines for parsing and sending. After all, one is just waiting for the other to finish. They might as well be the same goroutine. Then you don't need either of the channels because they were just to let these two goroutines communicate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T20:35:24.617",
"Id": "35670",
"Score": "0",
"body": "That's a good point. Nothing can happen in the second goroutine until it receives from the channel. Because of that, there's no reason for it to be separate from the first one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T18:55:59.750",
"Id": "23124",
"ParentId": "23050",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T01:26:57.497",
"Id": "23050",
"Score": "3",
"Tags": [
"design-patterns",
"go"
],
"Title": "Am I using Golang concurrency correctly to increase reliability?"
}
|
23050
|
<p>Is the subroutine <code>test1</code> ugly?/uglier than the others?</p>
<pre><code>#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.1;
use Data::Dumper;
my $ref = { one => 1, two => 2, three => 3 };
sub test1 {
my ( $ref ) = @_;
$ref->{three} = 4;
}
test1( $ref );
sub test2 {
$ref->{three} = 4;
}
test2( $ref );
sub test3 {
my ( $ref ) = @_;
$ref->{three} = 4;
return $ref;
}
$ref = test3( $ref );
say Dumper $ref;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:18:20.503",
"Id": "35543",
"Score": "3",
"body": "The argument in `test2( $ref );` is ignored."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:04:48.540",
"Id": "35544",
"Score": "1",
"body": "@HunterMcMillen I had not thought of it."
}
] |
[
{
"body": "<p>Here are some considerations when writing such functions:</p>\n\n<ul>\n<li><p>By passing the function all of the variables it needs (<code>test1</code>), you don't need to rely on global variables. This makes the function <strong>easier to test</strong>, more <strong>predictable</strong> (no side effects) and <strong>easier to refactor</strong> as you can move it to another module or file easily. If it relied on global variables, it would be broken if the variable is moved or its data structures changed.</p></li>\n<li><p>Returning the original reference is not necessary for <code>test3</code>, because <strong>the original <code>$ref</code> is changed</strong>. Returning is useful if you want to chain function calls.</p></li>\n<li><p>Modifying the arguments passed your function directly can be surprising to the function's caller. If you do this, make it clear in the documentation. If you actually want to make a new copy of the object, modify it and return it, use something like <a href=\"http://search.cpan.org/perldoc?Clone\">Clone</a>. Of course, this can be slow.</p></li>\n<li><p>Just in case you are writing object accessors/mutators: please consider using a module such as <a href=\"http://search.cpan.org/perldoc?Class%3a%3aAccessor\">Class::Accessor</a> or the more heavyweight but extensive <a href=\"http://search.cpan.org/perldoc?Moose\">Moose</a> which can generate such functions for you automatically.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T16:20:34.600",
"Id": "23052",
"ParentId": "23051",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "23052",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:07:53.427",
"Id": "23051",
"Score": "2",
"Tags": [
"perl"
],
"Title": "Code style: passing a reference to subroutine"
}
|
23051
|
<p>I made this small program to demonstrate to myself an example of interface. I wanted to confirm whether it is correct and if there is anything more I should know about interfaces other than the importance of implementing polymorphism and multiple inheritance.</p>
<pre><code>//program.cs
class Program
{
static void Main(string[] args)
{
Dog oDog = new Dog();
Console.WriteLine(oDog.Cry());
Cat oCat = new Cat();
Console.WriteLine(oCat.Cry());
Console.ReadKey();
}
//IAnimal.cs
interface IAnimal
{
string Cry();
}
//Dog.cs
class Dog : IAnimal
{
public string Cry()
{
return "Woof!";
}
}
//Cat.cs
class Cat : IAnimal
{
public string Cry()
{
return "Meow!";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:14:49.050",
"Id": "35551",
"Score": "0",
"body": "If you want to know more about interfaces, Code Review is not the right site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:17:08.363",
"Id": "35552",
"Score": "0",
"body": "Why is that? I am just asking my example to be reviewed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:19:42.323",
"Id": "35553",
"Score": "3",
"body": "But you asked for more than that. “are there anything more I should know about interfaces” That doesn't have anything to do with reviewing your code."
}
] |
[
{
"body": "<p>Your code is quite simple and works, there is not much to review.</p>\n\n<p>Few points:</p>\n\n<ol>\n<li>You shouldn't use variable names like <code>oDog</code>. If the <code>o</code> is meant to indicate that it's an object, then that information already contained in the type of the variable, so the prefix is useless. If it indicates something else, then it's very confusing.</li>\n<li>Your code is not a very good example, because it would work exactly the same even without the interface.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:24:55.327",
"Id": "35554",
"Score": "0",
"body": "Yes, about anything is an object in C#, and thousands of types are available in the class library, making it virtually impossible to find an appropriate prefix for one of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:43:12.270",
"Id": "35555",
"Score": "0",
"body": "How would it work exactly the same without interface?\nWithout interface an Animal class would have the Cry() method and it would not vary according to the class it was inherited by e.g.Dog and Cat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:50:45.417",
"Id": "35557",
"Score": "1",
"body": "@Md.lbrahim There is no `Animal` class in the code you posted. And the `Main()` method really doesn't use the interface in any way."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:18:39.360",
"Id": "23058",
"ParentId": "23057",
"Score": "4"
}
},
{
"body": "<p>A better exercise/code snippet to demonstrate the usefulness of an interface would be something like:</p>\n\n<pre><code>static void PrintAnimal(IAnimal animal)\n{\n Console.WriteLine(animal.Cry());\n}\n\nstatic void Main(string[] args)\n{\n IAnimal dog = new Dog();\n IAnimal cat = new Cat();\n PrintAnimal(dog);\n PrintAnimal(cat);\n\n Console.ReadKey();\n}\n</code></pre>\n\n<p>The client expecting the interface (<code>IAnimal</code>) only cares about that interface and not the specific implementation (<code>Dog</code>, <code>Cat</code>, etc). Therefore you could have the <code>PrintAnimal</code> method (maybe class at some point) handle any kind of animal you may happen to want in the future. Your example would work whether you had an interface or not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:30:19.247",
"Id": "23059",
"ParentId": "23057",
"Score": "1"
}
},
{
"body": "<p>An interface is like a contract. In you case - all clases that inherits from <code>IAnimal</code> must have a <code>Cry()</code> method... (which is really mean :) )</p>\n\n<p>In in you example you are not really using the interface. try writing it like this:</p>\n\n<pre><code>IAnimal animal1 = new Dog();\nConsole.WriteLine(animal1.Cry());\n\nIAnimal animal2 = new Cat();\nConsole.WriteLine(animal2.Cry());\n</code></pre>\n\n<p>And see that it still works.</p>\n\n<p>Now try adding a method to your <code>Cat</code> class. Perhaps an <code>Eat()</code> method.</p>\n\n<pre><code>class Cat : IAnimal {\n public string Cry()\n {\n return \"Meow!\";\n }\n\n public string Eat()\n {\n return \"Meow i'm so full - mice is my favorite!\";\n } }\n</code></pre>\n\n<p>And then try calling that method with <code>animal2</code> instance. You will notes you can't!</p>\n\n<p><code>animal2.Eat(); //<-- compile time error</code></p>\n\n<p>Because we are now using <code>animal2</code> only as <code>IAnimal</code>. And all we know about an <code>IAnimal</code> is that it can <code>Cry()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:32:40.923",
"Id": "23060",
"ParentId": "23057",
"Score": "2"
}
},
{
"body": "<p>Your example accesses the cat through a variable of type <code>Cat</code> and the dog through <code>Dog</code>. This would work, even if both classes did not implement a common interface. Inheritance is not involved.</p>\n\n<p>In order to really demonstrate the usefulness of polymorphism I suggest the following code:</p>\n\n<pre><code>interface IAnimal\n{\n string Name { get; set; }\n string Cry();\n}\n\nclass Dog : IAnimal\n{\n public string Name { get; set; }\n public string Cry()\n {\n return \"Woof!\";\n }\n}\n\nclass Cat : IAnimal\n{\n public string Name { get; set; }\n public string Cry()\n {\n return \"Meow!\";\n }\n}\n</code></pre>\n\n<p>And here is a possible test:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var animals = new List<IAnimal>();\n\n animals.Add(new Dog { Name = \"Robby\" });\n animals.Add(new Dog { Name = \"Fify\" });\n animals.Add(new Cat { Name = \"Mimy\" });\n\n PrintAnimals(animals);\n\n Console.ReadKey();\n}\n\nprivate static void PrintAnimals(IEnumerable<IAnimal> animals)\n{\n foreach (IAnimal animal in animals) {\n Console.WriteLine(\"Here is {0}: {1}\", animal.Name, animal.Cry());\n }\n}\n</code></pre>\n\n<p>It demonstrates that different types of animals can be treated the same way, but behave differently. This is what polymorphism is about. The word means many (poly) shapes or forms (morph). You can add different types of animals to a collection.</p>\n\n<p>The <code>PrintAnimals</code> method has a parameter of type <code>IEnumerable<IAnimal></code> allowing you to pass it different types of collections (arrays, lists, linked lists, stacks and many more, as yet another example of polymorphism). It uses a unique <code>Console.WriteLine</code> statement for all types of animals, without even knowing of which type an animal really is. The only thing it knows is, that it implements <code>IAnimal</code>. You could even add new types of animals later, without having to change the <code>PrintAnimals</code> method and it would still work as expected.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T17:10:45.710",
"Id": "35558",
"Score": "0",
"body": "Could you please elaborate a bit how this demonstrates more of interface?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T17:24:08.947",
"Id": "35561",
"Score": "2",
"body": "Your example accesses the cat through a variable of type `Cat` and the dog through `Dog`. This would work, even if both classes did not implement the interface. Inheritance is not involved. My `PrintAnimals` method does not need to know the `Cat` and `Dog` classes. `PrintAnimals` could be defined in a different assembly where `Cat` and `Dog` are not accessible (if they are not `public`). Both, cats and dogs, are accessed through the same variable `IAnimal animal`. You could even add a new kind of animal later. `PrintAnimals` would still work without any changes and without recompilation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T04:24:30.293",
"Id": "35579",
"Score": "0",
"body": "\"Polymorphism is the ability of derived classes inheriting from the same base class to respond to the same method call in their own unique way\" -Beginning C# OOP By Dan Clark. So, in my example, I inherited from IAnimal and had different implementation of Cry depending on the class (Dog,Cat). So, is not that all? Why is it important to have a PrintAnimal method to demonstrate Polymorphism?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T18:46:14.087",
"Id": "35597",
"Score": "0",
"body": "Your example does not respond to the same method call. It responds to `Dog.Cry` and `Cat.Cry`. Those are are two different methods. My example always reponds to the same method call `IAnimal.Cry`. You wrote `Dog oDog = new Dog();`. If you changed it to `IAnimal oDog = new Dog();`, you would be responding to the same method call."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-02-23T16:35:48.873",
"Id": "23061",
"ParentId": "23057",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "23061",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T15:29:18.497",
"Id": "23057",
"Score": "6",
"Tags": [
"c#",
".net",
"inheritance",
"interface",
"polymorphism"
],
"Title": "Understanding interface with animal classes"
}
|
23057
|
<p>I'm writing a function to increase a string so, for example, "aac" becomes "aad" and "aaz" becomes "aba". The result is horribly inelegant, I can't get it simple enough and I feel I'm missing something. How to improve that code?</p>
<pre><code>function inc_str(str){
var str = str.split("").map(function(a){ return a.charCodeAt(0); });
var n = 1;
while (n<str.length){
str[str.length-n]++;
if (str[str.length-n] > "z".charCodeAt(0))
str[str.length-n] = "a".charCodeAt(0),
++n;
else
break;
};
return str.map(function(a){ return String.fromCharCode(a); }).join("");
};
</code></pre>
<p>Extra points for a brief functional style solution! (Even if it needs to implement other functional functions such as zip or whatever.)</p>
|
[] |
[
{
"body": "<p>A recursive approach is much more elegant in this case:</p>\n\n<pre><code>function inc_str(str) {\n var last = str[str.length - 1],\n head = str.substr(0, str.length - 1);\n if (last === \"z\") {\n return inc_str(head) + \"a\";\n } else {\n return head + String.fromCharCode(last.charCodeAt(0) + 1);\n }\n}\n</code></pre>\n\n<p>Making it wrap around for <code>inc_str('z')</code> is left as an exercise for the reader (hint: <code>last</code> becomes <code>undefined</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T17:26:03.170",
"Id": "35563",
"Score": "0",
"body": "Hah! You couldn't resist opening an account just for this :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T17:42:11.617",
"Id": "35567",
"Score": "2",
"body": "Yay I'm glad I motivated someone to joining in. Great way to start, also. That was the obvious thing I was missing, recursion! Adapting from your answer, I got the one-liner: `function inc_str(str){ return (last(str) == \"z\") ? inc_str(head(str)) + \"a\" : head(str) + inc_char(last(str)); };` So elegant! Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T17:49:52.613",
"Id": "35568",
"Score": "0",
"body": "@Dokkat you shouldn't write your code so condensed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T18:12:33.853",
"Id": "35570",
"Score": "0",
"body": "That's fine, this isn't meant to be human readable as it is the base of an AI programming system I'm developing. Less tokens = better and I must avoid varaibles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T19:14:57.407",
"Id": "35571",
"Score": "0",
"body": "@Dokkat, so you wrote it with your eyes closed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T01:03:12.207",
"Id": "35576",
"Score": "0",
"body": "@radarbob that's not the point, the system won't accept statements and variable definitions. Notice everything is an expression. This is analyzed by the AI. Are you curious to see it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T02:55:30.710",
"Id": "35577",
"Score": "0",
"body": "@Dokkat yes please"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T17:46:42.373",
"Id": "35596",
"Score": "0",
"body": "I'm finishing my work and will post it on Github probably by march 15, I've made a note to update you guys then!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T09:08:06.613",
"Id": "35864",
"Score": "0",
"body": "Please note that the current implementation doesn't handle edge case properly. What do you want inc_str('z') to be for instance ?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T17:22:43.177",
"Id": "23064",
"ParentId": "23063",
"Score": "8"
}
},
{
"body": "<p>I suppose this could be written as:</p>\n\n<pre><code> function inc_str(str){\n return !/^[a-z0-9]$/i.test(str[str.length-1]) ? str :\n str.substr(0,str.length-1) + \n ( /z/i.test(str[str.length-1]) \n ? String.fromCharCode(str.charCodeAt(str.length-1)-25) \n : String.fromCharCode(str.charCodeAt(str.length-1)+1))\n}\n// usage\ninc_str('aaa'); //=> 'aab'\ninc_str('aaz'); //=> 'aaa'\ninc_str('aaZ'); //=> 'aaA'\ninc_str('aa2'); //=> 'aa3'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T02:41:40.783",
"Id": "43719",
"Score": "0",
"body": "Your code doesn't roll over. `inc_str('az')` outputs as \"aa\" but should be \"ba\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T06:22:58.110",
"Id": "23252",
"ParentId": "23063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T16:59:35.400",
"Id": "23063",
"Score": "1",
"Tags": [
"javascript",
"strings"
],
"Title": "Elegant function to \"increase\" a JavaScript string - for example, turning \"aac\" into \"aad\""
}
|
23063
|
<p>I'm trying to output aggregate information about a directory tree (file extension plus accumulative count and size per file type) with PowerShell.</p>
<p>This is as far as I've got.</p>
<pre><code>gci -r -ea Si `
| group { if ($_.PSIsContainer) {""} else {$_.Extension} } `
| select Name, Count, @{n="Measure"; e={$_.Group | measure Length -Sum -Average} }`
| sort Count -desc `
| ft Name, Count, @{n="SizeMB"; e={"{0:N1}" -f ($_.Measure.Sum / 1MB)}; a="right"} -Auto
</code></pre>
<p>which gives me </p>
<pre><code>Name Count SizeMB
---- ----- ------
.jar 2489 262,2
1592 1,2
.vim 1147 7,1
.xml 1087 9,6
.dll 803 657,3
.png 762 9,1
.js 380 1,9
.txt 360 14,1
.py 305 1,4
.gyp 266 0,3
.exe 262 198,3
.mui 178 47,1
.c 157 0,1
.md 137 0,3
.html 132 1,1
.tmpl 113 0,1
[...]
</code></pre>
<p>Not too bad for my first stab at PowerShell, but it feels unwieldy and I'm wondering if this could be made more elegant.</p>
|
[] |
[
{
"body": "<p>You are running your select twice and saving an unused Average from your Select-Object</p>\n\n<pre><code>gci -r -ea Si `\n| group { if ($_.PSIsContainer) {\"\"} else {$_.Extension} } `\n| sort Count -desc `\n| ft Name, Count, @{n=\"SizeMB\"; e={\"{0:N1}\" -f (($_.Group | measure Length -Sum).Sum / 1MB)};a=\"right\"} -Auto\n</code></pre>\n\n<p>You have to move the Group Measurement to the FT line from the Select. </p>\n\n<p>If you want this a little more readable, you can pull the formatting HashTable out of the pipeline:</p>\n\n<pre><code>$sizeMB = @{n=\"SizeMB\"; \n e={\"{0:N1}\" -f (($_.Group | measure Length -Sum).Sum / 1MB)};\n a=\"right\"}\n\ngci -r -ea Si `\n| group { if ($_.PSIsContainer) {\"\"} else {$_.Extension} } `\n| sort Count -desc `\n| ft Name, Count, $sizeMB -Auto\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:45:54.897",
"Id": "25683",
"ParentId": "23068",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T22:32:40.273",
"Id": "23068",
"Score": "2",
"Tags": [
"powershell"
],
"Title": "Summarize a directory with PowerShell"
}
|
23068
|
<p>Does my main class have too much code? For some reason i have the feeling that I should put all of my thread starts and joins in a for loop just to reduce the amount of code. I dunno if that will hurt readability on this class? Also is it normal for a main class to be initialize just to call one method? I only did this since I was getting an error regarding static vs non static. </p>
<pre><code>import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
public class Main {
public static String[] table;//Table for the ingredients
public static void main(String[] args) {
//Gets the number of iterations from the user then maybe pass it to the agent who will wait/notifty until the loop is over
Main main = new Main();
main.runThreads();
}
public void runThreads(){
int numofTests;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of iterations to be completed:");
numofTests = Integer.parseInt(in.nextLine());///Gets the number of tests from the user
Agent agent = new Agent(numofTests);
Smoker Pat = new Smoker ("paper", "Pat");
Smoker Tom = new Smoker ("tobacco", "Tom");
Smoker Matt = new Smoker ("matches", "Matt");
for (int i = 0; i < numofTests; i++){
Thread thread1 = new Thread(Pat);
Thread thread2 = new Thread(Tom);
Thread thread3 = new Thread(Matt);
Thread thread4 = new Thread(agent);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Smoker.latch = new CountDownLatch(1);//Resets the countdown latch for the smokers
System.out.println("*********************");
}
System.out.println("*********************");
System.out.println("Pat has smoked a total of " + Pat.numOfSmokes);
System.out.println("Matt has smoked a total of " + Matt.numOfSmokes);
System.out.println("Tom has smoked a total of " + Tom.numOfSmokes);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I would add some structure. As a general statement I'd say that good structure(s) helps reduce code. Make collections (list, array, whatever) for each of Smokers and Threads.</p>\n\n<p>I would also look into string formatting so you can loop through the Smoker collection and do your output. You do not want to hard code \"Pat\", \"Mat\", \"Tom\". The Smoker class has a Name property, use it!</p>\n\n<blockquote>\n <p>I only did this since I was getting an error regarding static vs non static.</p>\n</blockquote>\n\n<p>You gotta do what you gotta do. It's fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T05:26:16.990",
"Id": "35583",
"Score": "0",
"body": "Never heard of String foramting I'll have to look into it, if at all possible would you mind providing an example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T14:12:19.440",
"Id": "35592",
"Score": "0",
"body": "There are two ways: String.format() or System.out.printf(). Here is a nice reference for printf (applies to both): http://web.cerritos.edu/jwilson/SitePages/java_language_resources/Java_printf_method_quick_reference.pdf. You may also just want to override toString() for the smokers and just call System.out.println(smoker)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T05:08:51.890",
"Id": "23073",
"ParentId": "23069",
"Score": "7"
}
},
{
"body": "<p>I will add some thoughts about the code. Some other things were already said by radarbob in the corresponding answer.</p>\n\n<pre><code>import java.util.Scanner;\nimport java.util.concurrent.CountDownLatch;\n\npublic class Main {\n public static String[] table;//Table for the ingredients\n</code></pre>\n\n<p><code>table</code> is not used, but probably in some other code. If it is node used, you should just delete it.</p>\n\n<pre><code> public static void main(String[] args) {\n //Gets the number of iterations from the user then maybe pass it to the agent who will wait/notifty until the loop is over\n Main main = new Main();\n main.runThreads();\n }\n</code></pre>\n\n<p>In this example, you could make the runThreads method static and just use <code>runThreads()</code>.</p>\n\n<pre><code> public void runThreads(){\n</code></pre>\n\n<p>As written above, it could be <code>public static void runThreads() {</code></p>\n\n<pre><code> int numofTests;\n</code></pre>\n\n<p>I suggest to not use abbreviations. So name it numberOfTests or numberOfRuns.</p>\n\n<pre><code> Scanner in = new Scanner(System.in);\n</code></pre>\n\n<p>This could be discussed. I would name it scannerIn, so everyone knows while reading what this is and is not confused with <code>System.in</code>. But as I said, it could be discussed.</p>\n\n<pre><code> System.out.print(\"Enter the number of iterations to be completed:\");\n numofTests = Integer.parseInt(in.nextLine());///Gets the number of tests from the user\n</code></pre>\n\n<p>The comment does not help, because it just repeats the line of the code. You should remove it. And I think for your goal, a <code>int numofTests = in.nextInt();</code> would be fine, shorter and more clear.</p>\n\n<pre><code> Agent agent = new Agent(numofTests);\n Smoker Pat = new Smoker (\"paper\", \"Pat\");\n Smoker Tom = new Smoker (\"tobacco\", \"Tom\");\n Smoker Matt = new Smoker (\"matches\", \"Matt\");\n</code></pre>\n\n<p>I do not know what happens here exactly. It could be interesting to use a Collection like a List for this.</p>\n\n<pre><code> for (int i = 0; i < numofTests; i++){\n Thread thread1 = new Thread(Pat);\n Thread thread2 = new Thread(Tom);\n Thread thread3 = new Thread(Matt);\n Thread thread4 = new Thread(agent);\n thread1.start();\n thread2.start();\n thread3.start();\n thread4.start();\n try {\n thread1.join();\n thread2.join();\n thread3.join();\n thread4.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n</code></pre>\n\n<p>With a list, this would be more compact.\nIf you do not need the loop variable, you could make this more clear with a while loop:</p>\n\n<pre><code>while (numofTests > 0) {\n ...\n --numofTests;\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code> Smoker.latch = new CountDownLatch(1);//Resets the countdown latch for the smokers\n System.out.println(\"*********************\");\n }\n</code></pre>\n\n<p>I do not understand this part of the code. As long as you do not make any interesting things inside the Smoker class, this has no effect. And even if you do, I would doubt the effect. The .join() methods will already end all threads. So the CountDownLatch will most probably do nothing here. If you do some things inside the Smoker class, you should provide some update method like <code>resetCountDownLatch</code>, the name should contain some description what you are doing inside the method (which I do not know, so the general name). Anyone reading this will wonder what is happening there. In general it is a good idea to keep your object internals inside your object and do not expose it to the outer world.</p>\n\n<pre><code> System.out.println(\"*********************\");\n System.out.println(\"Pat has smoked a total of \" + Pat.numOfSmokes);\n System.out.println(\"Matt has smoked a total of \" + Matt.numOfSmokes);\n System.out.println(\"Tom has smoked a total of \" + Tom.numOfSmokes);\n }\n }\n</code></pre>\n\n<p>This looks like you update the static <code>numOfSmokes</code> variables inside the instantiated objects. If you do this in a multithreaded environment, be sure to take care about synchronization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:23:01.640",
"Id": "35812",
"Score": "0",
"body": "Wow thanks for all the detailed comments. The table arrays is used in another class, and all the print with the numOfSmokes are called after the threads are finished. numOfSmokes isn't static so that each object has its own number. I'll definitely try and stop abbreviating my variables, its a bad habit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:09:26.663",
"Id": "35817",
"Score": "0",
"body": "Ok, if it is not static, you should make it private and provide a getter. Everyone will expect this behavior (as well as myself in this example). And even if it could feel ridiculous for such small examples, it has a lot of advantages. So it is better to do it in the common way."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T17:59:36.493",
"Id": "23227",
"ParentId": "23069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T02:37:20.727",
"Id": "23069",
"Score": "-1",
"Tags": [
"java",
"multithreading",
"simulation"
],
"Title": "Launching a multithreaded simulation of smokers"
}
|
23069
|
<p>I've written a short library for manipulating matrices for 3D drawing. I've tried to strike a balance between speed and readability. Anything to improve?</p>
<pre><code>%!
%mat.ps
%Matrix and Vector math routines
/ident { 1 dict begin /n exch def
[
1 1 n { % [ i
[ exch % [ [ i
1 1 n { % [ [ i j
1 index eq { 1 }{ 0 } ifelse % [ [ i b
exch % [ [ b i
} for % [ [ b+ i
pop ] % [ [ b+ ]
} for % [ [b+]+ ]
]
end } def
/rotx { 1 dict begin /t exch def
[ [ 1 0 0 ]
[ 0 t cos t sin neg ]
[ 0 t sin t cos ] ]
end } def
/roty { 1 dict begin /t exch def
[ [ t cos 0 t sin ]
[ 0 1 0 ]
[ t sin neg 0 t cos ] ]
end } def
/rotz { 1 dict begin /t exch def
[ [ t cos t sin neg 0 ]
[ t sin t cos 0 ]
[ 0 0 1 ] ]
end } def
/.error where { pop /signalerror { .error } def } if
/dot { % u v
2 copy length exch length ne {
/dot cvx /undefinedresult signalerror } if
% u v
0 % u v sum
0 1 3 index length 1 sub { % u v sum i
3 index 1 index get exch % u v sum u_i i
3 index exch get % u v sum u_i v_i
mul add % u v sum
} for % u v sum
3 1 roll pop pop % sum
} bind def
% [ x1 x2 x3 ] [ y1 y2 y3 ] cross [ x2*y3-y2*x3 x3*y1-x1*y3 x1*y2-x2*y1 ]
/cross { % u v
dup length 3 ne 2 index length 3 ne or {
/cross cvx /undefinedresult signalerror } if
% u v
exch aload pop 4 3 roll aload pop % x1 x2 x3 y1 y2 y3
[
5 index 2 index mul % ... [ x2*y3
3 index 6 index mul sub % ... [ x2*y3-y2*x3
5 index 5 index mul % ... [ x2*y3-y2*x3 x3*y1
8 index 4 index mul sub % ... [ x2*y3-y2*x3 x3*y1-x1*y3
8 index 5 index mul % ... [ x2*y3-y2*x3 x3*y1-x1*y3 x1*y2
8 index 7 index mul sub % ... [ x2*y3-y2*x3 x3*y1-x1*y3 x1*y2-x2*y1
]
7 1 roll 6 { pop } repeat
} bind def
/transpose { STATICDICT begin
/A exch def
/M A length def
/N A 0 get length def
[
0 1 N 1 sub { /n exch def
[
0 1 M 1 sub { /m exch def
A m get n get
} for
]
} for
]
end } dup 0 6 dict put def
/matmul { STATICDICT begin
/B exch def
B 0 get type /arraytype ne { /B [B] def } if
/A exch def
A 0 get type /arraytype ne { /A [A] def } if
/Q B length def
/R B 0 get length def
/P A length def
Q A 0 get length ne {
/A A transpose def
/P A length def
Q A 0 get length ne {
A B end /matmul cvx /undefinedresult signalerror
} if
} if
[
0 1 P 1 sub { /p exch def % rows of A
[
0 1 R 1 sub { /r exch def % cols of B
0
0 1 Q 1 sub { /q exch def % terms of sum
A p get q get
B q get r get mul
add
} for
} for
]
} for
]
end } dup 0 10 dict put def
%u v {operator} vop u(op)v
%apply a binary operator to corresponding elements
%in two vectors producing a third vector as result
/vop { 1 dict begin
/op exch def
2 copy length exch length ne {
/vop cvx end /undefinedresult signalerror
} if
[ 3 1 roll % [ u v
0 1 2 index length 1 sub { % [ ... u v i
3 copy exch pop get % u v i u_i
3 copy pop get % u v i u_i v_i
op exch pop % u v u_i(op)v_i
3 1 roll % u_i(op)v_i u v
} for % [ ... u v
pop pop ]
end } def
%length of a vector
/mag { 0 exch { dup mul add } forall } def
/elem { % M i j
3 1 roll get exch get % M_i_j
} def
/det {
dup length 1 index 0 get length ne { /det cvx /typecheck signalerror } if
1 dict begin /M exch def
M length 2 eq {
M 0 0 elem
M 1 1 elem mul
M 0 1 elem
M 1 0 elem mul sub
}{
M length 3 eq {
M aload pop cross dot
}{ /det cvx /rangecheck signalerror } ifelse
} ifelse
end
} def
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-16T21:31:03.483",
"Id": "191941",
"Score": "1",
"body": "Current version: https://github.com/luser-dr00g/xpost/blob/master/data/mat.ps"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-30T07:25:28.743",
"Id": "220312",
"Score": "0",
"body": "This code is used to produce the images in these posts across the SE network: [1](http://stackoverflow.com/questions/12274863/how-to-trap-my-surface-patches-to-prevent-the-background-from-bleeding-through) [2](http://stackoverflow.com/questions/14558814/how-do-bezier-patches-work-in-the-utah-teapot) [3](http://stackoverflow.com/questions/14807341/how-to-do-a-space-partitioning-of-the-utah-teapot)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-30T07:25:39.447",
"Id": "220313",
"Score": "0",
"body": "[4](http://codegolf.stackexchange.com/questions/22620/draw-the-utah-teapot) [5](http://codegolf.stackexchange.com/questions/17270/raytracer-in-odd-or-high-level-language/17271?s=5|2.2239#17271) [6](http://codegolf.stackexchange.com/questions/22756/shortest-program-that-displays-a-red-3d-cube/23224#23224)"
}
] |
[
{
"body": "<p>I just noticed some issues with the <code>vop</code> procedure. It's not nestable the way it's written. So you can't use it to add two matrices like <code>m1 m2 { {add}vop }vop</code>. I've got a favorite trick using <code>token</code> that'll fix this. But I've got serious versioning issues, because I've post this code everywhere with no identifying marks!! I'm an idiot. </p>\n\n<p>So another big improvement would be, maybe, a copyright notice, um, a release date, a version number?!</p>\n\n<hr>\n\n<p>I've also got a handful of routines that I've considered adding because I keep needing them in the same programs that use this. But they're not really related to matrices, so I've kept them out to avoid the kitchen-sink problem.</p>\n\n<pre><code>/div { dup 0 eq { pop 10000 }{ div } ifelse } bind def\n/normalize{[1 index mag 2 index length 1 sub{dup}repeat]{div}vop}def\n/tan { dup sin exch cos div } def\n</code></pre>\n\n<p>Replacing <code>div</code> with a version that doesn't explode on divide-by-zero has gotten things to run that otherwise wouldn't, often enabling me to locate the problem visually.</p>\n\n<p><code>normalize</code> probably should be in there, if it weren't for the versioning issue.</p>\n\n<p>And <code>tan</code> is curiously omitted from the PostScript operator set. Not sure if this is the best way, but it's probably the simplest. But this requires the <code>div</code> guard, because tangents go to infinity when the <code>cos</code> is 0. The practical selection of <em>infinity</em> is perhaps best left to the individual program. So, I suppose those two should stay out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-14T06:28:34.110",
"Id": "23898",
"ParentId": "23074",
"Score": "2"
}
},
{
"body": "<p>As far as readability goes, maybe you'd like to add an <code>arg1 arg2 arg3 -- result1 result2</code> type of comment to each function? So we know what was on the stack before invoking, and what we expect to find afterward? Almost equivalently, you might show a unit test invoking your function and verifying the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T06:42:07.733",
"Id": "39848",
"Score": "0",
"body": "Good advice. I usually do that and wonder why I didn't here. I'm working up a new interpreter to run it, but it will have these things before entering the repository. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T06:49:06.327",
"Id": "39849",
"Score": "0",
"body": "Oh, I remember! I was hoping the stylized local argument convention would make the parameters apparent on the functions without the usual comment. They either construct the argument directly where the layout naturally illustrates the result, or contain intermediate stack-comments up through the final line, illustrating the result. But, it appears it's *too clever* which is bad. The entire lack of comments in the determinant function `det` was an oversight. Rats! `matmul` and `transpose` need comments, too. :("
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-14T21:48:58.270",
"Id": "25091",
"ParentId": "23074",
"Score": "3"
}
},
{
"body": "<p>Much later, I notice an error in the <code>matmul</code> routine if the right argument is a vector, it should be promoted to a column vector in order to multiply with a left matrix. This code doesn't do that.</p>\n\n<p>Rather than</p>\n\n<pre><code>B 0 get type /arraytype ne { /B [B] def } if\n</code></pre>\n\n<p>it needs to make unit subarrays of each element of B.</p>\n\n<pre><code>B 0 get type /arraytype ne {\n /B [ 0 1 B length 1 sub {\n B exch 1 getinterval\n } for ] def\n} if\n</code></pre>\n\n<p>Oh, and <code>mag</code> should probably take a <code>sqrt</code>. </p>\n\n<p>And <code>det</code> should signal the <code>undefinedresult</code> error rather than <code>typecheck</code> if the argument is not a square matrix. Perhaps it should signal a <code>typecheck</code> is the argument is not an array or scalar number.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-27T10:09:47.940",
"Id": "118039",
"ParentId": "23074",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25091",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T05:52:48.013",
"Id": "23074",
"Score": "4",
"Tags": [
"performance",
"matrix",
"postscript"
],
"Title": "Manipulating matrices for 3D drawing"
}
|
23074
|
<p>I'm trying to migrate from JavaScript to CoffeeScript. However I'm not sure about the best way to optimize the code generated by js2coffee. </p>
<p>Below is the original JavaScript source :</p>
<pre><code>var async = require('async');
var context = {};
context.settings = require('./settings');
async.series([setupDb, setupApp, listen], ready);
function setupDb(callback)
{
context.db = require('./db.js');
context.db.init(context, callback);
}
function setupApp(callback)
{
context.app = require('./app.js');
context.app.init(context, callback);
}
// Ready to roll - start listening for connections
function listen(callback)
{
context.app.listen(context.settings.http.port);
callback(null);
}
function ready(err)
{
if (err)
{
throw err;
}
console.log("Ready and listening at http://localhost:" + context.settings.http.port);
}
</code></pre>
<p>And below is the generated CoffeeScript :</p>
<pre><code>setupDb = (callback) ->
# Create our database object
context.db = require("./db")
# Set up the database connection, create context.db.posts object
context.db.init context, callback
setupApp = (callback) ->
# Create the Express app object and load our routes
context.app = require("./app")
context.app.init context, callback
# Ready to roll - start listening for connections
listen = (callback) ->
context.app.listen context.settings.http.port
callback null
ready = (err) ->
throw err if err
console.log "Ready and listening at http://localhost:" + context.settings.http.port
async = require("async")
context = {}
context.settings = require("./settings")
async.series [setupDb, setupApp, listen], ready
</code></pre>
<p>Now, I'm not sure if the <code>context</code> variable is required in CoffeeScript. In the JavaScript source its function is to share the common set of setting across the various components of the application such as database and the settings. Will a proper use of the <code>=></code> operator in CoffeeScript help ? If yes how ?</p>
|
[] |
[
{
"body": "<p>The CoffeeScript looks fine to me. You'll still need the <code>context</code> var just as in plain JS, because you're not dealing with <code>this</code>. If you were, you could maybe use the fat arrow to preserve the <code>this</code> context, but even so it'd require some refactoring, and end up very different from the original JS.</p>\n\n<p>CoffeeScript's fat arrow is basically meant to be used where you'd otherwise do the <code>var that = this;</code> trick in JavaScript. But since you're not doing such things in your JavaScript, there's no need or opportunity for it in the CoffeeScript either.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T11:57:15.810",
"Id": "23077",
"ParentId": "23076",
"Score": "2"
}
},
{
"body": "<p>I'd make context into a class with all those functions as methods on it. I think that makes your structure a bit clearer and more flexible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T17:09:43.993",
"Id": "23085",
"ParentId": "23076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23077",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T11:13:52.487",
"Id": "23076",
"Score": "3",
"Tags": [
"javascript",
"coffeescript",
"callback"
],
"Title": "Passing Context in CoffeeScript"
}
|
23076
|
<p>I have to perform an IF statement in my Javascript code. I utilised the first method shown below:</p>
<pre><code>(someVar1 !== "someString") && (someVar2[i].disabled = (someVar3.find("." + someVar4).length == 0));
</code></pre>
<p>Is the shortening of an if like this ok to do if my code is to be viewed by other members of my team? I have been told that it is a bit unclear and should instead use something like the following instead:</p>
<pre><code>if (someVar1 !== "someString") {
var bool = someVar3.find("." + someVar4).length == 0;
someVar2[i].disabled = bool;
}
</code></pre>
<p>What are people's thoughts on this? Was it reasonable for me to implement the first method? Was it fair for me to be told I should change it and not use the <code>(someVar) && doThis</code> version of an if?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T12:45:07.823",
"Id": "35587",
"Score": "3",
"body": "`someVar && doThis` is sometimes okay. In your case, I'd definitely go with option #2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T13:09:07.693",
"Id": "35589",
"Score": "0",
"body": "You could also use the `!!` boolean-coercion trick (`x.disabled = !!someVar3.find(\".\" + someVar4).length`) if you wanted. But I'd also stick with option #2 - it's more easily readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T18:57:55.013",
"Id": "35598",
"Score": "0",
"body": "It is not clear what `someVar3.find(\".\" + someVar4).length == 0` is supposed to represent. Choose a speaking name for the Boolean variable like maybe `hasNoExtension`."
}
] |
[
{
"body": "<p>The second part of the condition in the first method (someVar2[i].disabled = (someVar3.find(\".\" + someVar4).length == 0)) is only an assignment and is always evaluated to true.</p>\n\n<p>It is clearer to use only the first part of the condition as a condition in if (someVar1 !== \"someString\") and move assignment inside the if statement, similarly as you did in the second method. </p>\n\n<p>Regarding the second method, I would avoid using names such as bool as they are keywords. Use another name instead. </p>\n\n<p>Also, in this particular case you are assigning value to variable 'bool' and then use it only once. You could assign the value directly to someVar2[i].disabled.</p>\n\n<pre><code>if (someVar1 !== \"someString\") {\n someVar2[i].disabled = someVar3.find(\".\" + someVar4).length == 0;\n}\n</code></pre>\n\n<p>You could also use inline if:</p>\n\n<pre><code>someVar2[i].disabled = (someVar1 !== \"someString\") ? (someVar3.find(\".\" + someVar4).length == 0) : <defaultValue>;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T20:54:59.657",
"Id": "35603",
"Score": "1",
"body": "This inline if is way clearer than the one in the original post!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T13:03:05.200",
"Id": "23080",
"ParentId": "23078",
"Score": "6"
}
},
{
"body": "<p>Three things are important when I am valuing between two alternatives: performance, readability and situations.</p>\n\n<p>Performance-wise, you can use jsperf.com to compare the performance differences. I used to test these two, but I don't remember the results clearly now. </p>\n\n<p>Readability is important when your code will be likely used, interacted, and handed over to your team members. If you are just writing your own widget, it is fine.</p>\n\n<p>As to situations, if the JavaScript file size is a bigger concern, then use the shorter version, for example, you are working on a project for the js1k competition.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T18:05:28.883",
"Id": "23330",
"ParentId": "23078",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T12:33:38.813",
"Id": "23078",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "If statement, is the shortened version readable enough?"
}
|
23078
|
<p>I didn't realize I am not a very good programmer at recently. I just come out from Uni, I want to become a reliable teammate. Please help me to improve my coding style/habbits. I have carefully re-written a file indexer class which I didn't do very well in my work. I come here, hope I can improve it in terms of code correctness, best practices and design pattern usage.</p>
<p>--FileIndexer.h--</p>
<pre><code>#ifndef FILE_INDEXER_90738592_HA8965371_DE0E_4ff7_95A0_11B956535E12_H // INDEXER is a name which is too common. It has potential to conflict with other macros. it's better to use a descriptive name.
#define FILE_INDEXER_90738592_HA8965371_DE0E_4ff7_95A0_11B956535E12_H
#include <vector>
#include <map>
#include <string>
// Try to avoid including the entire std, since it contaminates the namespace and may cause ambiguous matches.
//using namespace std;
class FileIndexer // : public baseClass, it's a wise way to inherit basic functionalities from its super class, if necessary.
{
public :
typedef unsigned int FileType;
enum File_Type_Action
{
FILE_NEED_NOACTION = 0x0000,
FILE_NEED_BACKUP = 0x0001,
FILE_NEED_SCAN = 0x0002
};
struct FileTypeInfo
{
FileType type;
unsigned actionRequired;
};
typedef std::map<std::wstring, FileTypeInfo> DynamicFileType; // we use the map data structure to allow to add more file types easily in future.
struct FileDef
{
// using the standard constant FILENAME_MAX is much safer than a hard-coded constant.
wchar_t drive[_MAX_DRIVE];
wchar_t name[_MAX_FNAME];
wchar_t path[_MAX_DIR];
wchar_t ext[_MAX_EXT];
_fsize_t size;
unsigned int type;
};
FileIndexer ();
virtual ~FileIndexer ();
unsigned int getMaxIndex ()
{
return m_maxIndices;
}
bool setMaxIndices (const unsigned int& maxIndices);
bool processDirectory (const wchar_t* name);
bool getFirstFile (const wchar_t* ext, unsigned int& fileNo, FileDef* fd);
bool getNextFile (unsigned int& fileNo, FileDef* fd);
void listFiles (const wchar_t* ext);
bool needsAction (const File_Type_Action& action, const FileDef* fd);
bool addSupportedFileType (const wchar_t* ext, const File_Type_Action& actionRequired = FILE_NEED_NOACTION);
void listSupportedFileTypes ();
// a possible functionality in future : import multiple file types
bool importSupportFileTypes (const wchar_t** exts, const File_Type_Action* actionRequired) {};
// a possible functionality in future : export multiple file types to a file
bool exportSupportFileTypes (const wchar_t* filename) {};
void _testIndexer ();
protected:
DynamicFileType m_supportedFileTypes; //dynamical supported File types
std::vector<FileDef> m_fileIndices; //allow more flexible memory allocation for file indexing
unsigned int m_maxIndices; // the maximum number of indices supported
private:
//Since data members are not pointer types, the default copy constructor and the default assignment operator are safe to use.
//FileIndexer (FileIndexer const & other );
//FileIndexer& operator= (FileIndexer const & other );
};
#endif //INDEXER_H
</code></pre>
<p>--FileIndexer.cpp--</p>
<pre><code>#include "stdafx.h"
#include "FileIndexer.h"
#include "stdlib.h"
#include "stdio.h"
#include "io.h"
#include <stack>
FileIndexer::FileIndexer()
{
m_maxIndices = 1024;
m_fileIndices.reserve( m_maxIndices ); // This saves computational time for std::vector repeatly realllocating the memory, when the elements are added one by one.
// Initialise the supported file types
FileTypeInfo tmp;
tmp.type = 1;
tmp.actionRequired = FILE_NEED_NOACTION;
m_supportedFileTypes[std::wstring(L".txt")] = tmp;
tmp.type = 2;
tmp.actionRequired = FILE_NEED_NOACTION;
m_supportedFileTypes[std::wstring(L".xml")] = tmp;
tmp.type = 3;
tmp.actionRequired = FILE_NEED_SCAN;
m_supportedFileTypes[std::wstring(L".exe")] = tmp;
tmp.type = 4;
tmp.actionRequired = FILE_NEED_BACKUP;
m_supportedFileTypes[std::wstring(L".doc")] = tmp;
tmp.type = 5;
tmp.actionRequired = FILE_NEED_NOACTION;
m_supportedFileTypes[std::wstring(L".xls")] = tmp;
tmp.type = 6;
tmp.actionRequired = FILE_NEED_NOACTION;
m_supportedFileTypes[std::wstring(L".ppt")] = tmp;
}
FileIndexer::~FileIndexer()
{
m_maxIndices = 0;
}
bool FileIndexer::setMaxIndices (const unsigned int& maxIndices)
{
if (maxIndices < m_fileIndices.max_size() ) //This checks against the theoretical limit on the size of a vector.
{
m_maxIndices = maxIndices;
return true;
}
else
return false;
}
bool FileIndexer::addSupportedFileType(const wchar_t* ext, const File_Type_Action& _actionRequired)
{
if (!ext) return false;
std::wstring s(ext);
DynamicFileType::iterator it = m_supportedFileTypes.find(s);
if (it == m_supportedFileTypes.end())
{
FileTypeInfo tmp;
tmp.type = m_supportedFileTypes.size() + 1;
tmp.actionRequired = _actionRequired;
m_supportedFileTypes[s] = tmp;
}
else
{
it->second.actionRequired = _actionRequired;
}
return true;
}
bool FileIndexer::processDirectory(const wchar_t* name)
{
if ( !name ) return false;
if (m_fileIndices.size() >= m_maxIndices) return false;
std::stack<std::wstring> pathNameST; //using stack is much more computationally efficient than the recursive function
std::wstring initialPath = name;
pathNameST.push(initialPath);
std::wstring curS, search, fname;
FileDef f;
DynamicFileType::const_iterator it;
do
{
curS = pathNameST.top();
pathNameST.pop();
search = curS + L"\\*";
_wfinddata_t fd;
intptr_t handle = _wfindfirst(search.c_str(), &fd);
if (handle != -1)
{
do
{
// if it's a sub-dir and not ".." and "." string, then push to stack
if ( fd.attrib & _A_SUBDIR && wcscmp(fd.name, L"..") && wcscmp(fd.name, L"."))
{
fname = curS + L"\\" + fd.name;
pathNameST.push(fname);
} /* else if it's a file (except system files) then */
else if (!(fd.attrib & _A_SYSTEM) && !(fd.attrib & _A_SUBDIR))
{
f.size = fd.size;
fname = curS + L"\\" + fd.name;
_wsplitpath( fname.c_str(), f.drive, f.path, f.name, f.ext );
it = m_supportedFileTypes.find ( std::wstring(f.ext) );
if ( it != m_supportedFileTypes.end())
{
f.type = it->second.type;
m_fileIndices.push_back(f);
// if fileIndex.size is equal to the maximum number of indices, the process should be terminated.
if (m_fileIndices.size() == m_maxIndices)
{
_findclose (handle);
return true;
}
}
}
}
while (_wfindnext(handle, &fd) == 0);
}
else
{
int err;
_get_errno(&err);
switch (err)
{
case EINVAL:
case ENOMEM:
_findclose (handle);
return false;
case ENOENT:
break;
default:
_findclose (handle);
return false;
}
}
_findclose (handle);
}
while (!pathNameST.empty());
return true;
}
bool FileIndexer::getFirstFile(const wchar_t* ext, unsigned int& fileNo, FileDef* fd)
{
if (!ext || !fd) return false;
DynamicFileType::const_iterator it;
bool ret = false;
it = m_supportedFileTypes.find(std::wstring(ext));
if (it == m_supportedFileTypes.end()) return false;
FileType type = it->second.type;
for (unsigned int i = 0; i < (unsigned int) m_fileIndices.size(); i++)
if (m_fileIndices[i].type == type)
{
*fd = m_fileIndices[i];
fileNo = i;
ret = true;
break;
}
return ret;
}
bool FileIndexer::getNextFile(unsigned int& fileNo, FileDef* fd)
{
if (!fd) return false;
bool ret = false;
for (unsigned int i = fileNo + 1; i < (unsigned int) m_fileIndices.size(); i++)
if (m_fileIndices[i].type == m_fileIndices[fileNo].type)
{
*fd = m_fileIndices[i];
fileNo = i;
ret = true;
break;
}
return ret;
}
void FileIndexer::listSupportedFileTypes ()
{
DynamicFileType::const_iterator it;
wprintf(L"%10s%15s\r\n", L"File Type", L"Extension");
for (it = m_supportedFileTypes.begin(); it != m_supportedFileTypes.end(); it++)
{
wprintf(L"%5u%15s\r\n", it->second.type , it->first.c_str());
}
}
void FileIndexer::listFiles(const wchar_t* ext)
{
FileDef fd;
unsigned int fileNo;
if ( getFirstFile(ext, fileNo, &fd) )
{
wprintf(L"%s files:\n", ext);
wprintf(L"%90s%15s\r\n", L"NAME", L"SIZE");
do
{
wprintf(L"%90s%15i\r\n", fd.name, fd.size);
}
while ( getNextFile(fileNo, &fd));
}
}
bool FileIndexer::needsAction(const File_Type_Action& action, const FileDef* fd)
{
if (!fd) return false;
DynamicFileType::const_iterator it = m_supportedFileTypes.find ( std::wstring(fd->ext));
if (it != m_supportedFileTypes.end())
{
return static_cast<bool>(it->second.actionRequired & action);
}
else
return false;
}
void FileIndexer::_testIndexer()
{
bool ret1 = setMaxIndices(3024);
bool ret2 = addSupportedFileType(L".pdf");
listSupportedFileTypes();
bool ret3 = processDirectory(L"D:\\");
bool ret4 = processDirectory(L"C:\\");
//processDirectory("C:\\test directory1" );
//processDirectory("C:\\test directory2" );
listFiles(L".exe");
listFiles(L".txt");
listFiles(L".xml");
listFiles(L".bat");
}
</code></pre>
<p>The code is compiled and tested in Windows. I have already tried to carefully improve it by myself. I know there are still lots of things I could miss. Please help me on this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T13:56:05.413",
"Id": "62777",
"Score": "0",
"body": "You should certainly get rid of `\"stdio.h\"` and `\"stdlib.h\"`"
}
] |
[
{
"body": "<p>Here's a few things you may want to consider:</p>\n\n<ol>\n<li><p>Remove commented out code and statements right away. Particularly the ones that seems to be left in there for educational purposes are just noise.</p></li>\n<li><p>Wrap your class into a namespace, if this is part of a project you should at least have a project scope namespace.</p></li>\n<li><p>Don't use fixed length char arrays for strings, this is C++ so use std::string or another suitable string implementation instead.</p></li>\n<li><p>Make the FileDef type a class with it's own methods instead of manipulating the members directly. It can probably be generalized so it won't need to be a private class under FileIndexer.</p></li>\n</ol>\n\n<p>You may also want to consider breaking the class into separate smaller classes, like DirectoryProcessor, FileIterator etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T05:01:30.670",
"Id": "35622",
"Score": "0",
"body": "For 3, I used void _wsplitpath(\n const wchar_t *path,\n wchar_t *drive,\n wchar_t *dir,\n wchar_t *fname,\n wchar_t *ext \n); which splits the full path name into separate wchar_t * buffers. Can I use std::string in this case? or are there any better way to accompanish this task?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T05:43:04.283",
"Id": "35624",
"Score": "0",
"body": "For 4, I put it inside the FileIndex class, because I try to design it simple and specific for the FileIndexing. I don't know how much efforts need to design a general FileDef that deals with all situations for the various formats. So I keep it simple and put it inside the class to avoid conflicting with other implementations. Thank you. I will improve my code accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T08:05:16.420",
"Id": "35628",
"Score": "0",
"body": "`_wsplitpath` is not a portable function, and looks unsafe too. Wrap it in an independent class or function, which can use std::string. As for #4, the namespace (#2) will avoid conflict with other implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T07:59:59.560",
"Id": "35710",
"Score": "0",
"body": "\"Wrap it in an independent class or function, which can use std::string.\" I think this is a nice way to make it more general. Thanks lot!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T14:16:28.690",
"Id": "23082",
"ParentId": "23079",
"Score": "4"
}
},
{
"body": "<p>Presumable this is supposed to be <code>enum File_Type_Action</code>:</p>\n\n<pre><code>struct FileTypeInfo\n{\n FileType type;\n unsigned actionRequired; // File_Type_Action actionRequired;\n};\n</code></pre>\n\n<p>Prefer std::wstring over character array:</p>\n\n<pre><code>struct FileDef\n{\n wchar_t drive[_MAX_DRIVE];\n wchar_t name[_MAX_FNAME];\n wchar_t path[_MAX_DIR];\n wchar_t ext[_MAX_EXT];\n _fsize_t size;\n unsigned int type;\n};\n</code></pre>\n\n<p>This is not a polymorphic type. So no need to have a virtual destructor:</p>\n\n<pre><code>/* virtual*/ ~FileIndexer ();\n// ^^^^^^^^^ Remove (unless you want people to inhert and extend!\n</code></pre>\n\n<p>By making you destructor virtual you are indicating that this class can be extended. But you have no virtual methods. So I see no point in using vvirutal here (it is also misleading).</p>\n\n<p>Pass by reference rather than pointer:</p>\n\n<pre><code>bool getFirstFile (const wchar_t* ext, unsigned int& fileNo, FileDef* fd);\n// ^^^^ ^^^^^\n</code></pre>\n\n<p>In the case of ext: I would use <code>std::wstring const&</code>.<br>\nUnless <code>fd</code> can be NULL pass by reference. This is an indication that you don't accept NULL values. <code>FileDef& fd</code></p>\n\n<p>You can simplify and make this more readable:</p>\n\n<pre><code>FileTypeInfo tmp;\ntmp.type = 1;\ntmp.actionRequired = FILE_NEED_NOACTION;\nm_supportedFileTypes[std::wstring(L\".txt\")] = tmp;\n\n// In C++03 add a constructor.\nm_supportedFileTypes[std::wstring(L\".txt\")] = FileTypeInfo(1, FILE_NEED_NOACTION);\n\n// In C++11 use the new syntax:\nm_supportedFileTypes[std::wstring(L\".txt\")] = {1, FILE_NEED_NOACTION};\n</code></pre>\n\n<p>The destructor is useless. Remove it:</p>\n\n<pre><code>FileIndexer::~FileIndexer()\n{\n m_maxIndices = 0; // The object is gone after this.\n // Thus this value no longer exists.\n // Thus accessing it would be undefined behavior\n // Thus is does not matter its value.\n}\n</code></pre>\n\n<p>Try not to use multiple lines to do very simple tasks. It makes it harder to read:</p>\n\n<pre><code>std::stack<std::wstring> pathNameST;\nstd::wstring initialPath = name;\npathNameST.push(initialPath);\n\n// Can be done like this:\npathNameST.push(name);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T04:34:06.953",
"Id": "35619",
"Score": "0",
"body": "thank you for your great work. 1. if one file type has multiple actions required to be performed. For example, \".exe\" is required to be scanned and backed up. Then, actionRequired = FILE_NEED_BACKUP | FILE_NEED_SCAN; Is this a right way to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T05:03:36.547",
"Id": "35623",
"Score": "0",
"body": "I used void _wsplitpath( const wchar_t *path, wchar_t *drive, wchar_t *dir, wchar_t *fname, wchar_t *ext ); which splits the full path name into separate wchar_t * buffers. Can I use std::string in this case? or are there any better way to accompanish this task if I want to use std::wstring?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T06:27:35.757",
"Id": "35626",
"Score": "0",
"body": "[boost::filesystem](http://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/index.htm) provides a comprehensive set of file system manipulation tools."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T19:38:39.997",
"Id": "23087",
"ParentId": "23079",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T12:40:05.967",
"Id": "23079",
"Score": "6",
"Tags": [
"c++",
"file-system",
"file"
],
"Title": "Simple C++ File Indexer"
}
|
23079
|
<p>My task was similar to <a href="https://codereview.stackexchange.com/questions/20961/java-multi-thread-file-server-and-client/">my last assignment</a> but this time I had to do it with UDP instead of TCP. This basically means I had to <code>emulate TCP over UDP</code>.</p>
<p>Multithreading was an interesting problem as I had to simulate <a href="http://www.inetdaemon.com/tutorials/internet/tcp/3-way_handshake.shtml" rel="nofollow noreferrer">TCP's 3-way handshake</a>. </p>
<p>I decided to use encapsulation and break up the file I'm transferring into 512 byte size blocks, except for the last block which is more likely going to be smaller. I then create my message object with the correct <code>segmentID</code> and a <code>bytesToWrite</code>. The <code>bytesToWrite</code> is needed to handle the last block, there is a better way to do this. I just got lazy here. I'll fix that when I have time.</p>
<p>Every segment received is acknowledged, after a 2x second timeout if there is no ACK then the segment is resent. In the event an ACK fails to get through the receiver will get a segment ID that is exactly -1 to the expected ID. In this way I know an ACK has failed and I resend it.</p>
<p>This has been tested locally using the built in fail simulator (2% chance a packet fails) and tested in the wild by asking a friend set the server up in London, England and I downloaded a 14.4mb file to my machine in Galway, Ireland. It took a long time and had 35 failed packets, 19 of which were failed ACKs.</p>
<p>Both the <code>Server</code> and <code>Client</code> use the <code>UDPFileReceiver</code> and <code>UDPFileSender</code> classes.</p>
<p><strong><code>Server</code></strong></p>
<pre><code>/*****
* CT326 - Assignment 12 - c.loughnane1@nuigalway.ie - 09101916
*/
package pkg12;
import java.io.*;
import java.net.*;
public class Server
{
private static int clientID = 1;
private static DatagramSocket serverSocket;
public static void main(String[] args) throws IOException
{
System.out.println("Server started.");
byte[] buffer = new byte[512];
/**
* ASSIGNMENT INSTRUCTION The server should be multi-threaded, and
* have one thread per connection.
*/
serverSocket = new DatagramSocket(8550);
while (true)
{
try
{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length );
serverSocket.receive(packet);
System.out.println("SERVER: Accepted connection.");
System.out.println("SERVER: received"+new String(packet.getData(), 0, packet.getLength()));
//new socket created with random port for thread
DatagramSocket threadSocket = new DatagramSocket();
Thread t = new Thread(new CLIENTConnection(threadSocket, packet, clientID++));
t.start();
} catch (Exception e)
{
System.err.println("Error in connection attempt.");
}
}
}
}
</code></pre>
<p><strong><code>CLIENTConnection</code> thread class</strong></p>
<pre><code>/*****
* CT326 - Assignment 12 - c.loughnane1@nuigalway.ie - 09101916
*/
package pkg12;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author c.loughnane1@nuigalway.ie - 09101916
*/
public class CLIENTConnection implements Runnable
{
private int clientID;
private byte[] buffer;
private int bytesToReceive;
private DatagramSocket clientSocket;
private DatagramPacket packet, initPacket;
private String userInput, filename, initString;
public CLIENTConnection(DatagramSocket clientSocket, DatagramPacket packet, int clientID) throws IOException
{
this.clientSocket = clientSocket;
this.packet = packet;
this.clientID = clientID;
}
@Override
public void run()
{
try
{
buffer = new byte[618];
System.out.println("THREAD: " + new String(packet.getData(), 0, packet.getLength()));
initString = new String(packet.getData(), 0, packet.getLength());
StringTokenizer t = new StringTokenizer(initString);
userInput = t.nextToken();
filename = t.nextToken();
if (t.hasMoreTokens())
{
bytesToReceive = new Integer(t.nextToken()).intValue();
}
switch (messageType.valueOf(userInput))
{
case put:
//sends a message gets the new port information to the client
send(packet.getAddress(), packet.getPort(), ("OK").getBytes());
//create Object to handle incoming file
new UDPFileReceiver(clientSocket);
break;
case get:
File theFile = new File(filename);
send(packet.getAddress(), packet.getPort(), ("OK").getBytes());
//create object to handle out going file
UDPFileSender fileHandler = new UDPFileSender(clientSocket, packet);
fileHandler.sendFile(theFile);
break;
default:
System.out.println("Incorrect command received.");
break;
}
} catch (IOException ex)
{
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("*** Transfer for client " + clientID + " complete. ***");
}
private void send(InetAddress recv, int port, byte[] message) throws IOException
{
DatagramPacket packet = new DatagramPacket(message, message.length, recv, port);
clientSocket.send(packet);
}
private void send(byte[] message) throws IOException
{
DatagramPacket packet = new DatagramPacket(message, message.length);
clientSocket.send(packet);
}
public enum messageType
{
get, put;
}
}
</code></pre>
<p><strong><code>Message</code> class</strong></p>
<pre><code>/*****
* CT326 - Assignment 12 - c.loughnane1@nuigalway.ie - 09101916
*/
package pkg12;
import java.io.Serializable;
public class Message implements Serializable {
private int segmentID;
private byte[] packet;
private int bytesToWrite;
public Message(){}
public Message(int segmentID, byte[] packet, int bytesToWrite) {
this.segmentID = segmentID;
this.packet = packet;
this.bytesToWrite = bytesToWrite;
}
public int getBytesToWrite() {
return bytesToWrite;
}
public int getSegmentID() {
return segmentID;
}
public byte[] getPacket() {
return packet;
}
}
</code></pre>
<p><strong><code>Client</code></strong></p>
<pre><code>/*****
* CT326 - Assignment 12 - c.loughnane1@nuigalway.ie - 09101916
*/
package pkg12;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.StringTokenizer;
/**
*
* @author c.loughnane1@nuigalway.ie - 09101916
*/
public class Client
{
private static byte[] buffer;
private static int port = 8550;
private static DatagramSocket socket;
private static BufferedReader stdin;
private static StringTokenizer userInput;
private static DatagramPacket initPacket, packet;
public static void main(String[] args) throws IOException
{
socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
buffer = new byte[618];
stdin = new BufferedReader(new InputStreamReader(System.in));
String selectedAction = selectAction();
userInput = new StringTokenizer(selectedAction);
try
{
switch (messageType.valueOf(userInput.nextToken()))
{
case put:
packet = new DatagramPacket((selectedAction).getBytes(), (selectedAction).getBytes().length, address, port);
socket.send(packet);
File theFile = new File(userInput.nextToken());
initPacket = receivePacket();
//create object to handle out going file
UDPFileSender fileHandler = new UDPFileSender(socket, initPacket);
fileHandler.sendFile(theFile);
break;
case get:
packet = new DatagramPacket((selectedAction).getBytes(), (selectedAction).getBytes().length, address, 8550);
socket.send(packet);
initPacket = receivePacket();
socket.send(initPacket);
//create Object to handle incoming file
new UDPFileReceiver(socket);
break;
}
} catch (Exception e)
{
System.err.println("not valid input");
}
socket.close();
}
private static DatagramPacket receivePacket() throws IOException
{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
return packet;
}
public static String selectAction() throws IOException
{
System.out.println("COMMANDS: get *filename*");
System.out.println("\t put *filename*");
System.out.println("\t example: put data.txt");
System.out.print("ftp> ");
return stdin.readLine();
}
public enum messageType
{
get, put;
}
}
</code></pre>
<p><strong><code>UDPFileSender</code></strong></p>
<pre><code>/*****
* CT326 - Assignment 12 - c.loughnane1@nuigalway.ie - 09101916
*/
package pkg12;
import java.io.*;
import java.net.*;
public class UDPFileSender
{
private int segmentID;
private int reSendCount;
private byte[] msg, buffer;
private FileInputStream fileReader;
private DatagramSocket datagramSocket;
private int fileLength, currentPos, bytesRead;
private final int packetOverhead = 106; // packet overhead
public UDPFileSender(DatagramSocket socket, DatagramPacket initPacket) throws IOException
{
msg = new byte[512];
buffer = new byte[512];
datagramSocket = socket;
//setup DatagramSocket with correct Inetaddress and port of receiver
datagramSocket.connect(initPacket.getAddress(), initPacket.getPort());
segmentID = 0;
}
public void sendFile(File theFile) throws IOException
{
fileReader = new FileInputStream(theFile);
fileLength = fileReader.available();
System.out.println("*** Filename: " + theFile.getName() + " ***");
System.out.println("*** Bytes to send: " + fileLength + " ***");
send((theFile.getName() + "::" + fileLength).getBytes());
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(reply);
//waits for receiver to indicate OK to send
if (new String(reply.getData(), 0, reply.getLength()).equals("OK"))
{
System.out.println("*** Got OK from receiver - sending the file ***");
//outer while to control when send operation comlete
//inner while to control ACK messages from receiver
while (currentPos < fileLength)
{
bytesRead = fileReader.read(msg);
Message message = new Message(segmentID, msg, bytesRead);
System.out.println("Sending segment " + message.getSegmentID() + " with " + bytesRead + " byte payload.");
byte[] test = serialize(message);
send(test, bytesRead + packetOverhead);
currentPos = currentPos + bytesRead;
//handle ACK of sent message object, timeout of 2 seconds. If segementID ACK is not received
//resend segment.
datagramSocket.setSoTimeout(2000);
boolean receiveACK = false;
while (!receiveACK)
{
try
{
datagramSocket.receive(reply);
} catch (SocketTimeoutException e)
{
send(test, bytesRead + packetOverhead);
System.out.println("*** Sending segment " + message.getSegmentID() + " with " + bytesRead + " payload again. ***");
reSendCount++;
}
if (new String(reply.getData(), 0, reply.getLength()).equals(Integer.toString(message.getSegmentID())))
{
System.out.println("Received ACK to segment" + new String(reply.getData(), 0, reply.getLength()));
segmentID++;
receiveACK = true;
}
}
}
System.out.println("*** File transfer complete...");
System.out.println(reSendCount + " segments had to be resent. ***");
} else
{
System.out.println("Recieved something other than OK... exiting");
}
}
private void send(byte[] message, int length) throws IOException
{
DatagramPacket packet = new DatagramPacket(message, length);
datagramSocket.send(packet);
}
private void send(byte[] message) throws IOException
{
DatagramPacket packet = new DatagramPacket(message, message.length);
datagramSocket.send(packet);
}
public byte[] serialize(Object obj) throws IOException
{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
objectStream.writeObject(obj);
objectStream.flush();
return byteStream.toByteArray();
}
}
</code></pre>
<p><strong><code>UDPFileReceiver</code></strong></p>
<pre><code>/*****
* CT326 - Assignment 12 - c.loughnane1@nuigalway.ie - 09101916
*/
package pkg12;
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPFileReceiver
{
private byte[] buffer;
private Message receiveMSG;
private DatagramSocket socket;
private String filename, initString;
private FileOutputStream fileWriter;
private DatagramPacket initPacket, receivedPacket;
private int bytesReceived, bytesToReceive, simulateBadConnection, expectedSegmentID;
private final boolean simulateMessageFail = false;//true if you want to simulate a bad connection
public UDPFileReceiver(DatagramSocket socket) throws IOException
{
this.socket = socket;
buffer = new byte[618]; //618 is the size of my message object. 512 payload, 106 overhead
System.out.println("*** Ready to receive file on port: " + socket.getLocalPort() + " ***");
initPacket = receivePacket();
initString = "Recieved-" + new String(initPacket.getData(), 0, initPacket.getLength());
//get the file name and byte size of file name
StringTokenizer t = new StringTokenizer(initString, "::");
filename = t.nextToken();
bytesToReceive = new Integer(t.nextToken()).intValue();
System.out.println("*** The file will be saved as: " + filename + " ***");
System.out.println("*** Expecting to receive: " + bytesToReceive + " bytes ***");
//tell the sender OK to send data
send(initPacket.getAddress(), initPacket.getPort(), ("OK").getBytes());
fileWriter = new FileOutputStream(filename);
//two while loops. First checks that there is still more data to receive
//and inner do/while is to error check on received packets and catch missing ACK
//sent to sender
while (bytesReceived < bytesToReceive)
{
receiveMSG = new Message();
do
{
receivedPacket = receivePacket();
try
{
receiveMSG = (Message) deserialize(receivedPacket.getData());
} catch (ClassNotFoundException ex)
{
System.out.println("*** Message packet failed. ***");
}
//logically if the last ACK sent fails to be received the UDPSender will resend the last segment.
//A simple check on the segemntID will catch this as it will be equal to expectedID - 1. Resending the ACK
//for this previous segment will eventually get through to the server to send the next expected segment.
if ((expectedSegmentID - 1) == receiveMSG.getSegmentID())
{
String ACK = Integer.toString(receiveMSG.getSegmentID());
send(initPacket.getAddress(), initPacket.getPort(), (ACK).getBytes());
System.out.println("*** Resending ACK for segment " + ACK + " ***");
}
if (simulateMessageFail)
{
simulateBadConnection = (Math.random() < 0.98) ? 0 : 1; //simulate a 2% chance a message object is lost
}
//by adding 1 to segmentIDExpected we can make the receiver determine a message object is lost
//as the server has a 2 second timeout before it will resend we can check the error control in this way.
} while (receiveMSG.getSegmentID() != (expectedSegmentID + simulateBadConnection));
expectedSegmentID++;
//handles the last byte segmentID size .getBytesToWrite()
fileWriter.write(receiveMSG.getPacket(), 0, receiveMSG.getBytesToWrite());
System.out.println("Received segmentID " + receiveMSG.getSegmentID());
//adding payload size for outer while condition
bytesReceived = bytesReceived + 512;
//simulate a 2% chance an ACK is lost
if (simulateMessageFail)
{
if ((Math.random() < 0.98))
{
String ACK = Integer.toString(receiveMSG.getSegmentID());
send(initPacket.getAddress(), initPacket.getPort(), (ACK).getBytes());
} else
{
System.out.println("*** failed to send ACK ***");
}
} else
{
String ACK = Integer.toString(receiveMSG.getSegmentID());
send(initPacket.getAddress(), initPacket.getPort(), (ACK).getBytes());
}
}
System.out.println("*** File transfer complete. ***");
fileWriter.close();
}
private DatagramPacket receivePacket() throws IOException
{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
return packet;
}
private void send(InetAddress recv, int port, byte[] message) throws IOException
{
DatagramPacket packet = new DatagramPacket(message, message.length, recv, port);
socket.send(packet);
}
private Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException
{
ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectStream = new ObjectInputStream(byteStream);
return (Message) objectStream.readObject();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T11:42:26.217",
"Id": "51151",
"Score": "0",
"body": "I tried compiling your code. It works fine for file size less than 512 bytes. For everything else I am getting [this](http://ideone.com/OYcGMq) exception. I am not sure what's wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-11T07:23:56.060",
"Id": "216183",
"Score": "0",
"body": "Use constants for PACKET_OVERHEAD and PREFERRED_TU (transmission unit, in memoriam MTU). Put them in the \"size expression\" instead of commenting it. @VelvetThunder bytesRead + packetOverhead a bit much for buffer, possibly."
}
] |
[
{
"body": "<ul>\n<li><p>You shouldn't do work in the constructor let alone ALL the work. You can move everything except <code>this.socket = socket;</code>\nfrom <code>UDPFileReceiver</code> constructor to a method <code>receive()</code>, like the <code>sendFile</code> method of <code>UDPFileSender</code>.</p></li>\n<li><p>There are unused fields, e.g. <code>buffer</code> from <code>CLIENTConnection</code>. You\nshould heed compiler warnings.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:00:56.467",
"Id": "35649",
"Score": "0",
"body": "Cheers. Point taken on the constructor. When one stares at the same code for so long basics slip past. I'll check on why I missed the missed buffer compiler warning too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T11:59:45.337",
"Id": "35724",
"Score": "0",
"body": "Thanks @abuzittin, I've changed my code as per your recommendations. I appreciate you took the time to check my code and point out the oversights."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:45:23.637",
"Id": "35728",
"Score": "1",
"body": "I turned this answer into community wiki as it was not meant to be a comprehensive review at the time it was accepted. I want to see some review on the network protocol, as may people who find this question through search engines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T19:59:51.743",
"Id": "35765",
"Score": "0",
"body": "I wasn't sure about accepting actually, I just wanted to give credit where it was due. I can remove the accepted answer, let me know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:53:18.267",
"Id": "35793",
"Score": "0",
"body": "You can unaccept it.I was trying to get things rolling and keep the question active."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T11:11:21.727",
"Id": "23108",
"ParentId": "23088",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T20:14:15.757",
"Id": "23088",
"Score": "5",
"Tags": [
"java",
"multithreading",
"homework",
"network-file-transfer"
],
"Title": "Java multithreaded file server and client - emulate TCP over UDP"
}
|
23088
|
<p>I'm writting a mark up for: <br>
<a href="https://i.stack.imgur.com/8Nyli.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Nyli.jpg" width="355" height="400"></a> <br>
And here is my HTML:</p>
<pre><code><div id="container">
<header>
<h1><img src="images/logo.png" alt="Jessica Priston - Photographer"></h1>
<nav id="mainNav">
<ul>
<li><a href="#">home</a></li>
<li><a href="#">blog</a></li>
<li><a href="#">works</a></li>
<li><a href="#">mail</a></li>
</ul>
</nav>
</header>
<div id="categories">
<ul>
<li>
<img src="images/weddings.jpg" alt="weddings">
<h4>Weddings</h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
</li>
<li>
<img src="images/nature.jpg" alt="nature">
<h4>Nature</h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
</li>
<li>
<img src="images/fashion.jpg" alt="fashion">
<h4>Fashion</h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
</li>
<li>
<img src="images/family.jpg" alt="family">
<h4>Family</h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit </p>
</li>
</ul>
<nav>
<button class="prev"></button>
<button class="next"></button>
</nav>
</div> <!-- categories -->
<div id="main">
<header>
<h2>View a collection of fantastic portfolio that reflects</h2>
<h3>my true passion towards what I do</h3>
</header>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit varius mi cum sociis natoque penatibus. et magnis dis parturient montes nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio. Morbi nunc odio gravida at cursus nec luctus a lorem. Maecenas</p>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit varius mi cum sociis natoque penatibus. et magnis dis parturient montes nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio. Morbi nunc odio gravida at cursus nec luctus a lorem. Maecenas</p>
<a href="#" class="read-more">Read more</a>
<ul>
<li><img src="images/seo.jpg" alt="seo"></li>
<li><img src="images/growth.jpg" alt="growth"></li>
<li><img src="images/good-cook.jpg" alt="good cook"></li>
<li><img src="images/prospect.jpg" alt="prospect"></li>
<li><img src="images/puresofr.jpg" alt="pure soft"></li>
</ul>
<nav>
<button class="prev"></button>
<button class="next"></button>
</nav>
</div>
<aside>
<section>
<h3>hi, friends!</h3>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
<img src="images/myphoto.jpg" alt="My photo">
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit </p>
<a href="#" class="read-more">Read more</a>
</section>
<section>
<h3>Services</h3>
<ul>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
<li>Lorem ipsum dolor</li>
<li>Lorem ipsum dolor</li>
<li>Lorem ipsum</li>
<li>Lorem</li>
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
<li>Lorem</li>
</ul>
</section>
<section>
<h3>What a new?</h3>
<article>
<h4><time>Nov 09, 2012</time></h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
</article>
<article>
<h4><time>Nov 12, 2012</time></h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
</article>
<article>
<h4><time>Nov 18, 2012</time></h4>
<p>Praesent vestibulum aenean Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit</p>
</article>
</section>
<section>
<h3>Testimonials</h3>
<blockquote>
<p><strong>Praesent vestibulum aenean</strong>
Nonummy hendrerit mauris. Hasellus porta. Fusce suscipit varius mi cum sociis natoque penatibus et magnis dis parturient montes nascetur.</p>
<footer>
<span class="name">Tom ford</span>
<span class="post">Manager</span>
</footer>
</blockquote>
<blockquote>
<p><strong>Hasellus porta. Fusce suscipit varius mi cum</strong> sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus. Nulla dui. Fusce feugiat malesuada odio.</p>
<footer>
<span class="name">Tom ford</span>
<span class="post">Manager</span>
</footer>
</blockquote>
</section>
</aside>
<footer>
<img src="images/logo.png" alt="small logo">
<small>© 2012 | Privacy Policy</small>
</footer>
</div> <!-- container -->
</code></pre>
<p>Is it semantically correct? Can <code>#categories</code> be presented as 4 <code>figure</code>s or <code>article</code>s. And also Im afraid for <code>nav</code> for my <code>button</code>s and <code>span.name, span.post</code> for author, is there more semantic one? Thank you everyone for help)</p>
|
[] |
[
{
"body": "<h3><code>#categories</code></h3>\n\n<p><code>#categories</code> needs to be a <code>section</code> element (instead of <code>div</code>), otherwise the <code>nav</code> would be in scope of the whole page (but it is only for the categories). Besides that, you shouldn't overjump heading levels.</p>\n\n<p>Each category should get its own sectioning element, too, otherwise the headings will make problems because they are in a <code>ul</code>. Maybe <code>article</code> is suitable here (depends on the actual content), otherwise <code>section</code>.</p>\n\n<p>However, I don't \"understand\" the categories … are they relevant to the main content for that page? If not, probably <code>aside</code> should be used. Or are they navigation? If yes, and if it is not included in the main nav, it should be <code>nav</code>, too, probably.</p>\n\n<h3><code>#main</code></h3>\n\n<p>It should be <code>section</code> instead of <code>div</code>, otherwise the <code>header</code> would be in scope of the whole page.</p>\n\n<p>I'm not sure I understand the content here. Are the icons (in the <code>ul</code>) part of this main content? Or are they secondary information? If so, they should go in <code>aside</code>. Then the \"Read more\" link would be the main navigation for that main content.</p>\n\n<h3><code>#main > header</code></h3>\n\n<p>The <code>header</code> inside of <code>#main</code> should be a <code>hgroup</code> (you could use <code>header</code> in addition, if you like/want it), otherwise the \"subheading\" would be included in the outline.</p>\n\n<pre><code><header> <!-- header could be omitted -->\n <hgroup>\n <h2>View a collection of fantastic portfolio that reflects</h2> <!-- could be h1 -->\n <h3>my true passion towards what I do</h3> <!-- could be h2 if h1 is used before -->\n </hgroup>\n</header>\n</code></pre>\n\n<h3><code>blockquote</code></h3>\n\n<p>The <code>footer</code> shouldn't be inside of <code>blockquote</code>, as it is not part of the quoted content. You could use <code>article</code> here to group it. Also, the name and job title shouldn't be in <code>span</code>, use <code>div</code> instead.</p>\n\n<pre><code><section>\n\n <h3>Testimonials</h3>\n\n <article>\n <blockquote>\n <p>…</p>\n </blockquote>\n <footer>\n <div class=\"name\">Tom ford</div>\n <div class=\"post\">Manager</div>\n </footer>\n </article>\n\n <article>\n …\n </article>\n\n</section>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T11:57:30.470",
"Id": "35636",
"Score": "0",
"body": "Thank you, Unor again) but I didn't understand: \"#categories needs to be a section\" - they don't have a heading, is that okay? \"Besides that, you shouldn't overjump heading levels\" - So for each category I have to use h2? But it will be at the same heading level with the #main. \"The footer shouldn't be inside of blockquote, as it is not part of the quoted content\" - but I've read at http://html5doctor.com/blockquote-q-cite/#change-2012-02-14 - \"... <footer> element, allowing us to add semantically separate information about the quote\" And footer is used for the same thing there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T12:09:47.857",
"Id": "35637",
"Score": "1",
"body": "@SakerONE: Regarding `footer` in `blockquote`: Your link points exactly to the statement that html5doctor.com was wrong about using it that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T12:11:57.763",
"Id": "35638",
"Score": "1",
"body": "@SakerONE: Regarding `section` for `#categories`: They don't *have* to have a heading, but what is important is that they *could* have a natural heading. So in your case it would be perfectly fine to use the heading \"Categories\" (or similar). If you don't want to display it, hide it visually (so that screenreaders still read it) or omit it altogether."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T12:13:53.033",
"Id": "35639",
"Score": "1",
"body": "@SakerOne: Regarding heading levels: Well, yes, that is exactly the point. When you use a `section` (see previous comment), the (implicit) heading of that `section` will be on the same level (while each category will be one level deeper). If the categories don't belong to the main content, they should be on the same level like the main content and the navigation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T12:17:47.660",
"Id": "35640",
"Score": "0",
"body": "\"Your link points exactly to the statement that html5doctor.com was wrong about using it that way\" - oh..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:13:35.417",
"Id": "23104",
"ParentId": "23090",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23104",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T23:02:46.233",
"Id": "23090",
"Score": "3",
"Tags": [
"html",
"html5"
],
"Title": "Semantically correct markup at practice"
}
|
23090
|
<p>I have 2 strings for example:</p>
<p><strong><code>abcabc</code></strong> and <strong><code>bcabca</code></strong></p>
<p>or</p>
<p><strong><code>aaaabb</code></strong> and <strong><code>abaaba</code></strong></p>
<p>I checked that second string is the same or not like first string but shifted.
<code>bcabca</code> = <code>..abca</code> + <code>bc..</code>.</p>
<pre><code>using System;
public class TOPSES
{
static string t1, t2;
static char[] t1c;
static char[] t2c;
static void Main()
{
int t;
t = int.Parse(Console.ReadLine());
while (t > 0)
{
t1 = Console.ReadLine();
t2 = Console.ReadLine();
string result = "no";
t1c = t1.ToCharArray();
t2c = t2.ToCharArray();
result = ChangeString(t1c[0], 0);
Console.WriteLine(result);
t--;
}
}
public static string ChangeString(char letter, int startIndex)
{
int index = t2.IndexOf(letter, startIndex);
if (index == -1)
return "no";
else
{
string newString = t2.Remove(0, index);
newString += t2.Remove(index, t2.Length - index);
if (t1 != newString)
return ChangeString(letter, ++index);
return "yes";
}
}
}
</code></pre>
<p>How can I improve this code to make it faster? Also, it will be nice if someone could explain what makes this 'program' slow.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:22:11.530",
"Id": "35606",
"Score": "2",
"body": "I would return a `bool` `true`/`false` instead of `\"yes\"`/`\"no\"`. You should be able to time the bottleneck yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:36:07.857",
"Id": "35607",
"Score": "0",
"body": "What makes your program slow? The fact that it has quadratic time complexity and that it creates a lot of garbage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:57:36.553",
"Id": "35609",
"Score": "0",
"body": "@svick so any idea how to improve this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T03:17:22.257",
"Id": "35615",
"Score": "3",
"body": "There is a trick to this question http://stackoverflow.com/questions/2553522/interview-question-check-if-one-string-is-a-rotation-of-other-string"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:06:02.200",
"Id": "35650",
"Score": "1",
"body": "@WooCaSh - You forgot the length check. Your code as-is will say that `aa` is a valid cycling of `aabbcc`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:47:02.007",
"Id": "35662",
"Score": "0",
"body": "I suspect a large part of the reason the first set of code is \"slow\" is due to excessive string creation. Because strings are immutable, all the concatenations with += and string.Remove calls create brand new strings. This happens twice for every execution of ChangeString's else branch, which can occur many times in a single iteration. The new code only creates one new string (per iteration) when it concatenates t1 with itself."
}
] |
[
{
"body": "<p>First, as mentioned in the comments, you should return the boolean values <code>true</code>/<code>false</code> instead of the string values <code>\"yes\"</code>/<code>\"no\"</code>. This should be faster, and is cleaner and more correct.</p>\n\n<p>Second, <code>int.Parse()</code> can be dangerous. Before I read the program and figured out how it worked, I entered the first string, only to have it promptly crash because it expected an integer. The solution to this involves two steps:</p>\n\n<ol>\n<li>Inform the user what input is expected</li>\n<li>Don't let invalid inputs crash the system</li>\n</ol>\n\n<p>I would do this:</p>\n\n<pre><code>int t;\ndo\n{\n Console.WriteLine(\"Enter the number of pairs to compare: \");\n} while (!int.TryParse(Console.ReadLine(), out t));\n</code></pre>\n\n<p><code>TryParse()</code> attempts to parse the value and place it in <code>t</code>, and returns a boolean value indicating success of failure.</p>\n\n<p>While I am discussing this section, <code>t</code> is not a very descriptive variable name. A better name would be <code>numPairs</code>, or something that tells what the variable is holding.</p>\n\n<p>Third, you don't need recursion and messy variable handling in the <code>ChangeString()</code> method. In fact, the entire program can be written in a simple loop in a single method:</p>\n\n<pre><code>static bool CompareVals(string a, string b)\n{\n if (a.Length != b.Length)\n {\n return false;\n }\n\n for (int i = 0; i < a.Length; i++)\n {\n a = a.Substring(1) + a[0];\n\n if (a == b)\n {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>This is better because you can pass it two strings from anywhere in your program, instead of having much of the logic in the calling method, and it is faster according to my profiler - it finishes in 6ms with the input <code>\"sdfghjkla\"</code> and <code>\"asdfghjkl\"</code>, compared to 44ms for your solution. It is also more straight-forward as to what it is doing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-11T03:10:30.067",
"Id": "90357",
"ParentId": "23091",
"Score": "2"
}
},
{
"body": "<p>A fastest solution could be something like:</p>\n\n<pre><code>static bool rotCmp(string a, string b) {\n if (a.length != b.length) return false;\n for (int i=0; i < a.length; ++i) {\n for (int j=0; j < b.length && (i+j < a.length ? a[i+j] == b[j] : a[i+j-a.length] == b[j]); ++j);\n if (j == b.length) return true;\n }\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-11T03:54:33.463",
"Id": "90358",
"ParentId": "23091",
"Score": "0"
}
},
{
"body": "<p>This program is organized in a bizarre way.</p>\n\n<ul>\n<li><code>t1</code>, <code>t2</code>, <code>t1c</code>, and <code>t2c</code> are static variables, which essentially make them \"global\" state. This makes your code difficult to follow.</li>\n<li><code>t2c</code> is a write-only variable — assigned but never used.</li>\n<li><code>t1c</code> is only barely used — you're only ever interested in the first character.</li>\n<li>It's not obvious what the purpose of <code>ChangeString()</code> is. What are you changing? At first glance, it appears to transform the input (which consists of a single <code>letter</code> and a <code>startIndex</code>) into a \"yes\"/\"no\" string.</li>\n</ul>\n\n<p>I would expect the program to follow this outline:</p>\n\n<pre><code>using System;\n\npublic class TOPSES\n{\n public static void Main()\n {\n for (int t = int.Parse(Console.ReadLine()); t >= 0; t--)\n {\n string s1 = Console.ReadLine(),\n s2 = Console.ReadLine();\n Console.WriteLine(IsRotation(s1, s2) ? \"yes\" : \"no\");\n }\n }\n\n public static bool IsRotation(string s1, string s2)\n {\n …\n }\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><code>Main()</code> should be <code>public</code>.</li>\n<li>A <code>for</code> loop gathers all the code related to <code>t</code> together, to make it easy to see what it's for.</li>\n<li>Avoid unnecessarily separating declarations and assignments.</li>\n</ul>\n\n<p>The algorithm you use is also too complicated: you're looking for places in <code>t2</code> that start with the initial character of <code>t1</code>, then checking if <code>t2</code>, if sliced and reassembled there, matches <code>t1</code>. But why use <code>string.IndexOf(Char, Int)</code> when you could just do <code>string.IndexOf(string)</code>?</p>\n\n<pre><code>public static bool IsRotation(string s1, string s2)\n{\n return s1.Length == s2.Length &&\n (s2 + s2).IndexOf(s1) >= 0;\n}\n</code></pre>\n\n<p>This involves just one string concatenation, and no slicing and dicing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-11T05:40:01.450",
"Id": "90361",
"ParentId": "23091",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:16:03.450",
"Id": "23091",
"Score": "5",
"Tags": [
"c#",
"strings"
],
"Title": "Slow two-strings comparer"
}
|
23091
|
<p>I'm a newb at C++ and I was wondering whether I used pointers correctly and whether it was appropriate to use them in this context.</p>
<p>Any other tips/information would be appreciated.</p>
<pre><code>#include <iostream>
using namespace std;
int euclideanAlgorithm(int *a, int *b);
int main() {
int x, y, a, b;
cin >> a;
cin >> b;
x = a;
y = b;
cout << x / euclideanAlgorithm(&a, &b) * y << endl;
return 0;
}
int euclideanAlgorithm(int *a, int *b) {
if (*b == 0) {
return *a;
}
while (*a >= *b) {
*a -= *b;
}
euclideanAlgorithm(b, a);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:59:19.480",
"Id": "35610",
"Score": "0",
"body": "Just FYI, this prints out the lowest common multiple of the two integers input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T04:37:54.610",
"Id": "35620",
"Score": "3",
"body": "Don't use `using namespace std;` See http://stackoverflow.com/q/1452721/14065"
}
] |
[
{
"body": "<p>If you come from C and you start using C++, you might be use to have pointers whenever you want a function to be able to update one of its parameter.\nIn C++, if you want to do so, you can use references which gives you a clearer and slightly safer result. Please refer to the <a href=\"http://en.wikipedia.org/wiki/Reference_%28C++%29\" rel=\"nofollow\">wiki page</a> for more details.</p>\n\n<p>However, I'd like to point out that whenever you compute the lowest common multiple of the two integers, you probably don't want to change the value of this integers.</p>\n\n<p>Thus, I'd expect the following code to do what you are trying to achieve (not tested, not even compiled):</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nint euclideanAlgorithm(int a, int b);\n\nint main() {\n int a, b;\n cin >> a;\n cin >> b;\n cout << a / euclideanAlgorithm(a, b) * b << endl;\n return 0;\n}\n\nint euclideanAlgorithm (int a, int b) {\n return (b == 0) ?\n a :\n euclideanAlgorithm(b, a % b);\n}\n</code></pre>\n\n<p>Then, regarding the style : you can avoid forward declaration by changing the order of the functions. Also, it would probably be better to call you function with a shorter but still more explicit name such as <code>gcd</code> (hiding the implementation details : whether you use Euclid's algorithm or Wk_of_Angmar's algorithm shouldn't make any big difference for the one who is using the function).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T01:41:04.103",
"Id": "23096",
"ParentId": "23093",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23096",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T00:53:15.907",
"Id": "23093",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Am I using pointers correctly?"
}
|
23093
|
<p>You can see a working example <a href="http://jsfiddle.net/ShaShads/GuL5K/1/embedded/result/" rel="nofollow">here</a>. Be sure to click on the canvas or the key inputs will not be detected!</p>
<p>Are there any ways I could improve upon this? Anything that should have been done differently? Any best practices I have not implemented?</p>
<pre><code>$(document).ready(function() {
window.addEventListener('keydown', keyPress, true); // event listener for keyboard presses
function keyPress(evt) {
if(engine.activeBlock) { // block is actively falling
switch(evt.keyCode) {
case 37: // left arrow
engine.activeBlock.keyLeft();
break;
case 39: // right arrow
engine.activeBlock.keyRight();
break;
case 40: // down arrow
engine.activeBlock.keyDown();
break;
}
}
}
// block object
function block() {
this.xStart = function() { // random x coordinate of starting position of block
var x = Math.floor(Math.random() * (engine.cellsX - 1 + 1)) + 1; // random number between 1 and cellsX
return (x - 1) * engine.cellSize;
};
this.x = this.xStart(); // x coordinate
this.y = 0 - (engine.cellSize * 1.5); // y coordinate
this.velocity = 1; // velocity of the block
this.generateColor = function() { // generates a random color
var colors = ['blue', 'red', 'green', 'black', 'orange']; // colors array
return colors[Math.floor(Math.random() * colors.length)];
};
this.color = this.generateColor(); // color of the block
this.keyLeft = function() { // key left
if(!engine.collisionLeft()) { // check collisions left side
this.x -= engine.cellSize;
}
};
this.keyRight = function() { // key right
if(!engine.collisionRight()) { // check collisions right side
this.x += engine.cellSize;
}
};
this.keyDown = function() { // key down
if(this.y > 0) { // block is on screen
this.velocity += 1; // increase block velocity
}
};
this.update = function() { // updates the blocks position
this.y += this.velocity; // increase velocity
engine.collisionBelow(); // check collisions below
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
};
}
// engine object
function engine() {
this.cellSize = 100; // size of each cell
this.cellsX = canvas.width / this.cellSize; // number of cells along the x axis
this.cellsY = canvas.height / this.cellSize; // number of cells along the y axis
this.totalCells = this.cellsX * this.cellsY; // total cells
this.buildGrid = function() { // builds grid
var arr = new Array(this.cellsX);
for(var i = 0; i < arr.length; ++i) {
arr[i] = new Array(this.cellsY);
}
return arr;
};
this.grid = this.buildGrid(); // holds grid
this.activeBlock = false; // where a falling block is placed
this.getGridCoords = function(i) { // x coordinate of where a block should be placed in grid
return Math.floor(i / this.cellSize);
};
this.drawGrid = function() { // outputs the blocks stored in grid
for(var i = 0; i < this.grid.length; ++i) {
for(var i2 = 0; i2 < this.grid[i].length; ++i2) {
if(this.grid[i][i2]) { // grid cell is occupied
ctx.fillStyle = this.grid[i][i2].color;
ctx.fillRect(this.grid[i][i2].x, this.grid[i][i2].y, this.cellSize, this.cellSize);
}
}
}
};
this.collisionBelow = function() { // check collisions below
if(this.activeBlock.y > (canvas.height - this.cellSize)) {
this.insertBlock(); // insert block into grid
} else if(this.grid[this.getGridCoords(this.activeBlock.x)][this.getGridCoords(this.activeBlock.y) + 1]) {
this.insertBlock(); // insert block into grid
}
};
this.collisionLeft = function() { // check collisions left
if(this.activeBlock.x <= 0) {
return true;
} else if(this.grid[this.getGridCoords(this.activeBlock.x) - 1][this.getGridCoords(this.activeBlock.y)]) {
return true;
} else if(this.grid[this.getGridCoords(this.activeBlock.x) - 1][this.getGridCoords(this.activeBlock.y) - 1]) {
return true;
} else if(this.grid[this.getGridCoords(this.activeBlock.x) - 1][this.getGridCoords(this.activeBlock.y) + 1]) {
return true;
}
};
this.collisionRight = function() { // check collisions right
if(this.activeBlock.x >= (canvas.width - this.cellSize)) {
return true;
} else if(this.grid[this.getGridCoords(this.activeBlock.x) + 1][this.getGridCoords(this.activeBlock.y)]) {
return true;
} else if(this.grid[this.getGridCoords(this.activeBlock.x) + 1][this.getGridCoords(this.activeBlock.y) - 1]) {
return true;
} else if(this.grid[this.getGridCoords(this.activeBlock.x) + 1][this.getGridCoords(this.activeBlock.y) + 1]) {
return true;
}
};
this.insertBlock = function() { // insert block into grid
this.activeBlock.x = this.cellSize * Math.floor(this.activeBlock.x / this.cellSize); // floor x coordinate to cellSize multiple
this.activeBlock.y = this.cellSize * Math.floor(this.activeBlock.y / this.cellSize); // floor y coordinate to cellSize multiple
this.grid[this.getGridCoords(this.activeBlock.x)][this.getGridCoords(this.activeBlock.y)] = this.activeBlock;
this.activeBlock = new block();
};
}
var canvas = $('canvas')[0]; // holds the canvas
var ctx = canvas.getContext('2d'); // holds the canvas context
var engine = new engine(); // initiate the engine
engine.activeBlock = new block(); // add block
function loop() { // game loop
ctx.fillStyle = '#eee';
ctx.fillRect(0, 0, canvas.width, canvas.height);
engine.activeBlock.update(); // update active block
engine.drawGrid(); // draw the grid of blocks
}
// run loop
setInterval(loop, 20);
});
</code></pre>
|
[] |
[
{
"body": "<p>Haven't looked at the code in detail, but here are some thoughts on the overall structure:</p>\n\n<p>Right now, there's some mixing of concerns and tight coupling going on. The engine calls update on the active block, but the block then calls back to the engine to check for collisions. In other words, the two are tightly coupled; they're dependent on each other, and its unclear where certain responsibilities lie.</p>\n\n<p>The block is a pretty simple object, which can be reduced to simply being an x, y position, and a velocity. And it should probably stop there. The engine would be responsible for moving the block (the block object can do the calculations, though), checking collisions, accepting keyboard input, etc.. I.e. keep the block \"dumb\"; it doesn't need to know its context.</p>\n\n<p>I'd also suggest making a similarly \"dumb\" grid object that the engine object can interrogate and instruct. I.e. the grid doesn't move blocks around, it simply keeps track of them for the engine. The grid could check for collisions, but it'd be up to the engine to ask.</p>\n\n<p>Where exactly to draw the boundaries between the objects and their responsibilities is up to you (there are many ways to break it down), but the idea is to keep things decoupled when possible. I.e. blocks don't rely on a grid or an engine being there; the grid may or may not care about blocks being blocks, just that there's <em>something</em> in a given cell, etc.. Perhaps there are more things, you can extract and/or abstract and encapsulate in objects or constructors, while the engine sits in the middle acting as controller. </p>\n\n<p>On a purely syntactical level, I'd move the methods of into the prototypes for the objects. That is, from this</p>\n\n<pre><code>function block() {\n // instance variables ...\n this.update = function () { ... }\n}\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>function Block() { // CamelCase since it's a constructor\n // instance variables ...\n}\n\nBlock.prototype.update = function () {\n ...\n};\n</code></pre>\n\n<p>This will make it easier to do prototypal inheritance, as the methods will actually be prototypal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:55:54.473",
"Id": "35632",
"Score": "0",
"body": "Thank you this has helped! This is my first ever game so I just tried to throw something together. I will try and improve on it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:20:11.693",
"Id": "23105",
"ParentId": "23095",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T01:33:05.460",
"Id": "23095",
"Score": "3",
"Tags": [
"javascript",
"collision",
"canvas"
],
"Title": "Canvas spatial grid collision"
}
|
23095
|
<p>I'm using Struts2 and Google App Engine. Below is my program for getting the country based on the IP of the visitor of the website.</p>
<p>In my Struts2 action:</p>
<pre><code>HttpServletRequest request = ServletActionContext.getRequest();
String IP = request.getRemoteAddr();
String countryCode = Utilities.fetchUrl( "http://api.hostip.info/country.php?ip=" + IP );
if ( countryCode != null){
String country = CountryUtil.COUNTRY_MAP.get( countryCode );
System.out.println("COUNTRY: " + country);
}
</code></pre>
<p>My <code>fetchUrl</code> static function:</p>
<pre><code>public static String fetchUrl(String strUrl){
String output = "";
String line = null;
try {
URL url = new URL( strUrl );
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = reader.readLine()) != null) {
output += line;
}
reader.close();
} catch (MalformedURLException e) {
System.out.println("ERROR CATCHED: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("ERROR CATCHED: " + e.getMessage());
return null;
}
return output;
}
</code></pre>
<p>My COUNTRY_MAP:</p>
<pre><code>public static final Map<String, String> COUNTRY_MAP;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("AF", "afghanistan");
map.put("AL", "albania");
...
map.put("ZW", "zimbabwe");
COUNTRY_MAP = Collections.unmodifiableMap( map );
}
</code></pre>
<p>Any suggestion on improving its speed? I also need suggestions for the coding.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T07:34:25.687",
"Id": "35627",
"Score": "1",
"body": "Have a look in http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumMap.html , and at Item 33 of Joshua Bloch's Extreme Java book"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T10:57:19.350",
"Id": "35633",
"Score": "3",
"body": "Not related to speed: `reader.close();` should be in a `finally`-block."
}
] |
[
{
"body": "<p>The slowest part will be the request to the remote server. There is not much you can do to make this faster. You may want to cache the results you get back from hostip, or you may want to have a local database.</p>\n\n<p>Furthermore, the API seems to return <code>XX</code> if it does not know the country, you may want to check for that.</p>\n\n<p>Also, you do not close the <code>InputStream</code> or the <code>InputStreamReader</code>, and it is possible that you do not close the <code>BufferedReader</code> when an exception occurs. I don't know exactly whether this will cause any problems.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T10:46:07.150",
"Id": "23107",
"ParentId": "23102",
"Score": "7"
}
},
{
"body": "<p>I would agree to the comment Answer from @Sjoerd. The slowest part is the http request. You could save some very little time to access this in other ways, but most probably, the packet transfer times are much higher than everything else.</p>\n\n<p>Beside this, you should clean up your utility method and make it more robust.<br>\nI would suggest to create a separate class, the constructor takes the ip as an argument. The class has a read or updateData method and has getters like <code>getCountryName()</code>, <code>getCountryCode()</code>, <code>getIp()</code> and so one.<br>\nThen you could use one of this the json or the xml: \n<a href=\"http://api.hostip.info/get_json.php\" rel=\"nofollow\">http://api.hostip.info/get_json.php</a><br>\n<a href=\"http://api.hostip.info/?ip=\" rel=\"nofollow\">http://api.hostip.info/?ip=</a><br>\nSee <a href=\"http://www.hostip.info/use.html\" rel=\"nofollow\">http://www.hostip.info/use.html</a></p>\n\n<p>And you have all information directly from the result. You should not create the map by youself, because you will easily forget something (my result was EU, you got this inside the map?) and you will never update it again.</p>\n\n<p>Next step would be to handle your exceptions in a proper way. You should have finaly blocks as already suggested and you should handle errors. If you have your own update method, it could return a boolean indicating the success. And so one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T10:54:51.907",
"Id": "506902",
"Score": "0",
"body": "{\"country_name\":\"(Unknown Country?)\",\"country_code\":\"XX\",\"city\":\"(Unknown City?)\",\"ip\":\"...\"}"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:17:54.140",
"Id": "23228",
"ParentId": "23102",
"Score": "1"
}
},
{
"body": "<p>The question is old, and has already valuable answers.</p>\n\n<p>By the way, two main adjustments can be done to drastically reduce the loading times:</p>\n\n<ol>\n<li><h3>Use a faster webservice:</h3>\n\n<ul>\n<li><p>Your service costs <strong>~ 300 ms</strong>:</p>\n\n<blockquote>\n <p>\"<a href=\"http://api.hostip.info/country.php?ip=\" rel=\"nofollow\">http://api.hostip.info/country.php?ip=</a>\" + IP</p>\n</blockquote></li>\n<li><p>This service costs <strong>~ 50 ms</strong>: </p>\n\n<blockquote>\n <p>\"<a href=\"http://api.wipmania.com/\" rel=\"nofollow\">http://api.wipmania.com/</a>\" + IP</p>\n</blockquote></li>\n</ul>\n\n<p>The timings are taken from Italy, but I guess the second webservice is faster no matter from where it's called. <br>It's a 600% performance improvement, so it's worthy of a try.\n<br>It can also be used with JSONP to get other useful data, eg. geolocalization, <a href=\"http://jsfiddle.net/AndreaLigios/cnfjrLd8/\" rel=\"nofollow\">as shown in this demo</a>.</p></li>\n<li><h3>Cache the data</h3>\n\n<p>Your server should call this webservice <strong>only once</strong> per-user. Then you can store the result (and retrieve it later instead of performing a new call), mainly in:</p>\n\n<ul>\n<li>user's Session: it will automatically expire and is already isolated;</li>\n<li>a centralized \"timed\" Map, manually handling the expiration of the values (eg. once a day, or once a hour, depending on how many users you have and how many RAM your server has).</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<p>With the two small changes described avoce, the loading time per-user would change from: </p>\n\n<blockquote>\n <p>~ 300 ms<br>\n ~ 300 ms<br>\n ~ 300 ms<br>\n ~ 300 ms<br>\n .......</p>\n</blockquote>\n\n<p>to:</p>\n\n<blockquote>\n <p>~ 50 ms<br>\n ~ 0 ms<br>\n ~ 0 ms<br>\n ~ 0 ms<br>\n .......</p>\n</blockquote>\n\n<p>, that sounds better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T14:20:46.030",
"Id": "82743",
"ParentId": "23102",
"Score": "1"
}
},
{
"body": "<p>The <a href=\"http://ipinfo.io\" rel=\"nofollow\">http://ipinfo.io</a> API should be significantly faster than hostip.info, and also more reliable. It has servers around the world and uses latency based DNS to route you to the closest/quickest one. By default it will return a lot of information about an IP:</p>\n\n<pre><code>$ curl http://ipinfo.io/8.8.8.8\n{\n \"ip\": \"8.8.8.8\",\n \"hostname\": \"google-public-dns-a.google.com\",\n \"city\": \"Mountain View\",\n \"region\": \"California\",\n \"country\": \"US\",\n \"loc\": \"37.3860,-122.0838\",\n \"org\": \"AS15169 Google Inc.\",\n \"postal\": \"94040\"\n}\n</code></pre>\n\n<p>But you can also get just the country code by adding <code>/country</code> to the URL</p>\n\n<pre><code>$ curl http://ipinfo.io/8.8.8.8/country\nUS\n</code></pre>\n\n<p>Depending on what you're doing with the country information you might be able to shift the query from the backend (your struts2 app) to the fontend (client side javascript), so that everything other than the country specific content can load immediately for the user, which would make the country lookup time less important.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T10:52:49.113",
"Id": "506901",
"Score": "0",
"body": "It's 2 months free."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-21T04:22:52.203",
"Id": "114607",
"ParentId": "23102",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23107",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T07:01:03.527",
"Id": "23102",
"Score": "6",
"Tags": [
"java",
"google-app-engine",
"url",
"struts2"
],
"Title": "Getting country based on IP"
}
|
23102
|
<p>I programmed a little log engine in C I plan to use in my project and maybe some others in future. I am very novice C programmer and would like to have feedback of some experienced ones on this. It's spawned over few files but I've joined them so it's easier to compile. Thank you.</p>
<pre><code>#include <stdarg.h>
#include <syslog.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "config.h"
/* this is log.h */
#define TPL_IDENT PACKAGE_NAME
enum tp_log_level {
TPL_DEBUG,
TPL_INFO,
TPL_ERR,
TPL_EMERG,
};
enum tp_log_mode {
TPLM_SYSLOG,
TPLM_FILE,
};
void tp_log_init(int mode, int level, int fd);
void tp_log_write(int level, const char *fmt, ...);
void tp_log_close(void);
/* end of log.h */
/* function from pio.c I use */
ssize_t tp_write(int fd, const void *buf, size_t len)
{
ssize_t ret, wlen = 0;
const char *ptr;
ptr = buf;
while (wlen != len) {
ret = write(fd, ptr, len-wlen);
if (ret == -1)
if (errno == EINTR)
continue;
else
return -1;
wlen += ret;
ptr += ret;
}
return wlen;
}
/* start of log.c */
static int log_fd = -1;
static int log_level;
static int log_mode;
static const char *level_txt[] = {
"DEBUG", "INFO", "ERROR", "EMERG"
};
static const int level_syslog[] = {
LOG_DEBUG, LOG_INFO, LOG_ERR, LOG_EMERG
};
void tp_log_init(int mode, int level, int fd)
{
assert(mode == TPLM_SYSLOG || mode == TPLM_FILE);
assert(mode == TPLM_FILE ? fd >= 0 : 1);
assert(level >= TPL_DEBUG && level <= TPL_EMERG);
switch (mode) {
case TPLM_FILE:
log_fd = fd;
break;
case TPLM_SYSLOG:
openlog(TPL_IDENT, LOG_PID|LOG_CONS, LOG_DAEMON);
break;
}
log_level = level;
log_mode = mode;
}
#define MAX_TIME_LEN 512
#define MAX_PREFIX_LEN 10
#define MAX_MSG_LEN 1024
#define MAX_POSTFIX_LEN 2
static void tp_vlog_write(int level, const char *fmt, va_list alist)
{
int ret, len;
time_t t;
struct tm *tm;
char msg[MAX_TIME_LEN+MAX_PREFIX_LEN+MAX_MSG_LEN+MAX_POSTFIX_LEN];
assert(log_fd);
assert(fmt);
assert(level >= TPL_DEBUG && level <= TPL_EMERG);
if (level < log_level)
return;
switch (log_mode) {
case TPLM_FILE:
t = time(NULL);
tm = localtime(&t);
if (tm == NULL)
abort();
len = strftime(msg, MAX_TIME_LEN, "%a, %d %b %Y %T %z", tm);
len += snprintf(msg+len, MAX_PREFIX_LEN, " [%s] ",
level_txt[level]);
ret = vsnprintf(msg+len, MAX_MSG_LEN, fmt, alist);
if (ret >= MAX_MSG_LEN)
len += MAX_MSG_LEN-1;
else
len += ret;
snprintf(msg+len, MAX_POSTFIX_LEN, "\n");
tp_write(log_fd, msg, len+1);
break;
case TPLM_SYSLOG:
#ifdef HAVE_VSYSLOG
vsyslog(level_syslog[level], fmt, alist);
#else
vsnprintf(msg, MAX_MSG_LEN, fmt, vl);
syslog(level_syslog[level], "%s", msg);
#endif
break;
}
}
void tp_log_write(int level, const char *fmt, ...)
{
va_list vl;
va_start(vl, fmt);
tp_vlog_write(level, fmt, vl);
va_end(vl);
}
void tp_log_close(void)
{
assert(log_fd);
switch (log_mode) {
case TPLM_SYSLOG:
closelog();
break;
case TPLM_FILE:
close(log_fd);
break;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall, the program is fairly well-written and clear. One particular good thing is that you have grasped the concept of private encapsulation in C, by placing the static keyword in all the right places. You also use const correctness for your function parameters. All of that is excellent program design, so keep using it! Below are my comments regarding various issues in the code:</p>\n\n<p><strong>Bugs found:</strong></p>\n\n<ul>\n<li>Always use <a href=\"http://en.wikipedia.org/wiki/Include_guard\" rel=\"nofollow\">header guards</a> or you will get all kind of strange linker or compiler problems.</li>\n</ul>\n\n<p><strong>Coding style, major issues:</strong></p>\n\n<ul>\n<li>You should add comments to each function declaration in the header file, explaining what the function does and what's the nature of the parameters.</li>\n<li>Never declare multiple variables on the same line, there is never a reason to do so and it can lead to subtle bugs such as <code>int* x, y;</code>, x is a pointer, y is not. Instead, declare every variable on a line of its own.</li>\n<li><p>Avoid multiple <code>return</code> statements inside functions, and also avoid <code>continue</code>. There are a few odd cases where they make sense, but most often they just indicate muddy program design or spaghetti code. Consider rewriting the whole function as:</p>\n\n<pre><code>ssize_t tp_write(int fd, const void *buf, size_t len)\n{\n ssize_t ret;\n ssize_t wlen = 0;\n const char *ptr;\n\n ptr = buf;\n for(wlen=0; wlen < len; wlen+=ret)\n {\n ret = write(fd, ptr, len-wlen);\n\n if (ret == -1 && errno != EINTR)\n {\n wlen = -1;\n }\n\n ptr += ret;\n }\n\n return wlen;\n}\n</code></pre></li>\n</ul>\n\n<p><strong>Coding style, minor issues:</strong></p>\n\n<ul>\n<li>I would separate standard C header #includes from non-standard ones, with a blank line, just as you have already separated library headers and user headers.</li>\n<li>Treat enums as unique variable types, not as integers. With a typedef you can achieve something that is essentially an unique type.</li>\n<li><p>Use for loops whenever doing trivial iterations. <code>tp_write</code> you could have been made more redable if you had written: </p>\n\n<p><code>for(wlen=0; wlen<len; wlen+=ret)</code></p></li>\n<li><p>Consider using a special coding style to indicate constants. It is very common to declare constant variables using only upper case letters, ie LEVEL_TXT rather than level_txt.</p></li>\n<li><p>Keep all #defines at the top of the file, or at least high up. Programmers expect to find everything pre-processor related in the beginning of the file.</p></li>\n<li><p>Never use if, for etc statements without following {}. This is a certain way to create subtle bugs. (Not all programmers may agree on this, but at least the MISRA-C coding standard does so).</p></li>\n</ul>\n\n<p><strong>Program design:</strong></p>\n\n<ul>\n<li>Avoid va_lists like the plague! Not only are they error prone with no type safety, not only are they hard to read, but there is never an actual reason to use them in C. It is a completely superfluous feature of the language. Back in the days when dinosaurs walked the earth, different programming languages competed over who had the most features (of questionable value). This is such a remain from those dinosaurs. I've programmed C for almost two decades without ever needing va_lists in any program, and then I've programmed everything from the most low-level real time systems to PC desktop fluff, and everything in between.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:27:41.423",
"Id": "35652",
"Score": "0",
"body": "Thank you for you comments. Just to note I use headers guards all the time just didn't included them since I was pasting everything as one file. Also can you please be more specific on va_lists? Why are they that bad? I see them all the time in opensource code. And how do I make generic function like tp_log_write without them? I see no other way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:36:50.550",
"Id": "35653",
"Score": "0",
"body": "Also, It seems to me that your rewrite of tp_write has a bug in case write returns -1 and errno is EINTR, it will substract -1 from ptr. And how will wlen = -1 stop the loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T00:41:14.720",
"Id": "35684",
"Score": "0",
"body": "`ALL_CAPS_IDENTIFIERS` are generally reserved for macros - I'm not a big fan of using them for non-macro constants. I'd suggest a leading `k_` in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T09:32:26.723",
"Id": "35714",
"Score": "0",
"body": "I don't agre with all your issues here, particularly about comments and allways brace after if/for etc. The warning against va_list is sound though, but refuting their usefullness is a bit harsh imo. Still lot's of good advice here! +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T10:38:03.200",
"Id": "35719",
"Score": "0",
"body": "@user2079392 The main issue is that there is no type safety in them whatsoever. You can happily show in ints into the va_list to a function expecting chars. The printf family of functions all have this weakness too, consider how many billions of bugs those have caused over the years."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T10:41:44.153",
"Id": "35720",
"Score": "0",
"body": "@user2079392 I haven't tested this or anything. The important thing I wanted to show is that there is no need for spaghetti. You are correct, there is a bug, you would need to `break` the loop from inside that if-statement. One single break inside a loop is usually considered as acceptable (reference MISRA-C:2004)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T10:44:05.137",
"Id": "35721",
"Score": "0",
"body": "@Yuushi If the program is written by an excellent programmer, there are no macros except for #defined pre-processor constants. Whether a constant is declared with #define or const isn't important. If your naming rules with constants collide with function-like macros, then the true problem is that you are using function-like macros in the first place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T10:47:13.780",
"Id": "35722",
"Score": "0",
"body": "I agree in general, but it's less for collision and more for uniformity. I guess I'm conditioned that whenever I see ALL_CAPS in C (or C++) I immediately assume \"Macro\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T11:01:48.747",
"Id": "35723",
"Score": "0",
"body": "@harald Regarding coding style, there will never be a consensus among programmers until a standard dictates what should be used. However, fuzzy, individual opinions by me and you have little value. MISRA-C lists the lack of braces as a safety concern. It is _not_ a style guide, it only concerns itself with program safety and is based on actual scientific research, where computer scientists have done population studies on what kind of bugs that cause critical errors in software. No braces is one such bug, therefore it is listed as a safety concern by MISRA-C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T14:30:33.050",
"Id": "35727",
"Score": "0",
"body": "@Lundin, I agree there will not be a consensus, and I dont't think it should be a goal either. I know about the MISRA-C recommendation, and understand the rationale for it. And while it's not bad advice to follow, I think the problem is something else than missing braces. But that's for another discussion in a more suitable forum :)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:05:23.867",
"Id": "23114",
"ParentId": "23110",
"Score": "1"
}
},
{
"body": "<p>I think you are in danger of reinventing the wheel. Syslog does what you need, including allowing you to filter the messages that actually get logged (see <code>setlogmask</code>). According to my man-page, it even has a <code>logopt</code> parameter in the <code>openlog</code> call that allows you to specify <code>LOG_PERROR</code>, telling Syslog to duplicate messages to <code>stderr</code> (which you can of course redirect to a file). Is there a reason why you might need messages <strong>not</strong> to go to the system logs?</p>\n\n<p>If that really wont do, then I'd look at writing a drop-in replacement for <code>syslog</code> and having your initialisation function setup a function pointer with the same prototype as <code>syslog(3)</code>. For example:</p>\n\n<pre><code>void (*tp_syslog)(int priority, const char *message, ...);\nvoid (*tp_closelog)(void);\n\nstatic FILE *log_file;\nstatic int log_maskpri;\n\nstatic void log_close(void)\n{\n if (log_file != NULL) {\n fclose(log_file);\n log_file = NULL;\n }\n}\n\nstatic size_t logdate(char *msg, size_t len)\n{\n time_t t = time(NULL);\n struct tm *tm = localtime(&t);\n return tm ? strftime(msg, len, \"%a, %d %b %Y %T %z\", tm) : 0;\n}\n\nstatic void log_write(int priority, const char *message, ...)\n{\n if (LOG_MASK(priority) & log_maskpri) {\n char date[100];\n size_t len = logdate(date, sizeof date);\n fwrite(date, len, 1, log_file);\n //fwrite(get_prio(priority), 10, 1, log_file);\n\n va_list va;\n va_start(va, message);\n vfprintf(log_file, message, va);\n va_end(va);\n }\n}\n\nvoid tp_log_init(const char *path, int mask)\n{\n if (path) {\n if ((log_file = fopen(path, \"a\")) != NULL) {\n tp_syslog = log_write;\n tp_closelog = log_close;\n log_maskpri = mask;\n return;\n }\n perror(path);\n }\n /* setup syslog if a log file was not specified or could not be opened */\n tp_syslog = syslog;\n tp_closelog = closelog;\n openlog(\"myident\", LOG_PID|LOG_CONS, LOG_DAEMON);\n setlogmask(mask);\n}\n</code></pre>\n\n<p>Note that I used <code>stdio</code> instead of raw file writes - why not? I also cheated in not printing the priority (level) name - is it useful? I also didn't redefine syslog's constants (log priorities, etc).</p>\n\n<p>You can call the log functions as normal:</p>\n\n<pre><code>tp_log_init(\"/path/to/logfile\", LOG_UPTO(LOG_ERR));\n\ntp_syslog(LOG_EMERG, \"hello %d\", 100);\ntp_closelog();\n</code></pre>\n\n<p>I'll write some comments on your code as it stands tomorrow (in a separate answer).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T03:23:39.387",
"Id": "23143",
"ParentId": "23110",
"Score": "0"
}
},
{
"body": "<p>The only thing that really sticks out to me is where you use the return value of <code>snprintf</code> etc without checking that it's valid in <code>tp_vlog_write()</code>. If <code>snprintf</code> returns a negative value you risk that the logging library introduces weird bugs in the host application. You don't want that!</p>\n\n<p>Otherwise there's not much to pick on in this code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T09:22:23.040",
"Id": "23155",
"ParentId": "23110",
"Score": "0"
}
},
{
"body": "<p>As promised, here are some comments on the actual code you posted.</p>\n\n<p>General:</p>\n\n<ul>\n<li><p>don't define multiple variables on the same line.</p></li>\n<li><p>is there a good reason to redefine log levels in <code>tp_log_level</code> rather than\nuse the levels Syslog defines?</p></li>\n<li><p>you have two arrays, <code>level_txt</code> and <code>level_syslog</code> that are dependent upon\nthe values of <code>tp_log_level</code> but nothing ties these together. In such a\nsmall program, this is unlikely to be a problem, but this sort of loose\ndependency tends to break with time - someone appends (or even inserts!) a\nvalue to one part without adjusting the other. Do you really need to log\nthe level text, \"DEBUG\" etc? Syslog doesn't. Why complicate the job? If\nyou just use syslog constants, both these arrays could be discarded. If you\nreally must use them, make a structure holding a level and a text and make\nan array of these; then at least you only have one dangling dependency...</p></li>\n<li><p>I personally don't have any dogmatic objection to multiple returns. Some\ncoding standards object to them on the grounds that they make functions\nunclear. I would argue the contrary: they can, if used well, make functions\nclearer.</p></li>\n</ul>\n\n<hr>\n\n<p>In <code>tp_write</code></p>\n\n<ul>\n<li><p>why using raw write (as opposed to stdio)? The fact that you test for\ninterrupted writes makes me think that you intend to log to a socket or a\nserial port etc... Is that so?</p></li>\n<li><p>you should get compiler warnings about comparisons and conversions between\nsize_t and ssize_t. Since the function only has two return values, -1 and\n<code>len</code>, and the caller knows the value of <code>len</code> anyway, it seems unnecessary\nto return anything but an int: 0 for success, and -1 for failure. That way\nyou can avoid using a ssize_t and the warnings it generates.</p></li>\n<li><p>you need braces in the if/else statements: the compiler has to <strong>assume</strong>\nthat the <code>else</code> belongs to the inner <code>if</code>. Using braces even when not\nstrictly necessary is generally considered good practice. But they can be\nugly...</p></li>\n<li><p>might be better coded as:</p>\n\n<pre><code>ssize_t tp_write(int fd, const void *buf, size_t len)\n{\n const char *p = buf;\n const char *end = p + len;\n\n while (p < end) {\n ssize_t ret = write(fd, p, (size_t) (end - p));\n if (ret > 0) {\n p += ret;\n }\n else if (errno != EINTR) {\n return -1;\n }\n }\n return 0;\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>In <code>tp_log_init</code></p>\n\n<ul>\n<li><p><code>mode</code> would be more logically of type <code>tp_log_mode</code></p></li>\n<li><p>I don't use asserts much. You are relying on the asserts to find problems\nthat the subsequent code does not handle (eg. the switch has no\n<code>default</code>).\nBut another approach is to allow the code to fail if the parameters are\nwrong by falling back on syslog. This works even when NDEBUG is defined\n(asserts disabled):</p>\n\n<pre><code>void tp_log_init(enum tp_log_mode mode, enum tp_log_level level, int fd)\n{\n log_level = level;\n if (mode == TPLM_FILE) {\n if (fd >= 0) {\n log_fd = fd;\n log_mode = TPLM_FILE;\n return;\n }\n /* print an error or abort() if you like */\n }\n openlog(TPL_IDENT, LOG_PID|LOG_CONS, LOG_DAEMON);\n log_mode = TPLM_SYSLOG;\n}\n</code></pre></li>\n</ul>\n\n<p><hr> In <code>tp_vlog_write</code></p>\n\n<ul>\n<li><p>MAX_TIME_LEN and MAX_MSG_LEN seem generous for a log message. Remember that\n<code>msg</code> is on the stack and if you are in a restricted environment, 1500 bytes\nmight be too much. <code>ctime</code> uses 26 bytes for the time/date, so I doubt your time\nformat needs 512.</p></li>\n<li><p><code>level</code> seems like it should be a <code>enum tp_log_level</code></p></li>\n<li><p>the switch could be done with if/else</p></li>\n<li><p>I would extract the creation of a time string into a separate function.\nAlso, why abort if <code>localtime</code> fails? This makes your code more fragile\nthan it needs to be - just don't call <code>strftime()</code> if <code>tm == NULl</code>.</p></li>\n<li><p>your assert(log_fd) fails if <code>log_fd == 0</code>. This should apply to the\nTPLM_FILE mode only.</p></li>\n<li><p>as I said before, printing the level text seems unnecessary. If you need\nit, use <code>strcpy</code> instead of <code>snprintf</code>.</p></li>\n<li><p>printing \"\\n\" could be done with <code>strcpy(msg+len, \"\\n\")</code></p></li>\n<li><p>Personally, I have no objection to the use of varargs in this code. @Lundin\nis right that it is not type-safe, but sometimes it has its uses. This\nseems a legitimate use to me.</p></li>\n</ul>\n\n<p><hr> In <code>tp_log_close</code></p>\n\n<ul>\n<li>your assert fails if <code>log_fd == 0</code>.</li>\n<li>if/else would be clearer.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T20:01:37.920",
"Id": "35820",
"Score": "0",
"body": "The reason I don't want to use syslog constants is that I cannot be sure if LOG_DEBUG is more or less than LOG_EMERG so I don't how to compare log_level with level in tp_log_write. Edit: well actually it could be done with macros at compile time I think but using my own constants seems a bit more clear"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T20:49:34.963",
"Id": "35831",
"Score": "0",
"body": "LOG_DEBUG is the most noisy, LOG_EMERG the least. On my Mac they have values 7 and 0 respectively. Syslog would compare them using the log mask, set by `setlogmask`. If you wanted only EMERG, ALERT, CRIT and ERR log messages to be logged you'd set the mask to LOG_UPTO(LOG_ERR) == 15. And to compare levels you'd do `(LOG_MASK(log_level) & mask != 0)` - see `log_write` in my other answer. By defining your own you cause yourself more work - translating between the two."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:29:23.860",
"Id": "23178",
"ParentId": "23110",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T14:20:25.580",
"Id": "23110",
"Score": "5",
"Tags": [
"c",
"logging"
],
"Title": "Little log engine in C"
}
|
23110
|
<p>I wrote a function for creating all possible translations of a source string, based on a multiple translation map. It works, but generates a lot of intermediate maps (see line marked with <em>*</em>). Is there a better solution? Maybe a more general solution to the "all possible combinations" problem?:</p>
<pre><code>/**
* <p>Add to 'targets' all possible variations of 'source', with replacements defined by 'translationsMap'.
* <p>For example, after the following call:
* <p>addAllReplacements("put the X on the Y", {X => {"cake","egg"}, Y => {"table","chair"}, targets)
* <p>targets should contain the following strings:
* <p>"put the cake on the table", "put the cake on the chair", "put the egg on the table", "put the egg on the chair"
*/
public static void addAllReplacements (String source, Map<String, Set<String>> translationsMap, Set<String> targets) {
if (translationsMap.isEmpty()) {
// no more replacements:
targets.add(source);
} else {
// pick an entry from the map:
Entry<String, Set<String>> e = translationsMap.entrySet().iterator().next();
String text = e.getKey();
Set<String> translations = e.getValue();
// Create a new translation map, without the currently translated text, for the recursive call:
HashMap<String, Set<String>> newTranslationMap =
new HashMap<String, Set<String>>(translationsMap); // *
newTranslationMap.remove(text);
for (String translation: translations) {
addAllReplacements(
source.replace(text, translation),
newTranslationMap,
targets);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You are using the Map more like a list...</p>\n\n<p>EDIT: this is NOT working:</p>\n\n<p>You could create an object to hold one translation ({X => {\"cake\",\"egg\"}) then instead of all the Maps you could use a List (of those translations) and always remove and use the first element and pass the shorter list to the next call of your method.</p>\n\n<p>EDIT: this IS working:</p>\n\n<p>You could use a List with the translation and add an index parameter in you method to know which element from the list use. Then you increment the index once before making the recursive calls...</p>\n\n<p>Here is some code (without constructors getters etc...):</p>\n\n<pre><code>public class Translations {\n final String key;\n final Set<String> translations;\n}\n\n\npublic static void addAllReplacements_2 (String source,List<Translations> translationsList, final int index, Set<String> targets) {\n if (index == (translationsList.size())) {\n // no more replacements:\n targets.add(source);\n } else {\n // pick an entry\n Translations translations = translationsList.get(index);\n String text = translations.getKey();\n Set<String> translationValues = translations.getTranslations();\n\n final int nextIndex = index+1;\n\n for (String translationValue: translationValues) {\n addAllReplacements_2(\n source.replace(text, translationValue),\n translationsList,nextIndex,\n targets);\n }\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T06:42:20.113",
"Id": "35707",
"Score": "0",
"body": "This doesn't work. I can remove and use the first element, however, when I will remove the second element in the next recursion level, it won't be available when I get to the second level later. For example, when I try this on the above example, I get: \"put the egg on the chair\", \"put the cake on the chair\", \"put the X on the table\" (the Y translation is first, it is done OK, but the X translation is done only once)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T10:16:44.257",
"Id": "35716",
"Score": "0",
"body": "You are right there is a problem with my solution, I edit my post to give a working solution..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:04:51.247",
"Id": "35816",
"Score": "0",
"body": "This is really a bad example of a recursion. You should not introduce a new index variable, you should pass a reduced list of Translations. And If you have a Translation object, you should do the logic inside the class. In this way, it is nothing else than a data transfer object."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T15:29:32.873",
"Id": "23112",
"ParentId": "23111",
"Score": "2"
}
},
{
"body": "<p>Some thoughts about the given code:</p>\n\n<pre><code>/**\n * <p>Add to 'targets' all possible variations of 'source', with replacements defined by 'translationsMap'.\n * <p>For example, after the following call:\n * <p>addAllReplacements(\"put the X on the Y\", {X => {\"cake\",\"egg\"}, Y => {\"table\",\"chair\"}, targets)\n * <p>targets should contain the following strings:\n * <p>\"put the cake on the table\", \"put the cake on the chair\", \"put the egg on the table\", \"put the egg on the chair\"\n */\n</code></pre>\n\n<p>It is a good way to provide JavaDoc and it is a very good idea to provide an example. I would just suggest to not use this <code><p></code>, instead a <code><br></code> or <code><br /></code> at the end. Or if you do not like this, you could put everything inside a <code><pre></pre></code>.</p>\n\n<hr>\n\n<pre><code>public static void addAllReplacements (String source, Map<String, Set<String>> translationsMap, Set<String> targets) {\n</code></pre>\n\n<p>I would avoid this C-Pointer style argument handling in the Java world. Just return the set. As a general rule, you should not modify any method arguments.</p>\n\n<hr>\n\n<pre><code>public static void addAllReplacements (String source, Map<String, Set<String>> translationsMap, Set<String> targets) {\n...\n}\n</code></pre>\n\n<p>This recursion looks a bit confusing and not suitable. I would use an iterative approach:</p>\n\n<pre><code>/**\n * Add to 'targets' all possible variations of 'source', with replacements defined by 'translationsMap'.<br>\n * Example:<br>\n * source = \"put the X on the Y\"<br>\n * mapStringToReplacementValueSet = {X => {\"cake\",\"egg\"}, Y => {\"table\",\"chair\"})<br>\n * <br>\n * => result = (\"put the cake on the table\", \"put the cake on the chair\", \"put the egg on the table\", \"put the egg on the chair\")\n */\npublic static Set<String> getAllReplacementsForSourceAndReplacementMap(final String source, final Map<String, Set<String>> mapStringToReplacementValueSet) {\n // plan: create a result set which contains the source\n // for every entry in the map (which corresponds to one replacement key)\n // for each replacement values go over all elements in the current set, do the replacement, add it to a new set\n // make the new set the current set.\n\n Set<String> result = new HashSet<>(Arrays.asList(source));\n\n for (final Entry<String, Set<String>> entry : mapStringToReplacementValueSet.entrySet()) {\n final String currentKey = entry.getKey();\n if (!source.contains(currentKey))\n continue;\n final Set<String> newResult = new HashSet<>();\n final Set<String> currentValue = entry.getValue();\n for (final String setItem : currentValue) {\n for (final String resultArrayItem : result)\n newResult.add(resultArrayItem.replace(currentKey, setItem));\n }\n result = newResult;\n }\n\n return result;\n}\n</code></pre>\n\n<p>Edit: If you use this Translations class, you could simplify the loop to:</p>\n\n<pre><code> for (Translation translationsItem : translations)\n result = translationsItem.apply(result)\n</code></pre>\n\n<p>And the logic goes inside the Translation class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:56:03.690",
"Id": "23230",
"ParentId": "23111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T15:08:41.333",
"Id": "23111",
"Score": "2",
"Tags": [
"java",
"recursion",
"combinatorics"
],
"Title": "multi-recursive replacement function"
}
|
23111
|
<p>Please review <code>unique_list</code>:</p>
<p><code>unique_list</code> implements a <code>list</code> where all items are unique. Functionality can also be described as <code>set</code> with order. <code>unique_list</code> should behave as a python <code>list</code> except:</p>
<ul>
<li>Adding items the end of the list (by <code>append</code>, <code>extend</code>) will do nothing if the item is already in the list.</li>
<li>Assigning to the middle of the list (<code>insert</code>, <code>__setitem__</code>) will remove previous item with the same value - if any.</li>
</ul>
<p></p>
<pre><code>class unique_list(list):
def __init__(self, initial_list = ()):
super(unique_list, self).__init__()
self.attendance = set()
self.extend(initial_list)
def __setitem__(self, index, item):
prev_item = self[index]
if prev_item != item:
if item in self.attendance:
prev_index_for_item = self.index(item)
super(unique_list, self).__setitem__(index, item)
del self[prev_index_for_item]
self.attendance.add(item)
else:
super(unique_list, self).__setitem__(index, item)
self.attendance.add(item)
def __delitem__(self, index):
super(unique_list, self).__delitem__(index)
self.attendance.remove(self[index])
def __contains__(self, item):
""" Overriding __contains__ is not required - just more efficient """
return item in self.attendance
def append(self, item):
if item not in self.attendance:
super(unique_list, self).append(item)
self.attendance.add(item)
def extend(self, items = ()):
for item in items:
if item not in self.attendance:
super(unique_list, self).append(item)
self.attendance.add(item)
def insert(self, index, item):
if item in self.attendance:
prev_index_for_item = self.index(item)
if index != prev_index_for_item:
super(unique_list, self).insert(index, item)
if prev_index_for_item < index:
super(unique_list, self).__delitem__(prev_index_for_item)
else:
super(unique_list, self).__delitem__(prev_index_for_item+1)
else:
super(unique_list, self).insert(index, item)
self.attendance.add(item)
def remove(self, item):
if item in self.attendance:
super(unique_list, self).remove(item)
self.attendance.remove(item)
def pop(self, index=-1):
self.attendance.remove(self[index])
return super(unique_list, self).pop(index)
def count(self, item):
""" Overriding count is not required - just more efficient """
return self.attendance.count(item)
</code></pre>
<hr>
<p>Here is my final (as of now) version:</p>
<pre><code>class unique_list(list):
__slots__ = ('__attendance',)
def __init__(self, initial_list = ()):
super(unique_list, self).__init__()
self.__attendance = set()
self.extend(initial_list)
def __setitem__(self, index, item):
prev_item = self[index]
if prev_item != item:
if item in self.__attendance:
prev_index_for_item = self.index(item)
super(unique_list, self).__setitem__(index, item)
del self[prev_index_for_item]
self.__attendance.add(item)
else:
super(unique_list, self).__setitem__(index, item)
self.__attendance.remove(prev_item)
self.__attendance.add(item)
def __delitem__(self, index):
super(unique_list, self).__delitem__(index)
self.__attendance.remove(self[index])
def __contains__(self, item):
""" Overriding __contains__ is not required - just more efficient """
return item in self.__attendance
def append(self, item):
if item not in self.__attendance:
super(unique_list, self).append(item)
self.__attendance.add(item)
def extend(self, items = ()):
for item in items:
if item not in self.__attendance:
super(unique_list, self).append(item)
self.__attendance.add(item)
def insert(self, index, item):
if item in self.__attendance:
prev_index_for_item = self.index(item)
if index != prev_index_for_item:
super(unique_list, self).insert(index, item)
if prev_index_for_item < index:
super(unique_list, self).__delitem__(prev_index_for_item)
else:
super(unique_list, self).__delitem__(prev_index_for_item+1)
else:
super(unique_list, self).insert(index, item)
self.__attendance.add(item)
def remove(self, item):
if item in self.__attendance:
super(unique_list, self).remove(item)
self.__attendance.remove(item)
def pop(self, index=-1):
self.__attendance.remove(self[index])
return super(unique_list, self).pop(index)
def count(self, item):
""" Overriding count is not required - just more efficient """
return self.__attendance.count(item)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T15:56:47.033",
"Id": "35648",
"Score": "0",
"body": "Not sure why but the code is cut half way through. Maybe it's too long? Is there a way to make sure all the code is displayed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T20:34:34.947",
"Id": "35669",
"Score": "1",
"body": "You'll find it worth comparing your implementation with the [`OrderedSet`](http://code.activestate.com/recipes/576694/) recipe."
}
] |
[
{
"body": "<pre><code>class unique_list(list):\n</code></pre>\n\n<p>I recommend not inheriting from list. You don't gain a whole lot from it as you need to overload pretty much all the methods anyways. By inheriting from list you might also get some methods you didn't think of or were added later and thus behave incorrectly because you should have overloaded them. I'd suggest having the backing list as an attribute instead of the base class.</p>\n\n<pre><code> def __init__(self, *args):\n</code></pre>\n\n<p>Why are you taking a variable number of arguments? That's not how list does it, and so why are you deviating here?</p>\n\n<pre><code> super(unique_list, self).__init__()\n self.attendance = set()\n self.extend(args)\n\n def __setitem__(self, index, item):\n prev_item = self[index]\n if prev_item != item:\n if item in self.attendance:\n prev_index_for_item = self.index(item)\n super(unique_list, self).__setitem__(index, item)\n del self[prev_index_for_item]\n else:\n super(unique_list, self).__setitem__(index, item)\n self.attendance.add(item)\n</code></pre>\n\n<p>Don't you need to update the self.attendance for the object you are overwriting? </p>\n\n<pre><code> def __delitem__(self, index):\n super(unique_list, self).__delitem__(index)\n self.attendance.remove(self[index])\n def __contains__(self, item):\n \"\"\" Overriding __contains__ is not required - just more efficient \"\"\"\n return item in self.attendance\n def append(self, item):\n if item not in self.attendance:\n super(unique_list, self).append(item)\n self.attendance.add(item)\n</code></pre>\n\n<p>In the other cases, new items take precedence over old items. But here, you are keeping the old item, and not appending the new item.</p>\n\n<pre><code> def extend(self, items = ()):\n</code></pre>\n\n<p>Why is there a default here? The function is no-op with the default.</p>\n\n<pre><code> for item in items:\n if item not in self.attendance:\n super(unique_list, self).append(item)\n self.attendance.add(item)\n</code></pre>\n\n<p>Ok, so you are deliberately keeping old items when appending to the end, and new items when setting? That just seems inconsistent and surprising.</p>\n\n<pre><code> def insert(self, index, item):\n if item in self.attendance:\n prev_index_for_item = self.index(item)\n if index != prev_index_for_item:\n super(unique_list, self).insert(index, item)\n if prev_index_for_item < index:\n del self[prev_index_for_item]\n else:\n del self[prev_index_for_item+1]\n else:\n super(unique_list, self).insert(index, item)\n self.attendance.add(item)\n</code></pre>\n\n<p>I'd suggest that you simplify this logic by breaking it into parts:</p>\n\n<pre><code>def insert(self, index, item):\n self.remove(item)\n super(self, unique_list).insert(index, item)\n self.attendance.add(item)\n</code></pre>\n\n<p>That way your code will be much clearer. I'd write all your functions in that manner and only deviate after performance was shown to be a concern.</p>\n\n<pre><code> def remove(self, item):\n if item in self.attendance:\n super(unique_list, self).remove(item)\n self.attendance.remove(item)\n def pop(self, index=None):\n if index is None:\n index = len(self.attendance) - 1\n</code></pre>\n\n<p>Can you get away with defaulting to -1?</p>\n\n<pre><code> self.attendance.remove(self[index])\n return super(unique_list, self).pop(index)\n def count(self, item):\n \"\"\" Overriding count is not required - just more efficient \"\"\"\n return self.attendance.count(item)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:06:15.913",
"Id": "35656",
"Score": "0",
"body": "\"In the other cases, new items take precedence over old items. But here, you are keeping the old item, and not appending the new item.\"\n\nThe idea is that appended items already in the list will keep their place. However if the programmers wants to explicitly make changes to the order - they will be able to do so using `[]` or `insert`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:12:31.663",
"Id": "35657",
"Score": "0",
"body": "`def insert`: If I `self.remove(item)` before `super(self, unique_list).insert(index, item)` the index might not be correct any more. That's why my code inserts first and removes later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:32:58.657",
"Id": "35658",
"Score": "0",
"body": "@PeriodicMaintenance, good point on the indexes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:41:19.813",
"Id": "35659",
"Score": "0",
"body": "@PeriodicMaintenance, I can see why you would have `insert` change the order and `append` keep it. But it doesn't follow the way those methods work on lists. That's why I think it'll be surprising and confusing to the user of this class.Basically, if append doesn't actually append, you shouldn't call it append."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:44:24.697",
"Id": "35660",
"Score": "0",
"body": "@PeriodicMaintenance, my suggestion is to make an OrderedSet rather than a unique list. Follow the set interface rather then the list interface. See the `OrderedDict` class in the collections module for a related example. As it stands you have the same methods as a list, but don't act like a list. But your class would act like a set, just with guaranteed orders and additonal methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:53:56.637",
"Id": "35663",
"Score": "0",
"body": "My original need was to replace all occurrences of `list` in my code, with unique_list. This is why I choose to follow the list interface. Other than that `OrderedSet` would probably be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T20:36:33.670",
"Id": "35671",
"Score": "0",
"body": "If you want to have a list-like interface, inherit from [`collections.MutableSequence`](http://docs.python.org/2/library/collections.html#collections.MutableSequence) instead of `list`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:51:38.813",
"Id": "35947",
"Score": "0",
"body": "@Gareth Rees, if I derive from collections.MutableSequence I will loose the list functionality on which unique_list is based. You see I do not want only \"list-like interface\" I need the list functionality as well."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:40:08.633",
"Id": "23116",
"ParentId": "23113",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23116",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T15:54:47.860",
"Id": "23113",
"Score": "2",
"Tags": [
"python",
"python-2.x"
],
"Title": "unique_list class"
}
|
23113
|
<p>I am a little new/rusty to this C++ stuff. Is this bad code? Can it be improved?</p>
<pre><code>#include <windows.h>
#include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>
bool _initialized_time = false;
void Wait() {
std::cout << "Prease any key to continue ..." << std::endl;
std::cin.get();
}
void print(char* _value) {
std::cout << _value << std::endl;
}
char ConvertIntToChar(int _int) {
return (char)(((int)'0')+_int);
}
int ReturnRandomNumber(int _start, int _end) {
if(_initialized_time == false) {
_initialized_time = true;
srand(time(0));
}
int n = rand() % _end + _start;
return n;
}
void ClearConsoleWindow() {
for (int i = 0; i < 40; i++) {
std::cout << " ";
}
}
void Wait(int _mil){
Sleep(_mil); // wait 1 second
}
enum eCardType { // THE TYPES OF CARDS
cNothing = 0,
cAce = 1,
cTwo = 2,
cThree = 3,
cFour = 4,
cFive = 5,
cSix = 6,
cSeven = 7,
cEight = 8,
cNine = 9,
cTen = 10,
cJack = 11,
cKing = 12,
cQueen = 13,
cJoker = 14,
cAceSmall = 15
};
enum eCardSuite { // THE SUITE OF THE CARDS
sNothing = 0,
sSpades = 1,
sHearts = 2,
sDiamonds = 3,
sClubs = 4
};
enum ePlayerType { // PLAYER TYPE COMPUTER OR PLAYER
pPlayer = 1,
pComputer = 2,
};
struct card { // CARD STRUCT CONTAINS THE SUITE AND TYPE
enum eCardSuite cSuite;
enum eCardType cType;
};
card _deck[52]; // THE DECK WHICH CONTAINS THE CARDS
const int _deck_size = 52; // THE MAXIMUM SIZE OF A DECK OF CARDS
card _player_cards[_deck_size]; // THE PLAYERS CARDS
card _computer_cards[_deck_size]; // THE COMPUTERS CARDS
bool _game_over = false; // IS THE GAME OVER OR NOT
bool _hand_delt = false; // HAS THE HAND BEEN DELT
char _next_move = ' '; // THE NEXT MOVE
const int _computer_hit_threshold = 17; // IF THE VALUE IS OVER THE MAXIMUM, OR EQUAL TO IT, IT WILL STAY
bool _player_stays = false; // DOES THE PLAYER STAY
bool _computer_stays = false; // DOES THE COMPUTER STAY
double _default_money = 2000.00; // DEFAULT MONEY AMOUNT
double _default_bet = 100.00;
double _player_money = 0.0; // AMOUNT PLAYER HAS
double _computer_money = 0.0; // AMOUNT COMPUTER HAS
bool _first_hit = true;
double _pot = 0.0;
double _temp_money = 0.0;
bool _deck_empty = false;
void ResetPlayerCards(ePlayerType _type) { // RESET PLAYER CARDS
switch(_type) {
case pPlayer:
for(int i = 0; i <= _deck_size - 1; i++) {
_player_cards[i].cSuite = sNothing;
_player_cards[i].cType = cNothing;
}
break;
case pComputer:
for(int i = 0; i <= _deck_size - 1; i++) {
_computer_cards[i].cSuite = sNothing;
_computer_cards[i].cType = cNothing;
}
break;
}
}
char* ReturnSuiteString(eCardSuite _suite) {
char* _result;
switch(_suite) {
case sNothing:
_result = "";
break;
case sSpades:
_result = "Spades";
break;
case sHearts:
_result = "Hearts";
break;
case sDiamonds:
_result = "diamonds";
break;
case sClubs:
_result = "clubs";
break;
}
return _result;
}
int ReturnCardValue(card _card) {
int _result;
switch(_card.cType) {
case cAceSmall:
_result = 1;
break;
case cAce:
_result = 10;
break;
case cTwo:
_result = 2;
break;
case cThree:
_result = 3;
break;
case cFour:
_result = 4;
break;
case cFive:
_result = 5;
break;
case cSix:
_result = 6;
break;
case cSeven:
_result = 7;
break;
case cEight:
_result = 8;
break;
case cNine:
_result = 9;
break;
case cTen:
_result = 10;
break;
case cJack:
_result = 10;
break;
case cQueen:
_result = 10;
break;
case cKing:
_result = 10;
break;
case cJoker:
_result = 0;
break;
}
return _result;
}
bool IsAce(card _card) {
bool _result = false;
if(_card.cType == cAce || _card.cType == cAceSmall) {
_result = true;
}
return _result;
}
bool IsValidCard(card _card) {
bool b = false;
if(_card.cSuite != sNothing && _card.cType != cNothing && _card.cType != cJoker) {
b = true;
}
return b;
}
int PlayerHandValue(ePlayerType _type) {
int _value = 0;
switch(_type) {
case pComputer:
for(int i = 0; i <= _deck_size - 1; i++) {
if(_computer_cards[i].cSuite != sNothing && _computer_cards[i].cType != cNothing && _computer_cards[i].cType != cJoker) {
_value = _value + ReturnCardValue(_computer_cards[i]);
}
}
break;
case pPlayer:
for(int i = 0; i <= _deck_size - 1; i++) {
if(_player_cards[i].cSuite != sNothing && _player_cards[i].cType != cNothing && _player_cards[i].cType != cJoker) {
_value = _value + ReturnCardValue(_player_cards[i]);
}
}
break;
}
return _value;
}
int PlayerCardCount(ePlayerType _type) {
int _add = 1;
int _count = 0;
switch(_type) {
case pComputer:
for(int i = 0; i <= _deck_size - 1; i++) {
if(_computer_cards[i].cSuite != sNothing && _computer_cards[i].cType != cNothing && _computer_cards[i].cType != cJoker) {
_count = _count + _add;
}
}
break;
case pPlayer:
for(int i = 0; i <= _deck_size - 1; i++) {
if(_player_cards[i].cSuite != sNothing && _player_cards[i].cType != cNothing && _player_cards[i].cType != cJoker) {
_count = _count + _add;
}
}
break;
}
return _count;
}
char* ReturnPlayerString(ePlayerType _type) {
char* _result;
switch(_type) {
case pPlayer:
_result = "Player";
break;
case pComputer:
_result = "Computer";
break;
}
return _result;
}
char* ReturnCardTypeString(eCardType _type) {
char* _result;
switch(_type) {
case cNothing:
_result = "";
break;
case cAceSmall:
_result = "Ace";
break;
case cAce:
_result = "Ace";
break;
case cTwo:
_result = "Two";
break;
case cThree:
_result = "Three";
break;
case cFour:
_result = "Four";
break;
case cFive:
_result = "Five";
break;
case cSix:
_result = "Six";
break;
case cSeven:
_result = "Seven";
break;
case cEight:
_result = "Eight";
break;
case cNine:
_result = "Nine";
break;
case cTen:
_result = "Ten";
break;
case cJack:
_result = "Jack";
break;
case cQueen:
_result = "Queen";
break;
case cKing:
_result = "King";
break;
case cJoker:
_result = "Joker";
break;
}
return _result;
}
bool DoesMoreCardsExistInDeck() {
bool _more_exists = false;
for(int i = 0; i <= _deck_size - 1; i++) {
if(IsValidCard(_deck[i])) {
_more_exists = true;
break;
}
}
return _more_exists;
}
card TakeNextCard() {
card _new_card;
for(int i = 0; i <= _deck_size - 1; i++) {
if(IsValidCard(_deck[i])) {
_new_card = _deck[i];
_deck[i].cSuite = sNothing;
_deck[i].cType = cNothing;
break;
}
}
return _new_card;
}
card GiveCard(ePlayerType _player_type, bool _show_computer = false) {
bool _say = false;
int _count = 0;
card _new_card;
_new_card.cSuite = sNothing;
_new_card.cType = cNothing;
if(DoesMoreCardsExistInDeck() == true) {
_new_card = TakeNextCard();
switch(_player_type) {
case pComputer:
_count = PlayerCardCount(pComputer);
_computer_cards[_count] = _new_card;
if(_show_computer == true) {
_say = true;
}
break;
case pPlayer:
_count = PlayerCardCount(pPlayer);
_player_cards[_count] = _new_card;
_say = true;
break;
}
if(_say == true) {
std::cout << ReturnPlayerString(_player_type) << " received " << ReturnCardTypeString(_new_card.cType) << " of " << ReturnSuiteString(_new_card.cSuite) << std::endl;
} else {
std::cout << ReturnPlayerString(_player_type) << " received an undisclosed card." << std::endl;
}
} else {
print("Deck Empty");
_deck_empty = true;
}
return _new_card;
}
bool IsCardAlreadyInDeck(card _card) {
bool _result = false;
for(int i = 0; i <= _deck_size - 1; i++) {
if(IsValidCard(_deck[i])) {
if(_card.cSuite == _deck[i].cSuite && _card.cType == _deck[i].cType) {
_result = true;
}
}
}
return _result;
}
int CanUseCard(card _cards[], card _card) {
bool _can_use = true;
int _temp_card_count = 0;
int _count;
for(int i = 0; i <= _deck_size - 1; i++) {
if(_card.cSuite != sNothing && _card.cType != cNothing && _card.cType != cJoker) {
if((_cards[i].cSuite == _card.cSuite) && (_cards[i].cType == _card.cType)) {
_temp_card_count++;
}
}
}
if(_card.cType == cAceSmall) { _can_use = false; }
if(IsCardAlreadyInDeck(_card) == true) { _can_use = false; }
if(_card.cSuite == sNothing || _card.cType == cNothing || _card.cType == cJoker) { _can_use = false; }
if(_temp_card_count == 4) { _can_use = false; }
return _can_use;
}
void ShuffleDeck() {
int i = 0;
_deck_empty = false;
for(int i = 0; i <= _deck_size - 1; i++) {
_deck[i].cSuite = sNothing;
_deck[i].cType = cNothing;
}
int _count = 0;
for(int i = 0; i <= _deck_size - 1; i++) {
card _new_card = {sNothing, cNothing};
int _continue = 1;
while(_continue == 1) {
_new_card.cSuite = (eCardSuite)ReturnRandomNumber(1, 4);
_new_card.cType = (eCardType)ReturnRandomNumber(1, 13);
if(CanUseCard(_deck, _new_card) == true) {
_continue = 0;
_deck[_count] = _new_card;
_count = _count + 1;
}
}
}
}
void Reset() {
_first_hit = true;
ClearConsoleWindow();
ResetPlayerCards(pPlayer);
ResetPlayerCards(pComputer);
_computer_stays = false;
_player_stays = false;
_hand_delt = true;
GiveCard(pComputer, true);
GiveCard(pPlayer, true);
GiveCard(pComputer, true);
GiveCard(pPlayer, true);
}
void PromptNewGame() {
std::cin >> _next_move;
switch(_next_move) {
case 'p':
Reset();
break;
case 'q':
_game_over = true;
break;
}
}
void UpdateLastCard(ePlayerType _type, card _card) {
int _count = 0;
_count = PlayerCardCount(_type) - 1;
if(_type == pPlayer) {
_player_cards[_count] = _card;
} else if (_type == pComputer) {
_computer_cards[_count] = _card;
}
}
void RewardWinner() {
if(PlayerHandValue(pPlayer) > PlayerHandValue(pComputer)) {
if(PlayerHandValue(pPlayer) >= 22) {
std::cout << "Computer Wins! Player: " << PlayerHandValue(pPlayer) << ", Computer: " << PlayerHandValue(pComputer) << std::endl;
_computer_money = _computer_money - _default_bet + _pot;
_player_money = _player_money - _default_bet;
_pot = 0.0;
} else {
std::cout << "Player Wins! Player: " << PlayerHandValue(pPlayer) << ", Computer: " << PlayerHandValue(pComputer) << std::endl;
_player_money = _player_money + _default_bet + _pot;
_computer_money = _computer_money - _default_bet;
_pot = 0.0;
}
} else if (PlayerHandValue(pPlayer) == PlayerHandValue(pComputer)) {
std::cout << "Draw! Player: " << PlayerHandValue(pPlayer) << ", Computer: " << PlayerHandValue(pComputer) << std::endl;
_player_money = _player_money - _default_bet;
_computer_money = _computer_money - _default_bet;
_pot = _pot + _default_bet;
} else if(PlayerHandValue(pComputer) > PlayerHandValue(pPlayer)) {
if(PlayerHandValue(pComputer) >= 22) {
std::cout << "Player Wins! Player: " << PlayerHandValue(pPlayer) << ", Computer: " << PlayerHandValue(pComputer) << std::endl;
_player_money = _player_money + _default_bet + _pot;
_computer_money = _computer_money - _default_bet;
_pot = 0.0;
} else {
std::cout << "Computer Wins! Player: " << PlayerHandValue(pPlayer) << ", Computer: " << PlayerHandValue(pComputer) << std::endl;
_computer_money = _computer_money + _default_bet + _pot;
_player_money = _player_money - _default_bet;
_pot = 0.0;
}
}
}
void Initialize() {
ShuffleDeck();
_computer_money = _default_money;
_player_money = _default_money;
card _temp_card;
do {
if(_player_money == 0) {
print("sorry, you are out of money [q]");
std::cin >> _next_move;
if(_next_move == 'q') {
_game_over = true;
}
} else if(_default_bet > _player_money) {
std::cout << "You only have " << _player_money << " but the bet is currently " << _default_bet << " [q]" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') {
_game_over = true;
}
} else {
if(_player_stays == true && _computer_stays == true) {
RewardWinner();
if(_player_money == 0) {
std::cout << "You are out of money [q] Quit" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') {
_game_over = true;
}
} else if(_default_bet > _player_money) {
std::cout << "You only have " << _player_money << " but the bet is currently " << _default_bet << " [q]" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') {
_game_over = true;
}
} else {
std::cout << "[p] Play Again [q] Quit" << std::endl;
PromptNewGame();
}
} else {
if(PlayerHandValue(pPlayer) >= 22) {
RewardWinner();
if(_player_money == 0) {
std::cout << "Player Busted with " << PlayerHandValue(pPlayer) << "! You are out of money [q] Quit" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') {
_game_over = true;
}
} else if(_default_bet > _player_money) {
std::cout << "You only have " << _player_money << " but the bet is currently " << _default_bet << " [q]" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') {
_game_over = true;
}
} else {
std::cout << "Player Busted with " << PlayerHandValue(pPlayer) << "! [p] Play Again [q] Quit" << std::endl;
PromptNewGame();
}
} else {
if(_hand_delt == false) { Reset(); }
if(_first_hit == true) {
std::cout << "Cards: " << PlayerCardCount(pPlayer) << ", Hand Value: " << PlayerHandValue(pPlayer) << ", Money: " << _player_money << "." << std::endl;
if(_deck_empty == true) {
std::cout << "[d] Shuffle Deck [s] Stay [c] Change bet amount [q] Quit" << std::endl;
} else {
std::cout << "[h] Hit Me [s] Stay [c] Change bet amount [q] Quit" << std::endl;
}
_first_hit = false;
} else {
if(_deck_empty == true) {
std::cout << "Cards: " << PlayerCardCount(pPlayer) << ", Hand Value: " << PlayerHandValue(pPlayer) << ", Money: " << _player_money << ". [d] Shuffle Deck [s] Stay [q] Quit" << std::endl;
} else {
std::cout << "Cards: " << PlayerCardCount(pPlayer) << ", Hand Value: " << PlayerHandValue(pPlayer) << ", Money: " << _player_money << ". [h] Hit Me [s] Stay [d] Shuffle Deck [q] Quit" << std::endl;
}
}
std::cin >> _next_move;
switch(_next_move) {
case 'd':
if(_deck_empty) {
ShuffleDeck();
break;
}
case 'c':
if(_first_hit == true) {
if(_pot == 0) {
std::cout << "You currently have: " << _player_money << " the current bet is " << _default_bet << ". Enter the new default amount: " << std::endl;
} else {
std::cout << "You currently have: " << _player_money << " the current bet is " << _default_bet << ". There is " << _pot << " in the pot. Enter the new default amount: " << std::endl;
}
std::cin >> _temp_money;
if(_temp_money >= _default_bet) {
_default_bet = _temp_money;
} else {
std::cout << "You cannot bet that much, because you don't have enough money." << std::endl;
}
}
break;
case 'q':
_game_over = true;
break;
case 'h':
_temp_card = GiveCard(pPlayer);
if(_temp_card.cType == cAce) {
std::cout << "Select Ace [1] Ace (10 Points) [2] Ace (1 Points)";
std::cin >> _next_move;
switch(_next_move) {
case '1':
_temp_card.cType = cAce;
break;
case '2':
_temp_card.cType = cAceSmall;
break;
}
UpdateLastCard(pPlayer, _temp_card);
}
break;
case 's':
_player_stays = true;
do {
_temp_card = GiveCard(pComputer, true);
if(_deck_empty == true) {
ShuffleDeck();
}
if(PlayerHandValue(pComputer) >= 22) {
RewardWinner();
if(_player_money == 0) {
std::cout << "Computer Busted with " << PlayerHandValue(pComputer) << "! You are out of money [q] Quit" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') { _game_over = true; }
} else if(_default_bet > _player_money) {
std::cout << "Computer Busted with " << PlayerHandValue(pComputer) << " but the bet is currently " << _default_bet << " [q]" << std::endl;
std::cin >> _next_move;
if(_next_move == 'q') { _game_over = true; }
} else {
std::cout << "Computer Busted with " << PlayerHandValue(pComputer) << "! [p] Play Again [q] Quit" << std::endl;
PromptNewGame();
}
ResetPlayerCards(pComputer);
break;
}
} while (PlayerHandValue(pComputer) < PlayerHandValue(pPlayer));
_computer_stays = true;
break;
}
}
}
}
} while (!_game_over);
}
int black_jack() {
Initialize();
Wait();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T04:52:41.817",
"Id": "35699",
"Score": "0",
"body": "Before using leading underscores in your identifiers. Read this: http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797"
}
] |
[
{
"body": "<p>Here are some suggestions for you:</p>\n\n<pre><code>bool _initialized_time = false;\n\nint ReturnRandomNumber(int _start, int _end) {\n if(_initialized_time == false) {\n _initialized_time = true;\n srand(time(0));\n }\n int n = rand() % _end + _start;\n return n;\n}\n</code></pre>\n\n<p>Avoid using global variables if at all possible. For this simple implementation of the game it probably does not matter, but unless you have a good reason to use them, it's just as well to get in the habit of avoiding them.</p>\n\n<p>In this case you should just initialize the random number generator when the program starts:</p>\n\n<pre><code>int black_jack() {\n srand(time(0)); \n Initialize();\n ...\n</code></pre>\n\n<p>Also you should avoid using leading underscores in identifiers, see <a href=\"https://stackoverflow.com/a/228797/270280\">this answer</a> for the reasoning. If needed you can use a trailing underscore instead, but don't add underscores for no reason.</p>\n\n<p>About naming, drop the <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">hungarian notation</a> too.</p>\n\n<p>Your <code>Initialize</code>function does a lot more than initialize the game. It is also very big. You should consider breaking it up into several smaller functions, and give them names that describes what they do.</p>\n\n<p>You do have a lot of good function with well chosen names already, like <code>PromptNewGame</code>, <code>ShuffleDeck</code>, <code>GiveCard</code> etc. Try to break the <code>Initialize</code>-function into similar chunks of well named functions.</p>\n\n<p>The <code>ReturnCardValue</code>-function could probably be a lot smarter. Just handle the special cases, and return the card type for the rest. Something like this, perhaps:</p>\n\n<pre><code>int ReturnCardValue(const card & c) {\n if (c.type > Nine)\n return 10;\n else\n return reinterpret_cast<int>(c.type);\n}\n</code></pre>\n\n<p>This may require the layout of your card type enum to be slightly different. Notica also that I chose to pass the card struct by reference instead of by value (copy). For a small struct like this it's not a big deal, but for bigger structs it's nice to avoid the copying if it's not needed.</p>\n\n<p>Also, you don't have to initialize every member of the enum as long as the values are consecutive. Try this instead:</p>\n\n<pre><code>enum CardType {\n Joker, AceSmall, Two, Three, Four, Five,\n Six, Seven, Eight, Nine, Ten, Jack, King,\n Queen, Ace\n};\n</code></pre>\n\n<p>Finally you may want to look into turning several parts of your program into classes. From the top of my head I can think of at least three immediately obvious ones, <code>Game</code>, <code>Player</code>, and <code>Card</code>. This would encapsulate the functionality in each element of the game into logical units and make the program easier to read and maintain at the same time.</p>\n\n<p>Allright, that's just some suggestions for you. Gives you at least somewhere to start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:10:16.727",
"Id": "35892",
"Score": "0",
"body": "Thanks I learned a lot here, I have improved my code a lot as a result."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T20:27:40.800",
"Id": "23125",
"ParentId": "23115",
"Score": "3"
}
},
{
"body": "<p>Everything @harald said:</p>\n\n<p>Is this correct?</p>\n\n<pre><code>int n = rand() % _end + _start;\n\n// Given the names of the parameters start and end\n// I would have thought it should be:\nint n = rand() % (_end-start) + _start;\n\n// This will give you a number in the range [start, end)\n</code></pre>\n\n<p>You can replace your big switch statements with a value look up:</p>\n\n<pre><code> int ReturnCardValue(card _card) {\n int _result;\n switch(_card.cType) {\n case cAceSmall:\n _result = 1;\n break;\n case cAce:\n _result = 10;\n break;\n case cTwo:\n _result = 2;\n break;\n\n // easier to write:\n\n int ReturnCardValue(Card card)\n {\n static int cardValue[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 10, 1 /*ACE SMALL IS 15*/ };\n return cardValue[card.cType];\n }\n</code></pre>\n\n<p>Rather than assigning true false based on <code>if statement</code>. Use the conditional of the if statement directly:</p>\n\n<pre><code>bool IsValidCard(card _card) {\n bool b = false;\n if(_card.cSuite != sNothing && _card.cType != cNothing && _card.cType != cJoker) {\n b = true;\n }\n return b;\n}\n\n// easier to write and read as:\nbool IsValidCard(card _card) {\n bool b = _card.cSuite != sNothing && _card.cType != cNothing && _card.cType != cJoker;\n\n return b;\n}\n</code></pre>\n\n<p>Choice of algorithm based on a type are better done using encapsulation and polymorphism:</p>\n\n<pre><code>int PlayerHandValue(ePlayerType _type) {\n int _value = 0;\n switch(_type) {\n case pComputer:\n value = // Compute Value base on Computer\n break;\n case pPlayer:\n value = // Compute Value based on Player\n break;\n }\n return _value;\n}\n\n// If you used the concept of Players:\n// The code looks like this:\nint PlayerHandValue(Player& player)\n{\n int _value = player.handValue();\n return _value;\n}\n\n// For this you need:\nclass Player\n{\n public:\n virtual ~Player() {}\n virtual int handValue() = 0;\n};\nclass HumanPlyaer: public Player;\n{\n public:\n virtual int handValue()\n {\n // Code for Human here\n }\n};\nclass ComputerPlyaer: public Player;\n{\n public:\n virtual int handValue()\n {\n // Code for Computer here\n }\n};\n// You can also add more styles of computer player without affecting\n// the logic of your code.\n</code></pre>\n\n<p>Try and use the standard algorithms:</p>\n\n<pre><code>void ShuffleDeck()\n{\n for(int i = 0; i <= _deck_size - 1; i++)\n {\n _deck[i].cSuite = static_cast<eCardSuite>(i / 13 + 1);\n _deck[i].cType = static_cast<eCardType>(i % 13 + 1);\n }\n std::random_shuffle(&data[0], &data[_deck_size]);\n}\n</code></pre>\n\n<p>Put repeated code into functions. That way if it is broken you only fix it in one place:</p>\n\n<pre><code> } else {\n std::cout << \"Player Wins! Player: \" << PlayerHandValue(pPlayer) << \", Computer: \" << PlayerHandValue(pComputer) << std::endl;\n _player_money = _player_money + _default_bet + _pot;\n _computer_money = _computer_money - _default_bet;\n _pot = 0.0;\n }\n\n // A couple of lines down you have:\n if(PlayerHandValue(pComputer) >= 22) {\n std::cout << \"Player Wins! Player: \" << PlayerHandValue(pPlayer) << \", Computer: \" << PlayerHandValue(pComputer) << std::endl;\n _player_money = _player_money + _default_bet + _pot;\n _computer_money = _computer_money - _default_bet;\n _pot = 0.0;\n } else {\n</code></pre>\n\n<p>Looks about the same from here:</p>\n\n<p>The Initialize function is getting a bit big.<br>\nYou way want to split it into subroutines so you can read the overall plan of the function without having to scroll the screen. A rule of thumb is that a function should not be longer than a screen in length (you want to be able to read the whole function in one go with out loosing track of what happens at one end).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T20:13:19.530",
"Id": "35893",
"Score": "0",
"body": "Thanks for the tips, I'm getting better all the time. Just looking at my code from a few days ago gives me the shivers. A lot of these things I already fixed, but the one I like the best is the \"static int card_values_[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 10, 1 };\" very elegant, I didn't think that it was possible. Also this doesn't work: //return rand() % (end_ - start_) + start_; i'm not sure why, the game doesn't load when I use it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T05:22:04.200",
"Id": "23148",
"ParentId": "23115",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T16:19:18.600",
"Id": "23115",
"Score": "3",
"Tags": [
"c++",
"beginner",
"game",
"playing-cards"
],
"Title": "Blackjack game with many conditionals and switches"
}
|
23115
|
<p>So i have a super class that has a 3 child classes. Those 3 child classes have multiple classes of their own. I was having troubles saving this into XML, so I decided to parse it out and do a little bit of maths to return the correct subclass type and make an instance of it. So after a little bit of digging it appears that the "easiest" method was to use reflection and LINQ . I'm new to LINQ (I've been very stubborn to use it). It appears to me to be something similar to SQL, which makes me think I'm doing this wrong (even though it works according to my unit tests)</p>
<pre><code>internal static CustomTask GetTask(string type)
{
var types = Assembly.GetAssembly(typeof(CustomTask)).GetTypes().Where(t => t.IsSubclassOf(typeof(CustomTask)));
Globals.WriteLog(types.ToString());
foreach (Type t in types)
{
Globals.WriteLog(t.FullName);
if (t.FullName.Contains(type))
{
Globals.WriteLog("^^^^^^^^^^FOUND IT^^^^^^^^^^");
var tasktype = Type.GetType(t.FullName);
return (CustomTask)Activator.CreateInstance(tasktype);
}
}
Globals.WriteLog("Fell through to switch statement, not fully implemented");
switch (type)
{
case "ScannerTask":
return new ScannerTask();
default:
return new UnassignTask();
}
}
</code></pre>
<p>I guess because I have unit tests I shouldn't be afraid to edit the LINQ statment, but it works, and it does seem rather clean. And I don't know what it would return if it didn't find a proper subclass (although it <strong>should</strong> seeing as the xml save method requires a CustomTask as part of its parameters) The switch statment is there to show what I was doing before I tried LINQ. So how can I make my LINQ statement only return the correct type so I can create a instance of it?</p>
<p><strong>EDIT</strong></p>
<p>Well this is what i'm down too. It passes all my tests, but still doesn't feel correct. thoughts?</p>
<pre><code> var types = Assembly.GetAssembly(typeof(CustomTask)).GetTypes();
var subclasses = types.Where(t => t.IsSubclassOf(typeof(CustomTask)));
var single = subclasses.Where(t => t.FullName.Contains(type)).Single();
Globals.WriteLog(single.ToString());
var tasktype1 = Type.GetType(single.ToString());
return (CustomTask)Activator.CreateInstance(tasktype1);
</code></pre>
<p><strong>EDIT2</strong></p>
<p>ok so with the one suggestion I have this now. I like it.. but i have a sneaky suspicion it could be better yet..</p>
<pre><code>internal static CustomTask GetTask(string type)
{
var types = Assembly.GetAssembly(typeof(CustomTask)).GetTypes();
var subclasses = types.Where(t => t.IsSubclassOf(typeof(CustomTask)));
var single = subclasses.Single(t => t.FullName.Equals(type));
Globals.WriteLog(single.ToString());
return (CustomTask)Activator.CreateInstance(single);
}
public static void SaveEventListener(XmlDocument xmlDocument, AbstractEventListener akel, string filename)
{
Globals.WriteLog("xml.SaveEventListener()+");
string query = string.Format("//Key[@Name='{0}']", akel.key);
var node = xmlDocument.SelectSingleNode(query);
if (node == null) // no value found save new
{
Globals.WriteLog("Creating new key");
XmlElement ele = xmlDocument.CreateElement("Key");
ele.SetAttribute("Name", akel.key.ToString());
var child = xmlDocument.CreateElement("Task");
child.SetAttribute("Type", akel.Task.GetType().FullName);
child.InnerText = akel.Task.GetOptionString();
ele.PrependChild(child);
xmlDocument.DocumentElement.PrependChild(ele);
}
else
{
//Need to implement a update yet.
}
xmlDocument.Save(filename);
Globals.WriteLog("xml.SaveEventListener()-");
}
public static AbstractEventListener LoadEventListener(XmlDocument xmlDocument, System.Windows.Forms.Keys keys)
{
Globals.WriteLog("xml.LoadEventListener()+");
AbstractEventListener ret = new AbstractEventListener(keys, new UnassignTask());
string query = string.Format("//Key[@Name='{0}']", keys);
var node = xmlDocument.SelectSingleNode(query);
if (node != null)
{
Globals.WriteLog("Found Key, parsing");
var type = node.ChildNodes[0].Attributes["Type"].Value;
var task = KeymonTask.GetTask(type);
ret.Task = task;
ret.Task.Parse(node.ChildNodes[0].InnerText);
}
Globals.WriteLog("xml.LoadEventListener()-");
return ret;
}
</code></pre>
<p>forinstance in the load function I have <code>ret = new AbstractEventListener(keys, new UnassignTask());</code> that portion could stand to be writen differently... well the whole method could stand a small fix I think. </p>
|
[] |
[
{
"body": "<p>There are a few things I notice:</p>\n\n<ul>\n<li><code>tasktype1</code> is redundant, since <code>single</code> is already of type <code>System.Type</code>, so\nthere is no need to do the <code>Type.GetType(single.ToString());</code> call. You can use <code>single</code> directly.</li>\n<li>The <code>.Where(t => t.FullName.Contains(type)).Single ()</code> call can instead be replaced with <code>.Single (t => t.FullName.Contains(type))</code></li>\n<li>The manner in which you match types could return incorrect results. <code>t.FullName.Contains(type)</code> will return any type where <code>type</code> is a substring of the fully-qualified type name. This can even include cases where <code>type</code> is a substring of one of the namespaces of your intended type. You may consider instead using <code>t.Name == type</code>.</li>\n</ul>\n\n<p>That reduces the updated code to the following:</p>\n\n<pre><code>var types = Assembly.GetAssembly(typeof(CustomTask)).GetTypes();\nvar subclasses = types.Where(t => t.IsSubclassOf(typeof(CustomTask)));\nvar single = subclasses.Single(t => t.Name == type);\nGlobals.WriteLog(single.ToString());\nreturn (CustomTask)Activator.CreateInstance(single);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T18:14:16.503",
"Id": "23120",
"ParentId": "23118",
"Score": "2"
}
},
{
"body": "<p>After you make the changes suggested by Dan Lyons, you might also consider using fluent syntax for the query:</p>\n\n<pre><code>var type = Assembly.GetAssembly(typeof(CustomTask)).GetTypes()\n .Where(t => t.IsSubclassOf(typeof(CustomTask)))\n .Single(t => t.Name == type);\n</code></pre>\n\n<p>Or you could combine the two predicates into one:</p>\n\n<pre><code>var type = Assembly.GetAssembly(typeof(CustomTask)).GetTypes()\n .Single(t => t.IsSubclassOf(typeof(CustomTask)) && t.Name == type);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T18:37:14.827",
"Id": "23122",
"ParentId": "23118",
"Score": "0"
}
},
{
"body": "<p>In a single statement it can be rewritten as following (without logging though):</p>\n\n<pre><code>return Assembly.GetAssembly(typeof(CustomTask)).GetTypes()\n .Where(t => typeof(CustomTask).IsAssignableFrom(t) && t.FullName.Contains(type))\n .Select(t => (CustomTask)Activator.CreateInstance(t))\n .SingleOrDefault();\n</code></pre>\n\n<p>Note that <code>Single</code> method throws exception if lookup won't find the class matching your criteria. If you prefer to return <code>null</code> in this case - use <code>SingleOrDefault</code> instead.</p>\n\n<p>Also, if this kind of code will be called quite often I would suggest to create a <code>Dictionary</code> that caches the mapping from previously looked up keywords (strings) to the type found.</p>\n\n<p>But in general your solution doesn't look correct from architectural point of view: you're trying to match a certain string to full name of the class (and that string most likely is not equal to full name, otherwise you could just call <code>Type.GetType()</code> method). It may cause side effects if someone will add a class containing the same substring: for example your intention is to use <code>\"ScannerTask\"</code> string to lookup <code>YourNamespace.ScannerTask</code> class, and it works correctly now. But after a year of intense development someone may decide to introduce some new fancy task called <code>MyNewNamespace.MuchBetterScannerTask</code>... and bang, your code is broken, since new class may suddenly pop out instead of expected one.</p>\n\n<p><strong>Update</strong>\nSince you're saving a full name of the type you don't need to search all assembly types for it, just do</p>\n\n<pre><code>internal static CustomTask GetTask(string fullname)\n{\n var type = Type.GetType(fullname);\n return type != null\n ? (CustomTask)Activator.CreateInstance(type)\n : new UnassignTask();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T19:24:46.673",
"Id": "35666",
"Score": "0",
"body": "here in a second i'll post my save method, and maybe that will shed some more light into why i'm not entirely worried about the newer potential tasks. But you do bring up a valid point in that the way I am looking for it needs to be revised. How do I set the default to something else? because I do have a default of `UnassignedTask` which essentially is a null Task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T20:40:27.527",
"Id": "35672",
"Score": "0",
"body": "That is a awesome update. I am actually going to use that answer instead. It is straight forward and easy. Thank you very much for your time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T18:44:18.357",
"Id": "23123",
"ParentId": "23118",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23123",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:29:29.060",
"Id": "23118",
"Score": "-2",
"Tags": [
"c#",
"linq",
"reflection"
],
"Title": "New to LINQ, not sure this is best practice"
}
|
23118
|
<p>How could I make this code shorter and faster?</p>
<pre><code>'Sheets("Summary(FG)") ComboBox1 items
For b = 3 To Sheets("CustomerList").Cells(3, 2).SpecialCells(xlLastCell).row
If Sheets("CustomerList").Cells(b, 2) <> "" Then
Worksheets("Summary(FG)").ComboBox1.AddItem (Sheets("CustomerList").Cells(b, 2))
Else
End If
Next
'Sheets("Summary(RawMat)") ComboBox1 items
For a = 2 To Sheets("RawMatList").Cells(2, 2).SpecialCells(xlLastCell).Column
If Sheets("RawMatList").Cells(2, a) <> "" Then
Worksheets("Summary(RawMat)").ComboBox1.AddItem (Sheets("RawMatList").Cells(2, a))
End If
Next
'Sheets("Summary(WIP)") ComboBox1 items
For c = 3 To Sheets("WIPList").Cells(3, 2).SpecialCells(xlLastCell).row
If Sheets("WIPList").Cells(c, 2) <> "" Then
Worksheets("Summary(WIP)").ComboBox1.AddItem (Sheets("WIPList").Cells(c, 2))
End If
Next
For Each Worksheet In Worksheets
Application.Goto Reference:=Range("A1"), Scroll:=True
Next Worksheet
</code></pre>
|
[] |
[
{
"body": "<p>For a faster version of the code you could add your range to an array and loop through that instead of looping through cells.</p>\n\n<p>For example:</p>\n\n<pre><code>Dim varray as Variant\nvarray = Sheets(\"CustomerList\").Range(\"B3:B\" & Cells(Rows.Count, \"B\").End(xlUp).Row).Value\n\nfor b = 1 to ubound(varray)\n If varray(b,1) <> \"\" Then\n Worksheets(\"Summary(FG)\").ComboBox1.AddItem (varray(b,1))\n End If\nnext b\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-15T15:25:24.407",
"Id": "23961",
"ParentId": "23119",
"Score": "2"
}
},
{
"body": "<p>Combobox and Listbox have a List property. You can assign an array to the List property to quickly fill up the control.</p>\n\n<p>The Value property of the Range object returns an array (if the Range is multicell).</p>\n\n<p>That means you can assign the Value property to the List property in one line. You just have to be careful that the column counts match. </p>\n\n<pre><code>Sub FillFinishedGoods()\n\n Dim rFG As Range\n\n With Sheets(\"CustomerList\")\n Set rFG = .Range(\"B3\", .Cells(.Rows.Count, 2).End(xlUp))\n End With\n\n Sheets(\"Summary(FG)\").ComboBox1.List = rFG.Value\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-20T19:26:00.657",
"Id": "24169",
"ParentId": "23119",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23961",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T17:33:42.533",
"Id": "23119",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Populate ComboBox"
}
|
23119
|
<p>Can I somehow make this a bit cleaner using <code>Math.[Something]</code>, without making a method for it?</p>
<pre><code>int MaxSpeed = 50;
if (Speed.X > MaxSpeed)
Speed.X = MaxSpeed;
if (Speed.X < MaxSpeed * -1)
Speed.X = MaxSpeed * -1;
if (Speed.Y > MaxSpeed)
Speed.Y = MaxSpeed;
if (Speed.Y < MaxSpeed * -1)
Speed.Y = MaxSpeed * -1;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T23:49:32.330",
"Id": "35680",
"Score": "3",
"body": "hmmm - please note: if you're using this to control speed in a 'non-grid' environment, the moving object will move faster than `MaxSpeed` in a diagonal direction (by about 40%)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T00:01:37.167",
"Id": "35681",
"Score": "0",
"body": "ah didn't think about that. tahts true. But up an down is only used for falling and jumping. and will have other max/min values."
}
] |
[
{
"body": "<p>I'm afraid there is no such built-in method. There is a similar question <a href=\"https://stackoverflow.com/questions/3176602/how-to-force-a-number-to-be-in-a-range-in-c\">here</a> where an extension method is proposed to force the number to be in range (copy-pasting it with cosmetic changes here):</p>\n\n<pre><code>public static class InputExtensions\n{\n public static int LimitToRange(this int value, int inclusiveMinimum, int inclusiveMaximum)\n {\n if (value < inclusiveMinimum) \n return inclusiveMinimum;\n if (value > inclusiveMaximum)\n return inclusiveMaximum;\n return value;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T07:36:48.157",
"Id": "35708",
"Score": "0",
"body": "@Leonid `System.Int32` and `int` are synonyms, or to be precise `int` is the C# alias for .NET type `System.Int32`, see description [here](http://msdn.microsoft.com/en-us/library/vstudio/5kzh1b5w.aspx)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T21:20:44.447",
"Id": "35767",
"Score": "0",
"body": "@Leonid Not sure about your feeling, they are absolutely the same. And I don't see any issues in creating extension method for a \"primitive\", as well as not sure why you mentioned boxing here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T21:39:56.370",
"Id": "23128",
"ParentId": "23126",
"Score": "5"
}
},
{
"body": "<p>There's a method in XNA called <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.mathhelper.clamp.aspx\">MathHelper.Clamp</a> that does what you need. I understand if you don't want to import XNA libraries for this one function, though. You can do this with extension methods. Here's an implementation that uses generics (so you can apply it to various types) so you can use it for ints, longs, anything that implements IComparable</p>\n\n<pre><code>static class Extensions\n{\n public static T Clamp<T> (this T self, T min, T max) where T: IComparable\n {\n if (self.CompareTo( min) <0)\n return min;\n return self.CompareTo(max) > 0 ? max : self;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T23:43:01.780",
"Id": "35679",
"Score": "0",
"body": "Thanks, check out my tags, actually this is for a XNA project so MathHelper.Clamp was exactly what i was looking for, thank you for the code aswell !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:05:32.313",
"Id": "35733",
"Score": "0",
"body": "Jeez, I think this is the first XNA code review I've seen. Glad I could help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T22:37:11.420",
"Id": "35840",
"Score": "2",
"body": "Why `IComparable` instead of `IComparable<T>`? And I'd use `Comparer<T>.Default.Compare` over `left.CompareTo(right)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T22:58:22.703",
"Id": "35843",
"Score": "0",
"body": "@CodesInChaos an interesting point wrt Comparer<t>.Default.Compare. I've only seen it used to safeguard against comparisons against null, but it'd totally be valid here too."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T22:59:45.107",
"Id": "23130",
"ParentId": "23126",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "23130",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T21:27:06.087",
"Id": "23126",
"Score": "7",
"Tags": [
"c#",
"integer",
"interval",
"xna"
],
"Title": "Determine if an int is within range"
}
|
23126
|
<p>Thought I share this piece of code to the world. But be aware, I am not sure if this piece of code is safe and efficient. Feel free to improve it or give some feedback and suggestions.</p>
<pre><code>#pragma region DOCUMENTATION ON: STD_COPY_VECTOR_TO_ARRAY
//////////////////////////////////////////////////////////////////////////////
// MACRO: STD_COPY_VECTOR_TO_ARRAY( Vector, Position, Length, Array ) //
// //
// DESCRIPTION: //
// A defined macro that is created to copy selected values of std::vector //
// an array. This defined macro takes 4 arguments. //
// //
// ARGUMENTS: //
// Vector - The std::vector that contains the values that will be copied. //
// Position - Position of the first value from Vector to be copied. //
// Note: The first value of Position is marked by the value of 0 and not 1. //
// Length - Amount of values to be copied from Vector. //
// Array - The Array that the values will be copied to. //
// //
// TIPS: //
// #1 - To copy all values within Vector, set the value of Position to 0 //
// and set the value of Length to the size of Vector (std::vector::size). //
//////////////////////////////////////////////////////////////////////////////
#pragma endregion
#define STD_COPY_VECTOR_TO_ARRAY( Vector, Position, Length, Array ) \
std::copy( Vector.begin( ) + Position, \
Vector.begin( ) + Position + Length , \
Array )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T01:40:18.160",
"Id": "35694",
"Score": "0",
"body": "This site is not for sharing code, it's for requesting review. And since that doesn't seem to be the primary reason you posted, I think this “question” is off topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T05:34:05.040",
"Id": "35704",
"Score": "0",
"body": "@svick: It does not matter what his original intention was. As long as somebody else can learn from there mistakes by reading the below discussion."
}
] |
[
{
"body": "<p>Basically, there are very few places in C++ where you want to use Macros. A lot of old C code used function-like macros because of performance reasons - calling a function requires creating a new stack frame. They were also used to get away from C's type system. With C++, <code>inline</code> functions and templates remove the need for this 99% of the time.</p>\n\n<pre><code>template <typename T>\ninline void copy_vector_to_array(const std::vector<T>& vec, \n std::size_t position, \n std::size_t length, \n T* array)\n{\n std::copy(vec.begin() + position, vec.begin() + position + length, array);\n}\n</code></pre>\n\n<p>In C++11, we can do better still - an erroneous length passed in above will cause problems, and will be hard to detect:</p>\n\n<pre><code>#include <vector>\n#include <array>\n#include <iterator>\n#include <cassert>\n\ntemplate <typename T, std::size_t N>\ninline void copy_vector_to_array(const std::vector<T>& vec, \n std::size_t position, \n std::size_t length, \n std::array<T, N>& array)\n{\n assert(length <= N);\n std::copy(std::begin(vec) + position, std::begin(vec) + position + length, \n std::begin(array));\n}\n</code></pre>\n\n<p>This will be just as efficient as the macro version, however, we also gain type safety, as well as (easy) bounds checking. </p>\n\n<p>We can also improve on it. So that it handles other container types:</p>\n\n<pre><code>template <typename C, std::size_t N>\ninline void copy_container_to_array(const C& container, \n std::size_t position, \n std::size_t length, \n std::array<typename C::value_type, N>& array)\n{\n assert(length <= N);\n std::copy(std::next(std::begin(vec), position), std::next(std::begin(vec), position + length), \n std::begin(array));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T01:34:51.527",
"Id": "35693",
"Score": "0",
"body": "Nicely done Yuushi!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T01:41:24.057",
"Id": "35695",
"Score": "0",
"body": "Isn't the `inline` modifier ignored by most modern compilers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T01:52:04.380",
"Id": "35698",
"Score": "0",
"body": "@svick It's a suggestion that the compiler is free to ignore based on whatever code analysis it does, and likely at `O3` will be somewhat superfluous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T05:25:45.647",
"Id": "35701",
"Score": "0",
"body": "We can improve on that by making it handle other container types :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T05:29:21.090",
"Id": "35702",
"Score": "0",
"body": "@LokiAstari True, best is to just work with iterators directly, which doesn't constrain you to container types at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T05:30:47.027",
"Id": "35703",
"Score": "0",
"body": "@svick: The `inline` modifier is ignored in terms of weather the compiler will inline the code. But it is required for the linker in this case. The compiler will decide whether to inline or not based on its own internal metrics that decide the most efficient mechanism."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T00:59:04.597",
"Id": "23138",
"ParentId": "23136",
"Score": "4"
}
},
{
"body": "<p>Since you're specifying the number of items rather than the start and end items, you might as well use the algorithm defined specifically for that purpose:</p>\n\n<pre><code>std::copy_n(std::next(std::begin(Vector), Position), Length, std::begin(Array));\n</code></pre>\n\n<p>Given the triviality of the code and its applicability to situations other than copying from a vector to an array, creating either a macro or an inline function for it seems a bit silly to me though -- more likely a loss than an improvement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T04:44:34.277",
"Id": "23146",
"ParentId": "23136",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23138",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T00:32:09.623",
"Id": "23136",
"Score": "4",
"Tags": [
"c++",
"macros"
],
"Title": "A defined macro to copy selected values of std::vector to an array using std::copy"
}
|
23136
|
<p>We've got a "catch-all" in <code>app.js</code> that renders a <code>.jade</code> file if it exists:</p>
<pre><code>app.get('*', routes.render);
</code></pre>
<blockquote>
<p>index.js</p>
</blockquote>
<pre><code>render: function(req, res) {
fs.exists('views' + req.url + '.jade', function(exists) {
if (exists) {
//substring: "/admin" -> "admin"
res.render(req.url.substring(1));
} else {
res.status(404);
res.render('404', {url: req.url});
}
});
}
</code></pre>
<p>Problem is, we've either got to move everything we don't want rendered this way into another folder, which is a hassle, or create a manual blacklist. Is there a better way of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:34:50.853",
"Id": "35954",
"Score": "0",
"body": "I guess this is only for static pages?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:45:21.283",
"Id": "35955",
"Score": "0",
"body": "Only for pages that don't require additional parameters (for example \"About Us\")"
}
] |
[
{
"body": "<p>Here are some examples of how most apps do:</p>\n\n<ul>\n<li>Apache renders everything in the folder. If you want to hide access to a subfolder, you do that with an htaccess in this subfolder.</li>\n<li>Define each route yourself. This'd mean having a whitelist in your case. (In some array or something.)</li>\n<li>Keep the routes in the database. This allows you to handle permissions easily.</li>\n</ul>\n\n<p>I haven't often seen the blacklist way. Why? Because of a simple security principle: <a href=\"http://en.wikipedia.org/wiki/Secure_input_and_output_handling#Whitelist_or_Blacklist.3F\" rel=\"nofollow\">blacklists may accidentally treat bad input as safe</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:55:55.030",
"Id": "23338",
"ParentId": "23139",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T00:59:22.343",
"Id": "23139",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"express.js"
],
"Title": "Render arbitrary jade in express"
}
|
23139
|
<p>I am trying to combine two programs that analyze strings into one program. The result should look at a parent string and determine if a sub-string has an exact match or a "close" match within the parent string; if it does it returns the location of this match </p>
<p>i.e. parent: abcdefefefef
sub cde is exact and returns 2
sub efe is exact and returns 4, 6, 8
sub deg is close and returns 3
sub z has no match and returns None</p>
<p>The first program I wrote locates exact matches of a sub-string within a parent string:</p>
<pre><code>import string
def subStringMatchExact():
print "This program will index the locations a given sequence"
print "occurs within a larger sequence"
seq = raw_input("Please input a sequence to search within: ")
sub = raw_input("Please input a sequence to search for: ")
n = 0
for i in range(0,len(seq)):
x = string.find(seq, sub, n, len(seq))
if x == -1:
break
print x
n = x + 1
</code></pre>
<p>The second analyzes whether or not there is an close match within a parent string and returns True if there is, and false if there isn't. Again a close match is an exact match or one that differs by only one character.</p>
<pre><code>import string
def similarstrings():
print "This program will determine whether two strings differ"
print "by more than one character. It will return True when they"
print "are the same or differ by one character; otherwise it will"
print "return False"
str1 = raw_input("Enter first string:")
str2 = raw_input("Enter second string:")
x = 0
for i in range(len(str1)):
if str1[i] == str2[i]:
x = x + 1
else:
x = x
if x >= len(str1) - 1:
print True
else:
print False
</code></pre>
<p>Any suggestions on how to combine the two would be much appreciated.</p>
|
[] |
[
{
"body": "<p>Firstly, a quick review of what you've done:</p>\n\n<p><code>import string</code> is unnecessary really. You utilize <code>string.find</code>, but you can simply call the find method on your first argument, that is, <code>seq.find(sub, n, len(seq))</code>. </p>\n\n<p>In your second method, you have:</p>\n\n<pre><code>if str1[i] == str2[i]:\n x = x + 1\nelse:\n x = x\n</code></pre>\n\n<p>The <code>else</code> statement is completely redundant here, you don't need it.</p>\n\n<p>I think we can simplify the logic quite a bit here. I'm going to ignore <code>raw_input</code> and take the strings as arguments instead, but it doesn't change the logic (and is arguably better style anyway). Note that this is not fantastically optimized, it can definitely be made faster:</p>\n\n<pre><code>def similar_strings(s1, s2):\n '''Fuzzy matches s1 with s2, where fuzzy match is defined as\n either all of s2 being contained somewhere within s1, or\n a difference of only one character. Note if len(s2) == 1, then\n the character represented by s2 must be found within s1 for a match\n to occur.\n\n Returns a list with the starting indices of all matches.\n\n '''\n block_size = len(s2)\n match = []\n for j in range(0, len(s1) - block_size):\n diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]\n if diff.count(0) and diff.count(0) >= (block_size - 1):\n match.append(j)\n if not match:\n return None\n return match\n</code></pre>\n\n<p>How does this work? Well, it basically creates a \"window\" of size <code>len(s2)</code> which shifts along the original string (<code>s1</code>). Within this window, we take a slice of our original string (<code>s1[j:j+block_size]</code>) which is of length <code>len(s2)</code>. <code>zip</code> creates a list of tuples, so, for example, <code>zip(['a','b','c'], ['x','y','z'])</code> will give us back <code>[(a, x), (b, y), (c, z)</code>].</p>\n\n<p>Then, we make a difference of all the characters from our <code>s2</code> sized block of <code>s1</code> and our actual <code>s2</code> - <code>ord</code> gives us the (integer) value of a character. So the rather tricky line <code>diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]</code> will give us a list of size <code>len(s2)</code> which has all the differences between characters. As an example, with <code>s1</code> being <code>abcdefefefef</code> and <code>s2</code> being <code>cde</code>, our first run through will give us the slice <code>abc</code> to compare with <code>cde</code> - which gives us <code>[-2, -2, -2]</code> since all characters are a distance of 2 apart.</p>\n\n<p>So, given <code>diff</code>, we want to see how many 0's it has, as two characters will be the same when their <code>ord</code> difference is 0. However, we need to make sure there is at least 1 character the same in our block (if you simply pass in <code>z</code>, or any string length 1, diff will always have length 1, and <code>block_size - 1</code> will be 0. Hence <code>diff.count(0) >= 0</code> will always be <code>True</code>, which is not what we want). Thus <code>diff.count(0)</code> will only be true if it is greater than 0, which protects us from this. When that's true, look at the block size, make sure it is at least <code>len(s2) - 1</code>, and if so, add that index to <code>match</code>.</p>\n\n<p>Hopefully this gives you an idea of how you'd do this, and I hope the explanation is detailed enough to make sense of some python constructs you may not have seen before.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T02:41:03.293",
"Id": "23142",
"ParentId": "23141",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T01:35:09.573",
"Id": "23141",
"Score": "2",
"Tags": [
"python"
],
"Title": "Python: Combing two programs that analyze strings"
}
|
23141
|
<p>I've been using this code for quite some time, but am wondering if there's any improvements I can make to it. Basically it's just code that runs when the page loads or if the code is run after page load, it will run right away. Do you see any cross browser compatibility issues or any more efficient ways of writing this? <code>ol()</code> is a predefined function to be run.</p>
<pre><code>(document.readyState=='complete') ?
ol():(window.addEventListener&&window.addEventListener("load",ol,false)||
window.attachEvent&&window.attachEvent("onload",ol));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T08:28:28.380",
"Id": "35712",
"Score": "2",
"body": "I suggest you take a look at jQuery's implementation of `.ready()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:47:59.600",
"Id": "35729",
"Score": "1",
"body": "There's some good coverage in Paul Irish's http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/ `.ready` coverage starts around 21:20. There's also some links to jQuery sources."
}
] |
[
{
"body": "<p>Just for dealing with <code>ready</code> alone I use <a href=\"http://jquery.com/\" rel=\"nofollow\">jQuery</a> -- it does the cross-browser heavy lifting, is well-tested and maintained. Minified, it's only 32K, and included from a CDN, you get fast delivery that may already be cached in your user's browser.</p>\n\n<p>And there is a <strong>lot</strong> more code than what you have above to deal with all of the browsers being ready.</p>\n\n<p>There's some good coverage in Paul Irish's <a href=\"http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source\" rel=\"nofollow\">10 Things I learned from the jQuery source screen-case</a> <code>.ready</code> coverage starts around 21:20. There's also some links to jQuery sources.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:02:03.770",
"Id": "35732",
"Score": "1",
"body": "using jQuery only for the ready event is to heavy.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:25:08.083",
"Id": "35738",
"Score": "0",
"body": "If you're not using a CDN, quite possibly. 32K is HUUUUGE. On my 300 baud modem it takes nearly a minute and a half to download. But the code above is nowhere near heavy enough. extract what you need from JQ, and credit it. I'd be surprised if you don't have other uses for it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:52:00.940",
"Id": "23172",
"ParentId": "23145",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T03:42:33.317",
"Id": "23145",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Add event listener when window loads"
}
|
23145
|
<p>I am working on a project in which I have two tables in a different database with different schemas. So that means I have two different connection parameters for those two tables to connect using JDBC-</p>
<p>Let's suppose below is the config.property file-</p>
<pre><code>TABLES: table1 table2
#For Table1
table1.url: jdbc:mysql://localhost:3306/garden
table1.user: gardener
table1.password: shavel
table1.driver: jdbc-driver
table1.percentage: 80
#For Table2
table2.url: jdbc:mysql://otherhost:3306/forest
table2.user: forester
table2.password: axe
table2.driver: jdbc-driver
table2.percentage: 20
</code></pre>
<p>Below method will read the above <code>config.properties</code> file and make a <code>ReadTableConnectionInfo</code> object for each tables.</p>
<pre><code> private static void readPropertyFile() throws IOException {
prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties"));
tableNames = Arrays.asList(prop.getProperty("TABLES").split(" "));
for (String arg : tableNames) {
ReadTableConnectionInfo ci = new ReadTableConnectionInfo();
String url = prop.getProperty(arg + ".url");
String user = prop.getProperty(arg + ".user");
String password = prop.getProperty(arg + ".password");
String driver = prop.getProperty(arg + ".driver");
double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage"));
ci.setUrl(url);
ci.setUser(user);
ci.setPassword(password);
ci.setDriver(driver);
ci.setPercentage(percentage);
tableList.put(arg, ci);
}
}
</code></pre>
<p>Below is the <code>ReadTableConnectionInfo class</code> that will hold all the <code>table connection info</code> for a particular table. </p>
<pre><code>public class ReadTableConnectionInfo {
public String url;
public String user;
public String password;
public String driver;
public String percentage;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
}
</code></pre>
<p>Now I am creating <code>ExecutorService</code> for specified number of threads and passing this <code>tableList</code> object (that I created by reading the <code>config.property file</code>) to constructor of <code>ReadTask class</code> -</p>
<pre><code>// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
service.submit(new ReadTask(tableList));
}
</code></pre>
<p>Below is my <code>ReadTask</code> class that implements <code>Runnable interface</code> in which each thread will make two connections for each table in the starting before doing anything meaningful.</p>
<pre><code>class ReadTask implements Runnable {
private Connection[] dbConnection = null;
private ConcurrentHashMap<ReadTableConnectionInfo, Connection> tableStatement = new ConcurrentHashMap<ReadTableConnectionInfo, Connection>();
private PreparedStatement preparedStatement = null;
private ResultSet rs = null;
private static Random random = new SecureRandom();
public ReadTask(LinkedHashMap<String, ReadTableConnectionInfo> tableList) {
this.tableLists = tableList;
}
@Override
public void run() {
try {
int j = 0;
dbConnection = new Connection[tableList.size()];
//loop around the map values and make the connection list
for (ReadTableConnectionInfo ci : tableList.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
tableStatement.putIfAbsent(ci, dbConnection[j]);
j++;
}
long startTime = System.currentTimeMillis();
long endTime = startTime + (10 * 60 * 1000);
while (System.currentTimeMillis() <= endTime) {
double randomNumber = random.nextDouble() * 100.0;
ReadTableConnectionInfo table = selectRandomConnection(randomNumber);
for (Map.Entry<ReadTableConnectionInfo, Connection> entry : tableStatement.entrySet()) {
//The below if condition will be fine from ThreadSafety issues?
if (entry.getKey().getTableName().equals(table.getTableName())) {
final String id = generateRandomId(random);
final String selectSql = generateRandomSQL(table);
preparedStatement = entry.getValue().prepareCall(selectSql);
preparedStatement.setString(1, id);
rs = preparedStatement.executeQuery();
}
}
}
}
}
private String generateRandomSQL(ReadTableConnectionInfo table) {
int rNumber = random.nextInt(table.getColumns().size());
List<String> shuffledColumns = new ArrayList<String>(table.getColumns());
Collections.shuffle(shuffledColumns);
String columnsList = "";
for (int i = 0; i < rNumber; i++) {
columnsList += ("," + shuffledColumns.get(i));
}
final String sql = "SELECT ID" + columnsList + " from "
+ table.getTableName() + " where id = ?";
return sql;
}
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) {
double limit = 0;
for (ReadTableConnectionInfo ci : tableLists.values()) {
limit += ci.getPercentage();
if (random.nextDouble() < limit) {
return ci;
}
throw new IllegalStateException();
}
return null;
}
}
private Connection getDBConnection(String url, String username, String password, String driver) {
Connection dbConnection = null;
try {
Class.forName(driver);
dbConnection = DriverManager.getConnection(url, username, password);
}
return dbConnection;
}
</code></pre>
<p>In my above <code>try</code> block, I am making <code>dbConnection array</code> for storing two different database connections. And then I have a <code>tableStatement</code> as ConcurrentHashMap in which I am storing <code>ReadTableConnectionInfo</code> object with its <code>dbConnection</code>. For example <code>Table1 object will have Table1 connection</code> in the <code>tableStatement</code> ConcurrentHashMap.</p>
<p>And then after that I am applying this logic-</p>
<pre><code>/* Generate random number and check to see whether that random number
* falls between 1 and 80, if yes, then choose table1
* and then use table1 connection and statement that I made above and do a SELECT * on that table.
* If that random numbers falls between 81 and 100 then choose table2
* and then use table2 connection and statement and do a SELECT * on that table
*/
1) Generating Random number between 1 and 100.
2) If that random number is less than table1.getPercentage() then I am choosing `table1` and then use `table1 connection` object to make a SELECT sql call to that database.
else choose `table2` and then use `table2 connection object` to make a SELECT sql call to that database.
</code></pre>
<p><strong>Problem Statement:-</strong></p>
<p>Are there any potential <strong>thread safety issues</strong> here in my <code>run</code> method?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T08:11:08.393",
"Id": "35711",
"Score": "1",
"body": "According to the FAQ the code should work but I'm afraid this one does not compile (`preparedStatement` is not declared anywhere, `while (System.currentTimeMillis() <= 60 minutes)` is an invalid expression)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T12:24:58.440",
"Id": "35725",
"Score": "1",
"body": "Nor do you show where `tableList` comes from - considering it is the only shared object in your code (unless `preparedStatement` or `rs` also are, but you don't show how they are declared either), this is clearly a critical piece of information. You also need to show how `getDBConnection` is implemented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T14:00:37.550",
"Id": "35726",
"Score": "1",
"body": "If you are using a .properties file, then it should be in the proper format (key-value pairs separated by `=`, not `:`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:11:38.567",
"Id": "35735",
"Score": "1",
"body": "@palacsint, That one I removed it intentionally, as it was straight forward. Anyways, I have added that chunk piece of code. Please take a look now and let me know if everything looks good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:13:20.283",
"Id": "35736",
"Score": "1",
"body": "@assylias, I have updated my code with `getDBConnection method` and added `preparedStatement and rs` as well. Regarding tableList, it is coming from the `readProperty` method right? and them I am passing it to `ExecutorService`. Please take a look now and let me know."
}
] |
[
{
"body": "<p>In summary, you have 2 shared resources: the <code>tableList</code> variable and the database.</p>\n\n<p>Regarding <code>tableList</code>, if:</p>\n\n<ul>\n<li><code>tableList</code> is fully populated <em>before</em> you submit the tasks to the executor service AND</li>\n<li>it is populated in the same thread as the main thread that creates the executor and submits the tasks AND</li>\n<li>it is not modified after that</li>\n</ul>\n\n<p>THEN the access in read-only mode to that shared variable is thread-safe (thanks to the semantics of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow\">the <code>submit</code> method which creates a happens-before relationship</a>.</p>\n\n<blockquote>\n <p>Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task.</p>\n</blockquote>\n\n<p>Regarding the access to the database, <code>DriverManager.getConnection()</code> is thread safe and you don't share the connection object across threads so you are fine (although it would probably be more efficient to use a connection pool).</p>\n\n<p><strong>So your code looks thread safe to me.</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:55:08.000",
"Id": "35744",
"Score": "0",
"body": "Thanks assylias for the suggestion. What about this if loop `if (entry.getKey().getTableName().equals(table.getTableName())) {` that I have in my while block? Is there any problem with that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:09:12.557",
"Id": "35748",
"Score": "0",
"body": "`tableStatement` is \"thread local\" (it is only accessed from one thread) - by the way you don't really need a concurrent map there for the same reason. And I suppose that `getTableName()`, which is not defined in your code, is a method of a `ReadTableConnectionInfo`, which is not modified once it is passed to your thread. So I don't see why there would be a problem there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:52:00.563",
"Id": "35751",
"Score": "0",
"body": "Thanks. That make more sense. Yes it is defined in `ReadTableConnectionInfo` class. And about why I am using `ConcurrentHashMap` is because- In the starting `for loop of my run method`, I am putting the data in Map. So I believe putting any data in `HashMap` is not thread safe so that is the reason I am using `ConcurrentHashMap` here. let me know if I am missing anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T18:01:09.990",
"Id": "35753",
"Score": "0",
"body": "@user21973 You populate and read the map from the same thread and no other thread has access to the map, so there is no thread safety concern. If the map were static and shared across your Runnables, then yes you would need to synchronize access."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:46:22.833",
"Id": "23175",
"ParentId": "23147",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-02-26T05:05:19.190",
"Id": "23147",
"Score": "3",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Thread Safety issues in the multithreading code"
}
|
23147
|
<p>I made a simple form validation. It's working alright. The thing is I want my code to be optimized. Can somebody show me some pointers to improve my code? Thanks in advance.</p>
<pre><code>$(document).ready(function(){
$('.submit').click(function(){
validateForm();
});
function validateForm(){
var nameReg = /^[A-Za-z]+$/;
var numberReg = /^[0-9]+$/;
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var names = $('#nameInput').val();
var company = $('#companyInput').val();
var email = $('#emailInput').val();
var telephone = $('#telInput').val();
var message = $('#messageInput').val();
var inputVal = new Array(names, company, email, telephone, message);
var inputMessage = ["name", "company", "email address", "telephone number", "message"];
var textId = ["#nameLabel", "#companyLabel", "#emailLabel", "#telephoneLabel", "#messageInput"];
$('.error').hide();
if($.trim(inputVal[0]) === ""){
$('#nameLabel').after('<span class="error"> Please enter your ' + inputMessage[0] + '</span>');
}else if(!nameReg.test(names)){
$('#nameLabel').after('<span class="error"> Letters only</span>');
}
if($.trim(inputVal[1]) === ""){
$('#companyLabel').after('<span class="error"> Please enter your ' + inputMessage[1] + '</span>');
}
if($.trim(inputVal[2]) === ""){
$('#emailLabel').after('<span class="error"> Please enter your ' + inputMessage[2] + '</span>');
}else if(!emailReg.test(email)){
$('#emailLabel').after('<span class="error"> Please enter a valid email address</span>');
}
if($.trim(inputVal[3]) === ""){
$('#telephoneLabel').after('<span class="error"> Please enter your ' + inputMessage[3] + '</span>');
}else if(!numberReg.test(telephone)){
$('#telephoneLabel').after('<span class="error"> Numbers only</span>');
}
if($.trim(inputVal[4]) === ""){
$('#messageLabel').after('<span class="error"> Please enter your ' + inputMessage[4] + '</span>');
}
return false;
}
});
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>First of all, you shouldn't use <code>$('.submit').click()</code> but <code>$('#myForm').submit()</code> as you will be able to submit forms by pressing <kbd>enter</kbd> too.</p></li>\n<li><p>To check if a string is a number, use <code>!isNan(string)</code> (see <a href=\"https://stackoverflow.com/a/175787/1149495\">this answer</a> for more information).</p></li>\n<li><p>Email regex are difficult things. Just check if there is someting before the <code>@</code> (with <code>.+?</code>) and if there is something after the <code>@</code> (again with <code>.+?</code>) and if that last part contains a <code>.</code> and a couple of characters (from 2 to 6)</p></li>\n<li><p>It would make the function a lot easier if you put all specific code outside it. E.g:</p></li>\n</ul>\n\n<pre class=\"lang-javascript prettyprint-override\"><code> validateForm({\n '#nameInput': {\n 'valid': function (value) {\n return /^[a-z]+$/i.test(value);\n },\n 'label': '#nameLabel',\n 'messages': {\n 'empty': 'Please enter your name',\n 'invalid': 'Letters only',\n },\n },\n '#companyInput': {\n 'label': '#companyLabel',\n 'messages': {\n 'empty': 'Please enter your company',\n },\n },\n // ...\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:38:32.840",
"Id": "23171",
"ParentId": "23152",
"Score": "2"
}
},
{
"body": "<p>I would use a for loop to test all values first. If one is invalid you can stop and fix before going on with the code or submitting. Here is a <a href=\"http://jsfiddle.net/h3dGe/1/\" rel=\"nofollow\">fiddle</a> without the submit callback so you can see how this would work.</p>\n\n<p>The following code is explained in the comments.</p>\n\n<pre><code>(function($) { //Wrap your function in an IIFE. Assign \"$\" to jQuery to avoid conflicts with other libraries.\n $('#myform').submit(function() { //Form can be submitted without a \"click\"\n //You only need to say \"var\" once. After that just use \",\" and bump to the next one.\n var names = \" \", //I set this one empty to show you how it works\n company = \" good\",\n email = \"dat shi cra\";\n\n var inputVal = [names, company, email],\n inputMessage = [\"name\", \"company\", \"email address\"],\n textId = [\"#nameLabel\", \"#companyLabel\", \"#emailLabel\"];\n\n\n for(var i=0;i<inputVal.length;i++){\n //We want to trim before the testing.\n //$.trim doesn't cut white space within the string.\n //ie: \" good\" will return \"good\", but \"goo d\" will return \"goo d\".\n inputVal[i] = $.trim(inputVal[i]);\n\n //Here is where we test for invalid entries.\n //Is the value undefined? Is it null? Or is it an empty string? If any of these, it is invalid.\n //You can add more tests if you like.\n if (typeof inputVal[i] === 'undefined' || inputVal[i] === null || inputVal[i] === \"\") {\n // \"i\" will tell you which position is invalid.\n // Call the function and tell it which one is invalid.\n invalidEntry(i);\n\n //Stop at the first invalid we find.\n //If you want to collect all the invalids, remove the return, make an array, and push the \"i\" to it, then do something with the array.\n //When the loop is done that array will contain all the invalid entries numbered accordingly.\n return false;\n }\n //This will run for EACH VALID entry.\n console.log(\"Yolo bitcholo! So far so good!\");\n };\n\n function invalidEntry(i) {\n //Get the index of the invalid and do your stuff.\n $(textId[i]).after(\"<span class='error'>Please enter a valid \" + inputMessage[i] + \".</span>\");\n }\n\n return this.some_variable //Only submit if this variable is set. This can contain your form data, which we would only want to submit if there is data to submit.\n });\n})(jQuery);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:46:55.323",
"Id": "23176",
"ParentId": "23152",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T08:56:22.230",
"Id": "23152",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Form Validation (JQuery)"
}
|
23152
|
<p>After posting my first question and my first attempt which you can see here:</p>
<p><a href="https://codereview.stackexchange.com/questions/23095/my-first-attempt-at-canvas-spatial-grid-collision-please-be-honest">Canvas spatial grid collision</a></p>
<p>I have re-written it to try and implement what the person gave as an answer. I didn't do the <code>prototype</code> method as it was overkill for this and besides I am saving that for my next project!</p>
<pre><code>$(document).ready(function() {
var canvas = $('canvas')[0]; // canvas object
var ctx = canvas.getContext('2d'); // canvas context
var engine = new engine(new grid(new block().getSize())); // run the game
window.addEventListener('keydown', keyPressDown, true); // event listener for keydown
function keyPressDown(evt) {
if(engine.activeBlock) { // block is falling
switch(evt.keyCode) {
case 37: // left arrow
engine.pressLeft();
break;
case 39: // right arrow
engine.pressRight();
break;
case 40: // down arrow
engine.activeBlock.pressDown();
break;
}
}
}
window.addEventListener('keyup', keyPressUp, true); // event listener for keyup
function keyPressUp(evt) {
if(engine.activeBlock) { // block is falling
switch(evt.keyCode) {
case 40:
engine.activeBlock.releaseDown();
break;
}
}
}
// block object
function block() {
this.x = 500; // x coord
this.y = 0; // y coord
this.size = 50; // size of block squared
this.getSize = function() { // returns size of the block
return this.size;
};
this.baseVelocity = 1; // base speed
this.velocity = this.baseVelocity; // current speed
this.genColor = function() { // random block color
var colors = ['yellow', 'red', 'blue', 'green', 'orange', 'fuchsia'];
return colors[Math.floor(Math.random() * colors.length)];
};
this.color = this.genColor(); // blocks color
this.update = function() { // update blocks position
this.y += this.velocity;
};
this.pressDown = function() { // key press down
this.velocity += 1;
};
this.releaseDown = function() { // key release down
this.velocity = this.baseVelocity;
};
this.moveLeft = function() {
this.x -= this.size;
};
this.moveRight = function() {
this.x += this.size;
};
}
// grid object
function grid(blockSize) {
this.cellSize = blockSize; // cell size of grid
this.cellsX = canvas.width / this.cellSize; // cells along x axis
this.cellsY = canvas.height / this.cellSize; // cells along y axis
this.buildGrid = function() { // returns built grid
var arr = new Array(this.cellsX);
for(var i = 0; i < arr.length; ++i) {
arr[i] = new Array(this.cellsY);
}
return arr;
};
this.arr = this.buildGrid(); // holds grid
this.getCoords = function(i) { // get relevant grid coords
return Math.floor(i / this.cellSize);
};
this.checkDown = function(block) { // check grid for collisions down
if(this.getCoords(block.y) == (this.cellsY - 1)) { // block has hit bottom of canvas
return true;
} else if(this.arr[this.getCoords(block.x)][this.getCoords(block.y) + 1]) { // block has landed on top of another block
return true;
}
};
this.checkLeft = function(block) { // check grid for collisions left
if(this.getCoords(block.x) <= 0) { // block has hit left edge
return true;
} else if(this.arr[this.getCoords(block.x) - 1][this.getCoords(block.y)]) { // block is on left
return true;
} else if(this.arr[this.getCoords(block.x) - 1][this.getCoords(block.y) - 1]) { // block is on left
return true;
} else if(this.arr[this.getCoords(block.x) - 1][this.getCoords(block.y) + 1]) { // block is on left
return true;
}
return false;
};
this.checkRight = function(block) { // check grid for collisions right
if(this.getCoords(block.x) >= (this.cellsX - 1)) {
return true;
} else if(this.arr[this.getCoords(block.x) + 1][this.getCoords(block.y)]) {
return true;
} else if(this.arr[this.getCoords(block.x) + 1][this.getCoords(block.y) - 1]) {
return true;
} else if(this.arr[this.getCoords(block.x) + 1][this.getCoords(block.y) + 1]) {
return true;
}
return false;
};
this.storeBlock = function(block) { // store block in grid
block.x = this.cellSize * Math.floor(block.x / this.cellSize); // floor x coord to nearest cellSize multiple
block.y = this.cellSize * Math.floor(block.y / this.cellSize); // floor y coord to nearest cellSize multiple
this.arr[this.getCoords(block.x)][this.getCoords(block.y)] = block;
};
}
// engine object
function engine(grid) {
this.framerate = 20; // framerate
this.activeBlock = new block(); // active block
this.nextBlock = new block(); // next block
this.drawBlock = function(block) { // draw block onto canvas
ctx.fillStyle = block.color;
ctx.fillRect(block.x, block.y, block.size, block.size);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(block.x, block.y, block.size, block.size);
ctx.fillStyle = block.color;
ctx.fillRect(block.x + (block.size / 10), block.y + (block.size / 10), block.size - ((block.size / 10) * 2), block.size - ((block.size / 10) * 2));
};
this.drawGrid = function() { // draw existing blocks stored in grid
for(var i = 0; i < grid.arr.length; ++i) {
for(var i2 = 0; i2 < grid.arr[i].length; ++i2) {
if(grid.arr[i][i2]) {
this.drawBlock(grid.arr[i][i2]);
}
}
}
};
this.pressLeft = function() { // press left
if(!grid.checkLeft(this.activeBlock)) { // check grid collision
this.activeBlock.moveLeft(); // move left
}
};
this.pressRight = function() { // press right
if(!grid.checkRight(this.activeBlock)) { // check grid collision
this.activeBlock.moveRight(); // move right
}
};
this.resetCanvas = function() { // reset canvas background
ctx.fillStyle = '#eee';
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
this.loop = function() { // the loop
this.resetCanvas();
this.drawGrid();
this.drawBlock(this.activeBlock);
this.activeBlock.update();
if(grid.checkDown(this.activeBlock)) { // check grid collision down
grid.storeBlock(this.activeBlock); // store block in grid
this.activeBlock = this.nextBlock;
this.nextBlock = new block();
}
};
this.run = function() { // set interval
setInterval(this.loop.bind(this), this.framerate); // bind the loop
};
this.run(); // run on instance
}
});
</code></pre>
<p>Are there any more improvements that I could change to this? Any best practices that I haven't done?</p>
<p>You can view what the code does <a href="http://jsfiddle.net/ShaShads/LM3PN/embedded/result/" rel="nofollow noreferrer">here</a>.</p>
|
[] |
[
{
"body": "<p>Just as a general point to consider, you're making <em>everything</em> public. Consider your Block</p>\n\n<pre><code>function block() {\n this.x = 500; // x coord\n this.y = 0; // y coord\n this.size = 50; // size of block squared\n this.getSize = function() { // returns size of the block\n return this.size;\n };\n}\n</code></pre>\n\n<p>Do you want someone to be able to change the size of your block? It doesn't look like you do.</p>\n\n<pre><code>var b = new block();\nb.size = -5 // I'm pretty sure you don't want this to be possible.\n</code></pre>\n\n<p>Consider only making things public if you want other parts of your script to be able to change it.</p>\n\n<pre><code>function Block() {\n this.x = 500;\n this.y = 0; \n var size = 50; \n this.getSize = function() { \n return size;\n };\n}\n\nvar b = new Block();\nb.size // doesn't exist -> people have to use getSize function.\n</code></pre>\n\n<p>Thinking about it fully, you'd probably want your x and y coordinates to be private too - it should only be possible to update it via your update function. If you're interested, check out this page: <a href=\"http://javascript.crockford.com/private.html\" rel=\"nofollow\" title=\"Private Members in JavaScript\">http://javascript.crockford.com/private.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:37:53.013",
"Id": "36250",
"Score": "0",
"body": "Thanks my first game I coded like this was in java for android and was pretty basic, guess I didn't think about the differences coding in javascript which is available client side."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:42:38.580",
"Id": "36251",
"Score": "0",
"body": "@ShaShads it's a pretty good effort :). Another small point would be your keyPressUp function, there's no point in using a switch statement if you only care about one possible value. Also, you need to check `evt.which` as well as `evt.keyCode` as some browsers use one and not the other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:45:42.257",
"Id": "36252",
"Score": "0",
"body": "Thanks for the info. I didn't even notice that about the `keyPressUp` function, I can guarantee that I copy/pasted it in a hurry to see if it worked from the `keyDown` functions!! Thanks buddy you have been a great help :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:51:06.620",
"Id": "36253",
"Score": "0",
"body": "@ShaShads looks like I was getting confused with jQuery about the event.which: http://stackoverflow.com/a/4471691/1402923. No problem, have fun!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T12:23:37.180",
"Id": "23480",
"ParentId": "23154",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23480",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T09:15:25.207",
"Id": "23154",
"Score": "0",
"Tags": [
"javascript",
"canvas",
"collision"
],
"Title": "Second attempt at canvas spatial grid collision"
}
|
23154
|
<p>I've tried to improve my code: separate HTML/PHP, much clear, next time change will be easier. After doing research on MVC/OOP, I've made the below code to learn.</p>
<p>I understand this is not the MVC pattern now. Can anybody help me fix it to become actual MVC?</p>
<ol>
<li>get the result from db (list all)</li>
<li>get the result from db (list search) </li>
</ol>
<p><strong>index.php</strong></p>
<pre><code>require_once 'grant.php';
require_once 'controller.php';
$controller = new controller();
$controller -> temp_index();
</code></pre>
<p><strong>controller.php</strong></p>
<pre><code>require_once 'model.php';
class controller{
public $model;
public function __construct(){
$this -> model = new model();
}
public function temp_index(){
require 'temp_index.php';
if($_REQUEST['submit'] == 'get_all'){
$result = $this -> model -> get_all();
require 'get_all.php';
}
else if($_REQUEST['submit'] == 'get_search'){
$result = $this -> model -> get_search();
require 'get_search.php';
}
}
}
</code></pre>
<p><strong>model.php</strong> // please ignore not use PDO</p>
<pre><code>class model{
public function get_all(){
$sql = "select * from tb order by id desc";
$query = mysql_query($sql) or die(mysql_error());
$result = array();
while($list = mysql_fetch_array($query)){
$result[] = $list;
}
return $result;
}
public function get_search(){
$search = mysql_real_escape_string($_POST['search']);
$search = trim($search);
if($search !== ''){
$sql = "select * from tb where ac_email like '%$search%'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) > 0){
$result = array();
while($list = mysql_fetch_array($query)){
$result['result'][] = $list;
}
return $result;
}
else{
$result['statu'] = 'can\'t find search';
return $result;
}
}else{
$result['statu'] = 'can\'t find search plz input text';
return $result;
}
}
}
</code></pre>
<p><strong>get_search.php</strong> // view</p>
<pre><code><div class="reslt_get_search">
<?php foreach ($result['result'] as $list) : ?>
<div><?php print"$list[ac_id]";?></div>
<div><?php print"$list[ac_email]";?></div>
<?php endforeach; ?>
<div><?php print"$result[statu]";?></div>
</div>
</code></pre>
<p><strong>temp_index.php</strong> // view</p>
<pre><code><form action="" method="POST">
<input type="submit" name="submit" value="get_all">
</form>
<form action="" method="POST">
<input type="text" name="search">
<input type="submit" name="submit" value="get_search">
</form>
</code></pre>
|
[] |
[
{
"body": "<p><strong>SQL Injection</strong></p>\n\n<p>You don't have to use PDO, but you have to use something to defend against SQL injection, and <code>mysql_real_escape_string</code> isn't it (for one because MySQL is deprecated, and also because it's way too easy to forget to put <code>'</code> around the variable in the query, and once it's forgotten it's hard to see that it's missing). Using prepared statement isn't hard (see <a href=\"http://php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow\">here for mysqli</a> and <a href=\"http://php.net/manual/en/pdo.prepared-statements.php\" rel=\"nofollow\">here for PDO</a>).</p>\n\n<p><strong>Early Return</strong></p>\n\n<p>If you return early, you can often reduce the nesting of if statements:</p>\n\n<pre><code>if($search == ''){\n $result['statu'] = 'can\\'t find search plz input text';\n return $result;\n}\n$sql = \"select * from tb where ac_email like '%$search%'\";\n$query = mysql_query($sql) or die(mysql_error());\n\nif(mysql_num_rows($query) < 0){\n $result['statu'] = 'can\\'t find search';\n return $result;\n}\n[...]\n</code></pre>\n\n<p><strong>Error Messages</strong></p>\n\n<p>I wouldn't just echo <code>mysql_error</code>, as it's probably not that informative for the user, and it might reveal information. Just write a custom error message. </p>\n\n<p>Your current error messages should also be better:</p>\n\n<ul>\n<li><code>can\\'t find search plz input text</code>: could be <code>You did not enter any Search terms.</code></li>\n<li><code>can\\'t find search</code>: could be <code>No results found for your Search term</code>.</li>\n</ul>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>classes should start with an uppercase letter.</li>\n<li><code>temp_index.php</code>: <code>search_form.php</code> would be better.</li>\n<li><code>get_search.php</code>: could be <code>search_result.php</code>.</li>\n<li><code>statu</code> isn't that much shorter than <code>status</code>, just write it completely.</li>\n</ul>\n\n<p><strong>Misc</strong></p>\n\n<ul>\n<li>make your <code>model</code> field private.</li>\n<li>be explicit in your request type. If you send <code>post</code> data, don't just get <code>request</code>, but <code>post</code>.</li>\n<li>don't just die in a model, throw an exception and let the controller handle it (ideally by passing a custom error message to the view).</li>\n<li><code>select *</code> is discouraged, just select what you actually need.</li>\n<li>use more spaces (after <code>print</code>, and after <code>)</code>).</li>\n<li><code>ac_email</code> seems user supplied, so I would filter it with <code>htmlspecialchars</code> before echoing (because of XSS; I hope that you cleaned the email address before inserting it in the database, but you can never be too save).</li>\n</ul>\n\n<p><strong>MVC</strong></p>\n\n<p>There is more than one definition of MVC out there, and especially in web applications the definitions are not all that clear (you can see this if you just do a quick google search, there are a lot of different diagrams out there). For example, the original approach of the model notifying the view of changes in the underlying data (<a href=\"http://lkubaski.files.wordpress.com/2012/12/mvc1.gif?w=550\" rel=\"nofollow\">see graphic here</a>) was abandoned by (most or all) web application frameworks (<a href=\"https://developer.chrome.com/static/images/mvc.png\" rel=\"nofollow\">see graphic here</a>).</p>\n\n<p>I would say that your solution is pretty much complying with the (or better an) MVC approach. You have a light-weight controller which processes user input, you have a view which reacts to the controller, and you have a model.</p>\n\n<p>What you should not do is access <code>$_POST</code> in the model. Just pass it to the model from the controller. And as mentioned above, your model also shouldn't just die.</p>\n\n<p>You could also create a class for the actual data instead of using arrays. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-27T12:05:42.783",
"Id": "68057",
"ParentId": "23160",
"Score": "3"
}
},
{
"body": "<p><strong>Object Oriented Programming Improvements</strong></p>\n\n<p>The first thing you can do to improve code like this is to use dependency injection, instead of instantiating objects with <code>new</code> inside of objects.</p>\n\n<pre><code>// Setup your class hierarchies like this.\n\nabstract class Controller\n{\n protected $model;\n\n protected function __construct(Model $model)\n {\n $this->model = $model;\n }\n}\n\nclass RootController extends Controller // or HomeController extends Controller\n{\n public function __construct(Model $model)\n {\n parent::__construct($model);\n }\n}\n</code></pre>\n\n<p>Then you execute:</p>\n\n<pre><code>$controller = new RootController(new RootModel()); // But, read on.\n</code></pre>\n\n<p>Notice the use of type hinting in the <code>__construct</code> function. Program to an interface, not an implementation. </p>\n\n<p>Use abstract classes (which you cannot make an instance of) to factor out common properties and methods into one place. Extend abstract classes with specific species of classes. This is where the power of polymorphism via the Strategy Pattern comes in to play!</p>\n\n<p>By type hinting with abstract classes, or interface types, you will not have to change your code simply because a different species of child object need to be used at some other point in time.</p>\n\n<p>If you find that the parents of several classes should have the same functionality or constants, factor again and define a PHP Interface and slap it on to a class like this.</p>\n\n<pre><code>class RootController extends Controller implements Printable\n{\n public function __construct(Model $model)\n {\n parent::_construct($model);\n }\n}\n</code></pre>\n\n<p>Where in this case, <code>Printable</code> would be a set of virtual functions, and or constants, that form a contract, forcing any class that implements <code>Printable</code> to define certain public functions / hooks so that it can be used as a \"Printable\" object by unrelated code in other places.</p>\n\n<p><strong>Model-View-Controller Improvements</strong></p>\n\n<p>In terms of MVC, you may want to consider how a <code>Model</code> is going to send data to a <code>View</code>. Using a <code>Controller</code>'s method as the working area for passing dat from a <code>Model</code> to a <code>View</code> is common. If a <code>Controller</code>'s method can act as a working space for a particular command, then \"M\" and \"V\" (<code>Model</code> and <code>View</code>) can use \"C's\" method as a place to coordinate things.</p>\n\n<p>Given the following, you could use your programming knowledge to devise a solution where a <code>View</code> is passed data from a <code>Model</code>, without injecting an instance of said <code>Model</code> into a <code>View</code>. In other words, you do not want to do this.</p>\n\n<pre><code>abstract class View\n{\n protected $model;\n\n protected function __construct(Model $model)\n {\n $this->model = $model;\n }\n}\n\nclass NewsletterView extends View\n{\n public function __construct(Model $model)\n {\n parent::__constrcut($model);\n }\n}\n</code></pre>\n\n<p>Summarizing, there are two well known options:</p>\n\n<ol>\n<li><p>Use a method of a <code>Controller</code> (i.e. a command). Have the <code>Model</code> pass a data structure (array or iterable object) to the <code>View</code>.</p></li>\n<li><p>Give the <code>View</code> a reference to the <code>Model</code> and delegate the chore of getting data to the <code>Model</code> within the <code>View</code>. However, as noted this is not what you want to do.</p></li>\n</ol>\n\n<p>Note that option #2 can create <em>strong coupling</em> between a <code>Model</code> and a <code>View</code>, because the <code>View</code> <em>must then use methods off of the</em> <code>Model</code> instance to get at data. If a <code>Model</code>'s methods change (such as the names, or method parameters), the <code>View</code> will have to change, accordingly.</p>\n\n<p>What you want to do is have a setup like this.</p>\n\n<pre><code>abstract class Controller\n{\n protected $model;\n protected $view;\n\n protected function __construct(Model $model, View $view)\n {\n $this->model = $model;\n $this->view = $view;\n }\n}\n\nclass NewsletterController extends Controller // or HomeController extends Controller\n{\n public function __construct(Model $model, View $view)\n {\n parent::__construct($model, $view);\n }\n\n /**\n * A totally made up method.\n */\n public function register(array $suscriberData) \n {\n $viewData = $this->model->addSubscriber($suscriberData));\n $this->view=>updateRegistrationPage($viewData);\n }\n}\n</code></pre>\n\n<p>Then you execute:</p>\n\n<pre><code>$controller = new NewsletterController(new NewsletterModel(), new NewsletterView());\n</code></pre>\n\n<p>(<strong>Note</strong>: A dependency injection container can resolve class dependencies off screen and just issue you the object you request! Very handy, but not mandatory.)</p>\n\n<p>Your URL to such a command would be:</p>\n\n<p><em><a href=\"http://yourdomain.com/newsletter/register\" rel=\"nofollow noreferrer\">http://yourdomain.com/newsletter/register</a></em></p>\n\n<p>Where \"newsletter\" is your <code>Controller</code>, and \"register\" is the <em>command</em>.</p>\n\n<p>Typically, the machinery of a framework (Front Controller / Router / Dispatcher), or just good programming generally, handles transforming the path component of a URL (<code>REQUEST_URI</code>) into an instance of a <code>Controller</code>. In that case, because instances are being created dynamically, you will want to use a class autoloader (as in <a href=\"https://www.php-fig.org/psr/psr-4/\" rel=\"nofollow noreferrer\">PHP-FIG PSR-4</a>) at minimum. Using an autoloader can eliminate all but one <code>require</code> statement for accessing classes. You will need one <code>require</code> statement to bring your autoloader code into scope. :-)</p>\n\n<p>This is why people are encouraged to use namespaces with their OO PHP code. Using a PSR-4 compliant autoloader will automatically find and load your custom classes! The implication being, that your <code>include_path</code> no longer needs to list every dog-on path that you have classes loading from! ;-)</p>\n\n<p>However, if you use modular HTML templates for your web pages (<code>require header.php</code>, <code>require footer.php</code>, <code>require aside.php</code>, etc ..), be sure to have the location of those files in your <code>include_path</code>!</p>\n\n<p>Dependency injection containers are not mandatory, but they do simplify the usage of objects by decoupling where a class is instantiated from where it is used. In other words, a DI container is a very precise gumball machine for objects and other data. :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:46:23.403",
"Id": "423870",
"Score": "0",
"body": "There is more than one implementation of an MVCish kind of software architecture. Many people use frameworks that adulterate the system. Without bowing to the frameworks and assuming people have to use them; or assuming that the frameworks are right to do it differently; a model that updates a view is the reference we can rely on to have a meaningful conversation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T16:44:53.110",
"Id": "219259",
"ParentId": "23160",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T11:20:05.583",
"Id": "23160",
"Score": "5",
"Tags": [
"php",
"mvc"
],
"Title": "mvc example: form post"
}
|
23160
|
<p>I want to check if the length of phone number is appropriate for specified country (let's consider that only some countries have restriction, another countries accept phone number with various length). I have a Map, where the correct pairs are defined so this map can be used as a reference in the condition:</p>
<pre><code>public static ErrCode checkStatePhoneLen(final String state, final String phoneNo)
{
String stateTmp = state.trim();
String phoneTmp = phoneNo.trim();
Integer phoneLen = new Integer(phoneTmp.length());
if ( statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))
{
return ERROR;
}
return SUCCESS;
}
</code></pre>
<p>My questions are:</p>
<ul>
<li>Is it better to use temporary variables or directly usage of already existed object? I can just use "<code>state.trim()</code>" instead of creating the variable <code>state_tmp</code> and so on. I think that advantages of the solution with temporary variables are better readability and debugging but disadvantages are the effort to create new variable by runtime (or is it optimized someway by compiler?) and more rows of code (but I prefer readability factor more than number of rows factor).</li>
<li><p>is it better to check if map contains the key and then compare, or to get value for given key and then check if it is not null and compare them? As following example:</p>
<p><code>Integer definedLen = (Integer) statePhoneNoMap.get(stateTmp);</code></p>
<p><code>if (definedLen != null && !definedLen.equals(phoneLen)){</code></p></li>
</ul>
<p>In this code sample, there is needed one more variable, but the condition is clearer. And, there is just one operation upon map (<code>get()</code>) instead of two in previous code (<code>containsKey()</code>, <code>get()</code>)</p>
<p>What is better solution? How would you modify this function?</p>
|
[] |
[
{
"body": "<pre><code>public static ErrCode checkStatePhoneLen(final String state, final String phoneNo) \n{\n String stateTmp = state.trim();\n String phoneTmp = phoneNo.trim();\n</code></pre>\n\n<p>The issue is that <code>stateTmp</code> is less readable than <code>state.trim()</code>, so if you want to create a new variable, make sure that the name carries your intent. You can go for \"normalizedState\", but since you're only trimming (and are not normalizing capitalization for example) then a variable is useless.</p>\n\n<pre><code> Integer phoneLen = new Integer(phoneTmp.length());\n</code></pre>\n\n<p>This one is useful! <code>phoneLen</code> is clearer than <code>phoneNo.trim().length()</code>. This answers your <strong>first question</strong>: it depends! Use new variable names when they do make thing clearer, but never use dummy names like <code>phoneTmp</code>, <code>phone1</code>, and so on. By the way, I may be mistaken, but are you certain <code>Integer</code> is necessary? Java should do autoboxing. I would simply write <code>int phoneLen = phoneNo.trim().length()</code>.</p>\n\n<pre><code> if (statePhoneNoMap.containsKey(stateTmp) && !phoneLen.equals(statePhoneNoMap.get(stateTmp)))\n {\n return ERROR;\n }\n return SUCCESS;\n</code></pre>\n\n<ol>\n<li>To <strong>answer your second question</strong>, you don't need to explicitely check for null: it's simpler to compare <code>phoneLen</code> and <code>statePhoneNoMap.get(stateTmp)</code> directly. If the latter is null, then the comparison will return false. If <code>phoneLen</code> is null, you don't want to return a value but throw an exception anyway, and this is what happens with your current code because <code>null.equals(...)</code> throws.</li>\n<li>It makes more sense to check for success and return <code>ERROR</code> if something went wrong.</li>\n<li>If you have an <code>ErrCode</code> type instead of a boolean, you have to return more explicit codes! Otherwise just return the condition directly.</li>\n</ol>\n\n<p>The code becomes:</p>\n\n<pre><code>public static ErrCode checkStatePhoneLen(final String state, final String phoneNo) \n{\n int phoneLen = phoneNo.trim().length();\n int stateTrimmed = state.trim();\n\n if (statePhoneNoMap.containsKey(stateTrimmed)\n && phoneLen == statePhoneNoMap.get(stateTrimmed))\n {\n return SUCCESS;\n }\n return ERROR;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:50:42.433",
"Id": "35730",
"Score": "0",
"body": "Thank you for answer. +1 for writing which one new variable is useful and why. I agree with you. The Map can contain just Object, no int type, that's the reason I use Integer (maybe I am wrong). If the state is not in map, I want to return SUCCESS. The comparing of int and null won't work in required way. I agree with points 4 and 5, I just use it in this way to simplify code and point only to issue with objects. The rest of code was deleted, modified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:01:12.577",
"Id": "35731",
"Score": "1",
"body": "@srnka Why don't you use [generics](http://docs.oracle.com/javase/tutorial/extra/generics/index.html)? Something like: `Map<Integer, Integer> statePhoneNoMap = new HashMap<Integer, Integer>()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T16:11:04.890",
"Id": "35734",
"Score": "0",
"body": "I use it: Map<String, Integer> statePhoneNoMap = new HashMap<String, Integer>(); So there is Integer, no int."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:37:11.107",
"Id": "35750",
"Score": "2",
"body": "Then, look at [autoboxing](http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T09:23:11.880",
"Id": "35800",
"Score": "0",
"body": "Thank you for link to autoboxing, I modify my function :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:50:48.030",
"Id": "35818",
"Score": "1",
"body": "\"I think (but could be wrong) that the comparison can simply use == since you are comparing ints\". No, both are Integers. If we change the method variable to int, we could get a NullPointerException because the vm tries to promote a null to int."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T07:33:35.487",
"Id": "35857",
"Score": "0",
"body": "srnka, thanks to @tb-, I realized that promoting a null to an int throws a NullPointerException, so I edited my answer to reflect this. Still untested, so it could contain errors."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T14:56:36.543",
"Id": "23165",
"ParentId": "23163",
"Score": "7"
}
},
{
"body": "<p>You should raise the level of abstraction and define the specific types <code>State</code> and <code>PhoneNumber</code>.</p>\n\n<p>In this way you can move the validation of the data where you build the objects removing all the cruft related to the fact that you use strings to represent higher level concepts.</p>\n\n<p>You then need to put in <code>PhoneNumber</code> a method that returns the corresponding state (maybe using a <code>static Map<Prefix, State></code> it is enough, even it is a little dirty).</p>\n\n<p>The method you need then turns into checking that the returned <code>State</code> is equal to the one passed to the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T09:28:11.307",
"Id": "35801",
"Score": "0",
"body": "Thank you, in first moment I thought that I design it in this way: new object and check of correctness of values in constructor. Since my code is just about parsing data from input, evaluating their correctness and put to output, I consider this as not useful - for this particular case. In global, I think it is good idea to raise the level of abstraction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T13:54:12.267",
"Id": "35873",
"Score": "0",
"body": "@srnka mariosangiorgio has a very good point here. Even if you don't abstract the state into an object as he suggests, you should at least move the trimming of the state (and the phone number) outside the `checkStatePhoneLen` function, since you'll most likely be needing those trimmed values in other contexts anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:16:50.703",
"Id": "23169",
"ParentId": "23163",
"Score": "4"
}
},
{
"body": "<p>I agree in a lot of thoughts from Quentin Pradet and mariosangiorgio. </p>\n\n<p>I will add some other viewpoint:</p>\n\n<blockquote>\n <p>Is it better to use temporary variables or directly usage of already existed object? I can just use \"state.trim()\" instead of creating the variable state_tmp and so on. I think that advantages of the solution with temporary variables are better readability and debugging but disadvantages are the effort to create new variable by runtime (or is it optimized someway by compiler?) and more rows of code (but I prefer readability factor more than number of rows factor).</p>\n</blockquote>\n\n<p>My personal rule is: If in doubt, create a variable with a good name. This leads to 2 results in this case:<br>\n1) I would avoid using tmp inside the variable. Instead of <code>stateTmp</code> use <code>trimmedState</code> or <code>stateTrimmed</code>. A name should always have a meaning. Temp or tmp is one of the worst choices (behind data). Same goes for <code>phoneTmp</code>. </p>\n\n<p>2a) I would not use a new variable for trimmed state. It is very clear from <code>state.trim()</code> what we have.<br>\n2b) I would use the new variable <code>final int phoneNumberLength = phoneNumber.trim().length();</code> This describes what we have. It is not directly clear from <code>phoneNumber.trim().length()</code>, one have to think what is happening here.</p>\n\n<blockquote>\n <p>is it better to check if map contains the key and then compare, or to get value for given key and then check if it is not null and compare them?</p>\n</blockquote>\n\n<p>I would get the value and check for null. My usual pattern is:</p>\n\n<pre><code>variable = ...\nif (something is wrong with variable){\n exit / failure handling\n}\ncontinue with normal code\n</code></pre>\n\n<p>This reduces branches, which reduces time finding out in which branch we are and what is the current state. It is always a bad sign if your indentation is somewhere in the 5. or 6. level. It is not so obvious from this small example, but will easily count on more complex code.</p>\n\n<hr>\n\n<pre><code>ErrCode\n</code></pre>\n\n<p>If it is an error code, name it ErrorCode. There is most probably not any reason to abbreviate it to ErrCode. Even more, if you have only 2 error codes, you should continue using boolean and if you have more complex things, it could be interesting to use exceptions. I do not like to return error codes, but this are probably just the results of bad experiences from C.</p>\n\n<hr>\n\n<pre><code>public static ErrCode checkStatePhoneLen(final String state, final String phoneNo)\n</code></pre>\n\n<p>Again, avoid abbreviations. And try to find method names, where you could \"read\" the source code.<br>\n<code>if (checkStatePhoneLen(...))</code> could not be read in a normal way, because you have to look up what is the expected result. Is it true or is it false? If you use a name like <code>isPhoneNumberCorrectForState</code>, you will have <code>if(isPhoneNumberCorrectForState(...))</code> which is completely clear for the reader.<br>\nIf ErrCode is an enum and you do a comparison like <code>if (checkStatePhoneLen(...) == ERROR)</code> then you should name it <code>getErrorCodeForPhoneNumberCorrectnessForState</code>. Which starts to be clumpy, which is a good sign to refactoring as mariosangiorgio suggested.</p>\n\n<hr>\n\n<p>If you put everything together, it could be something like this:</p>\n\n<pre><code>public static boolean isPhoneNumberCorrectForState(final String phoneNumber, final String state) {\n final int phoneNumberLength = phoneNumber.trim().length();\n\n final Integer maximumPhoneNumberLength = mapStateToMaximumPhoneNumberLength.get(state.trim());\n\n if (maximumPhoneNumberLength != null && phoneNumberLength > maximumPhoneNumberLength) {\n return false;\n }\n return true;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T20:14:32.923",
"Id": "23234",
"ParentId": "23163",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23165",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T14:17:34.980",
"Id": "23163",
"Score": "5",
"Tags": [
"java",
"optimization"
],
"Title": "Defining of new, temporary, variables or usage of already known ones?"
}
|
23163
|
<p>What is the difference between this two way and Which one is best? What do you suggest?</p>
<p><strong>1.</strong><br>
Use of query (db) directly in CI_Controller. as:</p>
<pre><code>$id = $this->input->post('id');
$query = $this->db->get_where('table1', array('id' => $id))->row();
$this->db->get_where('table2', array('idre' => $query->idre));
</code></pre>
<p><strong>Or</strong></p>
<p><strong>2.</strong><br>
Use of query (db) in CI_Model and call it in CI_Controller. as:</p>
<p>CI_Model:</p>
<pre><code>function GetWhere($table,$where){
return $this->db->get_where($table, $where);
}
</code></pre>
<p>CI_Controller:</p>
<pre><code>$id = $this->input->post('id');
$query = $this->model_name->GetWhere('table1', array('id' => $id))->row();
$this->model_name->GetWhere('table2', array('idre' => $query->idre));
</code></pre>
<p><strong>UPDATE:</strong></p>
<p><strong>3.</strong> <br>
I use the following code true in model as mvc?</p>
<pre><code>$id = $this->input->post('checked');
foreach ($id as $val) {
$query_check = $this->db->get_where(table3, array('id'=>$val));
$row = $query_check->row();
if($query_check->num_rows() > 0 || $row->id != $this->session->userdata('id')){
foreach ($query_check->result() as $value) {
$id_relation = $value->id_relation;
$this->db->where('idre', $idre)->delete(array(table3, 'table4'));
}
}
}
</code></pre>
<p>Whether this is a good example of mvc? How can fix 2 example above for good mvc?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>What is the difference between this two way and Which one is best? What do you suggest?</p>\n</blockquote>\n\n<p>The difference is that you seperate the concerns in the second example. This means that you can change from database type (e.g. a SQL database, a XML file, an array, ect.) without changing to much code. In fact, you only create a new Model and you are ready!</p>\n\n<blockquote>\n <p>Whether this is a good example of mvc? How can fix 2 example above for good mvc?</p>\n</blockquote>\n\n<p>I think you mean that you want to know if this is correct MVC and, if not, how to change it. It is better to put all those logic (except the first line) inside a Model and call that specific method inside your controller. I have used CI once, so I can't help you with code examples...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:08:00.137",
"Id": "23166",
"ParentId": "23164",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T14:48:25.087",
"Id": "23164",
"Score": "0",
"Tags": [
"php",
"codeigniter"
],
"Title": "A good example of codeigniter MVC?"
}
|
23164
|
<p>I can't get a peer review where I work, I was wondering how my code was and how could it be improved.</p>
<p><a href="https://github.com/lamondea/uploader" rel="nofollow">https://github.com/lamondea/uploader</a></p>
<p>Is it a good practice to use functions in classes or should it be replaced by external function that use the object returned by the class:</p>
<pre><code>class _export
{
public $nbr;
public $file;
public function __construct($file,$nbr=0){
if($nbr != 0 && ($file->ext == 'jpg' || $file->ext == 'png' || $file->ext == 'gif'))
thumbnailer($file,$nbr);
else {
move_uploaded_file($file->tmp_name, ($file->loc).($file->name));
return $file->name;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:53:27.283",
"Id": "35752",
"Score": "0",
"body": "I really never used peer review and I just started using classes, so I guess the whole /class/uploader.class.php would be the important for that matter. I will add a part, but still it would be hard to choose a part since the uploader work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T08:36:57.583",
"Id": "35797",
"Score": "2",
"body": "Two general things about the code, 1) class name shouldn't start with \"_\", 2) Looks like you are doing the validation in constructor which is not good. Let the constructor just for initialization stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T13:46:02.067",
"Id": "35805",
"Score": "0",
"body": "Is there a norm about naming the classes?"
}
] |
[
{
"body": "<p>I'm not sure if using classes is better or worse but I am starting to see files being called as functions more than a single file with function within. This is a more common upload script.</p>\n\n<pre><code>$allowedExts = array(\"gif\", \"jpeg\", \"jpg\", \"png\");\n$temp = explode(\".\", $_FILES[\"file\"][\"name\"]);\n$extension = end($temp);\n\nif ((($_FILES[\"file\"][\"type\"] == \"image/gif\")\n || ($_FILES[\"file\"][\"type\"] == \"image/jpeg\")\n || ($_FILES[\"file\"][\"type\"] == \"image/jpg\")\n || ($_FILES[\"file\"][\"type\"] == \"image/pjpeg\")\n || ($_FILES[\"file\"][\"type\"] == \"image/x-png\")\n || ($_FILES[\"file\"][\"type\"] == \"image/png\"))\n && ($_FILES[\"file\"][\"size\"] < 20000)\n && in_array($extension, $allowedExts)){\n if ($_FILES[\"file\"][\"error\"] > 0){\n echo \"Error: \" . $_FILES[\"file\"][\"error\"] . \"<br>\";\n }\n else{\n echo \"Upload: \" . $_FILES[\"file\"][\"name\"] . \"<br>\";\n echo \"Type: \" . $_FILES[\"file\"][\"type\"] . \"<br>\";\n echo \"Size: \" . ($_FILES[\"file\"][\"size\"] / 1024) . \" kB<br>\";\n echo \"Stored in: \" . $_FILES[\"file\"][\"tmp_name\"];\n }\n}\nelse{\n echo \"Invalid file\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T20:53:56.583",
"Id": "54494",
"Score": "0",
"body": "The `$allowedExts` array is a good idea! You could use a similar array for `$_FILES[\"file\"][\"type\"]` too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T21:13:56.920",
"Id": "54495",
"Score": "1",
"body": "Agreed, i would shorten this and say if($_FILES[\"file\"][\"type\"] is in $ArrayofMetaData) or something to that affect. It would look much cleaner."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T19:59:16.680",
"Id": "33951",
"ParentId": "23177",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:14:02.243",
"Id": "23177",
"Score": "3",
"Tags": [
"php"
],
"Title": "File uploader in php"
}
|
23177
|
<p>A <a href="https://stackoverflow.com/a/15090751/1968">post by Yakk</a> alerted me to the idea of named operators in C++. This look splendid (albeit <strong>very</strong> unorthodox). For instance, the following code can be made to compile trivially:</p>
<pre><code>vector<int> vec{ 1, 2, 3 };
cout << "3 in " << vec << ": " << (3 <in> vec) << '\n'
<< "5 in " << vec << ": " << (5 <in> vec) << '\n';
</code></pre>
<p>Of course the whole thing has to be generic so any binary function-like thing can be used to define operators, e.g.</p>
<pre><code>auto in = make_named_operator(
[](int i, vector<int> const& x) {
return find(begin(x), end(x), i) != end(x);
});
</code></pre>
<p>I’d like to know whether the following implementation is sufficient to handle all “interesting”<sup>1</sup> cases, and whether it’s robust. For instance, I’m storing the operands in references. That should work since they’re only stored until after the expression has completed, and thus should never go stale. I’m especially interested in feedback on the return types of the operator functions below and on the design rationale of using the <code><…></code> syntax for named operators.<sup>2</sup></p>
<p>It <em>seems</em> to handle templates as well as a mixture of different types (and cv-qualification).</p>
<pre><code>#include <utility>
template <typename F>
struct named_operator_wrapper {
F f;
};
template <typename T, typename F>
struct named_operator_lhs {
F f;
T& value;
};
template <typename T, typename F>
inline named_operator_lhs<T, F> operator <(T& lhs, named_operator_wrapper<F> rhs) {
return {rhs.f, lhs};
}
template <typename T, typename F>
inline named_operator_lhs<T const, F> operator <(T const& lhs, named_operator_wrapper<F> rhs) {
return {rhs.f, lhs};
}
template <typename T1, typename T2, typename F>
inline auto operator >(named_operator_lhs<T1, F> const& lhs, T2 const& rhs)
-> decltype(lhs.f(std::declval<T1>(), std::declval<T2>()))
{
return lhs.f(lhs.value, rhs);
}
template <typename T1, typename T2, typename F>
inline auto operator >=(named_operator_lhs<T1, F> const& lhs, T2 const& rhs)
-> decltype(lhs.value = lhs.f(std::declval<T1>(), std::declval<T2>()))
{
return lhs.value = lhs.f(lhs.value, rhs);
}
template <typename F>
inline constexpr named_operator_wrapper<F> make_named_operator(F f) {
return {f};
}
</code></pre>
<p>For the interested, <a href="https://github.com/klmr/named-operator" rel="noreferrer">a full example implementation is on GitHub</a>.</p>
<hr>
<p><sup>1</sup> <insert your definition of “interesting” here></p>
<p><sup>2</sup> I considered other alternatives, such as <code>%…%</code> which is used by R, and allowing different operators (as done by Yakk) to allow for different operator precedences but I decided against that because I think it makes operator precedence even more complicated than it already is in C++.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T18:25:07.807",
"Id": "35755",
"Score": "8",
"body": "Now C++ has `<tothepowerof>` operator"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:46:27.223",
"Id": "35957",
"Score": "4",
"body": "Very clever. **BUT** with great power comes the opportunity to abuse and confuse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T16:14:32.573",
"Id": "73909",
"Score": "1",
"body": "I think that all `operator` may be `constexpr`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-17T09:54:19.043",
"Id": "198006",
"Score": "4",
"body": "@LokiAstari : `Very clever. BUT with great power comes the opportunity to abuse and confuse` : That's a Java thing... :-) ... The C++ version of the proverb would be \"With great power comes great responsibility\", and we are engineers, not script kiddies... My guess is that in *some* cases, it can be incredibly useful, and I'm happy to have discovered (two years after the fact) Konrad's work on GitHub, because it adds alternatives..."
}
] |
[
{
"body": "<p>I would add rvalue reference support with moving of temporaries.</p>\n\n<p><code><op></code> seems to be too low precidence to be practical - you end up having to <code>(bracket)</code> everything (as demonstrated above). % at least binds tightly.</p>\n\n<p>I do like <code>a <op>= b</code>. Better than my <code>a +op= b</code>.</p>\n\n<p>Forwarding <code>operator()</code> from the operator to the function lets you forget the function behind the operator entirely: <code>in(3, vec)</code> -- very Haskell.</p>\n\n<p>N ary infix operators that defer application of <code>f</code> allow <code>s <append> s2 <append> s3</code> to run as efficiently as possible. But doing that cleanly might be hard.</p>\n\n<p>Not sure what <code>inline</code> is intended to do above.</p>\n\n<p>For an interesting test case, implement <code>(std::future<T> %then% [](T)->U)->std::future<U></code> (where that lambda is a placeholder for a functor)</p>\n\n<p>Block some copy and move ctors to prevent persistance, and friend the approriate operators.</p>\n\n<p>As noted, I allowed arbitrary binary operators (chosen when you <code>make_infix</code>) to bracket the named operator: the precidence of the resulting named operator exactly matches the bracketing operators. So <code>+append+</code> has precidence of <code>+</code> and <code>*in*</code> has precidence of <code>*</code>. Of the 3 first use cases (lin alg, container append, then) for two of them the named operators where variants of existing operators, and matching their precidence seemed useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T09:11:36.597",
"Id": "35799",
"Score": "0",
"body": "`inline` is there to make this ODR compliant. I’m never sure whether templates actually need this (non-templates definitely do) but always adding it doesn’t hurt. Thanks for the feedback, those are some interesting ideas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T21:53:25.833",
"Id": "35835",
"Score": "0",
"body": "@KonradRudolph templates are always inline (except perhaps for extern templates which nobody uses)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T22:07:24.673",
"Id": "35837",
"Score": "2",
"body": "@Zoidberg (fully) specialized template functions do need `inline` apparently. And it is harmless elsewhere..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-18T16:12:49.057",
"Id": "151833",
"Score": "1",
"body": "@KonradRudolph So, I edited the [original post](http://stackoverflow.com/a/15090751/1774667) to include a dozen-line named operator library that uses ADL and tags. `struct op_tag {}; static named_operators::make_operator<op_tag> op;` then `invoke( lhs, op_tag, rhs )` is called when the `lhs *op* rhs` happens in an ADL-enabled context. Means you don't need to use a function object, and you have full overload machinery available: someone can even overload your operator in their own namespace for their own types. It seems much cleaner than the single function object approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T12:44:25.033",
"Id": "474654",
"Score": "0",
"body": "I like your solution so much. I have felt the need for named operators. However a problem with this is that autofomatters (e.g. clang format) will mess up the nice `a <op> b` into `a < op > b`. The only thing I found that keeps the white spaces as indented are increment/decrement operators: `a --op-- b`. Any other solutions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T22:01:10.423",
"Id": "474865",
"Score": "0",
"body": "@bolov Yes, autoformatters prevent communicating meaning with whitespace."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T00:35:10.850",
"Id": "23195",
"ParentId": "23179",
"Score": "19"
}
},
{
"body": "<p>I'm not a language lawyer (merely a dabbler), but the idea is interesting, and I'm quite fan of the brakets <code><op></code> flavor of the named operator.</p>\n\n<p>Why not add unary operators?</p>\n\n<p>This would make the following code possible:</p>\n\n<pre><code>c = a <op> b ; // your code\nc = !op> a ; // asymmetrical prefix named operator\nc = --op> a ; // symmetrical prefix named operator\nc = a <op-- ; // symmetrical suffix named operator\n</code></pre>\n\n<p>I had a (nostalgia-based) preference for <code>!</code>, but there aren't a lot of available operators in C++ that can be symmetrical, and <code>--</code> and <code>++</code> are high in priority order.</p>\n\n<p>In the other hand, simple function calls already do that nicely (but for the suffix notation):</p>\n\n<pre><code>c = !op> a ; // asymmetrical prefix named operator\nc = op(a) ; // function notation\n\nc = --op> a ; // symmetrical prefix named operator\nc = a <op-- ; // symmetrical suffix named operator\n</code></pre>\n\n<p>... Is there a domain where writing --op> alongside would be cleared than writing op() alongside ?</p>\n\n<p>If yes, then aren't unary operators definitely needed?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-17T12:09:08.317",
"Id": "198031",
"Score": "1",
"body": "“... Is there a domain where writing --op> alongside would be cleared than writing op() alongside ?” — I think that’s the crux of the question, and I’m not sure that’s the case (although I can think of potential situations, such as matrix transposition)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-17T11:11:53.410",
"Id": "107861",
"ParentId": "23179",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23195",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T18:21:20.023",
"Id": "23179",
"Score": "52",
"Tags": [
"c++",
"c++11",
"operator-overloading"
],
"Title": "Named operators in C++"
}
|
23179
|
<p>I like the radix function and found a really neat way to compute its inverse in Python with a lambda and <code>reduce()</code> (so I really feel like I'm learning my cool functional programming stuff):</p>
<pre><code>def unradix(source,radix):
# such beauty
return reduce(lambda (x,y),s: (x*radix,y+s*x), source, (1,0))
</code></pre>
<p>where:</p>
<pre><code>>>> unradix([1,0,1,0,1,0,1],2)
(128,85)
</code></pre>
<p>But its dizygotic twin is unable to use the same pattern without an ugly hack:</p>
<pre><code>def radix(source,radix):
import math
hack = 1+int(math.floor(math.log(source)/math.log(radix)))
# ^^^^ ... _nearly_ , such beauty
return reduce(lambda (x,y),s: (x/radix,y+[x%radix]), xrange(hack), (source,[]))
</code></pre>
<p>where:</p>
<pre><code>>>> radix(85,2)
(0, [1, 0, 1, 0, 1, 0, 1])
</code></pre>
<p>How can I remove the hack from this pattern? Or failing that, how can I rewrite this pair of functions and inverse so they use the same pattern, and only differ in "mirror-symmetries" as much as possibly?</p>
<p>By mirror symmetry I mean something like the way <em>increment</em> and <em>decrement</em> are mirror images, or like the juxtaposition of <code>x*radix</code> versus <code>x/radix</code> in the same code location as above.</p>
|
[] |
[
{
"body": "<p>The reverse operation to folding is unfolding. To be honest, I'm not very\nfluent in python and I couldn't find if python has an unfolding function.\n(In Haskell we have\n<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3afoldr\" rel=\"nofollow\">foldr</a>\nand its complement \n<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3aunfoldr\" rel=\"nofollow\">unfoldr</a>.)</p>\n\n<p>Nevertheless, we can easily construct one:</p>\n\n<pre><code>\"\"\"\nf accepts a value and returns None or a pair.\nThe first element of the pair is the next seed,\nthe second element is the value to yield.\n\"\"\"\ndef unfold(f, r):\n while True:\n t = f(r);\n if t:\n yield t[1];\n r = t[0];\n else: \n break;\n</code></pre>\n\n<p>It iterates a given function on a seed until it returns <code>None</code>, yielding intermediate results. It's dual to <code>reduce</code>, which takes a function and an iterable and produces a value. On the other hand, <code>unfold</code> takes a value and a generating function, and produces a generator. For example, to create a list of numbers from 0 to 10 we could write:</p>\n\n<pre><code>print list(unfold(lambda n: (n+1, n) if n <= 10 else None, 0));\n</code></pre>\n\n<p>(we call <code>list</code> to convert a generator into a list).</p>\n\n<p>Now we can implement <code>radix</code> quite nicely:</p>\n\n<pre><code>def radix(source, radix):\n return unfold(lambda n: divmod(n, radix) if n != 0 else None, source);\n\nprint list(radix(12, 2));\n</code></pre>\n\n<p>prints <code>[0, 0, 1, 1]</code>.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Folding (<code>reduce</code>) captures the pattern of consuming lists. Any function that sequentially consumes a list can be eventually written using <code>reduce</code>. The first argument to <code>reduce</code> represents the core computation and the third argument, the accumulator, the state of the loop. Similarly, unfolding (my <code>unfold</code>) represents the pattern of producing lists. Again, any function that sequentially produces a list can be eventually rewritten using <code>unfold</code>.</p>\n\n<p>Note that there are functions that can be expressed using either of them, as we can look at them as functions that produce or consume lists. For example, we can implement <code>map</code> (disregarding any efficiency issues) as</p>\n\n<pre><code>def map1(f, xs):\n return reduce(lambda rs, x: rs + [f(x)], xs, [])\n\ndef map2(f, xs):\n return unfold(lambda xs: (xs[1:], f(xs[0])) if xs else None, xs)\n</code></pre>\n\n<hr>\n\n<p>The duality of <code>reduce</code> and <code>unfold</code> is nicely manifested in a technique called <a href=\"https://en.wikipedia.org/wiki/Deforestation_%28computer_science%29\" rel=\"nofollow\">deforestation</a>. If you know that you create a list using <code>unfold</code> only to consume it immediately with <code>reduce</code>, you can combine these two operations into a single, higher-order function that doesn't build the intermediate list:</p>\n\n<pre><code>def deforest(foldf, init, unfoldf, seed):\n while True:\n t = unfoldf(seed);\n if t:\n init = foldf(t[1], init);\n seed = t[0];\n else:\n return init;\n</code></pre>\n\n<p>For example, if we wanted to compute the sum of digits of 127 in base 2, we could call</p>\n\n<pre><code>print deforest(lambda x,y: x + y, 0, # folding part\n lambda n: divmod(n, 2) if n != 0 else None, # unfolding\n 127); # the seed\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T21:47:34.107",
"Id": "35769",
"Score": "0",
"body": "A beautiful and symmetric radix! A *great* explanation as well. Thanks for teach me, and \"us\", something!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T22:33:46.853",
"Id": "35772",
"Score": "0",
"body": "(in spirit) +1 for deforest, that *soo* cool."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T22:47:30.013",
"Id": "35773",
"Score": "0",
"body": "@PetrPudlák so I understand, we are using our function (that would have been in unfold) on init, one time, then we are using our fold function on the yield value of that 'unfold' function, and accumulating that into init. And we are 're'-unfolding with the seed value. So we interleave folding into init, and unfolding out of seed. If we were to capture the sequences of seed and init, they would reproduce the lists being produced and consumed at each step of the deforest while loop. Does that sound right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T08:01:45.600",
"Id": "35795",
"Score": "0",
"body": "@CrisStringfellow Yes, it's just like you say."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T08:02:43.853",
"Id": "35796",
"Score": "0",
"body": "@PetrPudlák good to know, thanks. Now I have learnt something else. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T21:37:19.217",
"Id": "23188",
"ParentId": "23180",
"Score": "4"
}
},
{
"body": "<p>I modified the answer by Petr Pudlák slightly, changing the <strong>unfold</strong> function to yield the last seed before exhaustion as it ends. </p>\n\n<pre><code>def unfold(f, r):\n while True:\n t = f(r)\n if t:\n yield t[1]\n r = t[0]\n else: \n yield r #<< added\n break\n</code></pre>\n\n<p>This enables some kind of accumulated value to be kept, like in the original <strong>unradix</strong> we can keep the highest power of the base greater than the source number. </p>\n\n<p>Using the modified <strong>unfold</strong> function we can keep it here, too. To do so I modified the radix like so:</p>\n\n<pre><code>def radix(source,radix):\n return unfold(lambda (n,maxpow): ((n/radix, maxpow*radix), n%radix) if n !=0 else None, (source,1))\n</code></pre>\n\n<p>I prefer my version better, since it keeps the first seed tuple <code>(source,1)</code> which is similar to the one for <strong>unradix</strong> , <code>(1,0)</code> each containing the appropriate identity for multiplicative or additive accumulation. And it outputs the radix as well as the highest power. </p>\n\n<pre><code>>>> list(totesweird.radix(121,3))\n[1, 1, 1, 1, 1, (0, 243)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T22:20:44.630",
"Id": "23190",
"ParentId": "23180",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "23188",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T18:25:39.303",
"Id": "23180",
"Score": "3",
"Tags": [
"python",
"functional-programming",
"lambda"
],
"Title": "Removing hackery from pair of radix functions"
}
|
23180
|
<p>I've written a SELECT statement that creates a List of all objects that depend on a single object, so that if I wanted to DROP that object I could DROP all referenced objects first without using CASCADE.</p>
<p>It's a long script and I'm not sure if it's gonna work in every situation, so I just wanted to ask if I've missed something or if there is a way to optimize / shorten this script.</p>
<pre><code>WITH RECURSIVE dep_recursive AS (
-- Recursion: Initial Query
SELECT
0 AS "level",
'enter_object_name' AS "dep_name", -- <- define dependent object HERE
'' AS "dep_table",
'' AS "dep_type",
'' AS "ref_name",
'' AS "ref_type"
UNION ALL
-- Recursive Query
SELECT
level + 1 AS "level",
depedencies.dep_name,
depedencies.dep_table,
depedencies.dep_type,
depedencies.ref_name,
depedencies.ref_type
FROM (
-- This function defines the type of any pg_class object
WITH classType AS (
SELECT
oid,
CASE relkind
WHEN 'r' THEN 'TABLE'::text
WHEN 'i' THEN 'INDEX'::text
WHEN 'S' THEN 'SEQUENCE'::text
WHEN 'v' THEN 'VIEW'::text
WHEN 'c' THEN 'TYPE'::text -- note: COMPOSITE type
WHEN 't' THEN 'TABLE'::text -- note: TOAST table
END AS "type"
FROM pg_class
)
-- Note: In pg_depend, the triple (classid,objid,objsubid) describes some object that depends
-- on the object described by the tuple (refclassid,refobjid).
-- So to drop the depending object, the referenced object (refclassid,refobjid) must be dropped first
SELECT DISTINCT
-- dep_name: Name of dependent object
CASE classid
WHEN 'pg_class'::regclass THEN objid::regclass::text
WHEN 'pg_type'::regclass THEN objid::regtype::text
WHEN 'pg_proc'::regclass THEN objid::regprocedure::text
WHEN 'pg_constraint'::regclass THEN (SELECT conname FROM pg_constraint WHERE OID = objid)
WHEN 'pg_attrdef'::regclass THEN 'default'
WHEN 'pg_rewrite'::regclass THEN (SELECT ev_class::regclass::text FROM pg_rewrite WHERE OID = objid)
WHEN 'pg_trigger'::regclass THEN (SELECT tgname FROM pg_trigger WHERE OID = objid)
ELSE objid::text
END AS "dep_name",
-- dep_table: Name of the table that is associated with the dependent object (for default values, triggers, rewrite rules)
CASE classid
WHEN 'pg_constraint'::regclass THEN (SELECT conrelid::regclass::text FROM pg_constraint WHERE OID = objid)
WHEN 'pg_attrdef'::regclass THEN (SELECT adrelid::regclass::text FROM pg_attrdef WHERE OID = objid)
WHEN 'pg_trigger'::regclass THEN (SELECT tgrelid::regclass::text FROM pg_trigger WHERE OID = objid)
ELSE ''
END AS "dep_table",
-- dep_type: Type of the dependent object (TABLE, FUNCTION, VIEW, TYPE, TRIGGER, ...)
CASE classid
WHEN 'pg_class'::regclass THEN (SELECT TYPE FROM classType WHERE OID = objid)
WHEN 'pg_type'::regclass THEN 'TYPE'
WHEN 'pg_proc'::regclass THEN 'FUNCTION'
WHEN 'pg_constraint'::regclass THEN 'TABLE CONSTRAINT'
WHEN 'pg_attrdef'::regclass THEN 'TABLE DEFAULT'
WHEN 'pg_rewrite'::regclass THEN (SELECT TYPE FROM classType WHERE OID = (SELECT ev_class FROM pg_rewrite WHERE OID = objid))
WHEN 'pg_trigger'::regclass THEN 'TRIGGER'
ELSE objid::text
END AS "dep_type",
-- ref_name: Name of referenced object (the object that depends on the dependent object)
CASE refclassid
WHEN 'pg_class'::regclass THEN refobjid::regclass::text
WHEN 'pg_type'::regclass THEN refobjid::regtype::text
WHEN 'pg_proc'::regclass THEN refobjid::regprocedure::text
ELSE refobjid::text
END AS "ref_name",
-- ref_type: Type of the referenced object (TABLE, FUNCTION, VIEW, TYPE, TRIGGER, ...)
CASE refclassid
WHEN 'pg_class'::regclass THEN (SELECT TYPE FROM classType WHERE OID = refobjid)
WHEN 'pg_type'::regclass THEN 'TYPE'
WHEN 'pg_proc'::regclass THEN 'FUNCTION'
ELSE refobjid::text
END AS "ref_type",
-- dependency type: Only 'normal' dependencies are relevant for DROP statements
CASE deptype
WHEN 'n' THEN 'normal'
WHEN 'a' THEN 'automatic'
WHEN 'i' THEN 'internal'
WHEN 'e' THEN 'extension'
WHEN 'p' THEN 'pinned'
END AS "dependency type"
FROM pg_catalog.pg_depend
WHERE deptype = 'n' -- look at normal dependencies only
AND refclassid NOT IN (2615, 2612) -- schema and language are ignored as dependencies
) depedencies
-- Recursion: Join with results of last query, search for dependencies recursively
JOIN dep_recursive ON (dep_recursive.dep_name = depedencies.ref_name)
WHERE depedencies.ref_name NOT IN(depedencies.dep_name, depedencies.dep_table) -- no self-references
)
-- Select and filter the results of the recursive query
SELECT
MAX(level) AS "level", -- drop highest level first, so no other objects depend on it
dep_name, -- the object to drop
MIN(dep_table) AS "dep_table", -- the table that is associated with this object (constraints, triggers)
MIN(dep_type) AS "dep_type", -- the type of this object
string_agg(ref_name, ', ') AS "ref_names", -- list of objects that depend on this (just FYI)
string_agg(ref_type, ', ') AS "ref_types" -- list of their respective types (just FYI)
FROM dep_recursive
WHERE level > 0 -- ignore the initial object (level 0)
GROUP BY dep_name -- ignore multiple references to dependent objects, dropping them once is enough
ORDER BY level desc, dep_name; -- level descending: deepest dependency first
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-21T08:16:14.270",
"Id": "253824",
"Score": "0",
"body": "I'm having difficulties to make this work on version 9.2.x. I have no result, this seems to be tied to dependent object name format. Could you give some example ? I'm trying to use this script to find the dependee of a table."
}
] |
[
{
"body": "<p>Looks good! Seemed to work for me, except in postgres 9.3 (harmless in previous) add:</p>\n\n<pre><code> WHEN 'm' THEN 'MATERIALIZED VIEW'::text\n</code></pre>\n\n<p>in the classType subquery.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T05:30:40.783",
"Id": "53290",
"Score": "0",
"body": "Btw ... what I would really like is a script which, given a new definition for a materialized view which doesn't affect the definition of dependents, would (in a transaction), drop dependents, alter original, and recreate dependents."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T16:34:43.303",
"Id": "57797",
"Score": "0",
"body": "could you elaborate a little more on your answer please?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T05:27:08.623",
"Id": "33279",
"ParentId": "23181",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T15:06:30.643",
"Id": "23181",
"Score": "7",
"Tags": [
"sql",
"recursion",
"postgresql"
],
"Title": "Get all recursive dependencies of a single database object"
}
|
23181
|
<p>My objective is to make an array of unique keys from a list of objects.</p>
<p>Example:</p>
<p>Input:</p>
<pre><code>var input = [{"a":1, "b":2}, {"a":3, "c":4}, {"a":5}]
</code></pre>
<p>Output:</p>
<blockquote>
<pre><code>[ "a", "b", "c" ]
</code></pre>
</blockquote>
<p>Current approach:</p>
<pre><code>var outputObj={};
input.map( function( obj ) {
Object.keys( obj ).map( function(key) {
outputObj[key] = 1;
})
});
// output obj is now { a : 1, b: 1, c: 1 }
var output = Object.keys( outputObj );
</code></pre>
<p>This works, but it just smells funny, partly because the map function is relying on side-effects. Is there a better way to do this?</p>
<p>In Java, I would create a <code>java.util.Set</code> and simply add all keys to it.</p>
|
[] |
[
{
"body": "<p>You could clean it up a bit by using <code>reduce</code> and <code>forEach</code> instead of map (especially as you don't need <code>map</code>'s return value, but are just using it as an iterator)</p>\n\n<pre><code>function uniqueKeys(objects) {\n var keys = objects.reduce(function (collector, obj) {\n Object.keys(obj).forEach(function (key) {\n collector[key] = true;\n });\n return collector;\n }, {});\n return Object.keys(keys);\n}\n</code></pre>\n\n<p>Alternatively, you could combine all the objects, and then use <code>Object.keys</code> on the result. Just be careful, as <code>extend</code>-type functions usually work on the passed objects directly (as the one below does), rather than returning a new object, so pass an empty object to use as collector:</p>\n\n<pre><code>function extend(target, source) {\n var key;\n for(key in source) {\n target[key] = source[key];\n }\n return target;\n}\n\nfunction uniqueKeys(objects) {\n var combined = objects.reduce(function (target, obj) {\n extend(target, obj);\n return target;\n }, {});\n return Object.keys(combined);\n}\n</code></pre>\n\n<p>If you've got an <code>extend</code> function that takes an arbitrary number of arguments, you could do something like</p>\n\n<pre><code>function uniqueKeys(objects) {\n var collector = {};\n extend.apply(null, [collector].concat(objects));\n return Object.keys(collector);\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/JEsWR/3/\" rel=\"nofollow\">Here are demos of each one</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T20:19:40.137",
"Id": "23184",
"ParentId": "23183",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23184",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T19:52:06.477",
"Id": "23183",
"Score": "4",
"Tags": [
"javascript",
"array"
],
"Title": "Finding unique values in an array"
}
|
23183
|
<p>I am creating a game that contains a Board and Pieces. The Board is basically a 2D array of Pieces. [Think smaller chess board]</p>
<p>One of the things that I want to accomplish is to be able to retrieve the left piece of a given.. (Also want to be able to retrieve the right, up, and down).</p>
<p>The easiest way to achieve this is to simply do something like:</p>
<pre><code>board[i-1][j] //which will give me the piece that's to the left of board[i][j]
</code></pre>
<p>The problem with just doing this is that this can get ugly and there is no error checking (array out of range).</p>
<p>I have a feeling that there may be a better data structure to use than a 2D array. </p>
<p>Also, I have two implementations that work, but neither really seem like a good idea</p>
<p>I have the following (untested) Java classes, which is a small scale of my application:</p>
<p>the class Board:</p>
<pre><code>public class Board
{
protected Piece[][] board;
public Board()
{
board = new Piece[7][7];
int ctr = 0;
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new Piece(i, j, ctr++);
}
}
}
public Piece PieceAt(int i, int j)
{
return board[i][j];
}
public Piece LeftOf(Piece p)
{
return PieceAt(p.verticalIndex, p.horizontalIndex - 1);
}
}
</code></pre>
<p>And the Piece class</p>
<pre><code>public class Piece
{
int verticalIndex;
int horizontalIndex;
int value;
public Piece(int i, int j, int value)
{
this.horizontalIndex = i;
this.verticalIndex = j;
this.value = value;
}
public Piece GetLeftPiece(Board b)
{
return (this.horizontalIndex == 0 ? null : b.PieceAt(this.horizontalIndex, this.verticalIndex - 1));
}
}
</code></pre>
<p>The first implementation sits in <code>Board.java</code>. The problem with this is that If I want to call it, it's a big ugly: <code>b.LeftOf(b.PieceAt(3,3))</code> where b is of type Board.</p>
<p>The second implementation seems like a better idea, however since the Pieces no nothing about each other, I have to include board in the method signature. </p>
|
[] |
[
{
"body": "<p>The first location of the <code>leftOf</code> method is the way to go. Putting it in <code>Piece</code> isn't very <a href=\"http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29\" rel=\"nofollow\">cohesive</a>. The latter would be just as ugly or uglier (<code>b.pieceAt(3,3).getLeftPiece(b)</code>). The syntax <code>board.leftOf(b.pieceAt(3,3))</code>, <a href=\"http://en.wikipedia.org/wiki/Rubber_ducking\" rel=\"nofollow\">read aloud,</a> communicates roughly your intent but might read better as <code>board.getPieceLeftOf(b.pieceAt(3,3))</code>. Further, the best way is to remove the middle man and change the interface:</p>\n\n<pre><code>public Piece getPieceLeftOf(int x, int y) {\n int leftLocation = x - 1;\n // Validate that location\n return pieceAt(leftLocation, y);\n}\n\n// ...later\nboard.getPieceLeftOf(3, 3);\n</code></pre>\n\n<p>Some style notes/thoughts:</p>\n\n<ul>\n<li>Since this is written in Java, you should be following the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow\">standard naming conventions</a>. camelCase for method names</li>\n<li>You have a lot of package and package-private fields, it's a better practice to make them private and then expose the ones that actually need to be exposed outside of the class. (<a href=\"http://www.oracle.com/technetwork/java/effectivejava-136174.html\" rel=\"nofollow\">Effective Java</a> Item 13).</li>\n<li>If there is no error checking for the <code>pieceAt</code> or <code>leftOf</code> methods then add it and communicate through javadocs what happens if there is no left piece, a request is made out of bounds, etc. Those are both implemenation and game-type rules that need to be considered.</li>\n<li>It seems like a simple 2D array is fine for this application. That is a pretty common structure for 2D chess/checkers type games (quick access, easy mental model, etc).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T21:43:29.203",
"Id": "23189",
"ParentId": "23186",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23189",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T21:21:41.373",
"Id": "23186",
"Score": "1",
"Tags": [
"java",
"array"
],
"Title": "2D Array: Retrieve the \"Left\" Item"
}
|
23186
|
<p>I am looking for feedback on this compact Python API for defining bitwise flags and setting/manipulating them. </p>
<p>Under the hood, FlagType extends <code>int</code> and all operations are true bitwise, so there is little to no performance impact. Also, because they are all <code>int</code>, any standard bitwise operation can be performed on them.</p>
<p><strong>Usage Example</strong></p>
<pre><code>>>> class sec(FlagType):
... admin = 1
... read = 2
... write = 4
... usage = 8
...
>>> flags = +sec.read -sec.write +sec.usage
>>> x.read
True
>>> print(flags)
10
>>> repr(flags)
"<sec (0b1010) {'write': False, 'usage': True, 'admin': False, 'read': True}>"
</code></pre>
<p>This code arose out of the desire to replace:</p>
<pre><code>class Name(Varchar):
InsertRead = True
InsertWrite = True
InsertRequired = True
UpdateRead = True
UpdateRequired = True
UpdateWrite = False
</code></pre>
<p>with:</p>
<pre><code>class Name(Varchar)
flags = +Read +Write +Required -UpdateWrite
</code></pre>
<p><strong>More Examples:</strong></p>
<pre><code>class color(FlagType):
red = 0b0001
blue = 0b0010
purple = 0b0011
_default_ = red
color()
:: <color (0b1) {'blue': False, 'purple': False, 'red': True}>
flags = +color.blue
flags
:: # Note the default of red came through
:: # Note that purple is also true because blue and red are set
:: <color (0b11) {'blue': True, 'purple': True, 'red': True}>
flags.blue
:: True
flags.red
:: True
flags -= color.blue
flags.blue
:: False
flags.purple
:: False
flags.red
:: True
flags
:: <color (0b1) {'blue': False, 'purple': False, 'red': True}>
flags[color.red]
:: True
</code></pre>
<p><strong>Source Code:</strong></p>
<pre><code>class FlagMeta(type):
def __new__(metacls, name, bases, classdict):
if '_default_' in classdict:
def __new__(cls, value=classdict.get('_default_')):
return int.__new__(cls, value)
del classdict['_default_']
classdict['__new__'] = __new__
cls = type.__new__(metacls, name, bases, classdict)
for flagname,flagvalue in classdict.items():
if flagname.startswith('__'):
continue
setattr(cls, flagname, cls(flagvalue))
return cls
def __setattr__(cls, name, value):
if type(value) is not cls:
raise AttributeError("Attributes of class '{0}' must be instances of '{0}'.".format(cls.__name__))
if type(value) is FlagType:
raise AttributeError("Class '{0}' is read-only.".format(cls.name))
type.__setattr__(cls, name, value)
class FlagType(int, metaclass=FlagMeta):
def __pos__(self):
'''
Creates a new default instance of the same class and then adds the current
value to it.
'''
return type(self)() + self
def __neg__(self):
'''
Creates a new default instance of the same class and then subtracts the current
value from it.
'''
return type(self)() - self
def __add__(self, other):
'''
Adding only works with flags of this class or a more generic (parent) class
'''
if not isinstance(self, type(other)):
raise TypeError("unsupported operand type(s) for {0}: '{1}' and '{2}'".format(('+'), type(self), type(other)))
return type(self)(self | other)
def __sub__(self, other):
'''
Subtracting only works with flags of this class or a more generic (parent) class
'''
if not isinstance(self, type(other)):
raise TypeError("unsupported operand type(s) for {0}: '{1}' and '{2}'".format(('-'), type(self), type(other)))
return type(self)(self & ~other)
def __getattribute__(self, othername):
'''
If the requested attribute starts with __, then just return it.
Otherwise, fetch it and pass it through the self[...] syntax (__getitem__)
'''
if othername.startswith('__'):
return object.__getattribute__(self, othername)
else:
return self[getattr(type(self), othername)]
def __setattr__(self, name, val):
'''
Readonly.
'''
raise AttributeError("'{0}' object is readonly.".format(type(self).__name__))
def __getitem__(self, other):
'''
Passing an instance of this same class (or a parent class) to the item getter[]
syntax will return True if that flag is completely turned on.
'''
if not isinstance(self, type(other)):
raise TypeError("unsupported operand type(s) for {0}: '{1}' and '{2}'".format(('-'), type(self), type(other)))
return self & other == other
def __repr__(self):
'''
For example:
<FieldFlag (0b1001) {'Read': True, 'Required': False, 'Write': True, 'Execute': False}>
'''
fields = {}
for c in type(self).__mro__[0:-2]: #up to but not including (int, object)
for fieldname, fieldvalue in c.__dict__.items():
if not fieldname.startswith('__'):
fields[fieldname] = self[fieldvalue]
return '<' + type(self).__name__ + ' (' + bin(self) + ') ' + str(fields) + '>'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T23:23:33.850",
"Id": "35775",
"Score": "0",
"body": "I would argue this isn't a Pythonic interface. Set attributes on an object instead of using flags, or use a `dict`."
}
] |
[
{
"body": "<p>One real-world use-case might be to pass such \"flags\" values to some ffi code, where these are used for efficiency, but in python it seem inefficient (as each instance basically introduces a dict plus an object struct) and much less readable.</p>\n\n<p>Imagine encountering such lines in someone's code - now how would you update some flags? list them? reset all?</p>\n\n<p>If it's not known, I think it won't be intuitive (contrast with facing regular dict with True/False values), and will require person to go dig into these classes.</p>\n\n<p>And while example like</p>\n\n<pre><code>class Name:\n InsertRead = True\n InsertWrite = True\n InsertRequired = True\n UpdateRead = True\n UpdateRequired = True\n UpdateWrite = False\n</code></pre>\n\n<p>Might be indeed overly verbose for someone who wrote it, I'd say it should be expanded with comments about what each of these flags means, <em>especially</em> if you're going to pass this structure around:</p>\n\n<pre><code>class Name:\n #: Perform database INSERT on read/write manipulations.\n InsertRead = True\n InsertWrite = True\n #: Will rollback the transaction with IntegrityError\n #: if INSERT was not performed (object with same value\n #: was already present).\n InsertRequired = True\n ...\n</code></pre>\n\n<p>As a bonus, you get crucial \"no surprises\" behavior, which I think other developers will appreciate, having to spend no time figuring out how to work with the thing.</p>\n\n<p>Another bonus - run Sphinx over it and get a good and readable <a href=\"https://scrapy.readthedocs.org/en/latest/topics/spiders.html#basespider\" rel=\"nofollow\">API reference</a>.</p>\n\n<p>Basically, I think it's cleverness for it's own sake.</p>\n\n<p>Sure, one can write custom language for some specific task on top of python, but place yourself in the shoes of someone coming at this with python knowledge only and it'd be hard to justify doing so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T21:52:31.333",
"Id": "36653",
"Score": "0",
"body": "`(x*2 for x in mylist)` is the same as much more verbose `def double(mylist): for x in mylist: yield x*2; ` and then referencing `double(mylist)` to use it. I don't think that syntax sugar is bad in and of itself."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T11:00:54.017",
"Id": "23258",
"ParentId": "23187",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T21:36:42.243",
"Id": "23187",
"Score": "4",
"Tags": [
"python",
"bitwise"
],
"Title": "Bitwise Flag code for Python"
}
|
23187
|
<p>I have a web application where I connect with a MySQL database using PDO and in some scripts there are a lot of queries one after the other which don't necessarily concern the same tables. i.e I will execute a SELECT statement in one, and then depending on some values I will UPDATE another and finally go and DELETE from another one.</p>
<p>The thing is I only recently learned PHP and MySQL and because I wasn't sure and wanted to be careful and to find easily any problems (and a little because I am a little ocd and anal about silly things like uniformity and coding style) in every query I used the following format</p>
<pre><code>try {
$statement = "
UPDATE/SELECT ...
FROM/SET ...
WHERE ...";
$query = $dbcnx->prepare($statement);
$flag = $query->execute();
}
catch (PDOException $e) {
$errorMsg = "...";
error_log($errorMsg,3,'../../xxx.log');
$response = ...;
$dbcnx->null;
return $response;
}
$result = $query->fetch/fetchAll/fetcColumn...
</code></pre>
<p>so I could find where any problem would occur (try/catch) and to be safe against injections and invalid characters (prepare) (I had some personal checks but I am pretty sure that a function specifically made for would be better).</p>
<p>When I had one or two queries it was fine but after the code grew it became a little too much code for little action/substance (like 16 lines for one query...)</p>
<p>So I would like some advise.
How do I make my code more manageable?
Is there some fundamental error in my logic on structure (the way I wrote it)?
Is there some rule for using try/catch? Is it more for developing and debugging and afterwards you can remove some blocks of it?
Is prepare enough for rudimentary security on queries?</p>
<p>I was thinking of making a function of just this block of code and calling it with the statement as a parameter. So I would just 'type' the query in the main body and then call the function where it would be prepared, executed and then return the result. Of course then I would always use fetchAll and would return an associative array but I think as long the datasets are small the memory usage would be fine (in any case in nowadays systems it should take A LOT to notice a difference, I think)...</p>
<p>EDIT: I was told about abstraction layer, which I admit I am a little fuzzy about. Basically it is a class which is instantiated every time the script/function runs and wrap the functions used repeatedly (along with the checking I do) inside it?</p>
|
[] |
[
{
"body": "<p>You're on the right track, what you're looking for is a DAL (Data Abstraction Layer), a class that represents a database connection.<br>\nThis will allow you to move your common code into the class so you can simply construct your SQL statement and pass it in, with the method returning the expected data.</p>\n\n<p>At a minimum you'd typically have, but aren't limited to:</p>\n\n<ul>\n<li>Constructor (__construct) to create a new database connection using the relevant permissions.</li>\n<li>Method to run your select statement (after input sanitization), returning a result set.</li>\n<li>Method to run statements that don't return a result set.</li>\n<li>Destructor (__destruct) to clean up and free any resources.</li>\n</ul>\n\n<p>This would give you the following advantages:</p>\n\n<ul>\n<li>Code reuse: only 1 copy of logging, connection initialization code, in 1 place.</li>\n<li>Code encapsulation: The details are hidden behind a public interface so you can easily fix bugs and add new features without breaking existing SQL calls.</li>\n<li>Pass in a complete SQL statement for centralized execution of SQL code.</li>\n<li>Optionally pass in a parameter to specify calling Fetch/FetchAll/FetchColumn.</li>\n<li>Easier debugging since your class will very quickly become very reliable as it gets heavily used and bugs are noticed and fixed.</li>\n<li>Logging would be done automatically whenever you ran an SQL statement.</li>\n<li>Easily add additional methods, such as input validation/sanitization.</li>\n<li>Additional methods for specific purposes depending on your requirements.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-24T18:33:02.337",
"Id": "24316",
"ParentId": "23191",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T23:05:17.680",
"Id": "23191",
"Score": "5",
"Tags": [
"php",
"mysql",
"pdo",
"formatting"
],
"Title": "Thoughts on organizing code for multiple mysql queries in php scripts"
}
|
23191
|
<p>I would love to show you one of my bigger scripts to improve my technique.
This script is some kind of Itempicker. You choose your <code>Item</code> first (<code>toprow</code>), then pick a color. The color of the active Item (basically the image) changes.</p>
<p>A big deal for me was actually to design the script that way. The way that all the Items keep their selected color. Further, the whole script shall allow to easily add new Items. I think this flexibility results in some more complex code. Do you think I've found a good trade-off?</p>
<p><a href="http://jsfiddle.net/d8H36/" rel="nofollow">Here is the live example</a>.</p>
<p>And here is the actual code of the Itempicker:</p>
<pre><code>$(document).ready( function() {
var candleAmount = 15; // Anzahl der Kerzen
var colorAmount = 21;
var candlePath = "images/kerzen/"; // relativer Pfad zu den Kerzen.png's
var candleFormat = ".png"; // Bildformat der Kerzen.png's
var singleImgCandles = [07, 09]; // Kerzen-Nr mit nur einer Farbvariante
var leftOutColor = [10]; // Kerzenfarben die ausgelassen werden sollen
$.globalEval("setVisibleRangeDone = false;");
for (var i=1; i <= candleAmount; i++) { // erstmaliges Erstellen der Kerzen-HTML Elemente samt Array-Erstellung
var i = correctIndex(i);
$("#container #candlePick").append("<li class='candle"+i+"'></li>");
var color = randomColor();
window["candle" + (i)] = {
"kind":i,
"color": color // i für alle Farben hintereinander
}
};
for (var i=1; i <= colorAmount; i++) { // erstmaliges Erstellen der Farbwahl-HTML Elemente
var i = correctIndex(i);
if ($.inArray( eval(i), leftOutColor ) !== -1) { // Kerzefarbe auslassen
$("#container #colorPick").append("<li><a class='hide color"+i+"' href='#'></a></li>");
} else {
$("#container #colorPick").append("<li><a class='color"+i+"' href='#'></a></li>");
};
};
function randomColor () { // farbe wird anhand von colorAmount.length erzeugt
a = colorAmount;
b = Math.random();
color = Math.ceil(b/(1/a))
color = correctIndex(color);
if ($.inArray( eval(color), leftOutColor ) !== -1) {
randomColor ();
}
return color;
};
function set() { // listenelemente werden mit zugewiesenen Hintergrundbildern versehen
$("#container #candlePick li").each( function() {
var i = getIndex(this);
kind = eval("candle"+i+".kind");
color = eval("candle"+i+".color");
if ( $.inArray( eval(kind), singleImgCandles ) !== -1) { // wenn die Kerze nur eine Farbvariante (oben definiert) hat
color = "01";
};
$(this).css("backgroundImage", "url("+candlePath+"kerze-"+color+"-"+kind+candleFormat+")");
});
};
function getIndex(_this) {
var i = ($(_this).index())+1;
var i = correctIndex(i);
return i;
};
function correctIndex(i) { // ist "i" einstellig, wird eine 0 vor "i" gestellt
if (i<"10") i="0"+i;
return i;
};
function setVisibleRange() {
if (setVisibleRangeDone !== true) {
var fittingAmount = fitIn("#candlePick li");
$.globalEval("visibleRange = [0, ("+fittingAmount+")-1];");
$.globalEval("setVisibleRangeDone = true;");
};
$("#candlePick li").hide();
for (i=visibleRange[0]; i<=visibleRange[1]; i++) {
$("#candlePick li").eq(i).show();
};
};
$(".candleNav.next").click( function() {
if (visibleRange[1]!==candleAmount-1) {
$.globalEval("visibleRange[0] += 1")
$.globalEval("visibleRange[1] += 1")
setVisibleRange();
};
});
$(".candleNav.prev").click( function () {
if (visibleRange[0]!==0) {
$.globalEval("visibleRange[0] -= 1");
$.globalEval("visibleRange[1] -= 1");
setVisibleRange();
};
});
function fitIn(element) { // Es wird zurückgegeben, wie oft ein Element von der Breite in sein Elternelement passt
var ownWidth = ($(element).width());
var ownBorder = 2; // muss per hand eingetragen werden.
var ownMargin = eval($(element).css("marginLeft").slice(-0, -2)) + eval($(element).css("marginRight").slice(-0, -2));
var ownPadding = eval($(element).css("paddingLeft").slice(-0, -2)) + eval($(element).css("paddingRight").slice(-0, -2));
var ownTotalWidth = ownWidth+ownMargin+ownPadding+ownBorder;
var parentWidth = $(element).parent().width();
var fits = Math.floor((parentWidth/ownTotalWidth));
return fits;
};
function center(element) { // Element wird in seinem Elternelement horizontal zentriert (padding, margin vernachlässigt!)
var ownWidth = $(element).width();
var parentWidth = $(element).parent().width();
var marginLeft = (parentWidth-ownWidth)/2;
$(element).css("marginLeft", +marginLeft+"px");
;}
$("#container #candlePick li").click( function() {
$("#container #candlePick li").removeClass("active"); // entfernt bei allen .active
$(this).addClass("active"); // fügt bei diesem .active hinzu
var i = getIndex(this);
color = (eval("candle"+i+".color"))-1;
$("#container #colorPick li a").removeClass("active");
$("#container #colorPick li a:eq("+color+")").addClass("active");
$("#candle").val(i);
color = eval("candle"+i+".color"); // nur für Einbau, Übergabe an Formular
$("#color").val(color); // nur für Einbau, Übergabe an Formular
if ( $.inArray( eval(i), singleImgCandles ) !== -1) { // wenn die Kerze nur eine Farbvariante (oben definiert) hat
$("#colorPick").fadeTo(300, 0.5);
} else {
$("#colorPick").fadeTo(300, 1.0);
};
});
$("#container #colorPick li a").click( function() {
$("#container #colorPick li a").removeClass("active");
$(this).addClass("active");
var i = getIndex( $(this).parent() );
var indexCandle = getIndex("#container #candlePick .active");
$.globalEval("candle"+indexCandle+".color = '"+i+"';");
$("#color").val(i); // nur für Einbau, Übergabe an Formular
set();
});
setVisibleRange();
center($("#candlePick"));
center($("#colorPick"));
set();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T01:40:41.197",
"Id": "35778",
"Score": "4",
"body": "Per the [FAQ], if you want your code to be reviewed, you need to paste it here, not just link to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T11:21:39.740",
"Id": "35804",
"Score": "0",
"body": "Well, it's quite long. But thank you, I'll do it."
}
] |
[
{
"body": "<p>Your script is quite long, so I'll see how far I can get. Maybe I'll add more later.</p>\n\n<ul>\n<li>Your fiddle is lacking the images, so I'm not 100% sure I understand the \"keep the color\" feature.</li>\n<li>Your comments should be in English if you post the code for review like this.</li>\n<li>Unfortunately the more puzzling functions such as <code>setVisibleRange</code> have no comments.</li>\n<li>You are using many global variables. Instead you should have a \"namespace object\" or a closure function, in which you store all \"global\" data. You may even consider working with objects, so that you can have multiple instances of your item picker on the same page.</li>\n<li>You should never ever need to use <code>eval</code> (or <code>$.globalEval</code>). It's slow and more importantly in 99.9 per cent of cases completely unnecessary. </li>\n<li>Some of your function names are quite poorly chosen. E.g. <code>correctIndex</code> sounds like it actually changes the index. Something like <code>formatIndex</code> would be better. And do I have to say something about \"<code>set</code>\"?</li>\n<li>You are converting the indexes unnecessarily to and fro between string and number.</li>\n<li>Are you aware of the consequences of not having a JavaScript-less fallback? Some statistics say up to 5% of users block JavaScript. This is obviously a shop web site. Can the owner afford losing 5% of his customers?</li>\n<li>You have far too much business logic in your code. Stuff like the hard-coded number of items or \"left out color\" should have no place in your JavaScript code. Instead of generating the <code>li</code> items in your JavaScript, have them generated server-side. That way your script doesn't even need to know how many items there are, or which items have been left out (by the server-side logic), it just works with the <code>li</code>s that are there. And if you also add radio buttons to the <code>li</code>s server-side (which you can hide with the JavaScript) then you have a chance to build a selector that works even for the users without JavaScript.</li>\n</ul>\n\n<p>That's it for now. If I have some time later, I'll come back and add some comments specific to the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T14:59:13.113",
"Id": "23219",
"ParentId": "23192",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T23:35:38.537",
"Id": "23192",
"Score": "4",
"Tags": [
"javascript",
"performance",
"jquery"
],
"Title": "Item-picker script"
}
|
23192
|
<p>I wonder which is better practice when I need to return the primary key value of a newly inserted record from a SQL stored procedure. Consider the following implementations:</p>
<p><strong>As Return Value</strong></p>
<pre><code>CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128) )
AS
BEGIN
INSERT [Records] ( [Value] ) VALUES ( @value );
RETURN SCOPE_IDENTITY();
END
</code></pre>
<p>Obviously this only works for <code>INT</code> keys, but it takes advantage of pre-existing functionality. Also, only works when inserting a single record. I have seen this done in few places, but I generally don't like it. </p>
<p><strong>As Output Parameter</strong></p>
<pre><code>CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128), @id INT = NULL OUTPUT )
AS
BEGIN
INSERT [Records] ( [Value] ) VALUES ( @value );
SET @id = SCOPE_IDENTITY();
END
</code></pre>
<p>Works for any type of key, including multi-column keys, but still only works when inserting a single record. This is my preferred method unless I absolutely <em>have</em> to insert more than one record at a time.</p>
<p><strong>As XML Output Parameter</strong></p>
<pre><code>CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128), @xmldata XML = NULL OUTPUT )
AS
BEGIN
DECLARE @inserted TABLE ( Id INT );
INSERT [Records] ( [Value] )
OUTPUT [inserted].[Id]
INTO @inserted ( [Id] )
VALUES ( @value );
SET @xmldata = (SELECT [Id] FROM @inserted FOR XML AUTO);
END
</code></pre>
<p>This is similar to the previous solution, but allows multiple records to be returned. Trying to parse the output would be a huge pain, but I suppose this would be suitable for some applications. For example, if a stored procedure can insert into several different tables, a single output parameter can describe all the inserted records. </p>
<p><strong>As Result Set</strong></p>
<pre><code>CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128) )
AS
BEGIN
DECLARE @inserted TABLE ( Id INT );
INSERT [Records] ( [Value] )
OUTPUT [inserted].[Id]
INTO @inserted ( [Id] )
VALUES ( @value );
SELECT * FROM @inserted;
END
</code></pre>
<p>Superficially, this may be appealing, especially if your calling this SP from ADO, since getting the result set from the command is very straight forward. To use this SP from SQL, however, you have to write an <code>INSERT-EXEC</code> script, which is somewhat inelegant, in my opinion (but still a lot better than parsing XML).</p>
<p>Perhaps there are other methods that I'm not even aware of. What is the best method of returning the newly inserted key value from this kind of stored procedure? Are there any guidelines for deciding which is the best method?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T00:16:44.473",
"Id": "36191",
"Score": "0",
"body": "I don't understand what the problem is with the XML output--parsing's not that difficult, and besides you can join XML to other data just like it's a RS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T20:05:31.340",
"Id": "36249",
"Score": "0",
"body": "@AmyBlankenship You may be right that there is no *problem* with an XML output parameter. I suppose I don't like it mainly because using XML in SQL has never set well with me. I've only had to do it a handful of times and every time, it just feels *bad*. (Maybe because in the projects where I had to use it, the choice to use XML was kind of a hack, and relational alternatives would've been much better)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T00:49:50.170",
"Id": "36275",
"Score": "0",
"body": "I like it because you can dump it out as is to a service or what have you. XML is really versatile."
}
] |
[
{
"body": "<p>I think you've already answered your own question to some degree: there are multiple options for returning data from a stored procedure and they all behave differently so there is no single answer. But there are definitely some general guidelines and common practices.</p>\n\n<p><code>RETURN</code> is a control-of-flow statement: its primary use is to exit a procedure, not to return data. But of course return codes are a very common feature of many programming languages, and the <a href=\"http://msdn.microsoft.com/en-us/library/ms190778%28v=sql.105%29.aspx\" rel=\"nofollow\">documentation</a> makes that usage pattern explicit: </p>\n\n<blockquote>\n <p>A stored procedure can return an integer value called a return code to\n indicate the execution status of a procedure</p>\n</blockquote>\n\n<p>So you should use this not to return <em>data</em>, but to return <em>metadata</em> about the execution of the procedure. Usually this means did it succeed or fail, and if it failed what was the error status. Whether or not you actually want to use this feature is entirely up to you, of course.</p>\n\n<p>Output parameters are the standard way of returning scalar values, and are especially useful when the procedure is called by another piece of TSQL code, because as you mentioned sharing data between stored procedures is <a href=\"http://www.sommarskog.se/share_data.html\" rel=\"nofollow\">not always easy</a>, especially if you want to share a result set. The only obvious reason not to use them for scalar values is if your client code - perhaps an ORM or DAL - and/or coding practices make it easier to consume a result set (more on that below).</p>\n\n<p>I'm not going to comment on your XML solution because I'm not an XML guy, but it seems very awkward and unless your client code could only consume XML then I'm not sure what the point would be.</p>\n\n<p>A result set is more flexible than an output parameter because it can return multiple rows (obviously), so if you need a result set then it's the only choice anyway.</p>\n\n<p>(Strictly speaking that isn't true, because you can return <a href=\"http://msdn.microsoft.com/en-us/library/ms175498%28v=sql.100%29.aspx\" rel=\"nofollow\">a cursor as an output parameter</a>, but avoiding cursors whenever possible is a good rule in TSQL and I personally don't see any advantage over returning a result set. Other than it being easier for calling code in TSQL to consume the cursor.)</p>\n\n<p>That all means that the 'correct' answer to your question is to use an output parameter when returning one key value, or a result set when returning more than one. But, that will add some complexity to your calling code because it needs to know which procedures return output parameters and which ones return result sets (or both).</p>\n\n<p>For that reason it's not uncommon for organizations to make explicit coding rules that say that stored procedures must always return data in result sets (usually one and only one per procedure). Then developers don't need to worry about it, they just always write code to consume result sets, even if some result sets always have just one row. This is an important consideration, because developers' time is usually by far the most expensive component of any application, so anything you can do to make development simpler, faster and less error-prone is very worthwhile.</p>\n\n<p>Perhaps there's a performance difference between using output parameters and result sets, but if you're worried about that then set up a test and gather some performance data (it's almost always better to test and measure performance yourself before asking someone else's opinion, since that person's general answer may turn out to be wrong for your specific case). And even if there is some performance difference, if it isn't big enough to impact your application then you can ignore it and use whichever mechanism you prefer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T18:30:19.177",
"Id": "23450",
"ParentId": "23193",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23450",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T23:37:44.487",
"Id": "23193",
"Score": "5",
"Tags": [
"sql",
"sql-server"
],
"Title": "Returning Key Values from Stored Procedures"
}
|
23193
|
<p>I'll try to provide exactly the amount of context that is necessary to understand the construct.</p>
<p>I built an API (well, a small part of one) that works and is kind of usable, but rather unpretty and badly testable, and most of all unpretty. Testability is also an issue.</p>
<p>The problem domain has the concept of an 'image' in the sense of a logical image of a database record. This image can be extracted from an execution context passed into the logic from the calling application, based on certain rules that need to have defaults but also be configurable on different levels.</p>
<p><strong>The goal</strong> is to be able to just take a dependency in an interface called <code>IFullImageSource</code> anywhere in the application (I am using an IoC container) and call its parameterless <code>GetImage()</code> method, having the implementation handle everything else.</p>
<p>The <code>IFullImageSource</code> implementation:</p>
<pre><code>public class SelectingFullImageSource : IFullImageSource
{
private readonly IImageRulesSet _rules;
private readonly IPluginExecutionContext _context;
public SelectingFullImageSource(IImageRulesSet rules, IPluginExecutionContext context)
{
this._rules = rules;
this._context = context;
}
public Entity GetImage()
{
StepStage stage = this._context.GetStepStage();
IImageRule rule = this._rules.GetRule(stage);
return rule.GetImage(this._context);
}
}
</code></pre>
<p>Everything needed to determine how to extract the image is contained within this part of the object graph; the rest of the application does not need to care at all.</p>
<p>Now let's go to the other end and start with the small parts.</p>
<p><code>IImageRulesSet</code> encapsulates a collection of <code>IImageRule</code> objects keyed by <code>StepStage</code> values (<code>StepStage</code> has overridden equality members); I will show that in a moment. The smallest components here are the <code>IImageRule</code> implementations. They generally look like this:</p>
<pre><code>public class TargetImageRule : IImageRule
{
public Entity GetImage(IPluginExecutionContext context)
{
return ((Entity)context.InputParameters["Target"]).Clone();
}
}
</code></pre>
<p>or</p>
<pre><code>public class PreImageRule : IImageRule
{
private readonly string _imageName;
public PreImageRule() { }
public PreImageRule(string imageName)
{
this._imageName = imageName;
}
public Entity GetImage(IPluginExecutionContext context)
{
string imageName = this._imageName ?? context.PrimaryEntityName;
return context.PreEntityImages[imageName];
}
}
</code></pre>
<p>These don't include the <code>StepStage</code> part because while that is determined solely from the context as well, the same <code>IImageRule</code> implementation can apply to several <code>StepStage</code> values.</p>
<p>The default rules set is provided as a dictionary of <code>StepStage</code> and <code>IImageRule</code>:</p>
<pre><code>public class DefaultImageRules : Dictionary<StepStage, IImageRule>, IDefaultImageRules
{
public DefaultImageRules() : this(null, null) { }
public DefaultImageRules(string preImageName, string postImageName)
: base(new Dictionary<StepStage, IImageRule>()
{
{new StepStage("Create", StepStage.PreStage), new TargetImageRule()},
{new StepStage("Create", StepStage.PostStage), new TargetImageRule()},
{new StepStage("Update", StepStage.PreStage), new MergeImageRule(new PreImageRule(preImageName), new TargetImageRule())},
{new StepStage("Update", StepStage.PostStage), new PostImageRule(postImageName)},
{new StepStage("Delete", StepStage.PreStage), new PreImageRule(preImageName)},
{new StepStage("Delete", StepStage.PostStage), new PreImageRule(preImageName)},
}) { }
}
</code></pre>
<p>This is where the unprettiness starts. The constructor "fallthrough" with <code>null</code> parameters (of all things!) seems rather sloppy; the same goes for the rule implementations - although local defaults are always available.</p>
<p>That means the following: Simply creating a <code>DefaultImageRules</code> object will pass <code>null</code> for all name parameters, but through</p>
<pre><code>container.Register<IDefaultImageRules>(new DefaultImageRules("preImage", null));
</code></pre>
<p>the developer can rename one of the images while the rule structure itself stays in place.</p>
<p>(Note: The <code>IDefaultImageRules</code> interface is only an empty marker interface deriving from <code>IDictionary<StepStage, IImageRule></code> for IoC and mockability; I can probably do away with this and use a derived class for unit tests that has</p>
<pre><code>this.Clear();
</code></pre>
<p>in its constructor before setting it up for the test again.)</p>
<p>This is also not testable very well. I can easily check whether the correct <code>IImageRule</code> implementation is returned for a <code>StepStage</code> value, but I can only test proper passing of the image names by creating an <code>IPluginExecutionContext</code> stub and setting it up with the expected image, then passing it into the <code>IImageRule</code> instance returned by the dictionary. This is actually testing two things at once - but then again that might not be an issue because the <code>IImageRule</code> implementations are individually tested anyway and "guaranteed" to work correctly.</p>
<p>Still, the whole thing seems a bit flaky.</p>
<p>This is being used in the following class that fulfills the <code>IImageRulesSet</code> dependency of the very first one I showed (yes, all those names are also still an issue):</p>
<pre><code>public class ImageRulesSet : IImageRulesSet
{
private readonly IDictionary<StepStage, IImageRule> _rules;
private readonly IDictionary<StepStage, IImageRule> _customRules;
private readonly IMergeImageRulesDictionaries _mergeImageRulesDictionaries;
public ImageRulesSet(IDefaultImageRules rules, ICustomImageRules customRules, IMergeImageRuleDictionaries mergeImageRulesDictionaries)
{
this._rules = rules;
this._customRules = customRules;
this._mergeImageRulesDictionaries = mergeImageRulesDictionaries;
}
private bool _rulesHaveBeenMerged = false;
private IDictionary<StepStage, IImageRule> Rules
{
get
{
if (!this._rulesHaveBeenMerged)
{
this._mergeImageRulesDictionaries.Merge(this._rules, this._customRules);
this._rulesHaveBeenMerged = true;
}
return this._rules;
}
}
public IImageRule GetRule(StepStage stepStage)
{
return this.Rules[stepStage];
}
}
</code></pre>
<p>The <code>ICustomImageRules</code>/<code>CustomImageRules</code> combination is exactly the same as the <code>DefaultImageRules</code> thing, except that the dictionary is empty by default.
The <code>IMergeRuleDictionaries</code> simply merges both, giving precedence to the 'custom' entries for identical <code>StepStage</code> values to allow for overriding default rules in addition to adding new ones.</p>
<p>That is about it; the object graph in total looks like this:</p>
<pre><code>SelectingFullImageSource : IFullImageSource
ImageRulesSet : IImageRulesSet
DefaultImageRules : IDefaultImageRules
IImageRule implementations
CustomImageRules : ICustomImageRules
IImageRule implementations
DefaultMergeRulesDictionaries : IMergeRulesDictionaries
IPluginExecutionContext (from calling application)
</code></pre>
<p>The configuration effort is the minimum possible, I think - registering instances of <code>IDefaultImageRules</code> and <code>ICustomImageRules</code> in the IoC container; the values for the custom rules can be written as a collection initializer for the dictionary.</p>
<p>What I'm looking for are opinions on the quality of this solution with respect to the SOLID principles and testability, as I currently think it is less than ideal, as well as (first and foremost) a more elegant solution. The only things I really need to retain are the outermost interface (<code>IFullImageSource</code>) and the degree of simplicity in configuring the rules - the exact way of doing that can be entirely different.</p>
<p>Oh, and suggestions about naming are also always welcome.</p>
|
[] |
[
{
"body": "<ol>\n<li>Why can't a <code>StepStage</code> contain a collection of <code>IImageRule</code>? Then there can be a collection of <code>StepStage</code>. This provides an abstraction level that I think is missing.</li>\n<li>Have <code>StepStage</code> implement <code>IEquatable</code>. Now the <code>StepStageCollection</code> can easily <code>Add</code>, <code>Contains</code>, etc.</li>\n<li><code>this._mergeImageRulesDictionaries.Merge(this._rules, this._customRules)</code> Seems to me there could be duplicates in these two sets and so rules could get dropped. This \"client\" method has to know internal stuff to merge what it's supposed to be using.</li>\n<li><code>ImageRulesSet</code> is the client code? Then it has no business merging rule sets. </li>\n<li>Can \"Crete\", \"Update\", \"Delete\" be an enum?</li>\n<li>Seems to me the client could/should be a template method(s) that pulls rules from the collections in the desired execution order. Therefore you must build up the abstractions more than you have now.</li>\n</ol>\n\n<h3>Structure and Encapsulating Functionality</h3>\n\n<ol>\n<li>Default/empty constructions of all classes.</li>\n<li>Optional and default method parameters.</li>\n<li>Implementing <code>IEquatable</code> is key to making <code>StepStage</code> behave like a key. We can ensure uniqueness in a collection.</li>\n<li>Lots of encapsulation with Key objects internally referencing it's \"value objects\" and vice versa. No more exposing \"core\" dictionary stuff to clients.</li>\n<li>Put all the construction grunt work into factories (not shown). I'm imagining an Abstract Factory because of the complexity I'm seeing.</li>\n<li>Make sub-factories. Can use them separately for testing, and composite them in an Abstract Factory.</li>\n<li><strong>More Testable</strong> due to all of the above. Importantly, decoupled from other stuff by the Factory. Looks like <code>SelectingFullImageSource</code> will have a factory and will pass in that context thing. The factory will have separate/independent references for the stuff below to build whatever.</li>\n</ol>\n\n<p></p>\n\n<pre><code>public enum CRUD {Undefined, Create, Update, Delete}\npublic enum Stage {Undefined, pre, post}\n\npublic class StepStage : IEquatable<StepStage> {\n protected CRUD Step {get; set;}\n protected Stage Stage {get; set;}\n protected ImageRuleCollection Images {get; set}\n\n public StepStage(CRUD step, Stage stage, ImageRuleCollection imageRules = null) {\n this.Step = step;\n this.Stage = stage;\n\n ImageRules = imageRules ?? new ImageRuleCollection(this);\n }\n\n // default constructor\n public StepStage() {\n this.Step = CRUD.Undefined;\n this.Stage = Stage.Undefined;\n }\n\n public bool Equals(StepStage other) {\n return (this.Step == other.Step && this.Stage == other.Stage);\n }\n\n // MUST ALSO OVERRIDE OBJECT.EQUALS & GETHASHCODE\n public override bool Equals(object obj) {\n // cast obj and call the IEquatable.Equals(). easy peasy\n }\n }\n\n public class StepStageCollection : List<StepStage> {\n\n public override bool Add(StepStage anotherSS) {\n if (!this.Contains(anotherSS)) { // no duplicate \"keys\"\n Add(anotherSS);\n return true;\n }\n\n return false;\n }\n\n // implement GetKeys(), GetValues() if needed\n }\n\npublic abstract class ImageRule : IEquatable<ImageRule> {\n protected StepStage myKey;\n\n // put the original IImageRule stuff in here.\n // I think we don't need an \"I\"interface. This abstract class\n // will do the job.\n\n public Image (StepStage theKey = null) {\n myKey = theKey ?? new StepStage;\n }\n\n public bool Equals(Image other) {\n return myKey.Equals(other.myKey);\n }\n\n public void SetKey(StepStage newKey){\n if(newKey == null) // throw exception\n myKey = newKey;\n }\n}\n\npublic class ImageRuleCollection : List<ImageRule> {\n // msdn says one should inherit Collection<T>. whatever.\n\n protected StepStage ourKey {get; set;}\n\n public ImageRuleCollection (StepStage theKey = null, params[] ImageRule imageRules = null) {\n ourkey = theKey ?? new StepStage();\n\n if (imageRules != null) {\n foreach(var imageRule in imageRules) {\n imageRule.SetKey(ourKey);\n Add(imageRule);\n }\n }\n }\n\n public void SetKey(StepStage newKey) {\n if(newKey == null) // throw exception\n\n ourKey = newKey;\n foreach(ImageRule imageRule in this) {\n imageRule.SetKey(ourKey);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T03:22:45.503",
"Id": "37716",
"ParentId": "23196",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T01:00:12.153",
"Id": "23196",
"Score": "6",
"Tags": [
"c#",
"unit-testing",
"api",
"dependency-injection"
],
"Title": "Doubts about the quality of an API designed for use with minimal effort"
}
|
23196
|
<p>This is based (somewhat loosely) on the code written in <a href="http://railscasts.com/episodes/88-dynamic-select-menus-revised" rel="nofollow">this railscast.</a> I'm planning to re-use it in different places throughout the site, so I made it a bit more generic rather than based on IDs. However, I'm certain there's probably room for improvement.</p>
<pre><code>jQuery ->
$('.org_type_choice').each ->
cat_obj = $(this).find('.org_category')
type_obj = $(this).find('.org_type')
categories = cat_obj.html()
org_type = type_obj.find(':selected').text()
opts = $(categories).filter("optgroup[label='#{org_type}']").html()
cat_obj.html(opts)
type_obj.change ->
org_type = $(this).find(':selected').text()
opts = $(categories).filter("optgroup[label='#{org_type}']").html()
cat_obj.html(opts)
</code></pre>
|
[] |
[
{
"body": "<p>I see a couple of small ways to improve this.</p>\n\n<ol>\n<li><p>DRY (Don't Repeat Yourself) the code. The code that runs on load is identical to the <code>change</code> event handler. So make it a function you can call from both places.</p></li>\n<li><p>Decouple it completely from the markup by dropping the \"org-*\" classes. It may not be \"orgs\" with \"categories\" and \"types\" that you're trying to select, but, say, \"cars\" with \"makes\" and \"models\". The basic idea is simply that there's a primary select element, and it scopes (filters) a secondary select element.</p></li>\n</ol>\n\n<p>For the second point, I'd use a custom <code>data-*</code> attribute on the primary select. You might call it <code>data-secondary</code>, and let its value be the ID of the secondary select element. E.g.</p>\n\n<pre><code><select data-secondary=\"categories\">...</select>\n<select id=\"categories\">...</select>\n</code></pre>\n\n<p>Now you can find all select elements that have an associated secondary select element, by saying <code>$(\"select[data-secondary]\")</code>. From there, you can find that secondary, and use the current logic. The markup declares the relationship and behavior, while the code can stay completely generic.</p>\n\n<p>I end up with code like this:</p>\n\n<pre><code>jQuery ->\n $(\"select[data-secondary]\").each ->\n primary = $ this\n secondary = $ \"##{primary.data 'secondary'}\" # find the secondary\n items = secondary.clone() # clone the secondary into memory\n\n updateSecondarySelect = ->\n scope = primary.find(\":selected\").text()\n secondary.html items.find(\"optgroup[label='#{scope}']\").html()\n\n primary.on \"change\", updateSecondarySelect # set up the event listener\n updateSecondarySelect() # do the initial filtering\n</code></pre>\n\n<p>(I've changed to CamelCase, but that's not important; use whatever style you prefer)</p>\n\n<p>Some extra error checking would be good (e.g. what happens if the secondary isn't found? If there's no optgroup matching the selected option in the primary, should the secondary maybe just be hidden? etc).</p>\n\n<p><a href=\"http://jsfiddle.net/tqxYM/\">Here's a demo</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T03:18:54.327",
"Id": "23202",
"ParentId": "23199",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23202",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T02:21:20.023",
"Id": "23199",
"Score": "1",
"Tags": [
"jquery",
"coffeescript"
],
"Title": "Dynamic dropdown update for site reuse"
}
|
23199
|
<p>I'm an experienced programmer but relatively new to Python (a month or so) so it's quite likely that I've made some gauche errors. I very much appreciate your time spent taking a look at my code.</p>
<p>My intention is to do some experimentation with 1D cellular automata. For now, just totalistic ones (rules only based upon sum of neighbor cells of given symmetric distance). I started off with code from the book <em>Think Complexity</em> which is available online and have adapted it slightly. I find the performance to be quite dismal. I am using Numpy arrays, and I think I may be able to improve performance markedly if I can figure out how to use stride_tricks but thus far I've been unsuccessful at that. For reasons I do not understand, it takes a couple seconds to run even 100 generations on a field 200 cells wide on an i7 processor with 16GB of RAM. </p>
<p>Even more distressing is that after running for awhile this code eats astonishing amounts of RAM! I am using matplotlib to generate images but am not terribly concerned about its speed, though it is slow. My experiments will be numeric when I can run them and few images will need to be generated. The time of a few seconds I mentioned earlier is solely the duration of running the <code>run()</code> method and does not include any of the rendering. I will be sharing the simple loop used for rendering simple images of each ruleset though because I imagine I am doing something in there that prevents the Python garbage collector from working properly, leading to the 10GB+ memory usage after running for awhile.</p>
<p>The cellular automata class:</p>
<pre><code>class CellularAutomata1DTotalistic(object):
def __init__(self, ruleset, width, radius=1, isRing=False):
self.cells = zeros((1, width + 1), dtype=int8)
self.width = width
self.radius = radius
self.rule = ruleset
self.isRing = isRing
self.table = self.buildTable(self.rule)
self.next = 0
def run(self, steps):
for i in xrange(steps):
self.step()
def step(self):
i = self.next
self.next += 1
if i == len(self.cells):
self.doubleCells()
for j in xrange(self.radius, self.width - self.radius):
self.cells[i, j] = self.table[self.cells[i - 1, j - self.radius:j + self.radius + 1].sum()]
def doubleCells(self):
newcells = zeros(self.cells.shape, dtype=int8)
self.cells = vstack((self.cells, newcells))
def reset(self):
self.cells = zeros((1, self.width + 1), dtype=int8)
self.next = 0
def startSingle(self):
self.reset()
self.cells[0, (self.width - 1) / 2] = 1
self.next = 1
def startWith(self, val):
self.reset()
# TODO: Center the provided pattern
self.cells[0] = val[:]
self.next = 1
def randomize(self, p):
for i, x in enumerate(random.random(width - 2)):
self.cells[0, i + 1] = int(x < p)
self.next = 1
def buildTable(self, rule):
table = {}
#bound = 2 ** (self.radius + 1)
bound = (self.radius * 2) + 2
for i, bit in enumerate(binary(rule, bound)):
table[bound - 1 - i] = bit
return table
def getLatest(self):
return self.cells[self.next - 1, :]
def getEntropy(self):
entropy = []
for i in xrange(1, self.next - 1):
p = float(self.cells[i].sum()) / float(self.width)
entropy.append(-(p * log(p, 2)))
return entropy
def getLiveCounts(self):
liveCounts = []
for i in xrange(0, self.next - 1):
liveCounts.append(self.cells[i].sum())
return liveCounts
def get_array(self, start=0, end=None):
"""Gets a slice of columns from the CA, with slice indices
(start, end). Avoid copying if possible.
"""
if start == 0 and end == None:
return self.cells[0:self.next, :]
else:
return self.cells[0:self.next, start:end]
def binary(n, digits):
"""Returns a tuple of (digits) integers representing the
integer (n) in binary. For example, binary(3,3) returns (0, 1, 1)"""
t = []
for i in range(digits):
n, r = divmod(n, 2)
t.append(r)
return tuple(reversed(t))
</code></pre>
<p>The simple program I am using to generate images of all rules run for 100 steps on a single black cell start state which has strictly increasing RAM usage:</p>
<pre><code>import CellularAutomata1DTotalistic as CA1DT
import CellularAutomata1DRenderer as CA1DR
r = CA1DR.PyplotRenderer()
def render100(rule, radius):
ca = CA1DT.CellularAutomata1DTotalistic(rule, 200, radius)
ca.startSingle()
ca.run(100)
r.draw(ca)
r.save('t[' + str(rule) + '][' + str(radius) + '].png')
def render100allrules(radius):
for rule in xrange(2 ** ((radius * 2) + 2)):
render100(rule, radius)
</code></pre>
<p>Thanks very much for any tips! I should mention that I was worried the resizing of the numpy array by doubling its size when it needed more space might have been what was slowing it down so I created an alternative version which pre-created the cells array of the necessary size in the run function and I saw no difference whatsoever in the performance (using IPythons timeit functionality on runs of 1000 steps on fields 2000 cells wide).</p>
|
[] |
[
{
"body": "<p>This is the slow bit of your program:</p>\n\n<pre><code>for j in xrange(self.radius, self.width - self.radius):\n self.cells[i, j] = self.table[self.cells[i - 1, j - self.radius:j + self.radius + 1].sum()]\n</code></pre>\n\n<p>The key to making faster numpy code is to vectorize. You want to get rid of explicit loops and instead use operations that contain implicit loops:</p>\n\n<p>First thing, we can break this loop into two loops, one will do the summing and the other will do the table lookup:</p>\n\n<pre><code> sums = zeros(self.width + 1, uint8)\n for j in xrange(self.radius, self.width - self.radius):\n sums[j] = self.cells[i - 1, j - self.radius:j + self.radius + 1].sum()\n\n for j in xrange(self.radius, self.width - self.radius):\n self.cells[i, j] = self.table[sums[j]]\n</code></pre>\n\n<p>The trick to vectorizing the first for loop is to realize that you can produce it by taking the cumulative sum and then subtracting. The sum of elements 10 - 16 is the sum of the elements up to 16 minus the sum of elements up to 10. We can ask numpy to calculate the sums once and then subtract the elements 2*self.radius elements apart like this:</p>\n\n<pre><code> sums = zeros(self.width + 1, uint8)\n cumsum = self.cells[i - 1].cumsum()\n sums[self.radius:self.width-self.radius] = cumsum[2*self.radius:] - cumsum[:self.width-2*self.radius]\n</code></pre>\n\n<p>However, we aren't using the beginning or the end of this sums array. So let shift the indexes and get rid of that.</p>\n\n<pre><code> cumsum = self.cells[i - 1].cumsum()\n sums = cumsum[2*self.radius:self.width] - cumsum[:self.width-2*self.radius]\n\n for j in xrange(self.radius, self.width - self.radius):\n self.cells[i, j] = self.table[sums[j - self.radius]]\n</code></pre>\n\n<p>Furthermore, that second loop can be rewritten to start from zero by shifting the indexes</p>\n\n<pre><code> for j in xrange(self.width - 2*self.radius):\n self.cells[i, j + self.radius] = self.table[sums[j]]\n</code></pre>\n\n<p>Next, self.table is a dictionary. But it'll be easier to vectorize if we make it a numpy array.</p>\n\n<pre><code> bound = (self.radius * 2) + 2\n table = zeros(bound, uint8)\n for i, bit in enumerate(binary(rule, bound)):\n table[bound - 1 - i] = bit\n return table\n</code></pre>\n\n<p>Now the loop looking up the table can be rewritten as:</p>\n\n<pre><code> self.cells[i, self.radius:self.width - self.radius] = self.table[sums]\n</code></pre>\n\n<p>This gives me:</p>\n\n<pre><code> cumsum = self.cells[i - 1].cumsum()\n sums = cumsum[2*self.radius:self.width] - cumsum[:self.width-2*self.radius]\n self.cells[i, self.radius:self.width - self.radius] = self.table[sums]\n</code></pre>\n\n<p>General code review:</p>\n\n<pre><code>class CellularAutomata1DTotalistic(object):\n\n def __init__(self, ruleset, width, radius=1, isRing=False):\n self.cells = zeros((1, width + 1), dtype=int8)\n</code></pre>\n\n<p>Why are you doing <code>width + 1</code>? That makes the code more complicated because you've got this extra cell. </p>\n\n<pre><code> self.width = width\n self.radius = radius\n self.rule = ruleset\n self.isRing = isRing\n</code></pre>\n\n<p>Python standard is to use lowercase_with_underscores for local variables, parameter, and attributes</p>\n\n<pre><code> self.table = self.buildTable(self.rule)\n self.next = 0\n\n def run(self, steps):\n for i in xrange(steps):\n self.step()\n\n def step(self):\n i = self.next\n</code></pre>\n\n<p>I recommend against using i here as its not immeadiately obvious what you are doing with it. </p>\n\n<pre><code> self.next += 1\n</code></pre>\n\n<p>I recommend having <code>self.counter = itertools.counter()</code> in <code>__init__</code>. Then <code>self.counter.next()</code> will return the next number.</p>\n\n<pre><code> if i == len(self.cells):\n self.doubleCells()\n\n for j in xrange(self.radius, self.width - self.radius):\n self.cells[i, j] = self.table[self.cells[i - 1, j - self.radius:j + self.radius + 1].sum()]\n\n def doubleCells(self):\n</code></pre>\n\n<p>Python standard convention is lowercase_with_underscores for method names</p>\n\n<pre><code> newcells = zeros(self.cells.shape, dtype=int8)\n self.cells = vstack((self.cells, newcells))\n</code></pre>\n\n<p>It might actually make more sense for self.cells to be a python list. Then you just append onto it. You may find it more useful to have it an array, but its something to consider</p>\n\n<pre><code> def reset(self):\n self.cells = zeros((1, self.width + 1), dtype=int8)\n self.next = 0\n</code></pre>\n\n<p>Consider whether you really want to have reset instead of just making a new object</p>\n\n<pre><code> def startSingle(self):\n self.reset()\n self.cells[0, (self.width - 1) / 2] = 1\n self.next = 1\n\n def startWith(self, val):\n self.reset()\n # TODO: Center the provided pattern\n self.cells[0] = val[:]\n self.next = 1\n\n def randomize(self, p):\n for i, x in enumerate(random.random(width - 2)):\n self.cells[0, i + 1] = int(x < p)\n self.next = 1\n</code></pre>\n\n<p>Use numpy's random functions. <code>self.cells[0, 1:-1] = numpy.random.random(width - 2) < p</code>. Actually self is undefined here suggesting you haven't done any testing on this function.</p>\n\n<pre><code> def buildTable(self, rule):\n table = {}\n #bound = 2 ** (self.radius + 1)\n</code></pre>\n\n<p>Don't keep dead code, just delete it</p>\n\n<pre><code> bound = (self.radius * 2) + 2\n for i, bit in enumerate(binary(rule, bound)):\n table[bound - 1 - i] = bit\n return table\n</code></pre>\n\n<p>Lookup numpy.unpackbits. It'll extract the bits from the number for you.</p>\n\n<pre><code> def getLatest(self):\n return self.cells[self.next - 1, :]\n\n def getEntropy(self):\n entropy = []\n for i in xrange(1, self.next - 1):\n p = float(self.cells[i].sum()) / float(self.width)\n entropy.append(-(p * log(p, 2)))\n return entropy\n</code></pre>\n\n<p>This could be readily vectorized, but its probably not performance critical.</p>\n\n<pre><code> def getLiveCounts(self):\n liveCounts = []\n for i in xrange(0, self.next - 1):\n liveCounts.append(self.cells[i].sum())\n return liveCounts\n\n def get_array(self, start=0, end=None):\n \"\"\"Gets a slice of columns from the CA, with slice indices\n (start, end). Avoid copying if possible.\n \"\"\"\n if start == 0 and end == None:\n return self.cells[0:self.next, :]\n else:\n return self.cells[0:self.next, start:end]\n</code></pre>\n\n<p>What if start is supplied but end is not?</p>\n\n<pre><code>def binary(n, digits):\n \"\"\"Returns a tuple of (digits) integers representing the\n integer (n) in binary. For example, binary(3,3) returns (0, 1, 1)\"\"\"\n t = []\n for i in range(digits):\n n, r = divmod(n, 2)\n t.append(r)\n\n return tuple(reversed(t))\n</code></pre>\n\n<p>This isn't a good place for a tuple, as it is a list of digits, not a collection of hetrogenous items.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T00:36:57.817",
"Id": "35846",
"Score": "0",
"body": "First off, thanks very much, your feedback is golden! Some of the things you questioned, such as various bits dealing with the unused cells on each end of the array were there to make it easier to adapt this code to allow the cells array to wraparound, that comes once I've got this down. You were right about randomize, I have never used it, should just remove it. You mentioned using a Python list rather than numpy array. I was using a numpy array because I thought it was the way to go for performance with this kind of thing, am I incorrect in that assumption? Again, thanks very much!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T00:53:37.540",
"Id": "35847",
"Score": "0",
"body": "@otakucode, numpy arrays are slower than python lists if used the same way. numpy arrays are faster only if you can use vector operations. If you are explicitly looping over the array you aren't gaining any performance. (Memory consumption will be down, but speed will not improve)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T00:58:00.113",
"Id": "35848",
"Score": "0",
"body": "@otakucode, regarding the wraparound, I suspect that unused cells aren't a good way of doing that. But I'll leave that up to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T02:15:28.140",
"Id": "35852",
"Score": "0",
"body": "I implemented the changes you suggested and it significantly improved the speed of my code. However, it still very rapidly consumes memory when run in the loop I posted. I'm very puzzled by this as I don't see how I could be leaving dangling references. Do you have any tips about that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T02:20:19.247",
"Id": "35853",
"Score": "0",
"body": "@otakucode, when I run your code (with my modifications) I'm not seeing the memory consumption issue. Perhaps you can supply a runnable example of your code in its current state?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T03:02:45.023",
"Id": "35854",
"Score": "0",
"body": "actually, I just did a quick experiment and left out the matplotlib rendering and the memory use was solid. Apparently my issue is in the code for the renderer somewhere, which is code I just took from the book. It's a lot more extra to get into, I wouldn't want to bother you with it, I will dig through it myself. Thanks for all of your help, your tips will help me a great deal going forward with my experiments!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:03:13.853",
"Id": "23207",
"ParentId": "23200",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23207",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T02:31:33.337",
"Id": "23200",
"Score": "2",
"Tags": [
"python",
"beginner",
"numpy",
"cellular-automata"
],
"Title": "Performance problems with 1D cellular automata experiment in Python with Numpy"
}
|
23200
|
<p>I'm new to using NUnit and have written a test to check for the existence of a database table. I have the below code that should check whether a new table named NewTable has been created in the database. It works correctly but I can't help feeling there's probably a better way of doing this. Thanks.</p>
<pre><code>using(var conn = context.NewConnection()) {
var tables = conn.GetSchema("Tables");
foreach(System.Data.DataRow row in tables.Rows) {
foreach(System.Data.DataColumn col in result.Columns) {
if(row[col.ColumnName].ToString() == "NewTable")
Assert.Pass();
}
}
}
Assert.Fail("NewTable not created");
</code></pre>
|
[] |
[
{
"body": "<p>I would do something like this instead -</p>\n\n<pre><code>using(var conn = context.NewConnection()) {\n var table = conn.GetSchema(\"Tables\");\n var tableNames = table.Rows.Cast<DataRow>()\n .Select(x => x[\"TABLE_NAME\"].ToString())\n .ToArray();\n Assert.That(tableNames.Contains(\"NewTable\"), Is.True);\n}\n</code></pre>\n\n<p>Tests are usually structured in Setup-Act-Assert fashion. A good unit test is one that tests just one condition on an action.</p>\n\n<p>Multiple asserts are practically unavoidable in certain cases, but having logic to decide when Assert should pass or fail isn't a good practice. The code under test should have the logic to branch, the test should only look at expected v/s actual results in a given scenario.</p>\n\n<p>In this case, our setup is - we get the schema from the database, and get the list of column names.</p>\n\n<p>Our logic (Act) is that certain column name must exist. So we write an assertion to ensure that. </p>\n\n<p>In other cases, there is an action and a result, the assertion is on the result. In this case, it is more of testing a state, so there isn't an assertion on the result of an action.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:23:53.707",
"Id": "35784",
"Score": "0",
"body": "Thank you for your answer! I think a simple explanation of why this is better (\"only one assert\", \"better use of existing constructs\", ...) could help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:26:12.000",
"Id": "35785",
"Score": "0",
"body": "wouldn't that check that there was a column returned by the GetSchema method named \"NewTable\"? I'm not sure that works. I want to check that a there is a table named \"NewTable\". I've just plugged that code in and the test now fails I'm afraid"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:31:04.427",
"Id": "35786",
"Score": "0",
"body": "@QuentinPradet - added a few lines on my thoughts around testing, hope it helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:34:02.227",
"Id": "35787",
"Score": "0",
"body": "Your answer inspired me to a better solution than I had. I have submitted an edit to the code so that it solves the exact question asked. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:37:05.220",
"Id": "35788",
"Score": "0",
"body": "@acqu13sce - I think you are right, the code might not work as it is. I didn't bother executing the getschema against a database. I'll try to make an edit that reflects something more real. Btw - I have included your edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:45:19.080",
"Id": "35790",
"Score": "0",
"body": "@SrikanthVenugopalan in response to your thoughts on unit tests, the code I pasted is in fact just the Assert part. Setup and Act are performed before my code snippet is run. Setup connects to a database and Act runs a method that should create a new table, I wanted to assert that it did. Thanks again and for including the edit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:50:54.457",
"Id": "35792",
"Score": "0",
"body": "@SrikanthVenugopalan Thank you, the answer is much clearer (and better) now!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T06:50:18.380",
"Id": "23206",
"ParentId": "23203",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23206",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T04:22:41.100",
"Id": "23203",
"Score": "2",
"Tags": [
"c#",
"database",
"unit-testing",
"nunit"
],
"Title": "Testing database table creation with NUnit"
}
|
23203
|
<p>I have a booking with a method <code>total</code> which calculates the total price of the booking from the sum of all the prices of activities that belong to appointments. A booking has many appointments and the following seems to give the right answer, but it seems horrid. How can I improve this?</p>
<pre><code> def total
# TODO shouldn't this be a db query?
total = 0
self.appointments.each do |appointment|
unless appointment.activity.price.nil?
total += appointment.activity.price.to_f
end
end
total
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:21:54.077",
"Id": "35783",
"Score": "0",
"body": "Hello, and welcome to Code Review! I don't know RoR enough to answer, but yes you need to understand how to do a sum query, which will avoid both the loop and the `nil` handling."
}
] |
[
{
"body": "<p>You can do this:</p>\n\n<pre><code>def total\n self.appointments.joins(:activity).sum(:price)\nend\n</code></pre>\n\n<p>You could perhaps simplify it a little, by making an explicit 2nd order <code>has_many</code> on your booking model:</p>\n\n<pre><code>has_many :appointments\nhas_many :activities, :through => :appointments\n</code></pre>\n\n<p>Then you can just do:</p>\n\n<pre><code>def total\n self.activities.sum(:price)\nend\n</code></pre>\n\n<p>In either case, it'll end up as a single DB-query.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T21:59:07.283",
"Id": "35836",
"Score": "0",
"body": "That has sped things up quite a bit even in my dev environment with a small data set & is obviously much more idomatic / simple / nicer to look at. Active record continues to amaze. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T16:33:48.693",
"Id": "23223",
"ParentId": "23204",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23223",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T04:26:05.420",
"Id": "23204",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Calculate sum of price on distant relation"
}
|
23204
|
<p>How do I make this more Ruby like? I want to return the host, for example
if the URL is "<a href="http://www.facebook.com" rel="nofollow">http://www.facebook.com</a>" then I want to get 'facebook.com'.</p>
<p>Any other sub-domains without 'www' should give the subdomin as well.
If the URL is "<a href="http://gist.github.com" rel="nofollow">http://gist.github.com</a>" then I want 'gist.github.com':</p>
<pre><code>def get_domain
a = @url.split('.')
a[-1] = a[-1].gsub(/\//,'')
if a[0][-3..-1] == "www"
a.delete_at(0)
else
a[0] = a[0].gsub(/https?:\/\//,'')
end
domain = a.join('.')
domain
rescue => e
puts e.message
end #end of get_domain
</code></pre>
|
[] |
[
{
"body": "<p>This is looking like a custom requirement. By looking at your code, you want to remove http(s) and www. part of the url</p>\n\n<pre><code>def get_custom_domain\n @url.gsub(/^((https?:\\/\\/)?(www\\.)?)/, '')\nend\n</code></pre>\n\n<p>But it will be better if you give more example of what you exactly want. I have written some specs <a href=\"https://gist.github.com/prathamesh-sonpatki/5045794\" rel=\"nofollow\">here</a>\nPlease update it if i am missing some edge case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T14:26:45.690",
"Id": "35806",
"Score": "1",
"body": "Parsing urls by hand is risky, for example try this one: `http://user:password@server.org/path/file`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:19:59.617",
"Id": "23208",
"ParentId": "23205",
"Score": "1"
}
},
{
"body": "<p>Use <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html#method-c-parse\">URI::parse</a>:</p>\n\n<pre><code>require 'uri'\nURI.parse(\"http://gist.github.com/a/b/c\").host.sub(/^www\\./, '')\n#=> \"gist.github.com\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T14:25:01.447",
"Id": "23216",
"ParentId": "23205",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T06:35:49.980",
"Id": "23205",
"Score": "4",
"Tags": [
"ruby",
"https"
],
"Title": "Refactor Ruby method for getting domain?"
}
|
23205
|
<p>I have a calculator created using C# that is running on a console. </p>
<p>The calculator accepts a string input (e.g. 5+5) then produces the result (5+5=10). It will then prompt the user to enter another operator which will continue the evaluation (e.g. 10+5=15). To terminate the program, one can type the string "done".</p>
<p>I would like to ask what other improvements I can make to increase the efficiency of my code.</p>
<pre><code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Calculator
{
class Calculate
{
ulong firstNumber { get; set; }
ulong secondNumber { get; set; }
public static ulong result = 0;
string equationOperator { get; set; }
public Calculate(ulong firstNumber, ulong secondNumber, string equationOperator)
{
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
this.equationOperator = equationOperator;
switch (this.equationOperator)
{
case "+":
result = this.firstNumber + this.secondNumber;
break;
case "-":
if (result < this.secondNumber)
{
result = this.secondNumber - this.firstNumber;
break;
}
result = this.firstNumber - this.secondNumber;
break;
case "/":
if (this.secondNumber == 0)
{
Console.WriteLine("\nCannot Divide by Zero!");
break;
}
result = this.firstNumber / this.secondNumber;
break;
case "*":
result = this.firstNumber * this.secondNumber;
break;
case "%":
result = this.firstNumber % this.secondNumber;
break;
}
Console.WriteLine("\n{0}\t{1}\t{2}\t= {3}", this.firstNumber, this.equationOperator, this.secondNumber, result);
}
}
class ContinueEval
{
public static void continueEvaluate()
{
string nextInput = "", equationOperator = "", secondNumber = "";
ulong prevResult;
while (nextInput != "done")
{
Console.Write("\n{0}",Calculate.result);
prevResult = Calculate.result;
nextInput = Console.ReadLine();
if (nextInput == "done")
break;
ushort n = 1;
for (n = 0; n < nextInput.Length; n++)
{
if (!(Regex.IsMatch(nextInput.Substring(0, n), @"^\d+$")))
{
equationOperator = nextInput[n].ToString();
break;
}
}
secondNumber = nextInput.Substring((n + 1), (nextInput.Length - 1));
switch (equationOperator)
{
case "+":
Calculate.result += ulong.Parse(secondNumber);
break;
case "-":
if (Calculate.result < ulong.Parse(secondNumber))
{
Calculate.result = ulong.Parse(secondNumber) - Calculate.result;
break;
}
Calculate.result -= ulong.Parse(secondNumber);
break;
case "/":
if (ulong.Parse(secondNumber) == 0)
{
Console.WriteLine("\nCannot Divide by Zero!");
break;
}
Calculate.result /= ulong.Parse(secondNumber);
break;
case "*":
Calculate.result *= ulong.Parse(secondNumber);
break;
case "%":
Calculate.result %= ulong.Parse(secondNumber);
break;
}
Console.WriteLine("\n{0}\t{1}\t{2}\t= {3}", prevResult, equationOperator, secondNumber, Calculate.result);
};
}
}
class ESlicer
{
public static void sliceEquation(string inputValue)
{
if (inputValue == "done")
Environment.Exit(0);
string firstNumber = "", secondNumber = "", equationOperator = "";
ushort n = 1, end = 0;
while (Regex.IsMatch(inputValue.Substring(0, n), @"^\d+$"))
{
firstNumber = inputValue.Substring(0, n);
if (!(Regex.IsMatch(inputValue[n].ToString(), @"^\d+$")))
{
equationOperator = inputValue[n].ToString();
break;
}
if (n > inputValue.Length)
break;
n++;
}
end = (ushort)(inputValue.Length - (firstNumber.Length + 1));
secondNumber = inputValue.Substring((n + 1), end);
Calculate p = new Calculate(ulong.Parse(firstNumber), ulong.Parse(secondNumber), equationOperator);
}
}
class Program
{
static void Main()
{
string inputValue;
Console.Write("Enter string of Equation: ");
inputValue = Console.ReadLine();
ESlicer.sliceEquation(inputValue);
ContinueEval.continueEvaluate();
Console.Write("Thank you for using!");
Console.Read();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:43:49.460",
"Id": "35789",
"Score": "4",
"body": "I would recommend you reading a good article about math expressions evaluation with C#: http://www.codeproject.com/KB/recipes/expressions_evaluator.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:49:58.327",
"Id": "35791",
"Score": "1",
"body": "% literally means percentage, but as an operator, it is a modulo operator. You might want to look at having percentage calculated explicitly. Also, try throwing exceptions instead of validating every step. You should also handle the exceptions expected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T15:36:23.573",
"Id": "35807",
"Score": "1",
"body": "Why did you define `result` as a `public static` attribute? In that way the attribute can be accessed an modified by other classes and it is shared across all the `Calculator` instances. Is it really what you need?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T21:51:27.537",
"Id": "35834",
"Score": "0",
"body": "Also, what do you mean by \"efficiency\"? How would you measure it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T01:32:01.173",
"Id": "35851",
"Score": "0",
"body": "I would like to know if the code can be shortened further or if there are any programming violations that occurred in the code. Thank you."
}
] |
[
{
"body": "<p>From your last comment, what you're actually looking for is not more efficiency (which is difficult to measure anyway), but more quality, and I think we can do that.</p>\n\n<p>The biggest problem is that the program is very hard to read and follow, and thus hard to maintain. This is for several reasons:</p>\n\n<ul>\n<li>Mixed responsibilities. You have split the work that your program needs to do into several classes, but not all of them do just one thing.</li>\n<li>Unclear program flow. This is in part a result the first issue. At any level of the program it is very hard to tell what the current state is, where it comes from and exactly how the current code influences what happens later, or which other code the current part directly depends on. This is also due to your intermixing of class instance code, static code and semi-static constructors. This is a rather small program that can be written in different styles, but not all at the same time.</li>\n</ul>\n\n<p>The most striking specific issue just from scrolling through the code is that the evaluation of the operator and the calculation of the result are present twice, and from looking more closely, it becomes clear that pretty much the whole program is present twice - the <code>ContinueEval</code> class has almost everything that is needed; that is because after the very first equation, the program only keeps looping within the <code>continueEvaluate()</code> method for all subsequent operations.</p>\n\n<p>That means that the <code>ContinueEval</code> class has a number of responsibilities:</p>\n\n<ul>\n<li>Taking the new input from the console</li>\n<li>Parsing the input</li>\n<li>Evaluating the operator</li>\n<li>Doing the actual calculation</li>\n<li>Displaying the result</li>\n<li>Looping back to take the next input</li>\n</ul>\n\n<p>That is a bit much to ask of one class. In addition, it duplicates the core functionality of the <code>ESlicer</code> (more or less) and <code>Calculate</code> classes in the process. One big problem this causes is that whenever you decide to change the way the input is parsed or add support for a new mathematical operation, you will have to make changes in two places, which is cumbersome and error prone.</p>\n\n<p>Let's break down the program flow that is currently a bit hidden, not least because of the use of global state in the <code>Calculate</code> class (try to avoid using global/static state as much as you can, and instead look for sensible ways to pass everything you need to the classes that require it; this will help a lot in making program flow and dependencies more explicit and easier to follow).</p>\n\n<ul>\n<li>Take the first input</li>\n<li>Parse it for the arguments and operator</li>\n<li>Calculate the first result</li>\n<li>(Start of the loop) Take the next input</li>\n<li>Parse it for the operator and argument</li>\n<li>Calculate the new result</li>\n<li>Loop back to take the next input</li>\n</ul>\n\n<p>Looking at this shows that there are three tasks that are being repeated - taking an input, parsing it and calculating the result. At least the latter two are non-trivial, and we should do what is necessary to only have the code for them once; this will help a lot in understanding and maintaining the program.</p>\n\n<p>I have tidied up the responsibilities and ended up with two classes for the main tasks, along with one to transfer the result of the parsed equation and a main loop which I left in <code>Program.Main()</code> for the time being[1]:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\nnamespace CalculatorX\n{\n public class Program\n {\n private static void Main()\n {\n Calculator calculator = new Calculator();\n EquationParser parser = new EquationParser();\n\n Console.Write(\"Enter string of Equation: \");\n\n bool doLoop = true;\n bool isFirstLoop = true;\n\n do\n {\n if (!isFirstLoop)\n {\n Console.Write(calculator.Result);\n }\n\n string inputValue = Console.ReadLine();\n if (\"done\" == inputValue)\n {\n doLoop = false;\n }\n else\n {\n ParseResult parsedInput = parser.Parse(inputValue);\n\n long firstArgumentForOutput = (isFirstLoop ? parsedInput.FirstArgument : calculator.Result);\n\n calculator.Process(parsedInput);\n\n Console.WriteLine(\"\\n{0}\\t{1}\\t{2}\\t= {3}\", firstArgumentForOutput, parsedInput.Operator, parsedInput.SecondArgument, calculator.Result);\n }\n\n isFirstLoop = false;\n }\n while (doLoop);\n\n Console.Write(\"\\r\\n\\r\\nThank you for using!\");\n Console.Read();\n }\n }\n\n public class Calculator\n {\n private bool _isInitialized;\n\n public long Result { get; private set; }\n\n public void Process(ParseResult parsedInput)\n {\n if (!this._isInitialized)\n {\n this.Result = parsedInput.FirstArgument;\n\n this._isInitialized = true;\n }\n\n switch (parsedInput.Operator)\n {\n case \"+\":\n this.Result += parsedInput.SecondArgument;\n break;\n\n case \"-\":\n this.Result -= parsedInput.SecondArgument;\n break;\n\n case \"*\":\n this.Result *= parsedInput.SecondArgument;\n break;\n\n case \"/\":\n this.Result /= parsedInput.SecondArgument;\n break;\n\n case \"%\":\n this.Result %= parsedInput.SecondArgument;\n break;\n\n default:\n break;\n }\n }\n }\n\n public class ParseResult\n {\n public long FirstArgument { get; set; }\n\n public string Operator { get; set; }\n\n public long SecondArgument { get; set; }\n }\n\n public class EquationParser\n {\n public ParseResult Parse(string input)\n {\n long firstArgument = 0;\n Match firstMatch = Regex.Match(input, \"^\\\\d+\");\n if (firstMatch.Success)\n {\n firstArgument = Convert.ToInt64(firstMatch.Value);\n }\n\n string operatorString = Regex.Match(input, \"\\\\D+\").Value;\n\n Match secondMatch = Regex.Match(input, \"\\\\d+$\");\n long secondArgument = Convert.ToInt64(secondMatch.Value);\n\n return new ParseResult()\n {\n FirstArgument = firstArgument,\n Operator = operatorString,\n SecondArgument = secondArgument\n };\n }\n }\n}\n</code></pre>\n\n<p>The significant differences to your solution are as follows:</p>\n\n<ul>\n<li>No hidden global state. Everything that is important can be followed on its way through the code, and each <code>Calculator</code> object completely controls everything its calculation depends on. You can now have hundreds of them at the same time, and they would work correctly, while with your <code>Calculate</code> class, they all would have shared and modified the same result.</li>\n<li>No hidden dependencies on other classes or static members. Your <code>ESlicer</code> class needs the <code>Calculate</code> class, but that is not apparent unless you actually happen to look into the code of that class and read that to the very last line.</li>\n<li>Testability. You would have no way to test the parsing of the input and the actual calculations separately in your program - you can only run the program, enter equations and look at the output to verify everything works correctly. I can use a unit test framework to write code that tests each of my classes independently - I can check if equations are parsed correctly, and I can check if all the calculations work without having to parse an equation first. Actually, both of these classes were written using the so-called <strong>Test-Driven Development (TDD)</strong> method, which is a great way to build code with a better structure and quality from the outset.</li>\n<li>Maintainability. When you find that something is not working correctly or need to extend the application (like adding 'power' as a new operation), it is very easy to make changes, because it's always very clear which parts of the code will be affected, and you can make changes with much less risk of breaking something, and thus with much greater confidence. This is also because you have no code duplications, so every change needs to be made in a single place only.\n(For example, my <code>EquationParser</code> class cuts quite a few corners with respect to input validation - I could now easily go ahead and do this, because I can be sure that I only need to make changes in that one class, and as long as it produces a correct <code>ParseResult</code>, the whole program will still work.)</li>\n</ul>\n\n<p>If you want to learn how to write well-structured, maintainable and evolvable high-quality code, making yourself familiar with the <strong>SOLID</strong> principles and the aforementioned <strong>Test-Driven Development</strong> is the way to go (I learned most of what I know from a guy named <strong>Mark Seemann</strong> - look him up; also look on YouTube for talks from <strong>Miško Hevery</strong>). Those are certainly no easy topics and may seem daunting, but they are worth every minute spent on them, because it is incredibly rewarding to see those things play out when you get the hang of them.\nAlso, try to keep your code as <strong>DRY</strong> as possible - DRY stands for \"Don't Repeat Yourself\" and means you should have as little duplicate code as possible, because duplicate code means more places to make changes, more places that can have bugs and more places to make mistakes.</p>\n\n<p>Most importantly - practice. The more, the better. Read up on the topics I mentioned, and try following those principles. It will often seem impossible at first, but you'll get ahead eventually. And don't forget to come back here with your results and ask for advice, because trying to get your head around everything on your own is often very difficult.</p>\n\n<hr>\n\n<p>[1] This would probably look slightly different if I was to write it as production code, but I wanted to keep it comprehensible in the first place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T00:50:34.257",
"Id": "36076",
"Score": "0",
"body": "Thank you very much! I had gained a lot of information from this since I am only starting to code in C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T02:48:19.240",
"Id": "36079",
"Score": "0",
"body": "If I may ask, are there any books that you recommend so that I can learn these kinds of programming practices more? Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T10:38:01.720",
"Id": "36090",
"Score": "0",
"body": "Nothing I could recommend to a beginner, unfortunately. Mark Seemann's *Dependency Injection in .NET* is an extremely insightful book, but doesn't teach SOLID outright and would probably be quite tough to understand for someone only just starting out. I myself picked up most things on the Internet in self-study."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T23:44:12.690",
"Id": "36444",
"Score": "0",
"body": "Just in case you come back here at some point - this seems to be pretty much the right thing for you: https://leanpub.com/KeepingSoftwareSoft It's a work in progress, and I have no idea of the quality, but content-wise it appears to be right as the next thing to read after a book that just covers the language features."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T17:48:01.820",
"Id": "23328",
"ParentId": "23209",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23328",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:23:32.073",
"Id": "23209",
"Score": "1",
"Tags": [
"c#",
"console",
"calculator",
"math-expression-eval"
],
"Title": "Calculator application running on a console"
}
|
23209
|
<p>i just wanted to confirm if my codes below is correct. Feel free to make corrections.</p>
<pre><code><?php
class createConnection
{
var $host="localhost";
var $username="root";
var $password="";
var $database="wilbert";
var $myconn;
function connectToDatabase()
{
$conn = mysql_connect($his->host,$this->username,$this->password);
if (!$conn)
{
die ("Cannot connect to the database");
}
else
{
$this->myconn = $conn;
echo "Connection established!";
}
return $this->myconn;
}
function selectDatabase()
{
mysql_select_db($this->database);
if(mysql_error())
{
echo "Cannot find the database ".$this->database;
}
else
{
echo "Database selected..";
}
}
function selectData()
{
mysql_select_db($this->database);
$result = mysql_query(" SELECT a.student_id, a.FirstName, b.First_Name FROM Student a LEFT JOIN teacher b ON a.student_id = b.student_id");
echo "<table border='1'>
<tr>
<th>Student_ID</th>
<th>First_Name</th>
<th>First_Name</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['student_id']. "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['First_Name'] . "</td>";
//echo "<td>" . $row['student_id'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
function closeConnection()
{
mysql_close($this->myconn);
echo "connection closed!";
}
}
?>
</code></pre>
<p>and here is my object.</p>
<pre><code><?php
include ('phpclass.php');
$connection = new createConnection(); //i created a new object
$connection->connectToDatabase(); // connected to the database
echo "<br />"; // putting a html break
$connection->selectDatabase();
echo "<br />";
$connection->selectData();
//$connection->closeConnection();// closed connection
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:20:53.713",
"Id": "35811",
"Score": "5",
"body": "I'd probably avoid using a deprecated library (i.e. `mysql_*`) too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T21:09:34.560",
"Id": "36257",
"Score": "0",
"body": "Either you should have cut and pasted a lot more carefully or shown us the error which occurred when you ran this ( `mysql_connect($his->host,$t...` )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T00:04:10.660",
"Id": "36274",
"Score": "0",
"body": "@symcbean - the above codes, my original codes are working but when I try the answers below, it doesnt work anymore :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T09:30:00.753",
"Id": "36291",
"Score": "1",
"body": "@lexter: really? What is $his ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-07T03:45:57.400",
"Id": "36337",
"Score": "0",
"body": "@symcbean - it's a typo.. it must be `$this`"
}
] |
[
{
"body": "<p>I am a fan of loose coupling so I would suggest that you take the values of host, username, password and database out of your class. Pass the values through the constructor and set them in the constructor. This makes it easier to reuse your code.</p>\n\n<p>Second, in classes such as one that creates a connection to a database I would not \"echo\" stuff. You better throw exceptions on error or return meaningful values to the caller.</p>\n\n<p>Last, I'd suggest other names. This might be nitpicking but this has more meaning to me:</p>\n\n<pre><code>$connection = new DatabaseConnection();\n$connection->open();\n$connection->connectDatabase();\n</code></pre>\n\n<p>So, wrapped up I would have something like:</p>\n\n<pre><code><?php\nclass DatabaseConnection\n{\n var $host;\n var $username;\n var $password;\n var $database;\n var $myconn;\n\n function __construct($dbhost, $user, $pass, $db)\n {\n $this->host = $dbhost;\n $this->username = $user;\n $this->password = $pass;\n $this->database = $db;\n }\n\n function open()\n {\n $conn = mysql_connect($his->host,$this->username,$this->password);\n if (!$conn)\n throw new Exception('Error establishing a connection.');\n else\n $this->myconn = $conn;\n\n return $this->myconn;\n }\n\n function connectDatabase()\n {\n mysql_select_db($this->database);\n if(mysql_error())\n throw new Exception(\"Cannot find the database \" . $this->database);\n }\n\n function selectData($query)\n {\n mysql_select_db($this->database);\n $result = mysql_query($query);\n return $result;\n }\n\n function closeConnection()\n {\n mysql_close($this->myconn);\n }\n}\n?>\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$connection = new DatabaseConnection(\"localhost\", \"root\", \"\", \"wilbert\");\n$connection->open();\n$connection->connectDatabase();\n$connection->selectData(\"SELECT a.student_id, a.FirstName, b.First_Name FROM Student a LEFT JOIN teacher b ON a.student_id = b.student_id\");\n</code></pre>\n\n<p>See how the other names make more sense? Try to avoid verbs as a classname. Methods can and most likely will be or contain verbs, but not classnames. Also, leaving the query out of the class leaves you the option to use the same code for other queries. </p>\n\n<p>Note that this is no perfect code, I was only suggesting what might be changed. Hope this helps! :)</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>You call the function selectData() and pass the query-string as a parameter. This changes nothing, it gives the same result as your code. Only in my case you can pass other queries to the function whereas your function is limited to the embedded query.</p>\n\n<p>Now for the result. This has also to do with the decoupling of your connection-class and what will be shown to the user. I showed u the usage of the class, the code below is how you can process the result. Create a function (but not in the connection class!) that returns the result in a table:</p>\n\n<pre><code>function resultTable($sqlResult)\n{\n $table = \"<table border='1'>\";\n $table .= \"<tr><th>Student_ID</th><th>First_Name</th><th>First_Name</th></tr>\";\n\n while($row = mysql_fetch_array($sqlResult))\n {\n $table .= \"<tr><td>\" . $row['student_id']. \"</td>\";\n $table .= \"<td>\" . $row['FirstName'] . \"</td>\";\n $table .= \"<td>\" . $row['First_Name'] . \"</td></tr>\";\n }\n $table .= \"</table>\";\n\n return $table;\n}\n</code></pre>\n\n<p>And the usage:</p>\n\n<pre><code>$connection = new DatabaseConnection(\"localhost\", \"root\", \"\", \"wilbert\");\n$connection->open();\n$connection->connectDatabase();\n$result = $connection->selectData(\"SELECT a.student_id, a.FirstName, b.First_Name FROM Student a LEFT JOIN teacher b ON a.student_id = b.student_id\");\necho resultTable($result);\n</code></pre>\n\n<p>You could create a new class in which you define all sorts of methods like these to process a result and return it to the view-file where you will show it on the screen. Hope this clarifies it. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T01:22:52.410",
"Id": "35850",
"Score": "0",
"body": "in the part of \n\nfunction selectData($query)\n{\n mysql_select_db($this->database);\n $result = mysql_query($query);\n return $result;\n}\n\nwhere will the $query get its values?\nis it possible to show the result in a table, because in my codes above. the results of the LEFT JOIN were embedded in an html table :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T08:10:18.447",
"Id": "35861",
"Score": "0",
"body": "Check my edited answer! ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T08:03:05.753",
"Id": "35929",
"Score": "0",
"body": "how will the class and object be connected in your codes?where is the \"include();\" line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T00:26:40.663",
"Id": "35976",
"Score": "0",
"body": "include('DatabaseConnection.php'); and then the lines of code from the section usage. For simplicity you can place the resultTable-function in the view-file. Otherwise place it in a separate file and include that file as wel with an include(). Then simply call the function with the SQL-result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T03:09:18.657",
"Id": "36080",
"Score": "0",
"body": "`echo resultTable($result);` `$result` doesnt have any values. am i correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-04T08:33:49.663",
"Id": "36083",
"Score": "0",
"body": "Did you use the exact code that I provided, and included all the files and functions? $result is what is returned from the selectData($query) function."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T08:43:49.683",
"Id": "23213",
"ParentId": "23210",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "23213",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:54:21.237",
"Id": "23210",
"Score": "2",
"Tags": [
"php"
],
"Title": "class and object in php"
}
|
23210
|
<p>I'm working on my larger project to date, and on top of that I'm using underscore for the first time.
All is working perfectly but I'd like some criticism on the use of underscore templating and underscore after function.</p>
<p>The goal of the app is to generate on the dom a messaging interface starting from an empty div. It gets initialized by passing the jQuery selector of that empty div.</p>
<p>I took out most of the code and left what I'd like to be reviewed the most, hope the flow of the app is quite clear anyway.</p>
<pre><code>(function($) {
$(document).ready(function() {
var mssg_tmpl = {
msg_container : ' \
<div class="row-fluid msg-container well" id="msg-<% id %>"> \
some html \
</div>',
msg_reply : ' \
<div class="reply well message"> \
some html \
</div>'
};
mssg = {
init : function(selector) {
this.$container = $(selector);
this.tmpl = {}; // List of compiled templates functions
this.compileTemplates(mssg_tmpl);
this.messages = [{ // THIS IS HARDCODE TO ILLUSTRATE BASIC STRUCTURE
id: 1, // Thread opener
children: [2,3,4] // Replies
}, {
id: 5,
children: [6,7,8]
}];
for ( var i in this.messages) {
this.$container.append(this.tmpl.msg_container(this.messages[i])); // fn msg_container is a compiled template
this.messages[i].$container = $('#msg-' + this.messages[i].id);
this.fetchChildren(this.messages[i]);
}
this.bindEvents();
this.collapseMessages();
return this;
},
compileTemplates : function(templates) {
for ( var k in templates) {
this.tmpl[k] = _.template(templates[k]);
}
},
fetchChildren : function(message) {
var renderChildren = _.after(message.children.length, function() {
children = _.sortBy(children, 'id'); // Sort replies (oldest first)
for ( var i in children) {
message.$container.find('div.msg-reply-container').before(mssg.tmpl.msg_reply(children[i])); // fn msg_reply is a compiled template
}
});
var children = [];
for ( var i in message.children) {
$.ajax({
url : 'getmessage.htm?messageId=' + message.children[i]
}).done(function(response) {
children.push(response);
renderChildren();
});
}
},
};
mssg = mssg.init('#messaging');
});
})(jQuery);
</code></pre>
|
[] |
[
{
"body": "<p>Since you asked to review only the underscore part,</p>\n\n<p>Just had one remark that I would suggest to move the templates to a script tag \"text/template\" rather than defining them as a variable.</p>\n\n<p>eg:</p>\n\n<pre><code><script type=\"text/template\" id=\"msg_container\">\n <div class=\"row-fluid msg-container well\" id=\"msg-<% id %>\">\n some html\n </div>\n</script>\n\n<script type=\"text/template\" id=\"msg_reply\">\n <div class=\"reply well message\">\n some html\n </div>\n</script>\n</code></pre>\n\n<p>Compile and use the same like below,</p>\n\n<pre><code>var msg_container = _.template($('#msg_container').html());\nvar msg_reply = _.template($('#msg_reply').html());\n</code></pre>\n\n<p>Though you asked to review only the '_' part but couldn't resist asking this question, From your example snippet I see 6 potential AJAX calls based on the loops. Wouldn't there be a performance problem since it completely relies on the number of messages and replies and what if the messages and replies are more or I could be missing the overall picture :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T15:27:53.283",
"Id": "35876",
"Score": "1",
"body": "Hi thanks for taking the time to read and comment!\nI know the best practice would be to move templates to a script tag but the goal is to make this a library than can be imported without much hassle into all the apps my company works on, so it's essential that who implements it in their code only has to include a js file, a css file, and an empty div where the app will be initialized. I am considering moving templates to a separate js file which could be a little better from the present solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T14:24:18.543",
"Id": "60985",
"Score": "0",
"body": "@DavidFregoli I would keep templates as much as possible out of the library. Separation of concerns."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T22:21:00.157",
"Id": "23244",
"ParentId": "23215",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "23244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T13:41:42.420",
"Id": "23215",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"underscore.js"
],
"Title": "Underscore and general app design review"
}
|
23215
|
<p><a href="//underscorejs.org" rel="nofollow">Underscore</a> is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in <a href="http://prototypejs.org/api" rel="nofollow">Prototype.js</a> or <a href="/questions/tagged/ruby" class="post-tag" title="show questions tagged 'ruby'" rel="tag">ruby</a> (e.g. the <a href="http://www.ruby-doc.org/core/classes/Enumerable.html" rel="nofollow"><code>Enumerable</code></a> module), but without extending any of the built-in JavaScript objects. It complements <a href="/questions/tagged/jquery" class="post-tag" title="show questions tagged 'jquery'" rel="tag">jquery</a> and <a href="/questions/tagged/backbone.js" class="post-tag" title="show questions tagged 'backbone.js'" rel="tag">backbone.js</a>. A similar library is <a href="/questions/tagged/lodash.js" class="post-tag" title="show questions tagged 'lodash.js'" rel="tag">lodash.js</a>.</p>
<p>Underscore provides 80-odd functions that support both the usual functional suspects: <code>map</code>, <code>select</code>, <code>invoke</code> — as well as more specialized helpers: function binding, JavaScript templating, deep equality testing and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of <code>forEach</code>, <code>map</code>, <code>reduce</code>, <code>filter</code>, <code>every</code>, <code>some</code> and <code>indexOf</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T14:32:43.197",
"Id": "23217",
"Score": "0",
"Tags": null,
"Title": null
}
|
23217
|
Underscore is a library for JavaScript that provides functional programming support.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T14:32:43.197",
"Id": "23218",
"Score": "0",
"Tags": null,
"Title": null
}
|
23218
|
<p>I want to find out if there are any improvements I can make to this code. How can I make it better, faster and use less queries? Or is it fine the way I wrote it?</p>
<pre><code><?php if ( $user_ID ) : ?>
<?php
global $user_identity;
?>
<div id="boxtop">
<div class="boxtop">
<div class="bus">
<div class="busl">
<span class="bin">
Bine ai revenit<a href="/edit-profile/"><b><?php echo $user_identity; ?></b> !</a>
</span>
<?php
global $current_user;
$current_user = wp_get_current_user();
?>
<a href="/utilizatori-inregstrati/">Utilizatori</a>|<a href="/edit-profile/">Profil</a>|<a href="<?php echo wp_logout_url( get_bloginfo('url') ); ?>" title="Logout">Logout</a>
</div>
<div class="busr">
<?php
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
echo get_avatar( $current_user->user_email, 40 );
}
?>
</div>
</div>
</div>
</div>
<?php else : ?>
<div id="boxtop">
<div class="boxtop">
<a class="fblogin" href="http://www.mysite.ro/wp-login.php?loginFacebook=1&redirect=http://www.mysite.ro" onclick="window.location = 'http://www.mysite.ro/wp-login.php?loginFacebook=1&redirect='+window.location.href; return false;"><img src="/wp-content/themes/movies/images/fb.png" title="Login with Facebook" /></a>
<form name="loginform" id="loginform" action="<?php echo get_option('siteurl'); ?>/wp-login.php" method="post">
<input value="Utilizator" class="input" type="text" size="10" tabindex="10" name="log" id="user_login" onfocus="if (this.value == 'Utilizator') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Utilizator';}" />
<input value="Parola" class="input" type="password" size="10" tabindex="20" name="pwd" id="user_pass" onfocus="if (this.value == 'Parola') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Parola';}" />
<input name="wp-submit" id="wp-submit" value="Login" tabindex="100" type="submit">
<span class="bin">
<span><a href="/recupereaza-parola/">Recuperare parola</a></span><span><a href="/inregistrare/">Inregistrare</a></span><input name="rememberme" id="rememberme" value="forever" tabindex="90" type="checkbox"> <span>Retine parola?</span>
</span>
<input name="redirect_to" value="<?php echo get_option('siteurl'); ?>" type="hidden">
<input name="testcookie" value="1" type="hidden">
</form>
</div>
</div>
</div>
<?php endif; ?>
</code></pre>
|
[] |
[
{
"body": "<p>Ok, a few things of note. Not really related to perfomance, but readability. To be fair though these are just details for better readability, your code is not so bad.</p>\n\n<p>This code is not expensive process wise, I was curious as to where <code>$User_id</code> comes from, because that is where the query you are worried about comes into play, but I trust your tables are properly indexed and output data is <a href=\"http://phpsecurity.org/code/ch01-4\" rel=\"nofollow\">properly escaped</a>.</p>\n\n<p>On line 12-14, I would put that php code up at top, all in a single php block.\nThis would separate the php from the html and make for better readability.</p>\n\n<p>Also, same thing for the php block on line 21. You call once again <code>$current_user = wp_get_current_user();</code> , but you already have <code>$current_user</code> from line 15. </p>\n\n<p>I would take this block to the top, and change the <code>echo get_avatar()</code> call to :</p>\n\n<pre><code>$avatar = \"\";\nif ( ($current_user instanceof WP_User) ) {\n $avatar = get_avatar( $current_user->user_email, 40 );\n} \n</code></pre>\n\n<p>By initialising the variable (best practice), in your html \"template code\" below <em>you can get away with just:</em></p>\n\n<pre><code>if ($avatar) { print $avatar; }\n</code></pre>\n\n<p>This habit leaves minimal <code>php</code> in the <code>html</code> and thus separates the logic from presentation.</p>\n\n<p>I assume indentation was lost when you pasted, so I will not patronize you on this.</p>\n\n<p>Hope this helps, happy coding.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:44:58.357",
"Id": "23232",
"ParentId": "23220",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T15:44:20.273",
"Id": "23220",
"Score": "3",
"Tags": [
"php"
],
"Title": "User Registration compress to use less querry, CPU posible"
}
|
23220
|
<p>Could you please critisize the logger class below? Can it be used in a multi threaded web environment? If not how can I improve it? Is there anything wrong with locking in WriteToLog method or multithreading in FlushLog method?</p>
<pre><code>public class Logger
{
private static Logger instance;
private static Queue<LogData> logQueue;
private static string logDir = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LogDirectory"]);
private static string logFile = "log.txt";
private static int maxLogAge = Int32.Parse(ConfigurationManager.AppSettings["LogMaxAge"]);
private static int queueSize = Int32.Parse(ConfigurationManager.AppSettings["LogQueueSize"]);
private static DateTime LastFlushed = DateTime.Now;
private Logger() { }
public static Logger Instance
{
get
{
if (instance == null)
{
instance = new Logger();
logQueue = new Queue<LogData>();
}
return instance;
}
}
public void WriteToLog(string message)
{
lock (logQueue)
{
LogData logEntry = new LogData(message);
logQueue.Enqueue(logEntry);
if (logQueue.Count >= queueSize || DoPeriodicFlush())
{
FlushLog();
}
}
}
private bool DoPeriodicFlush()
{
TimeSpan logAge = DateTime.Now - LastFlushed;
if (logAge.TotalSeconds >= maxLogAge)
{
LastFlushed = DateTime.Now;
return true;
}
else
{
return false;
}
}
private void FlushLog()
{
System.Threading.ThreadPool.QueueUserWorkItem(q => {
while (logQueue.Count > 0)
{
LogData entry = logQueue.Dequeue();
string logPath = logDir + entry.LogDate + "_" + logFile;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPath, true, System.Text.Encoding.UTF8))
{
file.WriteLine(string.Format("{0}\t{1}", entry.LogTime, entry.Message));
}
}
});
}
~Logger()
{
FlushLog();
}
}
public class LogData
{
public string Message { get; set; }
public string LogTime { get; set; }
public string LogDate { get; set; }
public LogData(string message)
{
Message = message;
LogDate = DateTime.Now.ToString("yyyy-MM-dd");
LogTime = DateTime.Now.ToString("HH:mm:ss.fff tt");
}
}
</code></pre>
<p>Thanks in advance,</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:41:55.920",
"Id": "35813",
"Score": "3",
"body": "This is one of those areas where there are so many available (free and otherwise) mature and proven logging frameworks that attempting to create a robust performant one from scratch is not a great use of one's time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:46:14.477",
"Id": "35814",
"Score": "1",
"body": "I'm just asking this question to learn something about thread safety and design patterns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:21:08.540",
"Id": "35821",
"Score": "7",
"body": "Don't re-invent the wheel; use log4net."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:21:20.760",
"Id": "35822",
"Score": "1",
"body": "This particular wheel has been invented multiple times. I suggest you take a look at one of the several options available."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:21:37.213",
"Id": "35823",
"Score": "1",
"body": "With worries like these you should be using something like log4net where all of these issues have been worked out: http://logging.apache.org/log4net/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:21:39.037",
"Id": "35824",
"Score": "1",
"body": "Your code is rather non-thread-safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:59:45.360",
"Id": "35826",
"Score": "0",
"body": "Please tell my mistakes. I know about log4net and the others. I just need to see some suggestions with your reasons to overcome my misunderstandings about the subject I mentioned above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:28:38.297",
"Id": "35827",
"Score": "1",
"body": "As said in the comments, you should take a look at log4net. It's thread-safe and a proven solution. Features: http://logging.apache.org/log4net/release/features.html NuGet package: https://nuget.org/packages/log4net/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T21:30:54.577",
"Id": "35832",
"Score": "1",
"body": "Correct me if I am wrong but this branch of stack exchange is called Code Review. So I assume it is kind of place to discuss any piece of code for any good reason and anilca asks the question to gain better insight about patterns and multi-threading. \nIt is nice you mention logger frameworks but least constructive comment would be look at class foo at bar framework since what you are looking is implemented perfectly there. Telling a person, use rather this or that can fit to StackOverflow much better."
}
] |
[
{
"body": "<p>This code is not thread safe. You synchronize (lock) while adding to the queue, but your code which removes from the code does not lock the queue, and will always run on a background thread, which is going to cause potential race conditions.</p>\n\n<p>If you really must write your own logging, I would, at the least, look into using <a href=\"http://msdn.microsoft.com/en-us/library/dd267265.aspx\"><code>ConcurrentQueue<T></code></a> to avoid the need for locking on adding. <code>BlockingCollection<T></code> would make this far simpler, as you could just have a thread call <code>GetConsumingEnumerable()</code> to process items as they're added.</p>\n\n<p>That being said, logging is something that's been handled many times, and handled well. You'd be far better off using something like the new <a href=\"http://entlib.codeplex.com/releases/view/101823\">Semantic Logging Application Block</a> (from P&P) or even <a href=\"http://logging.apache.org/log4net/\">log4net</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:06:26.713",
"Id": "35828",
"Score": "0",
"body": "Thanks for your answer! I'm gonna take a look at your suggestions. I did not even know the classes you mentioned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:09:43.487",
"Id": "35829",
"Score": "1",
"body": "@anilca Great - that being said, for logging, using a pre-made solution is really just about always a superior option."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:29:54.793",
"Id": "23236",
"ParentId": "23229",
"Score": "4"
}
},
{
"body": "<p>Your singleton is not thread safe in first place. Please look at :\n<a href=\"http://www.yoda.arachsys.com/csharp/singleton.html\" rel=\"nofollow\">Thread safe singleton implementation in C#</a></p>\n\n<p>It is better to use Synchronized wrapper of the Queue. Queue is not thread safe.</p>\n\n<p>Then i think lock in the WriteToLog redundant if you use thread safe Queue. Because each thread will safely enqueue log message it can not lead that if statement there to a wrong state.</p>\n\n<p>However lock is definitely needed in FlushLog since the Queue is being enumerated there (thread safe Queue does not help in enumeration).</p>\n\n<p>Finally there is an IO operation in a singleton, it is best to handle possible exceptions that is likely to come from an IO operation. You would not like to thrash your singleton easily.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T21:16:28.230",
"Id": "23239",
"ParentId": "23229",
"Score": "3"
}
},
{
"body": "<p>Easy way to make your logger thread safe:</p>\n\n<p>Change:</p>\n\n<pre><code>private static Logger instance;\nprivate static Queue<LogData> logQueue;\n\npublic static Logger Instance\n{\n get\n {\n if (instance == null)\n {\n instance = new Logger();\n logQueue = new Queue<LogData>();\n }\n return instance;\n }\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>private static Logger instance = new Logger();\nprivate static ConcurrentQueue<LogData> logQueue = new ConcurrentQueue<LogData>();\n\npublic static Logger Instance\n{\n get\n {\n return instance;\n }\n}\n</code></pre>\n\n<p>I would honestly just use <a href=\"http://nuget.org/packages/log4net\" rel=\"nofollow\">log4net</a> and extend it to support your use case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T07:48:05.970",
"Id": "35859",
"Score": "0",
"body": "After that change will I still need lock statements in my methods?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T08:55:45.597",
"Id": "35863",
"Score": "0",
"body": "Anilca, yes you have to lock. But not all of them. Read my explanation that is given as an answer.\nIt is not thread-safe only by making construction thread-safe or using Thread-safe data structure. There are other concerns. Please read the answers above. It is explained by myself and by Reed Copsey so far."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T10:03:16.937",
"Id": "35866",
"Score": "0",
"body": "And what if my framework is older than 4.0? Is it possible to make my logger thread safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T10:17:07.587",
"Id": "35868",
"Score": "1",
"body": "You can check what are the available data structures and thread api for the specific version of the framework that you use by checking documentation.\nBasically I worked with .NET before but currently (and mostly using Java) and regardless of the framework, platform there are some rules like you have to pick thread-safe data structure and you have to lock when you are iterating over that data structure. Therefore by taking into account those rules you can pick up the right api classes and methods for your specific case."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T00:59:01.153",
"Id": "23247",
"ParentId": "23229",
"Score": "0"
}
},
{
"body": "<p>Why hasn't anyone suggested Nlog? It's far better than Log4Net and is still actively maintained, unlike Log4Net, which hasn't been updated since version 1.2.10, published April 19, 2006. Also, Log4Net documentation blows. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/710863/log4net-vs-nlog\">https://stackoverflow.com/questions/710863/log4net-vs-nlog</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T13:02:43.407",
"Id": "35872",
"Score": "0",
"body": "Last log4net release was 2012-11-29"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T05:19:46.833",
"Id": "23250",
"ParentId": "23229",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23236",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T18:32:31.580",
"Id": "23229",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"multithreading",
"thread-safety",
"locking"
],
"Title": "Designing a better logger class"
}
|
23229
|
<p>I just started to learn Haskell, and i wrote a function that walks the directory tree recursively and pass the content of each directory to a callback function:</p>
<ul>
<li>The content of the directory is a tuple, containing a list of all the sub-directories, and a list of file names.</li>
<li>If there is an error, the error is passed to the callback function instead of the directory content (it use <code>Either</code>).</li>
</ul>
<p>So here is the type of the callback function: </p>
<pre class="lang-haskell prettyprint-override"><code>callback :: FileName -> Either IOError ([FileName], [FileName]) -> IO ()
</code></pre>
<p>And here is the type of my <code>walk</code> function:</p>
<pre class="lang-haskell prettyprint-override"><code>walk :: FilePath -> (FilePath -> Either IOError ([FilePath], [FilePath]) -> IO ()) -> IO ()
</code></pre>
<p>And here is my complete code:</p>
<pre class="lang-haskell prettyprint-override"><code>module Test where
import System.FilePath ((</>))
import Control.Monad (filterM, forM_, return)
import System.IO.Error (tryIOError, IOError)
import System.Directory (getDirectoryContents, doesFileExist, doesDirectoryExist)
myVisitor :: FilePath -> Either IOError ([FilePath], [FilePath]) -> IO ()
myVisitor path result = do
case result of
Left error -> do
putStrLn $ "I've tryed to look in " ++ path ++ "."
putStrLn $ "\tThere was an error: "
putStrLn $ "\t\t" ++ (show error)
Right (dirs, files) -> do
putStrLn $ "I've looked in " ++ path ++ "."
putStrLn $ "\tThere was " ++ (show $ length dirs) ++ " directorie(s) and " ++ (show $ length files) ++ " file(s):"
forM_ (dirs ++ files) (\x -> putStrLn $ "\t\t- " ++ x)
putStrLn ""
walk :: FilePath -> (FilePath -> Either IOError ([FilePath], [FilePath]) -> IO ()) -> IO ()
walk path visitor = do
result <- tryIOError listdir
case result of
Left error -> do
visitor path result
Right (dirs, files) -> do
visitor path result
forM_
(map (\x -> path </> x) dirs)
(\x -> walk x visitor)
where
listdir = do
entries <- (getDirectoryContents path) >>= filterHidden
subdirs <- filterM isDir entries
files <- filterM isFile entries
return (subdirs, files)
where
isFile entry = doesFileExist (path </> entry)
isDir entry = doesDirectoryExist (path </> entry)
filterHidden paths = do
return $ filter (\path -> head path /= '.') paths
main :: IO ()
main = do
walk "/tmp" myVisitor
walk "foo bar" myVisitor
putStrLn "Done :-/"
</code></pre>
<p>As you can see, there is a lot of code and i <code>import</code> a lot of things...
I'm sure there is a better way to do that, and i'm interested in any
<code>{idea,hint,tip}</code> to improve this piece of code.</p>
<p>Thanks in advance :-)</p>
|
[] |
[
{
"body": "<p>You might be interested in the concept of iteratees/pipes that can be used to solve this problem. It allows you to separate producing the tree and consuming it somewhere else without direct callback functions: You create a producer that enumerates the directory tree, perhaps some filters that modify the data and a separate consumer that works on the data. And then compose and run the whole pipeline. See also <a href=\"https://stackoverflow.com/q/14259229/1333025\">Streaming recursive descent of a directory in Haskell</a>.</p>\n\n<p>There are also specialized Haskell packages for that such as <a href=\"http://hackage.haskell.org/package/directory-tree\" rel=\"nofollow noreferrer\">directory-tree</a>, which you can use or study.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> As an example I reworked your code using <a href=\"http://hackage.haskell.org/package/conduit\" rel=\"nofollow noreferrer\">conduit</a>. This library (and others based on the same principle) has several advantages, namely:</p>\n\n<ul>\n<li>It separates the producer of the data with its consumer.</li>\n<li>In a source you just call <code>yield</code> when you want to send a piece of data to the pipe.</li>\n<li>In a sink you call <code>await</code> whenever you want to receive a piece of data (here we used more specialized <code>awaitForever</code>).</li>\n<li>You can have <em>conduits</em> that sit in the middle and consume and produce values at the same time. They can do whatever processing on the stream, mixing calls to <code>yield</code> and <code>await</code> as they wish.</li>\n<li>This allows you to create complex computation where the behavior of your components depends on data sent/deceived earlier. We use this in our source (traversing a directory tree), and I also added it to the sink (visitor) - it keeps track of how many directories it has been passed so far.</li>\n<li>Both source and sink (and intermediate conduits, if any) can have finalizers.</li>\n</ul>\n\n<p>Some suggestions:</p>\n\n<ol>\n<li>Create your own data types instead of using combinations of <code>Either</code> and <code>(,)</code>. It makes your code shorter and easier to understand.</li>\n<li>Sometimes it's worth declaring new functions instead of using complex <code>case ... of</code> expressions. It can make code easier to read.</li>\n<li><a href=\"http://hackage.haskell.org/package/hlint\" rel=\"nofollow noreferrer\">hlint</a> can suggest how to (syntactically) improve a piece of code.</li>\n</ol>\n\n<hr>\n\n<pre><code>import System.FilePath ((</>))\nimport Control.Monad (filterM, forM_, return)\nimport System.IO.Error (tryIOError, IOError)\nimport System.Directory (getDirectoryContents, doesFileExist, doesDirectoryExist)\nimport Control.Monad.Trans.Class (lift)\nimport Data.Conduit\n\ndata DirContent = DirList [FilePath] [FilePath]\n | DirError IOError\ndata DirData = DirData FilePath DirContent\n\n-- Produces directory data\nwalk :: FilePath -> Source IO DirData\nwalk path = do \n result <- lift $ tryIOError listdir\n case result of\n Right dl@(DirList subdirs files)\n -> do\n yield (DirData path dl)\n forM_ subdirs (walk . (path </>))\n Left error\n -> yield (DirData path (DirError error))\n\n where\n listdir = do\n entries <- getDirectoryContents path >>= filterHidden\n subdirs <- filterM isDir entries\n files <- filterM isFile entries\n return $ DirList subdirs files\n where \n isFile entry = doesFileExist (path </> entry)\n isDir entry = doesDirectoryExist (path </> entry)\n filterHidden paths = return $ filter (\\path -> head path /= '.') paths\n\n-- Consume directories\nmyVisitor :: Sink DirData IO ()\nmyVisitor = addCleanup (\\_ -> putStrLn \"Finished.\") $ loop 1\n where\n loop n = do\n lift $ putStrLn $ \">> \" ++ show n ++ \". directory visited:\"\n r <- await\n case r of\n Nothing -> return ()\n Just r -> lift (process r) >> loop (n + 1)\n process (DirData path (DirError error)) = do\n putStrLn $ \"I've tried to look in \" ++ path ++ \".\"\n putStrLn $ \"\\tThere was an error: \"\n putStrLn $ \"\\t\\t\" ++ show error\n\n process (DirData path (DirList dirs files)) = do\n putStrLn $ \"I've looked in \" ++ path ++ \".\"\n putStrLn $ \"\\tThere was \" ++ show (length dirs) ++ \" directorie(s) and \" ++ show (length files) ++ \" file(s):\"\n forM_ (dirs ++ files) (putStrLn . (\"\\t\\t- \" ++))\n\nmain :: IO ()\nmain = do\n walk \"/tmp\" $$ myVisitor\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-16T19:06:00.083",
"Id": "36998",
"Score": "0",
"body": "I don't want to add too many dependencies to my software, so i won't use\n`directory-tree` ; However, `conduit` seems great and can probably be used in\nsereral parts of my software, so i think i will use it. Anyway, your code is\nmore cleaner than mine, especially the 2ⁿᵈ function. \nThanks for your response\n:-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T20:10:49.110",
"Id": "23233",
"ParentId": "23231",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "23233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T19:00:39.790",
"Id": "23231",
"Score": "7",
"Tags": [
"haskell",
"recursion",
"directory"
],
"Title": "Is there a better way to walk a directory tree?"
}
|
23231
|
<p>This code computes the function <code>(3x^2-4x+16) / (5x^2+2x-4)</code>. I ran the program and it works, but I am fairly new to assembly language and am not quite sure how to make the most efficient use of the registers. Does this look ok or is there a better way to do it?</p>
<pre><code>.text
.globl main
main:
ori $8, $0, 3 #put x into $8
ori $9, $0, 3 #puts 3 into $9
ori $10, $0, 4 #puts 4 into $10
ori $11, $0, 16 #puts 16 into $11
mult $8, $8 #Squares x
mflo $13 #$13 = x^2
mult $9, $13 #Computes 3x^2
mflo $14 # $14 = 3x^2
mult $10, $8 # lo = 4x
mflo $15 # $9 = 4x
sub $16, $14, $15 # $16 = 3x^2 -4x
add $17, $16, $11 #$17 = 3x^2 - 4x + 16
ori $8, $0, 1 #put x into $8
ori $9, $0, 5 #puts 5 into $9
ori $10, $0, 2 # put 2 into $10
ori $11, $0, 4 # puts 4 into $11
mult $8, $8 #Squares x
mflo $13 #$13 = x^2
mult $9, $13 #Computes 5x^2
mflo $14 # $14 = 5x^2
mult $10, $8 # lo = 2x
mflo $15 # $9 = 2x
add $16, $14, $15 # $16 = 5x^2 +4x
sub $18, $16, $11 #$17 = 5x^2 + 2x - 4
div $17, $18 #divides 2 functions
mflo $8 #quotient
mfhi $9 #remainder
## End of file
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T00:25:10.560",
"Id": "35845",
"Score": "0",
"body": "I won't provide you any assembly advice but would it be relevant to compile some simple C/C++ code and check the corresponding assembly code. Here's my attempt : \nint main(int x,char **a){return (3*x*x-4*x+16)/(5*x*2+2*x-4);}. This is stupid code but I wanted to keep it simple.\n(You can check the assembly output with http://gcc.godbolt.org/ )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T07:44:13.130",
"Id": "35858",
"Score": "0",
"body": "use $zero, $s... and $t... for registers. makes code more readable and robust. http://en.wikipedia.org/wiki/MIPS_architecture#Compiler_register_usage"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T07:48:39.557",
"Id": "35860",
"Score": "0",
"body": "As long as you do not do load or store, what difference does it make if you use 7 temp registers or 8?"
}
] |
[
{
"body": "<p>There are multiple issues:</p>\n\n<p>first, try to make the program work: These two lines are contradictory</p>\n\n<pre><code>ori $8, $0, 3 #put x into $8\nori $8, $0, 1 #put x into $8\n</code></pre>\n\n<p>Perhaps the real idea is to move a function parameter to $8.</p>\n\n<p>The second thing is redundant calculation:\nInstead of squaring x twice, you should be able to</p>\n\n<pre><code>mul $8, $8\nmflo $13\nmflo $14\n</code></pre>\n\n<p>To catch the result in two registers.</p>\n\n<p>There's no need to reserve registers for all the immediates, as one can at least add the last coefficients 16 and (-4) with</p>\n\n<pre><code>addi $x, $x, 16\n</code></pre>\n\n<p>Multiplications with small constants are also often better executed with a series of shifts and adds. Especially here x*4 equals x<<2 and x*2 == x+x, which leads to one less instruction for both operations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T11:13:02.540",
"Id": "23259",
"ParentId": "23245",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T22:53:33.363",
"Id": "23245",
"Score": "5",
"Tags": [
"optimization",
"beginner",
"assembly"
],
"Title": "Computing a mathematical function in MIPS assembly"
}
|
23245
|
<p>As part of my data collection, I have to run multiple kinds of coverage processing on multiple Java projects. Below is my main <code>Makefile</code> intented only for gmake. Portability is not a requirement for me (for this project), but DRY and following make best practices are. Please comment on my code, and if there is any way to make this better.</p>
<pre><code>.PHONY: checkout all clobber clean $(checkout.all)
.SECONDARY: $(addprefix projects/,$(names))
root:=$(CURDIR)
names=$(shell cat etc/projects.txt)
checkout.all=$(addprefix checkout-,$(names))
clean.all=$(addprefix clean-,$(names))
testgen.types=original randoop tpalus
all:
@echo use 'make <type>-<project>'
@echo projects = $(names)
@echo types = $(testgen.types)
checkout: $(checkout.all)
@echo $@ done.
checkout-%: projects/%/pom.xml
@echo $@ done.
projects build: ; mkdir -p $@
projects/%/pom.xml: | projects build
cd projects && $(root)/bin/checkout $*
touch $@
clean: $(clean.all)
@echo $@ done.
clean-%: | projects/%/pom.xml
cd projects/$* && git clean -xfd && git reset --hard
@echo $@ done.
clobber-%:
cd projects && rm -rf $*
#-----------------------------------------------------------------
root:=$(CURDIR)
define testgen =
$1 : $(addprefix $(1)-,$(names))
@echo $$(@) done.
$1-% : projects/%/.$(1).done
@echo $$(@) done.
%/.$1.done : | %/pom.xml
echo $$(MAKE) -C $$(*) root=$$(root) $(1)
endef
$(foreach var,$(testgen.types),$(eval $(call testgen,$(var))))
</code></pre>
<p>Some clarification about the intended purpose of this project. I am doing an analysis on a large number of projects from github. My method of action is to clone each project, run multiple tests on them. Before running any project, I do a git clean to make sure that the artifacts of previous tests are not present in the project directories. The <code>types</code> of tests and projects <code>names</code> vary frequently, and hence I have kept them outside the main Makefile.</p>
|
[] |
[
{
"body": "<pre><code>.PHONY: checkout all clobber clean $(checkout.all)\n</code></pre>\n\n<p>There's no <code>clobber</code> target, so I <em>think</em> that will be ignored.</p>\n\n<hr>\n\n<p>The <code>root</code> variable is unnecessary (<code>CURDIR</code> should be well known by anyone using <code>make</code>), and is even defined twice.</p>\n\n<hr>\n\n<pre><code>names=$(shell cat etc/projects.txt)\n</code></pre>\n\n<p>In my experience it's more common to write out the list in the makefile. If this is so long as to clutter up the file, you could create a separate makefile for variables like this and <code>include variables.mk</code> or similar.</p>\n\n<hr>\n\n<pre><code>projects build: ; mkdir -p $@\n</code></pre>\n\n<p>Why not split this into two lines? Also, the <code>-p</code> doesn't make any difference since it's only creating a single directory under the current one.</p>\n\n<hr>\n\n<pre><code>touch $@\n</code></pre>\n\n<p>This looks like a hack to get around <code>checkout</code> not updating the modified date properly, or to rebuild a project when <code>make</code> doesn't think it needs to be rebuilt. You might be able to just set the relevant target <code>.PHONY</code> or change it so that rebuilding is only done when necessary.</p>\n\n<hr>\n\n<pre><code>cd projects/$* && git clean -xfd && git reset --hard\n</code></pre>\n\n<p>This is rather brutal. I'd rather advise to use <a href=\"http://evbergen.home.xs4all.nl/nonrecursive-make.html\">non-recursive <code>make</code></a> (based on <a href=\"http://miller.emu.id.au/pmiller/books/rmch/\">Recursive Make Considered Harmful</a>) and enumerate the files to remove to make sure you never remove anything other than generated files. You could have a separate target with <code>cd projects/$* && git clean -xnd</code> to check whether there's anything you still need to clean.</p>\n\n<hr>\n\n<pre><code>clobber-%:\n cd projects && rm -rf $*\n</code></pre>\n\n<p>This also looks dangerous. You're effectively saying that <code>make clobber-whatever</code> will delete <code>whatever</code> no matter what it is. I can't recall where I heard this advice, but I do believe it's good practice to enumerate the files which makefiles can and should work with, rather than adding general-purpose tactical nuclear missiles.</p>\n\n<hr>\n\n<pre><code>define testgen =\n...\n$(foreach var,$(testgen.types),$(eval $(call testgen,$(var))))\n</code></pre>\n\n<p>There's a lot of indirection going on here, so it's difficult to understand what will actually be run in the end. Are you sure this couldn't be done simpler?</p>\n\n<hr>\n\n<p>This is a personal preference, but I tend to avoid any <code>echo</code> statements because the <code>make</code> output should make it clear what is actually happening, and comments like this often tend to get out of sync with the rest of the code. On the other hand, you can include special targets to <a href=\"https://github.com/l0b0/make-includes/blob/master/variables.mk\">get the value of all/any variables</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T23:23:13.080",
"Id": "35972",
"Score": "0",
"body": "Thank for your comments, my clarifications are as follows"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T23:24:36.620",
"Id": "35973",
"Score": "0",
"body": "I need the $root directory to save the location of outer project directory (it is passed to the recursive make). I have control only over the top level makefile. the inner projects under projects/... are independent projects expected to only expose a makefile with defined targets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T23:25:27.150",
"Id": "35974",
"Score": "0",
"body": "`mkdir -p` will not fail if the directory exists unlike `mkdir`. Hence the usage. Also I dont want to `projects build: ; mkdir -p $@` split this since that would be counter to DRY principle. I agree about `touch`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T09:48:25.447",
"Id": "35984",
"Score": "1",
"body": "Reasonable caveats all, and the main reason code review for strangers is difficult: You don't know which constraints the other is working under."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T10:11:38.253",
"Id": "35985",
"Score": "0",
"body": "I agree, and given the lack of info, your review was pretty good. thanks."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T15:00:54.643",
"Id": "23313",
"ParentId": "23246",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "23313",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T23:03:06.307",
"Id": "23246",
"Score": "7",
"Tags": [
"java",
"git",
"make",
"maven"
],
"Title": "Coverage processing on multiple Java projects with gmake"
}
|
23246
|
<p>I'm new to PHP and had to put together a function that loads a random image from an array (it works fine). Here's what I came up with. Could it be improved? Any feedback would be appreciated.</p>
<pre><code><?php
function displayRandomPhotoArea() {
$photoAreas = array("imageURL1", "imageURL2", "imageURL3", "imageURL4", "imageURL5");
$randomNumber = rand(0, (count($photoAreas) - 1));
echo '<img src="' . $photoAreas[$randomNumber] . '" width="725" height="194">';
}
// Display a random image here
displayRandomPhotoArea();
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T08:52:30.080",
"Id": "35862",
"Score": "1",
"body": "I don't think this can be improved that much. You could make it more generic by passing the url-array as a parameter and return a random image-tag instead of directly displaying it."
}
] |
[
{
"body": "<p>Try to use <strong>array_rand</strong> function, code will look cleaner: </p>\n\n<pre><code><?php\nfunction displayRandomPhotoArea() \n{\n $photoAreas = array(\"imageURL1\", \"imageURL2\", \"imageURL3\", \"imageURL4\", \"imageURL5\");\n\n $randomNumber = array_rand($photoAreas);\n $randomImage = $photoAreas[$randomNumber];\n\n echo \"<img src=\\\"$randomImage\\\" width=\\\"725\\\" height=\\\"194\\\">\";\n}\n\ndisplayRandomPhotoArea();\n?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T08:57:18.140",
"Id": "23254",
"ParentId": "23253",
"Score": "3"
}
},
{
"body": "<pre><code><?php\nfunction displayRandomPhotoArea() {\n $photoAreas = array(\"imageURL1\", \"imageURL2\", \"imageURL3\", \"imageURL4\", \"imageURL5\");\n\n $randomNumber = rand(0, (count($photoAreas) - 1));\n</code></pre>\n\n<p>You can use directly the <code>array_rand</code> instead of this combination of rand and count, but this <a href=\"http://www.php.net/manual/fr/function.array-rand.php#105265\" rel=\"nofollow\">comment on the documentation</a> says that it is not too random, so you can keep your code like this. More generally, always try to make use of the standard library in PHP which offers a number of useful functions.</p>\n\n<pre><code> echo '<img src=\"' . $photoAreas[$randomNumber] . '\" width=\"725\" height=\"194\">';\n</code></pre>\n\n<p>You should return the string here, instead of echoing it. This is better design for a number of reasons:</p>\n\n<ul>\n<li>This separates the concern of echoing with the concern of building the string</li>\n<li>You don't want to restrict yourself to simply echoing it, you might want to use it afterwards in other ways</li>\n<li>You should start echoing only when you're certain that you're not going to issue a redirect to another page. Even if this is not an issue today, it will be someday, and you should be prepared.</li>\n</ul>\n\n<p>Regarding separation of concern, it is good practice to separate logic (here choosing a random image) and presentation (displaying the image). Web frameworks use variations of a <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">design pattern named</a> MVC which you might want to learn about, at least to separate your views from the rest of your code. This might not be needed if your code is very short, but it's still an useful tool.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T08:57:43.710",
"Id": "23255",
"ParentId": "23253",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23255",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T08:24:29.460",
"Id": "23253",
"Score": "4",
"Tags": [
"php",
"array",
"random",
"image"
],
"Title": "Function that Loads a Random Image from an Array"
}
|
23253
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.