body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have this assignment to write the optimized space and time code for finding the sum of all primes under 2 million. I'm using the following function to check if each number is prime:</p>
<pre><code>int IsPrime(unsigned int number) {
if (number <= 1) return 0;
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
</code></pre>
<p>And running a <code>for</code> loop from 1 to 2 million using a <code>long double</code>, and checking each number if it is prime and then adding it. Is there a more optimized method to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:35:51.460",
"Id": "11171",
"Score": "0",
"body": "Why are you using a long double in the outer loop? Will you show all of your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:43:03.580",
"Id": "11172",
"Score": "1",
"body": "You *have* searched ... right? Various trivial optimizations are discussed at great length on the inter-webs. Many numbers can be trivial skipped. (All evens > 2, all numbers ending in 0 or 5 > 5, every second \"advance 2\" > 3, etc.) Also, consider `i < sqrt(number)`, where `sqrt(number)` is a constant for the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T17:43:54.207",
"Id": "11186",
"Score": "1",
"body": "[Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)"
}
] |
[
{
"body": "<p>There are dozens of possible optimizations. The most obvious -- why are you multiplying <code>i</code> by itself every pass in the loop?! Just calculate the loop cut off <em>once</em>.</p>\n\n<p>And why <code>i++</code>?! After you test 2, there's no reason to test 4, 6, or 8. You can test 2, and then start from 3 adding <em>2</em> each time instead of one.</p>\n\n<p>Also, since you need to find <em>all</em> the primes up to a given point, you should be using a sieve rather than testing each number.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:35:56.500",
"Id": "11173",
"Score": "0",
"body": "Please clarify your answer. What is a sieve? Why should he not multiply by i?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:36:17.187",
"Id": "11174",
"Score": "0",
"body": "Also, do not test against any even numbers except 2!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:37:16.167",
"Id": "11175",
"Score": "5",
"body": "A [sieve](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) is a means of finding all primes less than a given number. He shouldn't multiply `i` by itself every time in the loop because it's a multiplication every single pass in the loop and it serves no purpose. He should just calculate what number he wants to loop to *once* rather than doing it each pass in the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:40:04.853",
"Id": "11176",
"Score": "0",
"body": "Eratosthenes sieve would be the more common name, except for those who are familiar with prime problems"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:40:52.380",
"Id": "11177",
"Score": "0",
"body": "Thanks for the clarification. Yes it is stupid multiplying the incremental variable. I didn't look close, thought he was multiplying the limit variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:43:07.663",
"Id": "11178",
"Score": "0",
"body": "Genius! Just learned something new ! Thanks @David Schwartz"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:43:17.977",
"Id": "11179",
"Score": "1",
"body": "The other well-known optimization for \"IsPrime\" is that you need not check for any factoring for values above sqrt(number) if you checked all the vales less that sqrt(number). (And for the love of Bob, don't inline sqrt(number) into your loop - calculate it once!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:44:51.250",
"Id": "11180",
"Score": "0",
"body": "You can also stop the search for factors of the number, N, as `sqrt(N)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:45:46.447",
"Id": "11181",
"Score": "0",
"body": "@selbie Whether or not that's an optimization depends on how you implement it. Squaring the loop index each time isn't much help. ;) If you're willing to write fast code to find the square root, that helps a lot. ([Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number) is one way.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:46:47.540",
"Id": "11182",
"Score": "0",
"body": "that's what I mean by \"don't inline\" the sqrt call into the for statement. Calculate it outside."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T19:02:41.207",
"Id": "38117",
"Score": "0",
"body": "Eratosthenes is probably the simplest and most intuitive sieve to implement, though other sieves are faster."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:34:17.663",
"Id": "7168",
"ParentId": "7167",
"Score": "15"
}
},
{
"body": "<p>Your <code>IsPrime</code> function looks OK. This won't help it's speed very much, but it will a little...</p>\n<pre><code>bool isPrime(unsigned int number) {\n if (number <= 1) {\n return false;\n } else if (number % 2 == 0) {\n return number == 2;\n } else {\n for (unsigned int i = 3; true; i += 2) {\n const unsigned int remainder = number % i;\n const unsigned int quotient = number / i;\n if (remainder == 0) {\n return false;\n } else if (quotient < i) {\n return true;\n }\n }\n }\n}\n</code></pre>\n<p>This takes about half the time because some processors (all x86 processors) have a combined 'find the remainder and quotient' instruction that this leverages. It also avoids testing even numbers. If your number is not divisible by 2, it won't be divisible by any other even number other, since all even numbers can also be divided by 2.</p>\n<p>Also, make sure you have compiler optimizations turned on.</p>\n<p>This is basically like hard-coding the very first step of the Sieve of Eratosthenes. Using the full sieve is likely a lot slower. But using the first step like this and hard-coding it as a step-distance will be much faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-12-26T05:42:01.847",
"Id": "7169",
"ParentId": "7167",
"Score": "4"
}
},
{
"body": "<p>As others have pointed out, you can cut your work in half by avoiding even numbers. However, avoiding even numbers after 2 is just the first part of using a sieve: if you filter by every prime number found up to the square root of a particular number that you want to test, you can check by only those numbers. </p>\n\n<p>Here is some java-like psuedocode to illustrate what I'm saying:</p>\n\n<pre><code>public List findPrime(int upperLimit){\n List primes = new List();\n primes.add(2);\n for(int i=3;i<upperLimit;i++){\n boolean primeFlag = true;\n for(test in primes){\n if(test > sqrt(i)\n break;\n if(i % test == 0){\n primeFlag = false; break;\n }\n }\n if(primeFlag) primes.add(i);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:50:55.103",
"Id": "7170",
"ParentId": "7167",
"Score": "0"
}
},
{
"body": "<p>To enumerate all prime number below a limit you could use <a href=\"http://rosettacode.org/wiki/Sieve_of_Eratosthenes#C.2B.2B\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> as mentioned by <a href=\"https://stackoverflow.com/a/8633196/4279\">@David Schwartz in the comment</a>:</p>\n\n<pre><code>#include <cmath>\n#include <iostream>\n#include <vector>\n#include <stdint.h>\n\nnamespace {\n // yield all prime numbers less than limit.\n template<class UnaryFunction>\n void primesupto(int limit, UnaryFunction yield)\n {\n std::vector<bool> is_prime(limit, true);\n\n const int sqrt_limit = std::sqrt(limit);\n for (int n = 2; n <= sqrt_limit; ++n)\n if (is_prime[n]) {\n yield(n); \n for (unsigned k = n*n, ulim = limit; k < ulim; k += n)\n //NOTE: \"unsigned\" is used to avoid an overflow in `k+=n`\n //for `limit` near INT_MAX\n is_prime[k] = false;\n }\n\n for (int n = sqrt_limit + 1; n < limit; ++n)\n if (is_prime[n])\n yield(n);\n }\n}\n\nint main() {\n uintmax_t sum = 0;\n primesupto(2000000, [&sum] (int prime) { sum += prime; });\n std::cout << sum << std::endl;\n}\n</code></pre>\n\n<h3><a href=\"http://ideone.com/OW197\" rel=\"nofollow noreferrer\">Demo</a></h3>\n\n<pre><code>$ g++ -std=c++0x sum-primes.cc -o sum-primes && ./sum-primes\n142913828922\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T07:00:52.977",
"Id": "7171",
"ParentId": "7167",
"Score": "8"
}
},
{
"body": "<p>I have done that before. The point is that you don't have to divide your number by all odd numbers smaller than it, but by all PRIME numbers smaller than it.</p>\n\n<p>So, pass the list of the prime numbers you had found to the function and divide your new number by each them. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T21:08:00.257",
"Id": "7499",
"ParentId": "7167",
"Score": "5"
}
},
{
"body": "<p>For every prime number <code>n>=5</code>, <code>n mod 6 returns 1</code> or <code>n mod 6 returns 5</code>. If you check these candidates for primeness by seeing if any prime number that is less than or equal to sqrt(n) divides a candidate could help eliminate many checks. When you do find a prime number, you could add to a list or, just add up to get the sum. The thing about this method is, it helps eliminate many checks that would simply return composite instead of prime, which is what you are looking for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:19:58.573",
"Id": "7607",
"ParentId": "7167",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T05:32:21.490",
"Id": "7167",
"Score": "9",
"Tags": [
"c++",
"performance",
"primes",
"homework"
],
"Title": "Sum of all primes under 2 million"
}
|
7167
|
<p>I am trying to remove duplicates from a string without using additional buffers.<br>
This seems to work correct, I think. Can this be improved? Should I be doing it differently? </p>
<pre><code>private static String removeDuplicates(char[] chars) {
if(chars == null)
return null;
int len = chars.length;
for(int i = 0; i < len; i++){
for(int j = i + 1; j < len;){
if(chars[i] == chars[j]){
int temp = j;
while(temp < len - 1){
chars[temp] = chars[temp + 1];
temp++;
}
len--;
}
else
j++;
}
}
return new String(chars, 0, len);
}
</code></pre>
|
[] |
[
{
"body": "<p>A few stylistic comments :</p>\n\n<ol>\n<li><p>I'd change the while loop for a for loop. It doesn't matter at all but I feel it better that way.</p></li>\n<li><p>You could perform <code>len--;</code> before the while (or for) loop so that you can go til <code>len</code> instead of <code>len - 1</code>.</p></li>\n</ol>\n\n<p>Then, as duplicates don't need to be close to each other (from what I understand), wouldn't it be easier to do something like (NOT TESTED AT ALL) :</p>\n\n<pre><code>private static String removeDuplicates(char[] chars) { \n if(chars == null) \n return null;\n int len = chars.length;\n int idx = 0; \n for (int i = 0; i < len; i++) {\n char c = chars[i];\n bool dup = false;\n for (int j = 0; j < idx; j++) {\n if (c == chars[j]) {\n dup = true;\n break;\n }\n }\n if (!dup) {\n chars[idx] = c;\n idx++;\n }\n }\n\n return new String(chars, 0, idx);\n}\n</code></pre>\n\n<p>The point would be to go through the string and for each characters, try to see if we have seen it already. If we haven't we store it, otherwise, we don't.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T20:47:17.560",
"Id": "7175",
"ParentId": "7173",
"Score": "4"
}
},
{
"body": "<p>Are you sure you want to return <code>null</code> if the <code>chars</code> parameter is null?<br>\nEither it is acceptable to pass <code>null</code> into your method - you can then use the <em><a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">Special Case Pattern</a></em> (also known as the <em>NullObjectPattern)</em> and <code>return \"\";</code><br>\nOr, you decide that passing <code>null</code> is not acceptable. In that case, it is advisable to <code>throw new IllegalArgumentException(\"chars may not be null!\");</code> </p>\n\n<p>Why? Because if you return <code>null</code>, and some completely unrelated class uses the return value after passing in <code>null</code> as a parameter, that will likely generate a <code>NullPointerException</code> which is going to be much more of a headache to debug.</p>\n\n<p>I'd personally be inclined to use the <code>special case pattern</code> because it treats the null argument as a legal case, reacting in the most non-disruptive way possible and keeping the system running, most likely without causing any random Exceptions later.</p>\n\n<p>However, some may argue that it is important for failures to be caught early, and if you see a <code>null</code>parameter as such a failure then definitely an <code>IllegalArgumentException</code>would make sense.</p>\n\n<p>So even though it seems logical to pass back <code>null</code> when you receive it, it's better to do the thing that will protect you from long debugging session later, which is to either <em>fail fast</em> or to not fail at all by treating an null input as a valid case.</p>\n\n<p>You said your intent was to</p>\n\n<blockquote>\n <p>remove duplicates from a string without using additional buffers</p>\n</blockquote>\n\n<p>yet you are passing in a <code>char[]</code>. You should pass in a <code>String</code> and then call <code>ToCharArray</code> <em>even if the exercise book says you shouldn't.</em> Otherwise, every time you call the method you will have first convert the input <code>String</code>to a <code>char[]</code>, cluttering the call site every single time. </p>\n\n<p>With an hard-to-understand algorithm like this, <strong>you should be using descriptive names</strong>. All these adjustments leave us with the following code:</p>\n\n<pre><code>private static String removeDuplicatesFrom(String original) {\n if (original == null) \n return \"\";\n char[] chars = original.toCharArray();\n int length = chars.length;\n for (int current = 0; current < length; current++) {\n // compare the current char with all following chars\n // and delete it if one of them is the same\n for (int next = current + 1; next < length;) {\n if (chars[current] == chars[next]) { \n // found a duplicate, need to delete it\n length--;\n for (int gap = next; gap < length; gap++) {\n // delete the duplicate and left-shift all remaining chars\n chars[gap] = chars[gap + 1];\n }\n } else\n next++;\n // current character is unique, move on\n }\n }\n return new String(chars, 0, length);\n}\n</code></pre>\n\n<p>Notice that I <em>was forced</em> to write four comments because I <strong>failed to make the code more expressive</strong>. I hate comments, but I used them here because I think your requirements don't allow you to <em>call other methods</em>. Am I right? Otherwise, you should do it as in <a href=\"https://stackoverflow.com/a/2598434/1106367\">this StackOverflow answer</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:17:45.717",
"Id": "11318",
"Score": "0",
"body": "@ codesparkle:I don't really see the gain in making the input parameter a `String` object instead of a `char []`.May be I am missing your point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:59:18.310",
"Id": "11321",
"Score": "0",
"body": "It depends on how the method is intended to be *used*. If you are going to remove duplicates from a `String`, you should pass in a `String`, otherwise you'll end up with a lot of duplicate code that converts the input to a `char[]`. If, on the other hand, your call sites will not be using Strings but char arrays, then you shouldn't be returning a String (because the calling code would have to convert it *back* to a `char`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T22:36:16.793",
"Id": "7176",
"ParentId": "7173",
"Score": "3"
}
},
{
"body": "<ol>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#430\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a></p>\n\n<blockquote>\n <p>if statements always use braces {}.</p>\n</blockquote>\n\n<p>It's error-prone, so change</p>\n\n<pre><code>if(chars == null) \n return null;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (chars == null) {\n return null;\n}\n</code></pre></li>\n<li><p>I agree with <em>@codesparkle</em>, it should throw an <code>IllegalArgumentException</code> or <code>NullPointerException</code> instead of returning with <code>null</code>.</p>\n\n<pre><code>if (chars == null) {\n throw new NullPointerException();\n}\n</code></pre></li>\n<li><p>I'd use a <code>for</code> loop instead of inner <code>while</code>. It's more readable since it's an everyday <code>for</code> loop which iterates from <code>j</code> to <code>len - 1</code>. Furthermore, this loop should be extracted out to a well-named method:</p>\n\n<pre><code>if (chars[i] == chars[j]) {\n len--;\n shiftArray(chars, len, j);\n} else {\n j++;\n}\n\n...\n\nprivate static void shiftArray(final char[] array, final int arrayLength,\n final int startIndex) {\n for (int i = startIndex; i < arrayLength; i++) {\n array[i] = array[i + 1];\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T17:33:59.850",
"Id": "11217",
"Score": "0",
"body": "+1 for suggesting to extract a method, but I do think the contrived exercise he is following won't allow him to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:14:50.253",
"Id": "11317",
"Score": "0",
"body": "@palacsint: I agree that the `shiftArray` method makes the code more readable, but is the extra cost of a function call worth it in this case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:41:36.730",
"Id": "11319",
"Score": "0",
"body": "The JVM is pretty smart about runtime optimizations, I don't think that it would be any slower. (Profile it!) http://stackoverflow.com/questions/7772864/would-java-inline-methods-during-optimization, http://stackoverflow.com/questions/6495030/java-how-expensive-is-a-method-call On the other hand, probably somebody have to maintain this method. You can save him or her a lot of time if you write easier to read code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T16:50:17.030",
"Id": "7184",
"ParentId": "7173",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T18:42:01.880",
"Id": "7173",
"Score": "7",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "Review on code for duplicate removal"
}
|
7173
|
<p>Delphi is a general purpose language for rapid development of native Windows, OS X and iOS applications. </p>
<p>The name also refers to the Delphi IDE, which is used to help edit and debug Delphi projects more efficiently. It is sold by Embarcadero, as a standalone product or included in RAD Studio, which includes other languages as well.</p>
<p>Delphi is used for the RAD Studio personality using Delphi as the programming language of choice. Delphi is an enhancement of Niklaus Wirth's language Pascal.</p>
<p>Delphi originated in 1995 at Borland, evolving from Turbo Pascal. It quickly became the language of choice for Windows programming. It is currently owned by Embarcadero, and is the second-largest Windows development platform after Microsoft's .NET.</p>
<p>Delphi is the father of C#, with the VCL being moved to the OS level and extended as the .NET framework. Delphi's Chief Architect [Anders Hejlsberg][19] is now Lead Architect for C# at Microsoft.</p>
<p>Among Delphi's strengths are its easy learning curve, consistent language architecture, a blazingly fast compiler, great execution speed, modern language constructs, its extensive Visual Component Library (VCL), and the associated visual form designer.</p>
<p>Variants: Some other Embarcadero products are or were released using the "Delphi" brand. A .NET variant called Delphi Prism (Delphi Prism is not a Delphi variant at all, Delphi.NET was. Prism is based on PascalScript codebase) exists that lives in MS Visual Studio and allows for cross platform development using Mono (also, CLR is not "cross-platform", but platform itself. It is offtopic here, as it is distinct). It's mostly compatible with Delphi syntax, but uses very different libraries. The Embarcadero PHP product used to be labelled "Delphi" until recently, and there is an AS/400 version of Delphi too. Both the PHP product and Prism are integrated in the main Embarcadero studio project in the current version, Rad Studio XE2.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T14:57:34.470",
"Id": "7180",
"Score": "0",
"Tags": null,
"Title": null
}
|
7180
|
Delphi is a language for rapid development of native Windows, OS X and iOS applications through use of Object Oriented Pascal. The name also refers to the Delphi IDE, which is used to help edit and debug Delphi projects more efficiently.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T14:57:34.470",
"Id": "7181",
"Score": "0",
"Tags": null,
"Title": null
}
|
7181
|
<p>Based on the standard implementation of <code>Array.sort</code> in JavaScript, would the following be a reasonable way of shuffling the contents of an array? Is it moderately efficient and will it produce a fairly even spread of results?</p>
<pre><code>Array.prototype.shuffle = function () {
return this.sort(function(){ return Math.random() - 0.5;});
};
</code></pre>
|
[] |
[
{
"body": "<p><a href=\"http://javascript.about.com/library/blsort4.htm\" rel=\"nofollow noreferrer\">This article</a> says that a test run on that algorithm showed a bias with items less likely to move farther away from their original location than near (a bias). </p>\n\n<p>My own intuition says that it could cause issues because the .sort() algorithm expects that when a given two elements are compared they will always have the same comparison result and yet that is not true when using this function. Therefore, I'm thinking that how well this work could also depend upon how the .sort() method was actually implemented internally.</p>\n\n<p><a href=\"http://javascript.about.com/library/blsort4.htm\" rel=\"nofollow noreferrer\">This article</a> shows what seems to me like a better algorithm for randomness, though I wouldn't expect it to be particularly efficient:</p>\n\n<pre><code>Array.prototype.shuffle = function() {\n var s = [];\n while (this.length) s.push(this.splice(Math.random() * this.length, 1));\n while (s.length) this.push(s.pop());\n return this;\n}\n</code></pre>\n\n<p>EDIT: Also just found this same question here: <a href=\"https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling\">https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling</a>. That answer suggests this which is based on the Fisher-Yates algorithm and would be a lot more efficient than the algorithm above: </p>\n\n<pre><code>function shuffle(array) {\n var tmp, current, top = array.length;\n\n if(top) while(--top) {\n current = Math.floor(Math.random() * (top + 1));\n tmp = array[current];\n array[current] = array[top];\n array[top] = tmp;\n }\n\n return array;\n}\n</code></pre>\n\n<p>And, here's a testpage that shows the results of your proposed method vs. the Fisher-Yates method in your browser: <a href=\"http://phrogz.net/JS/JavaScript_Random_Array_Sort.html\" rel=\"nofollow noreferrer\">http://phrogz.net/JS/JavaScript_Random_Array_Sort.html</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T21:45:04.963",
"Id": "11236",
"Score": "0",
"body": "+1 on Fisher-Yates as a common and efficient algorithm for shuffling that is used in many places. You can read more about the algorithm http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T18:22:47.833",
"Id": "7187",
"ParentId": "7186",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7187",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T17:39:06.570",
"Id": "7186",
"Score": "3",
"Tags": [
"javascript",
"array",
"sorting",
"shuffle"
],
"Title": "JavaScript shuffle idea"
}
|
7186
|
<p>I posted the following Matlab script in response to a question on <a href="http://dsp.stackexchange.com">Signal Processing</a>. Here is the <a href="https://dsp.stackexchange.com/questions/1036/what-are-high-frequencies-and-low-frequencies-in-a-signal/1038">questions</a> with my <a href="https://dsp.stackexchange.com/questions/1036/what-are-high-frequencies-and-low-frequencies-in-a-signal/1038#1038">answer</a>.</p>
<p>I am looking for comments on how to make this code more instructive for the questioner. Any other code review comments are also welcomed.</p>
<pre><code>fs = 2^10; %sample frequency in Hz
T = 1/fs; %sample period in s
L = 2^20; %signal length
t = (0:L-1) * T; %time vector
A1 = 0.2; %amplitude of x1 (first signal)
A2 = 1.0; %amplitude of x2 (second signal)
f1 = 1; %frequency of x1
f2 = 50; %frequency of x2
x1 = A1*sin(2*pi*f1 * t); %sinusoid 1
x2 = A2*sin(2*pi*f2 * t); %sinusoid 2
y = x1 + x2;
%Plot signal
figure;
set(gcf,'Color','w'); %Make the figure background white
plot(fs*t(1:100), y(1:100));
set(gca,'Box','off'); %Axes on left and bottom only
str = sprintf('Signal with %dHz and %dHz components',f1,f2);
title(str);
xlabel('time (milliseconds)');
ylabel('Amplitude');
%Calculate spectrum
Y = fft(y)/L;
ampY = 2*abs(Y(1:L/2+1));
f = fs/2*linspace(0,1,L/2+1);
i = L/fs * (max(f1,f2)) + 1; %show only part of the spectrum
%Plot spectrum.
figure;
set(gcf,'Color','w'); %Make the figure background white
plot(f(1:i), ampY(1:i));
set(gca,'Box','off'); %Axes on left and bottom only
title('Single-Sided Amplitude Spectrum of y(t)');
xlabel('Frequency (Hz)');
ylabel('|Y(f)|');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T09:25:10.730",
"Id": "34943",
"Score": "1",
"body": "Y = fft(y)/L\nWhy do you divide by L?"
}
] |
[
{
"body": "<p>Your time vector definition is defined a bit strange, I would go for the more standardized form of</p>\n\n<p>startpoint:stepsize:endpoint</p>\n\n<pre><code>endpoint = T*(L-1) % is this correct?\n0:T:endpoint\n</code></pre>\n\n<p>Besides this you could perhaps add some comments in the calculate spectrum section, but for the rest it looks quite clear.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-22T13:38:18.400",
"Id": "17809",
"ParentId": "7188",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T19:10:55.883",
"Id": "7188",
"Score": "3",
"Tags": [
"matlab",
"signal-processing"
],
"Title": "Matlab code demonstrating use of fft (Fast Fourier Transform)"
}
|
7188
|
<p>I've written a quick "local document crawler" that fetches the title tag and an expandable amount of metatag information from files on a webserver.</p>
<p>I develop in .net for a living and don't have a clue what I'm doing, but the site I'm helping with only has PHP hosting.</p>
<p>The goal is to gather metadata from files on a server, hopefully cache the output that uses the data, and display it to the user.</p>
<p>We experienced some x-files stuff when the first cache-file was written, and the system itself is rather slow, even when not recursing. (There's about 200 files being read in a request)
The x-files stuff being php files disappearing from ftp view, which might be due to permissions being automatically set by the hosting provider.</p>
<p>Another thing I really don't understand is why some pages just don't seem to match my regular expressions for the metatags, so if anyone spots the issue you have my thanks.</p>
<p>General class:</p>
<pre><code><?php
class MetaEnumerator
{
private $patterns = array(
"title" => "/<title>([^<]*)<\\x2Ftitle>/ix",
"keywords" => '/<meta(?=[^>]*name="keywords")\s[^>$]*content="([^"]*)[">]*$/ixu',
"description" => '/<meta(?=[^>]*name="description")\s[^>$]*content="([^"]*)[">]*$/ixu'
);
private $endPattern = "/<\/head>/ixu";
private $path = "";
private $recursive = false;
private $files = null;
function __construct($path, $recursive) {
$this->path = $path;
$this->recursive = $recursive;
}
public function AddPattern($key, $pattern)
{
$this->patterns[$key] = $pattern;
}
public function GetFiles()
{
$this->files = array();
$this->AddItems($this->path);
usort($this->files, array("MetaEnumerator", "CompareTitle"));
return $this->files;
}
private static function CompareTitle($a, $b) {
return strcmp($a["title"], $b["title"]);
}
private function AddItems($path)
{
foreach(scandir($path) as $item) {
$this->AddItem($path, $item);
}
}
private function AddItem($path, $item)
{
$fullPath = "$path/$item";
if ($this->IsFolder($fullPath, $item) && $this->recursive) {
$this->AddItems($fullPath);
}
else if ($this->IsHtmlFile($fullPath)) {
$this->AddFile($fullPath);
}
}
private function AddFile($fullPath)
{
$fileInfo = $this->GetFileInfo($fullPath);
array_push($this->files, $fileInfo);
}
private function GetFileInfo($file)
{
$fileInfo = array();
$fileInfo["path"] = $file;
$fileInfo["modified"] = filemtime($file);
$ptr = fopen($file, "r");
foreach ($this->patterns as $key => $value) {
$fileInfo[$key] = $this->FindPattern($ptr, $value);
}
fclose($ptr);
return $fileInfo;
}
private function FindPattern($ptr, $pattern)
{
$retVal = "";
rewind($ptr);
while (($line = fgets($ptr)) !== FALSE) {
if (preg_match($pattern, $line) > 0) {
$retVal = preg_replace($pattern, "$1", $line);
break;
}
if (preg_match($this->endPattern, $line) > 0) {
break;
}
}
return $retVal;
}
private function IsFolder($path, $item)
{
return is_dir($path) && $this->IsPhysical($item);
}
private function IsPhysical($folderPath) {
return $folderPath !== "." && $folderPath !== "..";
}
private function IsHtmlFile($filePath)
{
$pathInfo = pathinfo($filePath);
return !is_dir($filePath) && $pathInfo["extension"] == "html";
}
}
</code></pre>
<p>A page using it:<br>
(<em>This hasn't been refactored yet, so lay off with the clean code comments.</em>)</p>
<pre><code><?
include "../../../utils/MetaEnumerator.php";
$files = scandir("..");
$maxDate = null;
foreach($files as $file) {
$date = filemtime("../$file");
if ($maxDate == null || $date > $maxDate) {
$maxDate = $date;
}
}
$cacheFile = "thispage.cache";
$cacheDate = file_exists($cacheFile) ? filemtime($cacheFile) : null;
if ($cacheDate >= $maxDate) {
include($cacheFile);
exit;
}
else
{
ob_start();
?>
<html>
<head>
<title>Our stuff</title>
</head>
<body>
<?
echo date("d.m.Y",$maxDate);
function AddTag($enumerator, $name) {
$metaPrefix = '/<meta(?=[^>]*name="';
$metaSuffix = '")\s[^>$]*content="([^"]*)[">]*$/ixu';
$enumerator->AddPattern($name, $metaPrefix.$name.$metaSuffix);
}
$enumerator = new MetaEnumerator("..", false);
AddTag($enumerator, "name");
AddTag($enumerator, "country");
AddTag($enumerator, "status");
AddTag($enumerator, "active");
$files = $enumerator->GetFiles();
echo "<table>";
echo "<tr>";
echo "<th>Name</th>".
"<th>Country</th>".
"<th>Status</th>".
"<th>Last update</th>";
echo "</tr>";
foreach($files as $file) {
if ($file["name"] == null) continue;
echo "<tr style=\"vertical-align: top;\">";
echo "<td><a href=\"".$file["path"]."\" target=\"_blank\">".$file["name"]."</a></td>".
"<td>".$file["country"]."</td>".
"<td>".$file["eruption"]."</td>".
"<td>".date("d.m.Y", $file["modified"])."</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
<?
$fp = fopen($cacheFile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:15:13.473",
"Id": "11426",
"Score": "0",
"body": "Why use PHP to crawl document? Wouldn't the parsing be much faster if you do with with BASH or other language? (PHP is more like server side scripting, but will not parse fastest i believe)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T08:35:20.277",
"Id": "11589",
"Score": "1",
"body": "Since the only server tech. available on the given site is PHP and the point is to be able to deploy a html file to a subfolder, and get overview/list/news/sitemap pages updated automatically. Requirements, requirements. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-14T09:21:48.887",
"Id": "170201",
"Score": "0",
"body": "I would use a `DOMDocument` instead of Regex to parse whenever possible"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T22:33:10.783",
"Id": "7194",
"Score": "2",
"Tags": [
"php"
],
"Title": "PHP local document crawler"
}
|
7194
|
<p>Inspired by another question here: <a href="https://codereview.stackexchange.com/questions/7167/sum-of-all-primes-under-2-million">Sum of Prime numbers under 2 million</a>, I decided to try and implement <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Eratosthenes' Sieve</a> from scratch using the algorithm described in the article.</p>
<pre><code>unsigned int CalculateSumOfPrimes(const unsigned int number) {
if(number <= 1) return 0;
if(number == 2) return 2;
std::vector<unsigned int> listOfPrimes;
CalculateListOfPrimes(listOfPrimes, number);
unsigned int sum = 0;
for(unsigned int i = 0; i < listOfPrimes.size(); ++i) {
sum += listOfPrimes.at(i);
}
return sum;
}
void CalculateListOfPrimes(std::vector<unsigned int>& container, const unsigned int number) {
if(container.size() != 0) {
std::cout << "Container must be empty!" << std::endl;
return;
}
unsigned int current_prime_check = 2;
std::vector<unsigned int> listOfNonPrimes;
while(current_prime_check < number) {
for(unsigned int i = current_prime_check; i < number; i += current_prime_check) {
if(i == current_prime_check) {
container.push_back(i);
continue;
}
if(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), i) != listOfNonPrimes.end()) continue;
listOfNonPrimes.push_back(i);
}
++current_prime_check;
while(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), current_prime_check) != listOfNonPrimes.end()) {
++current_prime_check;
}
}
}
</code></pre>
<p>Currently the major bottleneck at large numbers (65536 or higher) is <code>CalculateListOfPrimes(...)</code> at 67% of the total 15 second run time.</p>
<p>Switching the usage from a <code>std::vector</code> to a <code>std::list</code> (since I'm only adding to the END of the the list, it seemed like a good idea), only saved 5%.</p>
<p>Looking at it, the inner while loop is going through EVERY possible number from the currently known non-prime number to the next unknown number, is there an algorithm to tell what the next number to check should be or whether or not the next number and potentially every number after it is guaranteed NOT to be in the list of primes?</p>
|
[] |
[
{
"body": "<p>You shouldn't append non-primes to a list and then perform a large number of find operations on it (which will all scan the entire container).</p>\n\n<p>Instead a sieve is a table of whether a number is a multiple of some prime or not. Something like this which you then fill out.</p>\n\n<pre><code>std::vector<bool> sieve(limit + 1);\n</code></pre>\n\n<p>Then for example <code>sieve[5]</code> being <code>false</code> means 5 is a prime, whereas <code>sieve[10]</code>, <code>sieve[15]</code> will be all set to true, as multiples of 5.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T23:56:33.677",
"Id": "7196",
"ParentId": "7195",
"Score": "2"
}
},
{
"body": "<h3>Your main in-effeciency is here:</h3>\n\n<pre><code>if(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), i) != listOfNonPrimes.end()) \n</code></pre>\n\n<p>For every non-prime you are a doing a search through the list of non primes. For both <code>std::vector</code> and <code>std::list</code> this is an O(n) operation.</p>\n\n<p>The usual way of implementing this is to have an array where the removed elements are represented by their index into the array and thus represent a complexity of O(1) to both set and check if an element has already been set to false.</p>\n\n<pre><code>std::vector<bool> sieve(number + 1, true);\n</code></pre>\n\n<p>Then the following lines can be replaced:</p>\n\n<pre><code>if(std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), i) != listOfNonPrimes.end())\n continue;\nlistOfNonPrimes.push_back(i);\n\n// Change too\nsieve[i] = false;\n</code></pre>\n\n<h3>Other things:</h3>\n\n<p>Every time through the loop you do a test:</p>\n\n<pre><code>if (i == current_prime_check) {\n container.push_back(i);\n continue;\n}\n</code></pre>\n\n<p>This is only true the first element.</p>\n\n<p>So hoist it out of the loop. Do the <code>container.push_back(i);</code> outside the loop and start <code>i</code> at the next position:</p>\n\n<pre><code>for (unsigned int i = 2 * current_prime_check; i < number; i += current_prime_check)\n // ^^^^ Start one place up from where you were.\n</code></pre>\n\n<h3>Replace the other find as well:</h3>\n\n<pre><code>++current_prime_check;\nwhile (std::find(listOfNonPrimes.begin(), listOfNonPrimes.end(), current_prime_check) != listOfNonPrimes.end()) {\n ++current_prime_check;\n}\n</code></pre>\n\n<p>If you use the sieve this can be replaced by a simple test into the sieve:</p>\n\n<pre><code>++current_prime_check;\nwhile (!sieve[current_prime_check]) {\n ++current_prime_check;\n}\n</code></pre>\n\n<h2>After Edit Comments:</h2>\n\n<h3>We can make it quicker.</h3>\n\n<p>Your function that generates the prime:</p>\n\n<pre><code>void CalculateListOfPrimes(std::vector<unsigned int>& container, const unsigned int number)\n</code></pre>\n\n<p>You pass an array the function fills the array then you processes the array as the next stage. A better solution would be to pass a function that is applied to each prime as you find it. Then you can have a simple version that pushes the values into a container. Or alternatively you can have a function that just sums up the primes (so you do not even need the container or have to iterate over it).</p>\n\n<p>So try:</p>\n\n<pre><code>template<typename Func>\nvoid CalculateListOfPrimes(Func const& action, const unsigned int number);\n</code></pre>\n\n<p>Then you could use it like this:</p>\n\n<pre><code>struct PB\n{\n std::vector<unsigned int>& cont;\n PB(std::vector<unsigned int>& c): cont(c) {}\n void operator()(unsigned int value) const { cont.push_back(value); }\n};\n…\nstd::vector<int> data;\nCalculateListOfPrimes(PB(data), 2000000);\n</code></pre>\n\n<p>Or you can have a specific function</p>\n\n<pre><code>struct Sum\n{\n unsigned int& sum;\n Sum(unsigned int& s) : sum(s) {}\n void operator()(unsigned int value) const { sum += value; }\n};\n…\nunsigned int total;\nCalculateListOfPrimes(Sum(total), 2000000);\n</code></pre>\n\n<h3>Comments:</h3>\n\n<p>Don't use <code>system(\"pause\");</code>. It's plainly platform specific. All you are doing is getting the program to wait. So read a line from the standard input.</p>\n\n<pre><code>std::getline(std::cin, line); // If you have other input you may need to flush first.\n</code></pre>\n\n<h3>Hash define not a good move.</h3>\n\n<p>Prefer to use a function (there is no performance penalty as it will probably be inlined). If you must use a hash define then define it like <a href=\"https://codereview.stackexchange.com/a/1686/507\">this</a>:</p>\n\n<pre><code>#define PAUSE do { /* Action To Pause */ } while(false)\n</code></pre>\n\n<h3><code>atoi()</code></h3>\n\n<pre><code>primes = CalculateListOfPrimes(std::atoi(argv[2]));\n</code></pre>\n\n<p>Not standard. No way to check failures.</p>\n\n<p>I <a href=\"https://stackoverflow.com/q/200090/14065\">would use boost::lexical_cast(argv[2])</a> it will throw an exception on failure.</p>\n\n<h3>Don't pass pointers around</h3>\n\n<pre><code>DisplayResult(&primes, 0);\n</code></pre>\n\n<p>Change the function so you pass by <code>const</code> reference. This avoids the copy, stops you from accidentally modifying the array, and you can't accidentally pass a <code>NULL</code> so its always valid.</p>\n\n<pre><code>void DisplayResult(std::vector<bool> const& container, const unsigned int sum);\n</code></pre>\n\n<h3>Truth values:</h3>\n\n<p>The result of the <code>==</code> operation is a boolean so you don't need to use a ternary operator on-top of that:</p>\n\n<pre><code>bool isSumArg = (std::strcmp(\"-s\", argv[1]) == 0 ? true : false);\n</code></pre>\n\n<p>is exactly equivalent to the easier-to-read</p>\n\n<pre><code>bool isSumArg = (std::strcmp(\"-s\", argv[1]) == 0);\n</code></pre>\n\n<h3>Prime specific values:</h3>\n\n<p>A quick optimization here. You do not need this loop to go all the way to <code>number</code>.</p>\n\n<p>You just need to loop as far as <code>sqrt(number)</code> after that nothing will affect the result.</p>\n\n<pre><code>while (current_prime_check < number) { … }\n</code></pre>\n\n<h3>Make functions do one thing.</h3>\n\n<p>This function does lots of different things depending on the inputs that are not related.</p>\n\n<pre><code>void DisplayResult(std::vector<bool>* container, const unsigned int sum) {\n if(container == NULL && sum == 0) {\n return;\n }\n\n if(sum != 0) {\n std::cout << \"Sum of Primes: \" << sum << std::endl;\n return;\n } else if(container != NULL) {\n std::cout << \"List of Primes:\" << std::endl;\n for(unsigned int i = 1; i < container->size(); ++i) {\n if(container->at(i) == true) std::cout << std::setw(15) << std::right << i << std::endl;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T01:46:03.003",
"Id": "11242",
"Score": "1",
"body": "Thanks, works great! From 15 seconds to 8 milliseconds. :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T02:31:19.670",
"Id": "11243",
"Score": "0",
"body": "@Casey: Post your final code as an addition to your question. Maybe we comment on it more. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T05:10:26.697",
"Id": "11247",
"Score": "0",
"body": "...And so added. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T06:32:49.587",
"Id": "11249",
"Score": "0",
"body": "Thanks for the comments on the new parts. Your comment on the CalculateListOfPrimes(...) accepting an array as an input is actually based on the old code; was this intentional? I'll take a look at the new suggestions a bit later as it's almost 1 AM and sleep is paramount."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-30T23:36:02.900",
"Id": "220410",
"Score": "0",
"body": "Jamal has rolled back the revised code. [Starting April 2014](http://meta.codereview.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c), the site policy is to avoid revising code in the question. If you would like to have your new code reviewed, please post a related question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-31T17:42:37.293",
"Id": "220481",
"Score": "0",
"body": "`std::atoi` *is* standard. But yes, it sucks."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T23:59:44.650",
"Id": "7197",
"ParentId": "7195",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "7197",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T23:19:40.170",
"Id": "7195",
"Score": "5",
"Tags": [
"c++",
"performance",
"primes"
],
"Title": "Prime Number calculation bottleneck"
}
|
7195
|
<p>I have a module, that fetches some object. Then other modules can use this object. Here is a little example of this task:</p>
<pre><code>var Structure = (function(){
var tree = null,
df = $.ajax({
'url' : '/some/path',
'type' : 'POST',
'data' : { some : 'data' },
'dataType' : 'json'
}),
ready = function(cb){
if (tree) {
cb(tree);
return
}
$.when(df).then(function(data){
tree = TreeHandler.create(data);
cb(tree);
});
};
return {
df : df,
ready : ready
};
})();
// Usage:
Structure.ready(function(data){
console.log (data);
// some actions with data
});
</code></pre>
<p>Am I right on doing this? How can this be made better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:03:53.323",
"Id": "11301",
"Score": "0",
"body": "Basically this is completely fine, however I would say it's unnecessarily complex. Can you expand on why you think you need this and can't just use a AJAX call with a callback function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:23:01.643",
"Id": "11330",
"Score": "0",
"body": "For example there are a lot of modules for this application, and all of them are able to use the `structure` obj. If `module1` has already fetched the `obj`, `module8` doesn't have to fetch it again. I imagine a way with `synchronous` AJAX call. After it all modules can simple use fetched object via variable name, but synchronous calls are evil - they block the browser."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T20:12:31.370",
"Id": "11456",
"Score": "0",
"body": "See http://api.jquery.com/jQuery.Callbacks/ for some ideas, like:\n$.Callbacks('once memory')"
}
] |
[
{
"body": "<p>I'm repeating @RoToRa for the sake putting it in answer form for beta-stats:</p>\n\n<p>Your syntax is fine. Without knowing more of the problem domain, it does seem a little unnecessary. Why not use callbacks on your <code>$.ajax()</code> call?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:25:00.943",
"Id": "7236",
"ParentId": "7198",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7236",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T00:06:44.437",
"Id": "7198",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Getting object when is ready"
}
|
7198
|
<p>I have two tables<br/> </p>
<pre><code>table_inventory
List item
inventory_rack_key(primarykey)
node_key
rack_id
inventory_item_key
in_coming_qty,locked_qty
quantity
table_item
inventory_item_key(primary key)
item_id,product_zone
</code></pre>
<p>The table example are provided here <a href="https://docs.google.com/spreadsheet/ccc?key=0AltIfHyzagUAdGVwTmE2SXdvMlNkOXBKcHZIaHJEZkE#gid=0" rel="nofollow">DB TABLES</a><br/>
I need query to find out those items for which <strong>(net_qty)</strong> i.e difference b/w sum of <code>in_coming_qty</code> & <code>quantity</code> & <code>locked_qty</code> is negative. arranged by <code>node_key,rack_id, item_id,net_qty</code><br/>
<br/>
<strong>Note:</strong> each distinct set <code>{node_key,rack_id, item_id,net_qty}</code> will have only 1 row in output.
For ex <code>:{node_key,rack_id, item_id}</code> = {ABD101,RK-01,562879} has 4 rows in <strong>table_inventory</strong>
but in output net_qty= -78(single row) .</p>
<p>The query I made is giving me result but can we do it in some other way?</p>
<pre><code>SELECT l.node_key,
l.rack_id,
i.item_id,
( SUM(l.quantity + l.in_coming_qty) - SUM(l.locked_qty) ) AS net_qty
FROM table_inventory l,
table_item i
WHERE l.inventory_item_key = i.inventory_item_key
GROUP BY l.node_key,
l.rack_id,
i.item_id
HAVING SUM(l.quantity + l.in_coming_qty) - SUM(l.locked_qty) < 0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T13:25:23.503",
"Id": "11267",
"Score": "0",
"body": "Which database engine are you using? MSSQL, Oracle, etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T13:57:59.047",
"Id": "11268",
"Score": "0",
"body": "@ChrisMarasti-Georg Oracle SQL Developer"
}
] |
[
{
"body": "<p>I am not exactly familiar with Oracle syntax, but I know that Oracle supports indexes on functions. I'm not sure if it will be used, since there is grouping involved, but you may wish to look into creating an index for this query if performance of the query becomes an issue. A guess at the syntax used to create the index would be:</p>\n\n<pre><code>Create index net_qty on table_inventory(SUM(quantity + in_coming_qty) - SUM(locked_qty));\n</code></pre>\n\n<p>You can search for \"Oracle function based index\" for more information.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T15:50:22.520",
"Id": "7224",
"ParentId": "7199",
"Score": "1"
}
},
{
"body": "<p>I assume that we can additionally GROUP BY <code>inventory_item_key</code> without changing the result. If we can further assume that there are no (or few) rows in <code>table_inventory</code> without a matching row in <code>table_item</code>, then this query should be a bit faster:</p>\n\n<pre><code>SELECT l.node_key\n ,l.rack_id\n ,i.item_id\n ,net_qty\nFROM table_item i\nJOIN (\n SELECT inventory_item_key, node_key, rack_id \n ,SUM(quantity + in_coming_qty - locked_qty) AS net_qty \n FROM table_inventory\n GROUP BY inventory_item_key, node_key, rack_id\n HAVING SUM(quantity + in_coming_qty - locked_qty) AS net_qty < 0\n ) l USING (inventory_item_key)\n</code></pre>\n\n<h3>Major points:</h3>\n\n<ul>\n<li><p>By aggregating and filtering the values <code>table_inventory</code> before the <code>JOIN</code>, fewer join-operations have to be made.</p></li>\n<li><p>I simplified your quantity aggregation to <code>SUM(quantity + in_coming_qty - locked_qty)</code>. the other possibility would be <code>SUM(quantity) + SUM(in_coming_qty) - SUM(locked_qty)</code>. Either way makes more sense that the mixture you had. You would have to test which is fastest.</p></li>\n<li><p>An explicit <code>JOIN</code> clause is preferable in SQL if applicable. In this case you can further simplify the syntax to <code>USING (inventory_item_key)</code>.</p></li>\n</ul>\n\n<p>The index @Chris proposes is impossible. Oracle has no way of knowing how to group these values. You need an index on <code>table_item.inventory_item_key</code>. Other than that I am not sure how to index aggregated values.</p>\n\n<p>If speed is imperative and the values in table_inventory do not change very often, you could create a <a href=\"http://www.ecst.csuchico.edu/~melody/courses/Fall2001CSCI379/DOC/server.815/a67775/ch2.htm\" rel=\"nofollow\">materialized view</a> out of the sub-query <code>l</code> or the whole query. This would be a decisive speed-up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:04:05.870",
"Id": "7232",
"ParentId": "7199",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T00:24:31.723",
"Id": "7199",
"Score": "1",
"Tags": [
"sql",
"oracle"
],
"Title": "SQL query for adding column value to compare with other column"
}
|
7199
|
<p>Here are some examples:</p>
<pre><code>[1, 2, 3, 4, 5] => [1, 2, 3, 4, 5]
[10, 15, 10, 15, 30] => [10, 15]
[1, 2, 3, 4, 1, 5, 6, 7] => [1, 2, 3, 4]
</code></pre>
<p>Here's my best (and deeply ugly) non-recursive, side-effect-free solution so far:</p>
<pre><code>x.scanLeft(List[Int]())((B, Term) => Term :: B).drop(1).takeWhile(i => !(i.tail contains i.head)).last.reverse
</code></pre>
<p>Minor optimization:</p>
<pre><code>x.tail.scanLeft(List(x.head))((B, Term) => Term :: B).takeWhile(i => !(i.tail contains i.head)).last.reverse
</code></pre>
<p>This is different from <code>distinct</code>:</p>
<pre><code>[1, 2, 3, 4, 1, 5, 6, 7] => [1, 2, 3, 4] and not [1, 2, 3, 4, 5, 6, 7]
</code></pre>
<p>Also, considering <code>List[_]</code> is a monoid, isn't there a <code>scan</code> that uses the monoid <code>zero</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T02:31:48.743",
"Id": "11244",
"Score": "1",
"body": "You probably just want the `distinct` method... see http://stackoverflow.com/questions/1538598/how-in-scala-to-find-unique-items-in-list"
}
] |
[
{
"body": "<p>This is a fold, not a scan. A scan produces something with the same number of elements, and change the elements. A fold produces something new.</p>\n\n<pre><code>def firstDistinct[T](s: Seq[T]) = s.foldLeft(Seq[T]() -> false) {\n case (result @ (_, true), _) => result\n case ((seq, _), el) if seq contains el => seq -> true\n case ((seq, _), el) => (seq :+ el) -> false\n}._1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T17:41:50.380",
"Id": "11298",
"Score": "0",
"body": "Almost... Your solution doesn't work with \"infinite\" lists, while mine does. I know I didn't said that in the original post, but it's worth mentioning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:18:01.230",
"Id": "11304",
"Score": "0",
"body": "Nevertheless, amazing display of your functional-fu!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:34:49.243",
"Id": "11315",
"Score": "0",
"body": "@HugoSFerreira Infinite lists are `Stream`, not `List`. Might first impulse _was_ going for `Stream`, but then I noticed you were restricting the solution to `List`... It should be doable with a lazy `foldRight`, which, iirc, Scala's isn't but Scalaz has."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:37:07.267",
"Id": "11331",
"Score": "0",
"body": "Thanks for the tip on scalaz. I was already wrapping my head on why foldRight was being strict."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T16:45:36.483",
"Id": "7225",
"ParentId": "7200",
"Score": "5"
}
},
{
"body": "<pre><code>def once(list:List[Int]) = {\n def go(acc:List[Int],set:Set[Int],rest:List[Int]):List[Int]=rest match{ \n case x::xs if ! set(x) => go(x::acc, set + x, xs)\n case _ => acc.reverse \n }\n go(Nil,Set(),list)\n}\n</code></pre>\n\n<p>And the mandatory one-liner, which would be actually nice if <code>distinct</code> were supported on <code>List.view</code>:</p>\n\n<pre><code>list.zip(list.distinct).takeWhile{case(x,y) => x==y}.map(_._1)\n</code></pre>\n\n<p><strong>[Edit]</strong></p>\n\n<p>There must be a nice one-liner for <code>Stream</code>s, too, but all I got so far is a train wreck... </p>\n\n<pre><code>st.scanLeft((Set[Int](),List[Int]()))((t,x) => if (t._1(x)) null else (t._1+x, x::t._2)).takeWhile(_ != null).last._2.reverse \n</code></pre>\n\n<p><strong>Edit 2</strong></p>\n\n<p>Basically the same construction idea, but more readable:</p>\n\n<pre><code>st.zip(st.scanLeft(Set[Int]())(_+_)).takeWhile{case(x,s)=> !s(x)}.map(_._1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T15:35:07.130",
"Id": "16824",
"Score": "0",
"body": "Very nice your one-liner! I'll award the +50... but could you also solve it with infinite lists (streams)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T15:01:52.017",
"Id": "10566",
"ParentId": "7200",
"Score": "4"
}
},
{
"body": "<pre><code> def first_distinct[T](x: Seq[T]) = {\n def iter(acc: Seq[T], met: Set[T], rest: Seq[T]): Seq[T] = {\n if (rest.isEmpty || (met contains rest.head)) acc\n else iter(acc :+ rest.head, met + rest.head, rest.tail)\n }\n iter(Vector.empty, Set.empty, x)\n }\n</code></pre>\n\n<p>This can be optimized, of course (but I'm not sure if compiler does this by itself). I'll write solution for lazy streams some time later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-22T20:42:29.207",
"Id": "15840",
"ParentId": "7200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T01:27:47.237",
"Id": "7200",
"Score": "5",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Finding the first stream of non-repeating elements in Scala (without recursion or side-effects)"
}
|
7200
|
<p>This is the proof-of-concept code with drafts for widgets for my current project that uses Google Maps. As a result the code produces 3 buttons in the top right corner:</p>
<p><img src="https://i.stack.imgur.com/BWWIc.png" alt="enter image description here"></p>
<p>Any advice on how I may improve it? (personally I'm specifically server-side developer and don't use JavaScript extensively, so expect a lot of no-no's in my code):</p>
<pre><code>$(function() {
var latlng = new google.maps.LatLng(-41.288771, 174.775314);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var terrainBtn = new MapTypeButton({ title: 'Terrain', mapType: google.maps.MapTypeId.TERRAIN });
terrainBtn.attach(map, google.maps.ControlPosition.TOP_RIGHT);
var satelliteBtn = new MapTypeButton({ title: 'Satellite', mapType: google.maps.MapTypeId.SATELLITE });
satelliteBtn.attach(map, google.maps.ControlPosition.TOP_RIGHT);
var mapBtn = new MapTypeButton({ title: 'Map', mapType: google.maps.MapTypeId.ROADMAP });
mapBtn.attach(map, google.maps.ControlPosition.TOP_RIGHT);
});
/**
* Helper function to implement JS inheritance
*/
Function.prototype.subclass= function(base) {
var c = Function.prototype.subclass.nonconstructor;
c.prototype = base.prototype;
this.prototype = new c();
};
Function.prototype.subclass.nonconstructor= function() {};
function CustomButton(options)
{
var defaults = {};
this.settings = $.extend({}, defaults, options);
}
CustomButton.prototype.render = function() {
this.jq = $('<div class="custom-map-button">' + this.settings.title + '</div>');
if (this.settings.classes) {
for (var i in this.settings.classes) {
this.jq.addClass('custom-map-button-' + this.settings.classes[i]);
}
}
return this.jq[0];
};
CustomButton.prototype.attach = function(map, position) {
this.map = map;
map.controls[position].push(this.render());
};
function MapTypeButton(options)
{
CustomButton.apply(this, arguments);
}
MapTypeButton.subclass(CustomButton);
MapTypeButton.prototype.render = function() {
var result = CustomButton.prototype.render.apply(this, arguments);
if (this.map.getMapTypeId() == this.settings.mapType) {
this.jq.addClass('custom-map-button-selected');
}
this.jq.addClass('custom-map-button-mapType');
return result;
};
MapTypeButton.prototype.attach = function(map, position, init) {
var t = this;
CustomButton.prototype.attach.apply(this, arguments);
t.jq.click(function() {
t.click();
});
};
MapTypeButton.prototype.click = function() {
$('.custom-map-button-mapType.custom-map-button-selected').removeClass('custom-map-button-selected');
this.map.setMapTypeId(this.settings.mapType);
this.jq.addClass('custom-map-button-selected');
};
</code></pre>
|
[] |
[
{
"body": "<p>Pretty good Zmayte!</p>\n\n<p>But, if I had to nitpick...</p>\n\n<pre><code>var defaults = {};\nthis.settings = $.extend({}, defaults, options);\n</code></pre>\n\n<p>The <code>defaults</code> is redundant, whilst an empty object.</p>\n\n<pre><code>for (i in this.settings.classes) {\n this.jq.addClass('custom-map-button-' + this.settings.classes[i]);\n}\n</code></pre>\n\n<p><code>i</code> is not defined, so you are doing property assignment on the global object, making <code>i</code> a global variable. A <code>for in</code> also iterates over all enumerable properties on the prototype chain. This can lead to problems when you don't know what has augmented <code>Object</code> and so on. Use <code>hasOwnProperty()</code> to prevent this problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T04:59:04.660",
"Id": "11245",
"Score": "0",
"body": "`defauls` will be filled with default values later. Fixed `i` visibility. And will read about `hasOwnProperty()` soon. Anything else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T05:07:54.063",
"Id": "11246",
"Score": "0",
"body": "@zerkms: Probably, but let me look later when I'm not supposed to be working :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T04:55:44.240",
"Id": "7203",
"ParentId": "7202",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T04:10:17.517",
"Id": "7202",
"Score": "5",
"Tags": [
"javascript",
"google-maps"
],
"Title": "Google Maps buttons"
}
|
7202
|
<p>I have a set of components that each need to both publish and receive messages using a multicast channel. In production, any one machine could host two or more of these components with 12 or more machines communicating with each other. </p>
<p>My question is... given that components on the same machine and components on separate machines are both sending and received. Have I set this up in the most efficient manner? (<em>Note: messages can periodically be lost with no ill effect</em>)</p>
<pre><code>private readonly static Socket _broadcastSocket;
private readonly static Socket _broadcastListeningSocket;
</code></pre>
<hr>
<pre><code>_broadcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_broadcastListeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse(_configuration.Server.AddressV4);
var ipep = new IPEndPoint(ip, _configuration.Server.Port);
_broadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
_broadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, _configuration.Server.TimeToLive);
_broadcastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
_broadcastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
_broadcastSocket.Connect(ipep);
var listenerIpep = new IPEndPoint(IPAddress.Any, _configuration.Server.Port);
_broadcastListeningSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
_broadcastListeningSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
_broadcastListeningSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
_broadcastListeningSocket.Bind(listenerIpep);
</code></pre>
<p>Messages are received using this following:</p>
<pre><code>_broadcastListeningSocket.Receive(payloadBuffer);
</code></pre>
<p>Messages are sent using the following:</p>
<pre><code>if (_broadcastSocket.Connected)
{
_broadcastSocket.Send(payload);
}
</code></pre>
<p>I'm a little new to this so I am assuming I am not setting all the options correctly, feel free to suggest setting of new options.</p>
|
[] |
[
{
"body": "<p>Unfortunately, I'm unable to comment about the actual options you are setting since</p>\n\n<ul>\n<li>while I've used Sockets in Java, I haven't used them in C#</li>\n<li>I'm finding it a bit hard to see what your code is doing because it isn't very expressive</li>\n</ul>\n\n<p>So, while I can do nothing about the first point (someone with more experience will have to help you out), we can certainly remedy the second problem by <strong>refactoring</strong> your code into a more readable form with less duplication.</p>\n\n<p>Let's start by declaring a new member variable to keep hold of the parsed IP address:</p>\n\n<pre><code>private static IPAddress _ipAddress = IPAddress.Parse(_configuration.Server.AddressV4);\n</code></pre>\n\n<p>We'll use this field in the methods that result from splitting up your monolithic function into several helpers, leaving us with the following:</p>\n\n<pre><code>_broadcastSocket = CreateBroadcastSocket();\n_broadcastListeningSocket = CreateBroadcastListeningSocket(); \n_broadcastSocket.Connect(GetEndpointOf(_ipAddress));\n_broadcastListeningSocket.Bind(GetEndpointOf(IPAddress.Any));\n</code></pre>\n\n<p>Those methods are defined as the following:</p>\n\n<pre><code>private static Socket CreateBroadcastSocket()\n{\n Socket s = CreateSocket(new MulticastOption(_ipAddress));\n s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, _configuration.Server.TimeToLive);\n return s;\n}\n\nprivate static Socket CreateBroadcastListeningSocket()\n{\n return CreateSocket(new MulticastOption(_ipAddress, IPAddress.Any));\n}\n\nprivate static Socket CreateSocket(MulticastOption multicastOption)\n{\n Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);\n s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);\n s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);\n return s;\n}\n</code></pre>\n\n<p>Note that it would have been <em>possible</em> to set the instance variables (<code>_broadcastListeningSocket</code>and <code>_broadcastSocket</code>) directly from the helper methods, instead of returning a new <code>Socket</code>, however I find the above implementation more <em>expressive</em> because we <strong>seperate the concerns</strong>: The helper methods know about how to create a configured Socket, while the method that calls them knows about what they have to be assigned to.</p>\n\n<h3>What to do if you find out you need to set the options differently?</h3>\n\n<ul>\n<li>Create a new <code>CreateXXXSocket()</code> method</li>\n<li>From that method, call <code>CreateSocket()</code> and</li>\n<li>configure the result and pass it back to the caller</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T11:49:44.770",
"Id": "11257",
"Score": "0",
"body": "Thanks... I take your point. I'll certainly incorporate some of this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T11:55:41.820",
"Id": "11258",
"Score": "0",
"body": "I'm sorry I couldn't help with the subject itself..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T12:39:55.390",
"Id": "11264",
"Score": "0",
"body": "Don't be sorry. This is a \"Code Review\" so comments such as yours are completely reasonable in my opinion (*e.g. style, readability, clarity, etc...*)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T11:40:47.320",
"Id": "7215",
"ParentId": "7206",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7215",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T09:07:44.953",
"Id": "7206",
"Score": "1",
"Tags": [
"c#",
"networking"
],
"Title": "Multicast Socket Configuration for Pub/Sub"
}
|
7206
|
<p>I know <a href="https://codereview.stackexchange.com/questions/2650/waiting-for-a-lock-to-release-with-thread-sleep">I've already asked a similar question</a>, but this feels quite different to me.</p>
<p>The main goal is to wait for a file to be accessible (read: waiting until the file lock releases), since it seems like there's no way to do this built into the .NET framework I've written a quick and dirty function to do this.</p>
<p>The requirements which should be kept in mind with this:</p>
<ul>
<li>The file shouldn't be locked <em>often</em>. Actually, it should be locked quite rarely (figure how often clients manage to still hit that).</li>
<li>There's no need for a limit, if the file is locked for longer then a second, something is fuc^H^H^Hscrewed up.</li>
<li>It should block the main thread until the file is available.</li>
</ul>
<pre><code>///<summary>
/// Tries to open the specified file over and over again until it is acessible.
///</summary>
public static FileStream WaitForStream(String filename, FileAccess fileAccess, FileShare, fileShare)
{
while(true) // Gives me the chills
{
try
{
return new FileStream(filename, FileMode.OpenOrCreate, fileAccess, fileShare);
}
catch (IOException ex)
{
Logger.LogError(ex); // Information purposes only
Threading.Thread.Sleep(250); // Just looks wrong
}
}
return null; // Only to keep the compiler happy.
}
</code></pre>
<p>The problems I see myself:</p>
<ul>
<li><code>while(true)</code></li>
<li><code>Thread.Sleep()</code></li>
<li>It might loop forever, but as I said, if that happens we need to intervene anyway.</li>
</ul>
<p>Reimplementing this with <a href="https://codereview.stackexchange.com/questions/3197/waiting-for-a-lock-to-release-with-manualresetevent-and-quartz">a similar solution I already used</a> smells like absolute overkill to me, given that this should be built-in functionality anyway. What stuff didn't I think about?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T12:05:32.880",
"Id": "11260",
"Score": "2",
"body": "http://stackoverflow.com/questions/1304/how-to-check-for-file-lock-in-c"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T14:10:00.480",
"Id": "11270",
"Score": "1",
"body": "Definitely problematic - if there's a different `IOException` that has no chance of resolving, you're effectively in an infinite loop. You should have a maximum retry count (or a maximum time limit) as a parameter that it gives up after."
}
] |
[
{
"body": "<p>How about making this an asynchrounous operation that only returns if the stream has successfully been opened. you can get rid of the while(true) and the thread sleep plus the new mthod call cn have a retry count.</p>\n\n<p>Here is what it might look like if you use C# 4.0 (not tested).</p>\n\n<pre><code>Task<FileStream> OpenStreamAsync(String filename, FileAccess fileAccess, FileShare fileShare,int retryCount){\n\n if (retryCount < 1)\n throw new Exception(\"maximum retry reached\");\n\n return \n Task.Factory.StartNew(() => new FileStream(filename, FileMode.OpenOrCreate, fileAccess, fileShare))\n .ContinueWithTask( task => {\n if (task.IsCompleted)\n return task;\n\n Logger.LogError(ex); // Information purposes only\n return TaskExtenstion2.Wait(TimeSpan.FromMilliseconds(250))\n .ContinueWithTask(t => OpenStreamAsync(filename, fileAccess, fileShare,retryCount--) );\n });\n}\n\npublic static class TaskExtenstion2 {\n\n /// Set the completionSource to the same values as the task\n public static void SetCompletionSource<TResult>(this Task<TResult> task, TaskCompletionSource<TResult> completionSource){\n if (task.IsCompleted){\n completionSource.SetResult(task.Result);\n }else if (task.IsCanceled){\n completionSource.SetCanceled();\n }else if (task.IsFaulted){\n completionSource.SetException(task.Exception);\n }\n }\n\n /// Continues a task with another task genrated by the specified function\n public static Task<U> ContinueWithTask<T,U>(this Task<T> sourceTask, Func<Task<T>,Task<U>> continuation){\n var completionSource = new TaskCompletionSource<U>();\n sourceTask.ContinueWith(firstTask => {\n var secondTask = continuation(firstTask);\n secondTask.ContinueWith(task => task.SetCompletionSource(completionSource));\n });\n return completionSource.Task;\n }\n\n /// returns true after a certain amount of time \n public static Task<bool> Wait(TimeSpan span){\n var completionSource = new TaskCompletionSource<bool>();\n Timer timer = null;\n timer = new Timer(_ => {\n using(timer) {\n completionSource.SetResult(true);\n }\n },null,span,TimeSpan.MaxValue);\n return completionSource.Task;\n }\n}\n</code></pre>\n\n<p>if you still want to block the main thread, getting the Result property of the returning task will <a href=\"http://msdn.microsoft.com/en-us/library/dd321468.aspx\" rel=\"nofollow\">make sure</a> of that </p>\n\n<pre><code>var stream = OpenStreamAsync(\"myFile\", FileAccess.ReadWrite, FileShare.None,20).Result;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T22:10:07.897",
"Id": "7328",
"ParentId": "7210",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T10:10:27.990",
"Id": "7210",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Waiting for a file to be accessible with Thread.Sleep() and exception catching"
}
|
7210
|
<p>This code basically finds duplicate strings within a file.</p>
<blockquote>
<p>An example: DUPLICATE_LENGTH set to 6, file contains: </p>
<pre><code>process hash michael honeycomb interrupt system call deadlock scheduling michael
</code></pre>
<p>The output will be <code>michael</code>, as its a duplicate with a length of 6 or
higher</p>
</blockquote>
<p>The following code shows my approach to solving this issue. If there are completely different ideas how to solve it, I'm open too, but primarily I'd like to get some feedback of the code I wrote.</p>
<p>I'm also searching performance optimizations as it gets kinda slow on large files.</p>
<pre><code>import codecs
# Constants
DUPLICATE_LENGTH = 30;
FILE_NAME = "data.txt"
SHOW_RESULTS_WHILE_PROCESSING = True
def showDuplicate(duplicate):
print("Duplicate found:{0}".format(duplicate))
fileHandle = codecs.open(FILE_NAME, "r", "utf-8-sig")
fileContent = fileHandle.read()
fileHandle.close()
substringList = [] #contains all possible duplicates.
duplicatesList = [] #contains all duplicates
for i in range(0, len(fileContent) - DUPLICATE_LENGTH):
end = i + DUPLICATE_LENGTH
duplicate = fileContent[i:end]
if duplicate in substringList and '|' not in duplicate:
duplicatesList.append(duplicate)
else:
substringList.append(duplicate)
resultList = []
currentMatch = duplicatesList[0]
currentMatchPos = 1
for i in range(1, len(duplicatesList)):
if currentMatch[currentMatchPos:] in duplicatesList[i]:
currentMatch += duplicatesList[i][-1]
currentMatchPos += 1
else:
if SHOW_RESULTS_WHILE_PROCESSING:
showDuplicate(currentMatch)
resultList.append(currentMatch) # this match is closed, add it!
currentMatch = duplicatesList[i]
currentMatchPos = 1
if not SHOW_RESULTS_WHILE_PROCESSING:
for duplicate in resultList:
showDuplicate(duplicate)
if not resultList:
print "Awesome, no duplicates were found!"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T01:10:17.987",
"Id": "30498",
"Score": "1",
"body": "related: [Effcient way to find longest duplicate string for Python (From Programming Pearls)](http://stackoverflow.com/questions/13560037/effcient-way-to-find-longest-duplicate-string-for-python-from-programming-pearl)"
}
] |
[
{
"body": "<p>Loop through the lines of the file, rather than reading it all into memory with <code>fileHandle.read()</code>.</p>\n\n<p>You can use <code>line.split()</code> to break the line into a list of words.</p>\n\n<p>Keep the words seen as a <code>set</code>, and the duplicates as another <code>set</code>. Each time you do <code>in</code> on a <code>list</code>, it has to scan through each element. Sets can do membership checking much more quickly.</p>\n\n<p>I'd do this:</p>\n\n<pre><code>import codecs\n\n# Constants\nDUPLICATE_LENGTH = 30;\nFILE_NAME = \"data.txt\"\n\nseen = set()\nduplicates = set()\nwith open(FILE_NAME) as input_file:\n for line in input_file:\n for word in line.split():\n if len(word) >= DUPLICATE_LENGTH and word in seen:\n duplicates.add(word)\n seen.add(word)\n</code></pre>\n\n<p><strong>edit:</strong> to look for duplicate sequences of length DUPLICATE_LENGTH, you could use a generator to yield successive chunks:</p>\n\n<pre><code>DUPLICATE_LENGTH = 30\nCHUNKS = 100\n\ndef read_sequences(stream, size):\n while True:\n chunk = stream.read(size * CHUNKS)\n if not chunk:\n break\n for i in range(len(chunk) - size + 1):\n yield chunk[i:i + size]\n</code></pre>\n\n<p>Then the loop would become:</p>\n\n<pre><code>seen = set()\nduplicates = set()\nwith open(FILE_NAME) as input_file:\n for word in read_sequences(input_file, DUPLICATE_LENGTH):\n if word in seen:\n duplicates.add(word)\n seen.add(word)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T13:11:31.023",
"Id": "11266",
"Score": "1",
"body": "Thanks for you comment. There's one difference in progressing the data with my code. It can just recognize single words, probably my example lacked a bit. Another one, what about \"balwmichaelkajfalsdfamsmichaelasjfal\" - find \"michael\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:59:31.913",
"Id": "11309",
"Score": "0",
"body": "Ah, ok - so you're looking for repeated sequences of length DUPLICATE_LENGTH? I'll update with more info."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T12:43:53.520",
"Id": "7218",
"ParentId": "7213",
"Score": "4"
}
},
{
"body": "<p>Firstly, your code doesn't actually work. Run it against your example data and DUPLICATE_LENGTH. It has no results. So I'm going to look at your code stylistically and ignore the algorithm for now:</p>\n\n<pre><code>import codecs\n\n# Constants\nDUPLICATE_LENGTH = 30;\n</code></pre>\n\n<p>No need for that semicolon</p>\n\n<pre><code>FILE_NAME = \"data.txt\"\nSHOW_RESULTS_WHILE_PROCESSING = True\n\n\ndef showDuplicate(duplicate):\n</code></pre>\n\n<p>python style guide recommends seperation_by_underscores for function names</p>\n\n<pre><code> print(\"Duplicate found:{0}\".format(duplicate))\n\n\n\nfileHandle = codecs.open(FILE_NAME, \"r\", \"utf-8-sig\")\nfileContent = fileHandle.read()\nfileHandle.close()\n</code></pre>\n\n<p>Python style guide recommends words_seperated_by_underscores for variable names.</p>\n\n<pre><code>substringList = [] #contains all possible duplicates.\nduplicatesList = [] #contains all duplicates\n\n\nfor i in range(0, len(fileContent) - DUPLICATE_LENGTH):\n</code></pre>\n\n<p>No need for the 0, <code>range(x) == range(0, x)</code></p>\n\n<pre><code> end = i + DUPLICATE_LENGTH\n duplicate = fileContent[i:end]\n</code></pre>\n\n<p>I'd combine those two lines. I'd also not call it a duplicate as its not a duplicate, just a substring.</p>\n\n<pre><code> if duplicate in substringList and '|' not in duplicate:\n</code></pre>\n\n<p>I not clear what significance the <code>|</code> has</p>\n\n<pre><code> duplicatesList.append(duplicate)\n else:\n substringList.append(duplicate)\n\n\n\nresultList = []\ncurrentMatch = duplicatesList[0]\ncurrentMatchPos = 1\n</code></pre>\n\n<p>Any sort of complex logic should really be in a function, not at the module level. </p>\n\n<pre><code>for i in range(1, len(duplicatesList)):\n</code></pre>\n\n<p>Do you really need the indexes? Maybe you should use <code>for duplicate in duplicatesList[1:]</code></p>\n\n<pre><code> if currentMatch[currentMatchPos:] in duplicatesList[i]:\n currentMatch += duplicatesList[i][-1]\n currentMatchPos += 1\n else:\n if SHOW_RESULTS_WHILE_PROCESSING:\n showDuplicate(currentMatch)\n\n\n resultList.append(currentMatch) # this match is closed, add it!\n currentMatch = duplicatesList[i]\n currentMatchPos = 1\n</code></pre>\n\n<p>I dislike the structure of this code. You are manipulating several variables across loop iterations which makes the code hard to follow. But since the algorithm is simply incorrect for what you are doing I can't really tell you how to fix it.</p>\n\n<pre><code>if not SHOW_RESULTS_WHILE_PROCESSING:\n for duplicate in resultList:\n showDuplicate(duplicate)\n\nif not resultList:\n print \"Awesome, no duplicates were found!\"\n</code></pre>\n\n<p>Ok, now for the actual algorithm. I think wilberforce has misinterpreted what you want. His algorithm requires the duplication to be aligned, which I don't think you want.</p>\n\n<p>The simple brute force strategy is as follows:</p>\n\n<pre><code># look at every position where the duplicates could start\nfor x_idx in range(len(file_content)):\n for y_idx in range(x_idx):\n # count the length of the duplicate\n for length, (x_letter, y_letter) in enumerate(zip(file_content[x_idx:], file_content[y_idx:])):\n if x_letter != y_letter:\n break\n # if its good enough, print it\n if length > DUPLICATE_LENGTH:\n showDuplicate(file_content[x_idx:x_idx + length])\n</code></pre>\n\n<p>A more efficient and clever algorithm is to use dynamic programming:</p>\n\n<pre><code># we create 2D list (list of lists) where lengths[x][y] will be length\n# of the duplicate which ends on letter x-1 and y-1 in the file content\n# so we will calculate the length of duplicate for every combination of two positions\nfile_size = len(file_content) + 1\nlengths = [ [None] * file_size for x in range(file_size) ]\n\n# If we are before the characters, the length of the duplicate string is \n# obviously zero\nfor x in range(file_size):\n lengths[x][0] = 0\n lengths[0][x] = 0\n\nfor x in range(1, file_size):\n # we don't check cases where x == y or y > x\n # x == y is trivial and y > x is just\n # the transpose\n for y in range(1, x):\n if file_content[x-1] == file_content[y-1]:\n # if two letters match, the duplicate length\n # is 1 plus whatever we had before\n duplicate_length = lengths[x][y] = lengths[x-1][y-1] + 1\n if duplicate_length > DUPLICATE_LENGTH:\n showDuplicate(file_content[x-duplicate_length:x])\n else:\n # if the files don't match the duplicate ends here\n lengths[x][y] = 0\n</code></pre>\n\n<p>My two programs produce slightly different results. The first says:</p>\n\n<pre><code>Duplicate found: michael\nDuplicate found:michael\n</code></pre>\n\n<p>The second says:</p>\n\n<pre><code>Duplicate found: michae\nDuplicate found: michael\n</code></pre>\n\n<p>The difference is because the actual match is 7 characters long. As a result, it matches twice. I don't know what results you actually do want, so I haven't looked into it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T11:47:18.437",
"Id": "11344",
"Score": "0",
"body": "That's brilliant! Exactly what I was looking for. A clean code analysis. Can you additionally show how you would merge the output to a consistent form efficiently? \"interr interru interrup interrupt\" -> \"interrupt\". I think it's about finding the 'longest' match."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T00:29:17.523",
"Id": "11718",
"Score": "0",
"body": "@Michael, easiest way is to just to check if the next letter matches. If it does, we don't have the longest match, and we shouldn't report that match."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T23:21:15.220",
"Id": "7240",
"ParentId": "7213",
"Score": "5"
}
},
{
"body": "<p>To find a duplicate of a length <code>6</code> or more in a string you could use regular expressions:</p>\n\n<pre><code>>>> import re\n>>> data = \"balwmichaelkajfalsdfamsmichaelasjfal\"\n>>> m = re.search(r\"(.{6,}).*?\\1\", data)\n>>> m and m.group(1)\n'michael'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T00:30:41.330",
"Id": "11719",
"Score": "0",
"body": "nice! Do you know how efficient it is?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T01:32:56.930",
"Id": "11720",
"Score": "0",
"body": "@Winston Ewert: it depends on `re` implementation and input data. It can be very inefficient e.g., `\"abcdefgh\"*100` takes 3 ms and `\"abcdefgh\"*1000` -- 2 seconds (10x input leads to 1000x time). It can be fixed in this case by specifying an upper limit on the duplicate length: `r\"(.{6,1000}).*?\\1\"` or by using [`regex`](http://pypi.python.org/pypi/regex) module that has different implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T17:16:16.717",
"Id": "7456",
"ParentId": "7213",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7240",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T10:59:14.340",
"Id": "7213",
"Score": "4",
"Tags": [
"python",
"optimization",
"algorithm",
"beginner",
"strings"
],
"Title": "Finding duplicate strings within a file"
}
|
7213
|
<p>In our embedded application, we have to replace <code>::operator new</code> and <code>::operator delete</code> to call a special <code>malloc()</code>, to ensure that the memory is allocated correctly. The code, written with <a href="https://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators">this guide</a> in mind, looks like this:</p>
<pre><code>#include <new>
#include <stdexcept>
// Regular scalar new
void* operator new(std::size_t n) throw(std::bad_alloc)
{
using namespace std;
for (;;) {
void* allocated_memory = ::operator new(n, nothrow);
if (allocated_memory != 0) return allocated_memory;
// Store the global new handler
new_handler global_handler = set_new_handler(0);
set_new_handler(global_handler);
if (global_handler) {
global_handler();
} else {
throw bad_alloc();
}
}
}
// Nothrow scalar new
void* operator new(size_t n, std::nothrow_t const&) throw()
{
if (n == 0) n = 1;
return malloc(n);
}
// Regular array new
void* operator new[](size_t n) throw(std::bad_alloc)
{
return ::operator new(n);
}
// Nothrow array new
void* operator new[](size_t n, std::nothrow_t const&) throw()
{
return ::operator new(n, std::nothrow);
}
// Regular scalar delete
void operator delete(void* p) throw()
{
free(p);
}
// Nothrow scalar delete
void operator delete(void* p, std::nothrow_t const&) throw()
{
::operator delete(p);
}
// Regular array delete
void operator delete[](void* p) throw()
{
::operator delete(p);
}
// Nothrow array delete
void operator delete[](void* p, std::nothrow_t const&) throw()
{
::operator delete(p);
}
// Driver function to make the sample code executable.
int main()
{
int* x = new int;
delete x;
int* y = new int[10];
delete[] y;
}
</code></pre>
<p>Is this code correct?</p>
<p>In particular:</p>
<ul>
<li>Do I need any special alignment handling?</li>
<li>Should there be any other differences between <code>operator new</code> and <code>operator new[]</code>?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T12:20:26.327",
"Id": "11262",
"Score": "0",
"body": "(This is technically not *overloading* the operators, but rather to replace them, but I still consider it relevant to the operator-overloading tag.)"
}
] |
[
{
"body": "<p>I am surprised this compiles and works (it does I test it)</p>\n\n<pre><code> global_handler();\n</code></pre>\n\n<p>As global handler is a pointer to a function I was expecting to see this:</p>\n\n<pre><code> (*global_handler)();\n</code></pre>\n\n<h3>Comments:</h3>\n\n<p>Throw specifiers (except no throw) have been deprecated in the latest standard.<br>\nSo you should probably follow their lead in that</p>\n\n<pre><code>void* operator new(std::size_t n) throw(std::bad_alloc)\n</code></pre>\n\n<p>The array version of new calls the no-throw version of new. </p>\n\n<pre><code>void* operator new[](size_t n, std::nothrow_t const&) throw()\n</code></pre>\n\n<p>Thus you are not getting the benefits of any registered out of memory handlers. Maybe you should just call the normal version of new so that the out of memory handlers are called for arrays as-well.</p>\n\n<blockquote>\n <p>Do I need any special alignment handling?</p>\n</blockquote>\n\n<p>No. malloc() provides memory that is aligned for any type.<br>\n<a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html\" rel=\"nofollow\">http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html</a></p>\n\n<blockquote>\n <p>Should there be any other differences between operator new and operator new[]?</p>\n</blockquote>\n\n<p>No. Apart from not using the out of memory handlers it looks fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T23:09:39.100",
"Id": "11322",
"Score": "0",
"body": "Thank you. I think the normal function call syntax is clearer, and is valid syntax even though it is a function pointer. I wrote the functions without the throw specifiers at first, exactly because of them being deprecated in C++0xb, but then the code wouldn't compile. (Maybe I had too strict warnings.) I will fix the regular `operator new[]` to correspond with regular `operator new`. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T17:47:48.810",
"Id": "7227",
"ParentId": "7216",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7227",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T12:19:18.637",
"Id": "7216",
"Score": "4",
"Tags": [
"c++",
"operator-overloading"
],
"Title": "Custom operator new and operator delete"
}
|
7216
|
<p>If I have a long string:</p>
<pre><code>// 10MB string
$string='';
for($run=0; $run<1000000; $run++)
$string.='012345689';
</code></pre>
<p>Then I perform many <code>substr</code>, cutting off small portions from the beginning.</p>
<pre><code>for($run=0; $run<100000; $run++)
{
$temp=substr($string,0,10);
DoSomething($temp);
$string=substr($string,10);
}
</code></pre>
<p>It is VERY slow (20 seconds), which I tracked down to: <code>substr($string,10)</code> as the cause of the problem. Seems it is rebuilding the entire variable each time, which slowing the whole script down.</p>
<p>How can this be optimized, without incrementing the <code>start</code> offset of the first <code>substr</code> in the second code fragment?</p>
<p>EDIT: for those who are upset, the reason why I don't want to use an offset is because this would require keeping the entire string in memory the whole time. I'm trying to optimize both speed and memory.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:01:22.260",
"Id": "11274",
"Score": "0",
"body": "Is the length of the substrings cut off at the beginning constant?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:03:25.887",
"Id": "11275",
"Score": "0",
"body": "There is no reason not to keep track of offsets, simply do `$temp = substr( $string, $offset, 10 ); $offset += 10;`.... instead of `$string=substr($string,10);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:03:33.000",
"Id": "11276",
"Score": "0",
"body": "Can you use a list rather a single string?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:03:42.963",
"Id": "11277",
"Score": "2",
"body": "Is this a real world use case - Doing 100000 operations on 1MB of data?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:04:55.343",
"Id": "11278",
"Score": "0",
"body": "Yes, it is constant. I padded all the values out so that I wouldn't have to search."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:05:54.347",
"Id": "11279",
"Score": "0",
"body": "Yes, a real world case, except it's probably 1,000,000 iterations on 100MB of data, about 1,000,000 times. Big project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:07:23.477",
"Id": "11280",
"Score": "0",
"body": "Are you able to `DoSomething()` as you read the string?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:09:20.493",
"Id": "11281",
"Score": "0",
"body": "Yes, each little extracted string gets put into an array and used for various calculations. In the real script that is, the above is an example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:11:17.470",
"Id": "11282",
"Score": "0",
"body": "Why are you padding the strings and concatenating them into a big one, only to chunk them down and put them in an array? Is there a reason you cannot go straight to an array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:16:29.680",
"Id": "11283",
"Score": "0",
"body": "It's all compressed and saved into a file between the first and second code fragment. You don't need to tear apart my examples, they are only to illustrate how to duplicate the issue, the examples themselves are not the real world problem, which would be impossible to post here because it's too long."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T19:55:27.797",
"Id": "11311",
"Score": "0",
"body": "I don't think you can free just *some* of the memory from the $string variable, thus you will have to rebuild the variable whenever you want to prune it. It also seems to me that you're really trying to optimize for memory, and your first attempt created a performance problem...? You mentioned the string is in a file, maybe just read part of the file (fseek) at a time and find the right balance of memory usage and file access overhead..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:43:19.020",
"Id": "11332",
"Score": "0",
"body": "Your 10MB string is missing a million 7's."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T16:06:22.593",
"Id": "11756",
"Score": "0",
"body": "General rule of thumb. You can optimize for memory, or for speed. Optimizing for one is usually at the expense of the other. There are exceptions to this of course but as a rule of thumb it tends to hold true most of the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-08T05:31:20.427",
"Id": "58815",
"Score": "0",
"body": "Try [chunk_split()](http://www.php.net/manual/en/function.chunk-split.php) and [str_split()](http://www.php.net/manual/en/function.str-split.php)."
}
] |
[
{
"body": "<p>Use</p>\n\n<pre><code>for($run=0; $run<100000; $run++)\n{\n$temp=substr($string,$run*10,10);\nDoSomething($temp);\n//$string=substr($string,10);\n}\n</code></pre>\n\n<p>You trade RAM for performance: The original string will not become shorter, but you don't need the very expensive copying of the string again and again</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:13:19.510",
"Id": "11284",
"Score": "0",
"body": "I was hoping there might be a way to cut the string without having to copy it over and over again. That sounds plausible to me. If it can't be done in PHP, then OK, this is the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:20:15.627",
"Id": "11285",
"Score": "0",
"body": "Small additional improvement: Rename $run to $offset and don't do $run++ but $offset += 10, so instead of increment and multiplication it only has to do an addition ... additionally saves a temporary variable (result of $run*10) ... while the effect will be hardly measurable relative to substr and DoSomething ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:21:46.203",
"Id": "11286",
"Score": "0",
"body": "How is it trading ram for performance? **Both**, RAM usage and performance are significantly better in the braindead obvious offset solution. I just tested it and `memory_get_peak_usage()` is 1.95 times higher than when using offset."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:24:20.010",
"Id": "11287",
"Score": "0",
"body": "It's thinkable to create something which will chop the string without copy, but that's not what makes sense in PHP as it has some downsides like disabling coy-on-write. Also mind that choping stuff of would usually not result in memory actually returned to a usable pool unless the shorter string is copied to some other memory segment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:25:49.103",
"Id": "11288",
"Score": "0",
"body": "@Esailiaja, in theory the original solution has a higher peak memory usage (during the copy it needs 2x the space) but in average is lower (need smaller chunks lateron) ... in theory"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:30:06.700",
"Id": "11289",
"Score": "1",
"body": "@johannes True but that metric is pretty useless. You will have to allocate 10mb vs 20mb for your script, which one you want?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:31:00.360",
"Id": "11290",
"Score": "0",
"body": "@Esalijia: Sorry for bein not precise enough: I ment a reasonable number of these scripts running parallell (which I consider a normal environment for PHP apps) will average lower in the original script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:34:23.797",
"Id": "11291",
"Score": "0",
"body": "Actually I don't care about PEAK memory usage at all. I can allocate any amount to the script. What I care about is the average memory usage of the running time of the script, since this will be run on multiple threads of multiple servers in parallel. It would save money on RAM if it uses less memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:36:15.730",
"Id": "11292",
"Score": "0",
"body": "@EugenRieck Yeah but you need to allocate twice as much memory which means you can run 50% less scripts to make sure they work. The average use is only a bit higher, you can see that metric by using `memory_get_usage` but if you want to know how much you need to reserve for the script altogether, use `memory_get_peak_usage` which is about 2 times higher for using `substr` over offset. Let's say you have 200mb memory for use, then you can only run 10 scripts because at some point they could use 20mb each. But if your scripts only use max 10mb each, you can safely run 20 scripts at a time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:40:05.810",
"Id": "11293",
"Score": "0",
"body": "I don't know why you are arguing seeing as my QUESTION was if there were a way in which the string can be cut without copying it to another variable (which was causing the original problem), in which case there would not be twice the peak memory usage as the length of the string."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T13:02:46.830",
"Id": "7221",
"ParentId": "7220",
"Score": "4"
}
},
{
"body": "<p>You can split string into array and then free memory by unsetting array elements when you don't need them anymore. Of cource PHP has big overhead for arrays, so you should split string into bigger parts then your read chunk size. Splitting a string by big chunks shouldn't be too slow. Example (badly tested, just a basic idea):</p>\n\n<pre><code><?php\nclass ScumbagString {\n //Our main strings array\n private $string_array=array();\n\n //Basic settings\n private $chunk_size;\n private $array_element_size;\n\n //Array position variables\n private $insert_key;\n private $read_key;\n\n //Positions in array elements\n private $insert_element_space_left;\n private $read_offset;\n\n /**\n * \n * @param Integer $chunk_size Size of a string you will read each time\n * @param Integer $chunks_concated Number of chunks in one array element\n * @param String $string String to add to internal array\n */\n public function __construct($chunk_size=10,$chunks_concated=1000,&$string='') {\n //Set default variables\n $this->insert_key=0;\n $this->read_key=0;\n\n $this->read_offset=0;\n\n $this->string_array[0]='';\n\n\n //Process passed variables\n $this->chunk_size=$chunk_size;\n $this->array_element_size=$chunk_size*$chunks_concated;\n $this->insert_element_space_left=$this->array_element_size;\n\n if($string) {\n $this->add($string);\n }\n }\n\n /**\n * Adds a string to the end of internal array\n * @param String $string String to add\n */\n public function add(&$string) {\n $str_length_left=strlen($string);\n $offset=0;\n while($str_length_left) {\n $substr_len=min($this->insert_element_space_left,$str_length_left);\n\n $this->string_array[$this->insert_key].=substr($string,$offset,$substr_len);\n $offset+=$substr_len;\n $str_length_left-=$substr_len;\n if($substr_len===$this->insert_element_space_left) {\n $this->insert_key++;\n $this->string_array[$this->insert_key]='';\n\n $this->insert_element_space_left=$this->array_element_size;\n }\n else {\n $this->insert_element_space_left-=$substr_len;\n }\n }\n\n\n }\n\n /**\n * Get a chunk from internal array.\n * @return Mixed Either a string of $chunk_size from the begining of array or FALSE if fails.\n */\n public function get() {\n //This is a special case\n if($this->read_key===$this->insert_key) {\n //Check if we have enough data written to read\n if($this->read_offset+$this->chunk_size>$this->array_element_size-$this->insert_element_space_left) {\n return FALSE;\n }\n }\n\n $return_str=substr($this->string_array[$this->read_key],$this->read_offset,$this->chunk_size);\n\n $this->read_offset+=$this->chunk_size;\n\n if($this->read_offset>=$this->array_element_size) {\n $this->read_offset=0;\n unset($this->string_array[$this->read_key]);\n $this->read_key+=1;\n }\n\n return $return_str;\n }\n}\n$sStr=new ScumbagString(10,5000);\n\n$string='';\nfor($run=0; $run<1000000; $run++) {\n $string.='0123456789';\n //If it is possible - avoid using $string at all, just do \n //$sStr->add('0123456789'); to lower peak memory usage\n}\n\n$sStr->add($string);\n\n//Free string if you will not use it anymore\nunset($string);\n\n//In this cycle memory usage should slowly drop\n//It will not drop by 10 each iteration, but it should drop\n//by 10*5000 (+ array element overhead) each 5000's iteration.\nfor($run=0; $run<1000000; $run++)\n{\n $temp=$sStr->get();\n DoSomething($temp);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T15:09:16.867",
"Id": "7222",
"ParentId": "7220",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T12:59:11.630",
"Id": "7220",
"Score": "3",
"Tags": [
"php",
"strings"
],
"Title": "PHP substr slow?"
}
|
7220
|
<p>I am trying to implement a TCP/UDP server so all I have to do is something like this:</p>
<pre><code>var server = new Server(Type.UDP, "127.0.0.1", 8888);
server.OnDataRecieved += Datahandler;
server.Start();
</code></pre>
<p>I have tried to make it perform as fast as possible by using Asynchronous calls where possible. </p>
<p>I basically would like to know if there is anything missing/any changes that people would recommend (and why). It is not finished yet as I need to handle exceptions better etc...</p>
<p>TODO: I need to complete the signature of the events to make them more meaningful, etc.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SBlackler.Networking
{
public sealed class HighPerformanceServer
{
private Int32 _currentConnections = 0;
Socket listener;
EndPoint ipeSender;
#region "Properties"
public Int32 Port { get; set; }
public Int32 CurrentConnections { get { return _currentConnections; } }
public Int32 MaxQueuedConnections { get; set; }
public IPEndPoint Endpoint { get; set; }
public ServerType Type { get; set; }
#endregion
#region "Constructors"
private HighPerformanceServer()
{
// do nothing
}
public HighPerformanceServer(ServerType type, String IpAddress)
{
Init(type, IpAddress, 28930);
}
public HighPerformanceServer(ServerType type, String IpAddress, Int32 Port)
{
Init(type, IpAddress, Port);
}
private void Init(ServerType server, String IpAddress, Int32 Port)
{
IPAddress ip;
// Check the IpAddress to make sure that it is valid
if (!String.IsNullOrEmpty(IpAddress) && IPAddress.TryParse(IpAddress, out ip))
{
this.Endpoint = new IPEndPoint(ip, Port);
// Make sure that the port is greater than 100 as not to conflict with any other programs
if (Port < 100)
{
throw new ArgumentException("The argument 'Port' is not valid. Please select a value greater than 100.");
}
else
{
this.Port = Port;
}
}
else
{
throw new ArgumentException("The argument 'IpAddress' is not valid");
}
// We never want a ServerType of None, but we include it as it is recommended by FXCop.
if (server != ServerType.None)
{
this.Type = server;
}
else
{
throw new ArgumentException("The argument 'ServerType' is not valid");
}
}
#endregion
#region "Events"
public event EventHandler<EventArgs> OnServerStart;
public event EventHandler<EventArgs> OnServerStarted;
public event EventHandler<EventArgs> OnServerStopping;
public event EventHandler<EventArgs> OnServerStoped;
public event EventHandler<EventArgs> OnClientConnected;
public event EventHandler<EventArgs> OnClientDisconnecting;
public event EventHandler<EventArgs> OnClientDisconnected;
public event EventHandler<EventArgs> OnDataReceived;
#endregion
public void Start()
{
// Tell anything that is listening that we have starting to work
if (OnServerStart != null)
{
OnServerStart(this, null);
}
// Get either a TCP or UDP socket depending on what we specified when we created the class
listener = GetCorrectSocket();
if (listener != null)
{
// Bind the socket to the endpoint
listener.Bind(this.Endpoint);
// TODO :: Add throttleling (using SEMAPHORE's)
if (this.Type == ServerType.TCP)
{
// Start listening to the socket, accepting any backlog
listener.Listen(this.MaxQueuedConnections);
// Use the BeginAccept to accept new clients
listener.BeginAccept(new AsyncCallback(ClientConnected), listener);
}
else if (this.Type == ServerType.UDP)
{
// So we can buffer and store information, create a new information class
SocketConnectionInfo connection = new SocketConnectionInfo();
connection.Buffer = new byte[SocketConnectionInfo.BufferSize];
connection.Socket = listener;
// Setup the IPEndpoint
ipeSender = new IPEndPoint(IPAddress.Any, this.Port);
// Start recieving from the client
listener.BeginReceiveFrom(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), connection);
}
// Tell anything that is listening that we have started to work
if (OnServerStarted != null)
{
OnServerStarted(this, null);
}
}
else
{
// There was an error creating the correct socket
throw new InvalidOperationException("Could not create the correct sever socket type.");
}
}
internal Socket GetCorrectSocket()
{
if (this.Type == ServerType.TCP)
{
return new Socket(this.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
else if (this.Type == ServerType.UDP)
{
return new Socket(this.Endpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
}
else
{
return null;
}
}
public void Stop()
{
if (OnServerStopping != null)
{
OnServerStopping(this, null);
}
if (OnServerStoped != null)
{
OnServerStoped(this, null);
}
}
internal void ClientConnected(IAsyncResult asyncResult)
{
// Increment our ConcurrentConnections counter
Interlocked.Increment(ref _currentConnections);
// So we can buffer and store information, create a new information class
SocketConnectionInfo connection = new SocketConnectionInfo();
connection.Buffer = new byte[SocketConnectionInfo.BufferSize];
// We want to end the async event as soon as possible
Socket asyncListener = (Socket)asyncResult.AsyncState;
Socket asyncClient = asyncListener.EndAccept(asyncResult);
// Set the SocketConnectionInformations socket to the current client
connection.Socket = asyncClient;
// Tell anyone that's listening that we have a new client connected
if (OnClientConnected != null)
{
OnClientConnected(this, null);
}
// TODO :: Add throttleling (using SEMAPHORE's)
// Begin recieving the data from the client
if (this.Type == ServerType.TCP)
{
asyncClient.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(DataReceived), connection);
}
else if (this.Type == ServerType.UDP)
{
asyncClient.BeginReceiveFrom(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), connection);
}
// Now we have begun recieving data from this client,
// we can now accept a new client
listener.BeginAccept(new AsyncCallback(ClientConnected), listener);
}
internal void DataReceived(IAsyncResult asyncResult)
{
try
{
SocketConnectionInfo connection = (SocketConnectionInfo)asyncResult.AsyncState;
Int32 bytesRead;
// End the correct async process
if (this.Type == ServerType.UDP)
{
bytesRead = connection.Socket.EndReceiveFrom(asyncResult, ref ipeSender);
}
else if (this.Type == ServerType.TCP)
{
bytesRead = connection.Socket.EndReceive(asyncResult);
}
else
{
bytesRead = 0;
}
// Increment the counter of BytesRead
connection.BytesRead += bytesRead;
// Check to see whether the socket is connected or not...
if (IsSocketConnected(connection.Socket))
{
// If we have read no more bytes, raise the data received event
if (bytesRead == 0 || (bytesRead > 0 && bytesRead < SocketConnectionInfo.BufferSize))
{
byte[] buffer = connection.Buffer;
Int32 totalBytesRead = connection.BytesRead;
// Setup the connection info again ready for another packet
connection = new SocketConnectionInfo();
connection.Buffer = new byte[SocketConnectionInfo.BufferSize];
connection.Socket = ((SocketConnectionInfo)asyncResult.AsyncState).Socket;
// Fire off the receive event as quickly as possible, then we can process the data...
if (this.Type == ServerType.UDP)
{
connection.Socket.BeginReceiveFrom(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), connection);
}
else if (this.Type == ServerType.TCP)
{
connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(DataReceived), connection);
}
// Remove any extra data
if (totalBytesRead < buffer.Length)
{
Array.Resize<Byte>(ref buffer, totalBytesRead);
}
// Now raise the event, sender will contain the buffer for now
if (OnDataReceived != null)
{
OnDataReceived(buffer, null);
}
buffer = null;
}
else
{
// Resize the array ready for the next chunk of data
Array.Resize<Byte>(ref connection.Buffer, connection.Buffer.Length + SocketConnectionInfo.BufferSize);
// Fire off the receive event again, with the bigger buffer
if (this.Type == ServerType.UDP)
{
connection.Socket.BeginReceiveFrom(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ref ipeSender, new AsyncCallback(DataReceived), connection);
}
else if (this.Type == ServerType.TCP)
{
connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(DataReceived), connection);
}
}
}
else if(connection.BytesRead > 0)
{
// We still have data
Array.Resize<Byte>(ref connection.Buffer, connection.BytesRead);
// call the event
if (OnDataReceived != null)
{
OnDataReceived(connection.Buffer, null);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
internal bool IsSocketConnected(Socket socket)
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
internal void DisconnectClient(SocketConnectionInfo connection)
{
if (OnClientDisconnecting != null)
{
OnClientDisconnecting(this, null);
}
connection.Socket.BeginDisconnect(true, new AsyncCallback(ClientDisconnected), connection);
}
internal void ClientDisconnected(IAsyncResult asyncResult)
{
SocketConnectionInfo sci = (SocketConnectionInfo)asyncResult;
sci.Socket.EndDisconnect(asyncResult);
if (OnClientDisconnected != null)
{
OnClientDisconnected(this, null);
}
}
}
public class SocketConnectionInfo
{
public const Int32 BufferSize = 1048576;
public Socket Socket;
public byte[] Buffer;
public Int32 BytesRead { get; set; }
}
public enum ServerType
{
None = 0,
TCP = 1,
UDP = 2
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:13:51.427",
"Id": "11302",
"Score": "0",
"body": "Define \"correct.\" It could mean any number of different things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:37:06.827",
"Id": "11306",
"Score": "0",
"body": "@JeffMercado, ie have I missed something or is there a best practise for a certain section of code that I am not aware (eg, receiving a connection)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-01T11:30:11.183",
"Id": "137145",
"Score": "0",
"body": "How to distinguish between multiple connected clients (requesting in parallel) when I receive the OnDataRecieved event? Maybe I haven't fully understand whats going on or this code is for one connected Client only."
}
] |
[
{
"body": "<p>At a quick glance, there are a couple minor things I noticed regarding how you handle your events:</p>\n\n<ul>\n<li><p>You are passing null event args. I would instead use EventArgs.Empty, as callers will typically assume the EventArgs object they get from the event handler will be non-null.</p></li>\n<li><p>You are using Interlocked.Increment on your connection counter, suggesting you are going to be using this in multi-threaded code.</p></li>\n</ul>\n\n<p>As such, you should note that</p>\n\n<pre><code>if (OnClientConnected!= null)\n{\n OnClientConnected (this, null);\n}\n</code></pre>\n\n<p>is not thread-safe. Instead, you will want to do something more like the following:</p>\n\n<pre><code>var evt = OnClientConnected;\nif (evt != null)\n{\n evt (this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>I would suggest converting all your internal members to private, unless there is a specific need for other classes to access them, which seems unlikely, given their content.</p>\n\n<p>Additionally, if SocketConnectionInfo.BufferSize is >= 0, then</p>\n\n<pre><code>if (bytesRead == 0 || (bytesRead > 0 && bytesRead < SocketConnectionInfo.BufferSize))\n</code></pre>\n\n<p>can be converted to</p>\n\n<pre><code>if (bytesRead < SocketConnectionInfo.BufferSize)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:42:41.780",
"Id": "11308",
"Score": "0",
"body": "thanks for the heads up about `EventArgs.Empty` didn't know that it existed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T19:47:18.980",
"Id": "11310",
"Score": "0",
"body": "@Dan Lyons - good suggestion on the private members, but isn't setting the evt var = OnClientConnection merely creating a pointer to the same object? How is this more thread safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:49:50.337",
"Id": "11333",
"Score": "1",
"body": "Thankfully, Eric Lippert has answered that one for me :) http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T19:10:18.057",
"Id": "22405",
"Score": "0",
"body": "@Aerik, good question. It's a legal optimization according to ECMA, but \"all of Microsoft's JIT compilers respect the invariant of not introducing new reads to heap memory and therefore, caching a reference in a local variable ensures that the heap reference is accessed only once\" (from CLR via C#, page 264-265). That means that it's thread safe on Microsoft implementations, and I guess that Mono would recognize the [very common] pattern to apply the same functionality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T19:13:46.527",
"Id": "22406",
"Score": "0",
"body": "There's more at http://stackoverflow.com/questions/7664046/allowed-c-sharp-compiler-optimization-on-local-variables-and-refetching-value-fr where it's noted that the ECMA specification differs from what .NET Framework 2.0 does."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T18:26:38.660",
"Id": "7228",
"ParentId": "7226",
"Score": "8"
}
},
{
"body": "<p>1, Create (at least) two classes. One for UDP and one for TCP. It would omit lots of code like this:</p>\n\n<pre><code>if (this.Type == ServerType.TCP) {\n ...\n} else if (this.Type == ServerType.UDP) {\n ...\n}\n</code></pre>\n\n<p>Maybe a common abstract parent class and a factory are also required.</p>\n\n<p>2, Anyway, in the following snippet the last <code>else</code> branch should throw an exception:</p>\n\n<pre><code>if (this.Type == ServerType.TCP) {\n ...\n} else if (this.Type == ServerType.UDP) {\n ...\n} else {\n return null;\n}\n</code></pre>\n\n<p>I don't think that there is any state when <code>Type != TCP</code> and <code>Type != UDP</code> too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T19:36:36.487",
"Id": "7229",
"ParentId": "7226",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "7228",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T17:44:28.987",
"Id": "7226",
"Score": "5",
"Tags": [
"c#",
"asynchronous",
"networking"
],
"Title": "Implementation of an asynchronous TCP/UDP server"
}
|
7226
|
<p>I have a subsystem in a web application that essentially allows users to build views of certain lists of objects. They can specify which columns to display, how to sort and group the list, and what filters they want to assign to the results set. These views of certain objects are fundamentally similar, but due to limitations of <code>NHibernate</code> I can't use generics on my domain view entities, so I have a series of classes that inherit from a <code>ViewBase</code> abstract class.</p>
<p>On the web UI side, I'm using Telerik's MVC grid to display the results, so I have to do some translation from the options present in the domain object and the settings the grid control expects. This process is where I see a lot of repeated code.</p>
<p>Here are two examples:</p>
<pre><code>public GridModel GetOpportunityViewResults(int viewId, GridCommand command)
{
var activeUser = UserContext.Current.GetActiveUser();
var viewSvc = DependencyResolver.Current.GetService<IViewService<OpportunityView>>();
var view = viewSvc.FindBy(viewId, activeUser);
// Replace view's ordering with the command options
var propertyTranslator = new OpportunitiesViewModelTranslator();
view.Orders = TelerikGridHelpers.GenerateViewOrderList(propertyTranslator.TranslateToDomainProperty, command);
// Get the results of the view
var itemsService = DependencyResolver.Current.GetService<IOpportunityService>();
IFutureValue<long> total;
var results = itemsService.FindByView(view, ((command.Page - 1) * view.PageSize), command.PageSize, activeUser, out total);
// Map the domain results to view models
var mapper = new ViewResultsMapper();
var viewModels = results.Select(o => mapper.MapToViewModel(o, view.VisibleProperties.ToList(), new OpportunityViewResultsRequiredProperties()));
// Return the grid model
return command.GroupDescriptors.Any()
? new GridModel
{
Data = TelerikGridHelpers.ApplyDynamicGrouping(viewModels.AsQueryable(), command.GroupDescriptors),
Total = Convert.ToInt32(total.Value)
}
: new GridModel
{
Data = viewModels,
Total = Convert.ToInt32(total.Value)
};
}
public GridModel GetCustomerViewResults(int viewId, GridCommand command)
{
var activeUser = UserContext.Current.GetActiveUser();
var viewSvc = DependencyResolver.Current.GetService<IViewService<CustomerOrganizationView>>();
var view = viewSvc.FindBy(viewId, activeUser);
// Replace view's ordering with the command options
var propertyTranslator = new CustomersViewModelTranslator();
view.Orders = TelerikGridHelpers.GenerateViewOrderList(propertyTranslator.TranslateToDomainProperty, command);
// Get the results of the view
var itemsService = DependencyResolver.Current.GetService<ICustomerOrganizationService>();
IFutureValue<long> total;
var results = itemsService.FindByView(view, ((command.Page - 1) * view.PageSize), command.PageSize, activeUser, out total);
// Map the domain results to view models
var mapper = new ViewResultsMapper();
var viewModels = results.Select(o => mapper.MapToViewModel(o, view.VisibleProperties));
// Return the grid model
return command.GroupDescriptors.Any()
? new GridModel
{
Data = TelerikGridHelpers.ApplyDynamicGrouping(viewModels.AsQueryable(), command.GroupDescriptors),
Total = Convert.ToInt32(total.Value)
}
: new GridModel
{
Data = viewModels,
Total = Convert.ToInt32(total.Value)
};
}
</code></pre>
<p>You can probably ignore the meat of what those methods do, because a lot of it is domain-related stuff. When I went to refactor this code to consolidate these methods, I came up with the following:</p>
<pre><code>public GridModel GetViewResults<TView, TEntity, TRequiredProps, TService, TTranslator>(int viewId, GridCommand command)
where TEntity: class, new()
where TView : ViewBase
where TRequiredProps : ReadOnlyCollection<string>, new()
where TService : IFindByView<TView, TEntity>
where TTranslator : IPropertyNameTranslator, new()
{
var activeUser = UserContext.Current.GetActiveUser();
var viewSvc = DependencyResolver.Current.GetService<IViewService<TView>>();
var view = viewSvc.FindBy(viewId, activeUser);
// Replace view's ordering with the command options
var propertyTranslator = new TTranslator();
view.Orders = TelerikGridHelpers.GenerateViewOrderList(propertyTranslator.TranslateToDomainProperty, command);
// Get the results of the view
var itemsService = DependencyResolver.Current.GetService<TService>();
IFutureValue<long> total;
var results = itemsService.FindByView(view, ((command.Page - 1) * view.PageSize), command.PageSize, activeUser, out total);
// Map the domain results to view models
var mapper = new ViewResultsMapper();
var viewModels = results.Select(o => mapper.MapToViewModel(o, view.VisibleProperties.ToList(), new TRequiredProps()));
// Return the grid model
return command.GroupDescriptors.Any()
? new GridModel
{
Data = TelerikGridHelpers.ApplyDynamicGrouping(viewModels.AsQueryable(), command.GroupDescriptors),
Total = Convert.ToInt32(total.Value)
}
: new GridModel
{
Data = viewModels,
Total = Convert.ToInt32(total.Value)
};
}
</code></pre>
<p>The advantage with this generics Frankenstein is that I can simplify the individual calls in the initial examples like so:</p>
<pre><code>public GridModel GetOpportunityViewResults(int viewId, GridCommand command)
{
return GetViewResults<OpportunityView, Opportunity, OpportunityViewResultsRequiredProperties, IOpportunityService, OpportunitiesViewModelTranslator>(viewId, command);
}
public GridModel GetCustomerViewResults(int viewId, GridCommand command)
{
return GetViewResults<CustomerView, CustomerOrganization, CustomerViewResultsRequiredProperties, ICustomerOrganizationService, CustomersViewModelTranslator>(viewId, command);
}
</code></pre>
<p>The disadvantage is that it's really smelly that way and technically Microsoft warns against too many type parameters on generic methods. It does the job, but holy crap is it ugly with all those generic parameters and constraints. Am I taking generics too far? Should I break up the bits of the method into a series of generic calls that only take one or two types?</p>
|
[] |
[
{
"body": "<p>Yes. I would break them up into serial calls. It should help things stay a bit more modular as well and make refactoring/alterations easier down the road. Not to mention it would be easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:56:49.763",
"Id": "11334",
"Score": "0",
"body": "The only thing about breaking them up is that it won't really do too much to cut down on repetition. I'd still have probably four sections where I'd make calls to another class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:18:36.963",
"Id": "7235",
"ParentId": "7233",
"Score": "1"
}
},
{
"body": "<p>For a specific closed generic <code>IFindByView<TView, TEntity></code>, are there multiple implementations? If not you could just retrieve <code>IFindByView<TView, TEntity></code> from the DI instead of <code>TService : IFindByView<TView, TEntity></code>. This would help to get rid one type parameter (<code>TService</code>).</p>\n\n<p>You can remove a second type parameter <code>TRequiredProps</code> by adding an argument <code>ReadOnlyCollection<string> requiredProperties</code> to the method. This also means the collection doesn't need to be <code>new()</code>-able (= one less constraint which the rest of your code has to adhere to).</p>\n\n<hr>\n\n<p>Now if you were to use a property DI container and do inversion of control instead of using the service locator (anti-?!) pattern you could also just ctor-inject the dependencies and instead of specifying which type to use by a generic type constraint, you could just as well configure the DI container to inject the right type given some conditions. How this is done depends on the DI container.</p>\n\n<p><a href=\"https://github.com/ninject/Ninject/wiki/Contextual-Binding\" rel=\"nofollow\">Here</a>'s an example of what Ninject can do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-05T08:53:40.177",
"Id": "99086",
"ParentId": "7233",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:13:25.607",
"Id": "7233",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Allowing users to build views of certain lists of objects"
}
|
7233
|
<p>I've got an MVC site, using <code>FormsAuthentication</code> and custom service classes for <code>Authentication</code>, <code>Authorization</code>, <code>Roles</code>/<code>Membership</code>, etc.</p>
<p><strong>Authentication</strong></p>
<p>There are three ways to sign-on:</p>
<ol>
<li>Email + Alias</li>
<li>OpenID</li>
<li>Username + Password</li>
</ol>
<p>All three get the user an auth cookie and start a session. The first two are used by visitors (session only) and the third for authors/admin with DB accounts.</p>
<pre><code>public class BaseFormsAuthenticationService : IAuthenticationService
{
// Disperse auth cookie and store user session info.
public virtual void SignIn(UserBase user, bool persistentCookie)
{
var vmUser = new UserSessionInfoViewModel { Email = user.Email, Name = user.Name, Url = user.Url, Gravatar = user.Gravatar };
if(user.GetType() == typeof(User)) {
// roles go into view model as string not enum, see Roles enum below.
var rolesInt = ((User)user).Roles;
var rolesEnum = (Roles)rolesInt;
var rolesString = rolesEnum.ToString();
var rolesStringList = rolesString.Split(',').Select(role => role.Trim()).ToList();
vmUser.Roles = rolesStringList;
}
// i was serializing the user data and stuffing it in the auth cookie
// but I'm simply going to use the Session[] items collection now, so
// just ignore this variable and its inclusion in the cookie below.
var userData = "";
var ticket = new FormsAuthenticationTicket(1, user.Email, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(30), false, userData, FormsAuthentication.FormsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { HttpOnly = true };
HttpContext.Current.Response.Cookies.Add(authCookie);
HttpContext.Current.Session["user"] = vmUser;
}
}
</code></pre>
<h3><code>Roles</code></h3>
<p>A simple flags enum for permissions:</p>
<pre><code>[Flags]
public enum Roles
{
Guest = 0,
Editor = 1,
Author = 2,
Administrator = 4
}
</code></pre>
<p>Enum extension to help enumerate flag enums:</p>
<pre><code>public static class EnumExtensions
{
private static void IsEnumWithFlags<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException(string.Format("Type '{0}' is not an enum", typeof (T).FullName));
if (!Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
throw new ArgumentException(string.Format("Type '{0}' doesn't have the 'Flags' attribute", typeof(T).FullName));
}
public static IEnumerable<T> GetFlags<T>(this T value) where T : struct
{
IsEnumWithFlags<T>();
return from flag in Enum.GetValues(typeof(T)).Cast<T>() let lValue = Convert.ToInt64(value) let lFlag = Convert.ToInt64(flag) where (lValue & lFlag) != 0 select flag;
}
}
</code></pre>
<h3><code>Authorization</code></h3>
<p>Service offers methods for checking an authenticated user's roles.</p>
<pre><code>public class AuthorizationService : IAuthorizationService
{
// Convert role strings into a Roles enum flags using the additive "|" (OR) operand.
public Roles AggregateRoles(IEnumerable<string> roles)
{
return roles.Aggregate(Roles.Guest, (current, role) => current | (Roles)Enum.Parse(typeof(Roles), role));
}
// Checks if a user's roles contains Administrator role.
public bool IsAdministrator(Roles userRoles)
{
return userRoles.HasFlag(Roles.Administrator);
}
// Checks if user has ANY of the allowed role flags.
public bool IsUserInAnyRoles(Roles userRoles, Roles allowedRoles)
{
var flags = allowedRoles.GetFlags();
return flags.Any(flag => userRoles.HasFlag(flag));
}
// Checks if user has ALL required role flags.
public bool IsUserInAllRoles(Roles userRoles, Roles requiredRoles)
{
return ((userRoles & requiredRoles) == requiredRoles);
}
// Validate authorization
public bool IsAuthorized(UserSessionInfoViewModel user, Roles roles)
{
// convert comma delimited roles to enum flags, and check privileges.
var userRoles = AggregateRoles(user.Roles);
return IsAdministrator(userRoles) || IsUserInAnyRoles(userRoles, roles);
}
}
</code></pre>
<p>I chose to use this in my controllers via an attribute:</p>
<pre><code>public class AuthorizationFilter : IAuthorizationFilter
{
private readonly IAuthorizationService _authorizationService;
private readonly Roles _authorizedRoles;
/// <summary>
/// Constructor
/// </summary>
/// <remarks>The AuthorizedRolesAttribute is used on actions and designates the
/// required roles. Using dependency injection we inject the service, as well
/// as the attribute's constructor argument (Roles).</remarks>
public AuthorizationFilter(IAuthorizationService authorizationService, Roles authorizedRoles)
{
_authorizationService = authorizationService;
_authorizedRoles = authorizedRoles;
}
/// <summary>
/// Uses injected authorization service to determine if the session user
/// has necessary role privileges.
/// </summary>
/// <remarks>As authorization code runs at the action level, after the
/// caching module, our authorization code is hooked into the caching
/// mechanics, to ensure unauthorized users are not served up a
/// prior-authorized page.
/// Note: Special thanks to TheCloudlessSky on StackOverflow.
/// </remarks>
public void OnAuthorization(AuthorizationContext filterContext)
{
// User must be authenticated and Session not be null
if (!filterContext.HttpContext.User.Identity.IsAuthenticated || filterContext.HttpContext.Session == null)
HandleUnauthorizedRequest(filterContext);
else {
// if authorized, handle cache validation
if (_authorizationService.IsAuthorized((UserSessionInfoViewModel)filterContext.HttpContext.Session["user"], _authorizedRoles)) {
var cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0));
cache.AddValidationCallback((HttpContext context, object o, ref HttpValidationStatus status) => AuthorizeCache(context), null);
}
else
HandleUnauthorizedRequest(filterContext);
}
}
</code></pre>
<p>I decorate Actions in my Controllers with this attribute, and like Microsoft's <code>[Authorize]</code> no params means let in anyone authenticated (for me it is Enum = 0, no required roles).</p>
<p>I am curious about the appropriateness of my setup:</p>
<ol>
<li><p>Do I need to manually snag the auth cookie and populate the <code>FormsIdentity</code> principal for the <code>HttpContext</code> or should that be automatic?</p></li>
<li><p>Are there any issues with checking authentication within the attribute/filter <code>OnAuthorization()</code>?</p></li>
<li><p>What are tradeoffs in using <code>Session[]</code> to store my view model vs. serializing it within the auth cookie?</p></li>
<li><p>Does this solution seem to follow the 'separation of concerns' ideals well enough?</p></li>
</ol>
|
[] |
[
{
"body": "<p>I'll take a stab at answering your questions and provide some suggestions:</p>\n\n<ol>\n<li><p>If you have FormsAuthentication configured in <code>web.config</code>, it will automatically pull the cookie for you, so you shouldn't have to do any manual population of the FormsIdentity. This is pretty easy to test in any case.</p></li>\n<li><p>You probably want to override both <code>AuthorizeCore</code> and <code>OnAuthorization</code> for an effective authorization attribute. The <code>AuthorizeCore</code> method returns a boolean and is used to determine whether the user has access to a given resource. The <code>OnAuthorization</code> doesn't return and is generally used to trigger other things based on the authentication status.</p></li>\n<li><p>I think the session-vs-cookie question is largely preference, but I'd recommend going with the session for a few reasons. The biggest reason is that the cookie is transmitted with every request, and while right now you may only have a little bit of data in it, as time progresses who knows what you'll stuff in there. Add encryption overhead and it could get large enough to slow down requests. Storing it in the session also puts ownership of the data in your hands (versus putting it in the client's hands and relying on you to decrypt and use it). One suggestion I would make is wrapping that session access up in a static <code>UserContext</code> class, similar to <code>HttpContext</code>, so you could just make a call like <code>UserContext.Current.UserData</code>. I can provide some code for this if you need some suggestions. This approach will let you hide the implementation so you can change from session to cookie and back without affecting other code that uses it.</p></li>\n<li><p>I can't really speak to whether it is a good separation of concerns, but it looks like a good solution to me. It's not unlike other MVC authentication approaches I've seen. I'm using something very similar in my apps in fact.</p></li>\n</ol>\n\n<p>One last question -- why did you build and set the FormsAuthentication cookie manually instead of using <code>FormsAuthentication.SetAuthCookie</code>? Just curious.</p>\n\n<p>Josh</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T06:14:21.253",
"Id": "11547",
"Score": "0",
"body": "Thanks for the review/answer. It's very helpful. This is a question I have going on StackOverflow (http://stackoverflow.com/questions/8567358/mvc-custom-authentication-authorization-and-roles-implementation) and been unhappy with the response. If you would, post your answer there and I'll give it to you. Also, if you would like to share your `UserContext` example for question #3 there too, that would be even more awesome. As for the cookie, it came before I used `Session[]` and I was setting it manually with a serialized encrypted ticket...'just leftover code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T16:48:20.107",
"Id": "11569",
"Score": "0",
"body": "I cross-posted this and added the `UserContext` code. Hope it helps."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:19:30.703",
"Id": "7286",
"ParentId": "7234",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "7286",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:14:12.970",
"Id": "7234",
"Score": "11",
"Tags": [
"c#",
"authentication",
"asp.net-mvc-3",
"authorization"
],
"Title": "Custom Authentication, Authorization, and Roles implementation"
}
|
7234
|
<p>I'm not a css expert so please help me figuring this out. Would you consider this as good css code?</p>
<p>Please point any issues if you believe this is not what you would exactly consider as good code.</p>
<pre><code> html { -webkit-text-size-adjust: 70%; }
body { margin:0px; padding:0px;font-family:Arial, Helvetica, sans-serif; }
{ font-size:14px;}
#wrap { width:100%; height:100%; background-color:#FFFFFF; padding: 0;}
#header {
padding: 10px;
height:251px;
}
#menu { width:100%; height:2.2em; margin-top:1%; background:#80b2e4; border- radius:10px; -moz-border-radius:10px; -webkit-moz-border-radius:10px;}
.top_menu_left {float:left; width:86%;height:35px; margin-left:3%;}
.top_menu_left li a { color:#fff !important; }
.top_menu_left li a:hover { color:#336699 !important; }
.top_menu_right {float:right; width:17%;;height:1.2em;}
li{list-style:none; float:left; color:#74677E;font-size:70%;font- weight:bold;font- family:Arial, Helvetica, sans-serif; text-align:left; padding:0 5px; -top:9px; color:#fff;}
.top_menu_left li {padding-right:1%; color:#fff;}
.top_menu_right li {padding-right:5%; color:#fff;}
#searchbar { width:100%; height:auto;margin-top:8%;}
#top_search {width:100%; height:auto;}
#bottom_search {width:89%; height:auto;padding-left:10.5%;font-size:75%;}
.sarch_box { width:10%; height:auto; float:left; margin-left:1%;font-size:75%;}
.box_1 { width:20%; height:auto; float:left;font-size:85%;}
.box_1 input { width:80%; height:1.2em;font-size:85%;}
.box_1 select { width:70%; height:1.5em;font-size:85%;}
.box_2 {width:2%; height:auto; float:left;}
#content { width:87%; height:auto; margin-left:11%; margin-top:0; }
#left_content { width:7%; height:auto; float:left; }
#left_searchbar_title {width:95%;height:2%;padding-top:1%;padding- bottom:1%;padding- left:5%;background-color:#A5D959;font-family:Arial, Helvetica, sans-serif;font-size:75%;}
#left_sidebar_content{width:100%;height:2%;background-color:#EFFFD8;font- family:Arial, Helvetica, sans-serif;font-size:75%;}
#main_content { width:59%; height:auto;float:left; }
.main_content_header {margin-left:2%;color:black;font-size:100%;font- family:Arial, Helvetica, sans-serif;font-weight:bold;margin-bottom:5%;}
.content_header {width:70%; height:auto; margin-left:3%;}
/*.left_1 {margin-left:2%;width:.05em; height:100px;background- image:url(images/verticalbar.gif);background-repeat:repeat-y;float:left;padding-left:2px; }*/
.left_1 {margin-left:2%;width:.05em; height:100px;background-image:none;background- repeat:repeat-y;float:left;padding-left:2px; }
/*.left_6 { width:.05em;height:100px;background- image:url(images/verticalbar.gif);background-repeat:repeat-y;float:left; }*/
.left_6 { width:.05em;height:100px;background-image:none;background-repeat:repeat- y;float:left; }
.left_content_middle {width:95%;float:left;font-size:80%;font-family:Arial, Helvetica, sans-serif; background:white; border:1px solid #c6c6c6;border-radius:10px; webkit-border-radius:10px; -moz-border-radius:10px}
.content_title {padding:2%; text-align:center; color:black; <!--#336699;-->font- weight:bold;font-size:100%;font-family:Arial, Helvetica, sans-serif; }
.content_line{size:2px; width:95%; background-image:url(images/horizotal-line.gif);}
.left_2 { margin-left:3%; width:21.5%; height:auto; float:left; }
.left_3 { width:23.5%;height:auto;float:left;}
.left_4 { width:23.5%;height:auto;float:left;}
.left_5 { width:23.5%;height:auto;float:left;}
#right_content { width:20%;height:auto;background-color:white;float:left;margin- left:1%;padding:10px; border:1px solid #c6c6c6; border-radius:10px; webkit-border- radius:10px; -moz-border-radius:10px}
.right_top { width:100%; height:auto; color:white; font-size:100%; color:#336699;}
.Left_portion { width:45%; height:auto; float:left;padding-left:8%;}
.right_portion { width:45%; height:auto; float:left;}
.right_content_title {color:#BB532E;font-weight:bold;font-size:70%;font-family:Arial, Helvetica, sans-serif;padding-bottom:4%;padding-top:5%; }
.right_content_body {color:#5E6472;font-size:70%;font-weight:bold;font-family:Arial, Helvetica, sans-serif;padding-bottom:3%;}
.menu_bar { width:10%; font-family:Arial, Helvetica, sans-serif; color:red; float:left; font-size:50%;}
.gap {width:35%;}
#footer {height:40px;width:100%;margin:auto;text-align:center;text- align:center;margin-top:2%;background:url('images/footer_bg.png') repeat-x; line-height:40px; color:white;}
.footer_menu {
color: white;
float: right;
height: 1.2em;
-left: 3%;
width: 70%;
}
.footer_menu li {
color: white;
padding-right: 1%;
}
.footer_menu li a { color:#fff; text-decoration:none;}
.footer_menu li a:hover { text-decoration:underline}
.footer_menu2 {
background: url("images/footer_bg2.png") repeat-x scroll 0 0 transparent;
color: grey;
float: left;
font-size: 13px;
margin-top: 21px;
width: 100%;
}
.footer_menu strong { font-weight:lighter; color:#666}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:36:11.883",
"Id": "11324",
"Score": "0",
"body": "Whats your markup those goes with this CSS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:37:17.673",
"Id": "11325",
"Score": "1",
"body": "Looks pretty good to me, whole point of using a css file is to reduce redundancy, and you don't seem to have much. Maybe the .Left_i from 3-5, but other than that it looks pretty good. Really depends on what you are trying to get out of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:38:06.283",
"Id": "11326",
"Score": "0",
"body": "What's the context? It looks like everything is relatively sized so the page will look different when the browser window is a different resolution. Can we see the HTML it's associated with? Also, is there a specific question you have about the css? \"Good\" and \"bad\" are kind of arbitrary right now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:40:31.933",
"Id": "11327",
"Score": "0",
"body": "Others will add more specifics, but as with all code, grouping and commenting CSS will greatly aid in maintainability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T23:18:36.190",
"Id": "11329",
"Score": "2",
"body": "There is **a lot of redundancy** and overspecification in your stylesheet. Too many `!important` declarations, too many repeated selectors and properties... the one thing that you don't have enough of is indentation."
}
] |
[
{
"body": "<p>I don't beleave it is \"good\" CSS code because:</p>\n\n<ul>\n<li>It is inconsistant (white space, multi/single line, etc)</li>\n<li>There are obvious syntax errors</li>\n<li>There is a lot of repetition</li>\n<li>It is mostly percent based sizes which will break in a lot of cases</li>\n<li>There is rules that will be used by default anyway, hence don't need to be specified</li>\n<li>There is too much use of the <code>!important</code> keyword</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:43:13.147",
"Id": "7238",
"ParentId": "7237",
"Score": "1"
}
},
{
"body": "<pre><code>html { -webkit-text-size-adjust: 70%; }\nbody { margin:0px; padding:0px;font-family:Arial, Helvetica, sans-serif; }\n</code></pre>\n\n<p>There's no need to specify the unit (px) if the value is 0</p>\n\n<pre><code>{ font-size:14px;}\n</code></pre>\n\n<p>This isn't styling anything</p>\n\n<pre><code>#wrap { width:100%; height:100%; background-color:#FFFFFF; padding: 0;}\n</code></pre>\n\n<p>Assuming #wrap is a div or other block level element it's unnecesarry to give it a width of 100% as all block elements <em>are</em> 100% wide by default. Padding is also 0 by default in almost all elements.</p>\n\n<pre><code>#header {\npadding: 10px;\n\nheight:251px;\n}\n</code></pre>\n\n<p>You should never give elements (except images/canvases) a height because if the user increases the font-size the element should adjust to the new size of the content.</p>\n\n<pre><code>#menu { width:100%; height:2.2em; margin-top:1%; background:#80b2e4; border- radius:10px; -moz-border-radius:10px; -webkit-moz-border-radius:10px;}\n</code></pre>\n\n<p>Again, no need to set the width and why would you suddenly use em for the height? It's common to also put the -browser-specific properties <em>before</em> the \"real\" ones.</p>\n\n<pre><code>.top_menu_left {float:left; width:86%;height:35px; margin-left:3%;}\n.top_menu_left li a { color:#fff !important; }\n.top_menu_left li a:hover { color:#336699 !important; }\n</code></pre>\n\n<p>Having something like \"left\" (or right, bold, red, etc) as a class name is not separating the content from the presentation. Also you should try to avoid using !important as it often leads to more use of !important and hard to find bugs.</p>\n\n<pre><code>.top_menu_right {float:right; width:17%;;height:1.2em;}\n</code></pre>\n\n<p>Again the class name is design related.</p>\n\n<pre><code>li{list-style:none; float:left; color:#74677E;font-size:70%;font- weight:bold;font- family:Arial, Helvetica, sans-serif; text-align:left; padding:0 5px; -top:9px; color:#fff;}\n</code></pre>\n\n<p>Do you <em>really</em> want all your li:s in your entire document to have this styling? There's also syntax errors (like -top).</p>\n\n<pre><code>.top_menu_left li {padding-right:1%; color:#fff;}\n.top_menu_right li {padding-right:5%; color:#fff;}\n</code></pre>\n\n<p>Again the class name - also, this should probably be next to the other styling of the same element.</p>\n\n<pre><code>#searchbar { width:100%; height:auto;margin-top:8%;}\n</code></pre>\n\n<p>No need to set width <em>or</em> height here as you set them to default values. Also - why would you use an #id here but a .class for almost everything else?</p>\n\n<p>I'll stop quoting code here as the rest contains pretty much the same faults.</p>\n\n<p><strong>A few things I would improve:</strong></p>\n\n<ul>\n<li>Don't use design related class or ID-names like left and right.</li>\n<li>Don't use !important - instead plan your code in a way that doesn't require it.</li>\n<li>Don't use percentages for everything.</li>\n<li>Structure your CSS in a way that makes a little more sense. You don't have to keep it all in one file (in fact, you probably shouldn't (but you should only <em>serve</em> one file to the browser though)). This tip would probably require an entire book but a few things to get you started:\n<ul>\n<li>Start with basic element selectors (like h1, p, a, ul etc) - the generic styling that will be default for everything on your page.</li>\n<li>Next do your layout - right/left columns and other areas for your \"modules\".</li>\n<li>Last style your modules - the #searchbar should have this bg, #recent-comments links should be red, the #footer's ul shouldn't have any bullets etc.</li>\n</ul></li>\n</ul>\n\n<p>Also, since everything else in HTML uses dash-separation I use that for my class and ID names as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T01:53:34.760",
"Id": "11469",
"Score": "0",
"body": "!important is very necessary when doing adaptive (or reactive) design. Dumb example: `body article br {display: none}` would mean there's no actual break when I use a `<br>` tag in within an `<article>` tag. But, lets say that I insert the `<br>` to cause a break on screen sizes less than 320px `@media screen and (max-width: 320px){ body article br {display: block !important;}}` without the `!important` that style will not display properly. `!important` exists for some very good reasons and should be used when appropriate since there are times when you can't \"html around\" it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T03:16:35.000",
"Id": "11471",
"Score": "1",
"body": "Or you could just put that styling _after_ the first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:42:12.867",
"Id": "11626",
"Score": "0",
"body": "I still don't see why using !important is \"bad\" and why it should be avoided. ergo http://css-tricks.com/when-using-important-is-the-right-choice/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T09:02:15.417",
"Id": "11684",
"Score": "0",
"body": "Well, in the article you link to it's explained why it's \"bad\" in the first paragraph. I agree that it can be useful _sometimes_ but _very_ rarely. I've used it to to style .todo elements to always have a red dotted border. But as the name suggests the .todo class is very temporary and never makes it to the live site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-10T17:40:45.000",
"Id": "26707",
"Score": "0",
"body": "I agree that !important should only be used when absolutely necessary. It's often used in a lazy fashion, which causes hell for developers that come across this later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-06T05:31:59.897",
"Id": "250486",
"Score": "0",
"body": "Powerful code review"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T23:11:29.600",
"Id": "7239",
"ParentId": "7237",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:34:24.963",
"Id": "7237",
"Score": "1",
"Tags": [
"css"
],
"Title": "Css code quality?"
}
|
7237
|
<p>This is a rot-n (rotate n times) encrypt/decrypt algorithm, where n can be any integer (+/-).</p>
<p>It's written to encrypt/decrypt all the alphabets (upper/lower case) and leaving behind all non-alphas.</p>
<p>rot-n where n is the key, is given in the first line of input file.</p>
<p>Everything is working fine. I just need help in optimizing it.</p>
<blockquote>
<p><strong>Challenge description</strong></p>
<p>Your submission will be tested against an input file that contains
ASCII characters. The input file starts at the very first line with a
N-digits positive or negative integer number that is your cipher,
followed by a new-line character. The second line starts with the
payload of the encrypted text until the end of file. Note that only
words (alphanumeric sequences) are encrypted and that every other
character (i.e. punctuation) must not be processed by your algorithm
and must also be copied ‘as is’ to the standard output.*</p>
</blockquote>
<pre><code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Fightsopa {
public void process(String input, int n) {
int abcd = n;
if (abcd < 0) {
abcd = (26 - ((0 - abcd) % 26));
}
int rot = 26 - abcd % 26; //for decrypting
// int rot= abcd % 26; //for encrypting
char out = 0;
for (char ch : input.toCharArray()) {
if (ch >= 65 && ch <= 90) {
if (ch + rot <= 90) {
out = (char) (ch + rot);
System.out.print(out);
} else {
out = (char) (ch + rot - 26);
System.out.print(out);
}
} else if (ch >= 97 && ch <= 122) {
if (ch + rot <= 122) {
out = (char) (ch + rot);
System.out.print(out);
} else {
out = (char) (ch + rot - 26);
System.out.print(out);
}
} else {
System.out.print(ch);
}
}
}
public void handler(File fFile) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader(fFile));
int rot = 0;
int count = 0;
while (scanner.hasNextLine()) {
if (count == 0) {
rot = scanner.nextInt();
scanner.nextLine();
} else {
String wordp = scanner.nextLine();
process(wordp, rot);
System.out.println();
}
count++;
}
scanner.close();
}
public static void main(String args[]) throws FileNotFoundException {
if (args.length > 0) {
File fFile = new File(args[0]); //Input file having the first line as the key
Fightsopa fsopa = new Fightsopa();
fsopa.handler(fFile);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First, your <code>process</code> method violates the Single Responsibility Principle: It calculates something, and it prints it out. Such coupling makes it inflexible. It's better to return a String, and letting the caller decide what to do with it.</p>\n\n<p>Second, you're code is way too complicated, handling all the different cases which are very dependent on the ASCII layout. Imagine next you want to support digits as well - oh my...</p>\n\n<p>I would suggest to do something along the lines...</p>\n\n<pre><code>public String process(String input, int n) {\n String abc = \"abcdefghijklmnopqrstuvwxyz\";\n String abcABC = abc + abc.toUpperCase();\n int len = abcABC.length();\n\n Map<Character, Character> map = new HashMap<Character, Character>();\n for (int i = 0; i < len; i++) {\n map.put(abcABC.charAt(i), abcABC.charAt((i + n + len) % len));\n }\n\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < input.length(); i++) {\n Character ch = map.get(input.charAt(i));\n if (ch == null) {\n throw new IllegalArgumentException(\"Illegal character \" + input.charAt(i));\n }\n sb.append(ch);\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>Note that I need to know <strong>nothing</strong> about ASCII encoding using that approach, so supporting other chars is a no-brainer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T16:25:23.527",
"Id": "11351",
"Score": "0",
"body": "@Second suggestion :\nI've wrote it to achieve the puzzle description stated above.I've made it depend on ASCII layout only because of the puzzle.\n---If i've wanted to support all ascii set\n`private String charset;\n private int len;\n sampa()\n {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < 128; i++)\n {\n sb.append((char)i);\n }\n charset=sb.toString();\n len=charset.length();\n }`\n\nCan u suggest me ,what changes i could do to my code to make it optimized."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T16:30:40.277",
"Id": "11352",
"Score": "0",
"body": "BTW, your code can only do rot only with in a range i.e (+/-)abcABC.length()"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T08:35:59.103",
"Id": "7253",
"ParentId": "7241",
"Score": "10"
}
},
{
"body": "<p>I agree with Landei, try separating the user interface from the logic. As far as I see your code doesn't handle digits (<em>alphanumeric</em> includes digits as well), so maybe you want to fix it. It's not clear how to rotate digits, but I prefer Landei's map if there is not any special requirement. Anyway, I didn't rewrite the core logic in the following notes.</p>\n\n<ol>\n<li><p>I'd start with extracting out a method:</p>\n\n<pre><code>final StringBuilder result = new StringBuilder();\nfor (final char ch : input.toCharArray()) {\n final char out = doRotate(ch, rotation);\n result.append(out);\n}\nSystem.out.println(result);\n\npublic char doRotate(final char ch, final int rot) {\n if (ch >= CHARCODE_UPPER_A && ch <= CHARCODE_UPPER_Z) {\n if (ch + rot <= CHARCODE_UPPER_Z) {\n return (char) (ch + rot);\n } else {\n return (char) (ch + rot - 26);\n }\n\n } else if (ch >= CHARCODE_LOWER_A && ch <= CHARCODE_LOWER_Z) {\n if (ch + rot <= CHARCODE_LOWER_Z) {\n return (char) (ch + rot);\n } else {\n return (char) (ch + rot - 26);\n }\n }\n return ch;\n}\n</code></pre>\n\n<p>Note the removed last <code>else</code> branch which was unnecessary. <code>return 0</code> is enough. It removes lots of duplicated <code>System.out.println</code> calls. (Maybe one time you want to write the results to a network socket or to a file.) Furthermore, it makes testing easier.</p>\n\n<pre><code>@RunWith(Parameterized.class)\npublic class FightsopaTest extends Fightsopa {\n\n private final char expectedChar;\n private final char inputChar;\n private final int rotate;\n\n public FightsopaTest(final char expectedChar, final char inputChar, \n final int rotate) {\n this.expectedChar = expectedChar;\n this.inputChar = inputChar;\n this.rotate = rotate;\n }\n\n @Parameters\n public static Collection<Object[]> data() {\n final Object[][] data = new Object[][] { \n { 'b', 'a', 1 }, \n { 'a', 'z', 1 }, \n { 'a', 'a', 26 }, \n { 'b', 'a', 27 }, \n };\n return Arrays.asList(data);\n }\n\n @Test\n public void testRotate() throws Exception {\n final char value = new Fightsopa().doRotate(inputChar, rotate);\n assertEquals(expectedChar, value);\n }\n}\n</code></pre>\n\n<p>(Of course it could have been written as a single <code>testRotate</code> method with lots of assert calls but this wouldn't enable <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">defect localization</a>.)</p></li>\n<li><p>I'd rename the <code>process</code> to <code>processLine</code> and extract out a <code>normalizeRotation</code> method too.</p>\n\n<pre><code>public String processLine(final String input, final int rotation) {\n final StringBuilder result = new StringBuilder();\n for (final char ch : input.toCharArray()) {\n final char out = doRotate(ch, rotation);\n result.append(out);\n }\n return result.toString();\n}\n\nprivate int normalizeRotation(final int rotation) {\n int abcd = rotation;\n if (abcd < 0) {\n abcd = (26 - ((0 - abcd) % 26));\n }\n final int normalizedRotation= abcd % 26; //for encrypting\n return normalizedRotation;\n}\n</code></pre>\n\n<p>Actually, this normalization logic should be run only once, right after the reading of the rotation value from the input file (see later).</p></li>\n<li><p>Using guard clauses makes the code flatten and more readable. </p>\n\n<pre><code>public static void main(final String args[]) throws FileNotFoundException {\n if (args.length != 1) {\n System.err.println(\"Missing parameter.\");\n return;\n }\n</code></pre>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n<li><p>Use variable names which explains the purpose, for example:</p>\n\n<pre><code>final File inputFile = new File(args[0]);\n</code></pre></li>\n<li><p>Method names should be verbs, <code>handler</code> should be <code>handle</code>.\n(Check <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\" rel=\"nofollow\">Code Conventions for the Java Programming Language, Naming Conventions</a>.)</p></li>\n<li><p>The <code>handle</code> method doesn't close the <code>Scanner</code> (and the underlying <code>FileReader</code>) in all execution paths. Put the <code>close</code> in a <code>finally</code> block:</p>\n\n<pre><code>final Scanner scanner = new Scanner(new FileReader(inputFile));\ntry {\n ...\n} finally {\n scanner.close();\n}\n</code></pre></li>\n<li><p>I'd break down the <code>handle</code> method to two methods: a <code>readRotation</code> and a <code>processFile</code>. I makes the <code>count</code> variable unnecessary, omits the <code>if</code> (inside the <code>while</code> loop) and makes the code more readable. (Here is the <code>normalizeRotation</code> call.)</p>\n\n<pre><code>public String handle(final File inputFile) \n throws FileNotFoundException, InputErrorException {\n final Scanner scanner = new Scanner(new FileReader(inputFile));\n try {\n final int rotation = readRotation(scanner);\n final int normalizedRotation = normalizeRotation(rotation);\n return processFile(scanner, normalizedRotation);\n } finally {\n scanner.close();\n }\n\n}\n\nprivate int readRotation(final Scanner scanner) throws InputErrorException {\n if (!scanner.hasNext()) {\n throw new InputErrorException(\"Unable to read rotation.\");\n }\n final int rotation = scanner.nextInt();\n scanner.nextLine();\n if (!scanner.hasNext()) {\n throw new InputErrorException(\"Unable to read rotation.\");\n }\n return rotation;\n}\n\nprivate String processFile(final Scanner scanner, final int rot) {\n final StringBuilder result = new StringBuilder();\n while (scanner.hasNextLine()) {\n final String line = scanner.nextLine();\n final String processedLine = processLine(line, rot);\n result.append(processedLine);\n result.append(\"\\n\");\n }\n return result.toString();\n}\n</code></pre></li>\n<li><p>Currently, the <code>Fightsopa</code> still violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>. It does the file processing and the encrypting too. It would be loosely coupled if a separate <code>RotateCoder</code> class did the encoding and <code>Fightsopa</code> class did the file processing.</p>\n\n<pre><code>public class RotateCoder {\n\n private static final int CHARCODE_LOWER_A = 97;\n private static final int CHARCODE_LOWER_Z = 122;\n private static final int CHARCODE_UPPER_A = 65;\n private static final int CHARCODE_UPPER_Z = 90;\n\n private final int normalizedRotation;\n\n public RotateCoder(final String config) {\n final int rotation = Integer.parseInt(config);\n normalizedRotation = normalizeRotation(rotation);\n }\n\n private int normalizeRotation(final int rotation) {\n int abcd = rotation;\n if (abcd < 0) {\n abcd = (26 - ((0 - abcd) % 26));\n }\n final int normalizedRotation = abcd % 26; // for encrypting\n return normalizedRotation;\n }\n\n public char encrypt(char ch) {\n if (ch >= CHARCODE_UPPER_A && ch <= CHARCODE_UPPER_Z) {\n if (ch + normalizedRotation <= CHARCODE_UPPER_Z) {\n return (char) (ch + normalizedRotation);\n } else {\n return (char) (ch + normalizedRotation - 26);\n }\n\n } else if (ch >= CHARCODE_LOWER_A && ch <= CHARCODE_LOWER_Z) {\n if (ch + normalizedRotation <= CHARCODE_LOWER_Z) {\n return (char) (ch + normalizedRotation);\n } else {\n return (char) (ch + normalizedRotation - 26);\n }\n }\n return ch;\n }\n\n}\n</code></pre>\n\n<p><code>Fightsopa</code>:</p>\n\n<pre><code>public class Fightsopa {\n\n public Fightsopa() {\n }\n\n public String processLine(final String input, final RotateCoder coder) {\n final StringBuilder result = new StringBuilder();\n for (final char ch : input.toCharArray()) {\n final char out = coder.encrypt(ch);\n result.append(out);\n }\n return result.toString();\n }\n\n public String handle(final File inputFile) \n throws FileNotFoundException, InputErrorException {\n final Scanner scanner = new Scanner(new FileReader(inputFile));\n try {\n final RotateCoder coder = createCoder(scanner);\n return processFile(scanner, coder);\n } finally {\n scanner.close();\n }\n }\n\n private RotateCoder createCoder(final Scanner scanner) \n throws InputErrorException {\n if (!scanner.hasNext()) {\n throw new InputErrorException(\"Unable to read rotation.\");\n }\n final String coderConfig = scanner.nextLine();\n return new RotateCoder(coderConfig);\n }\n\n private String processFile(final Scanner scanner, final RotateCoder coder) {\n final StringBuilder result = new StringBuilder();\n while (scanner.hasNextLine()) {\n final String line = scanner.nextLine();\n final String processedLine = processLine(line, coder);\n result.append(processedLine);\n result.append(\"\\n\");\n }\n return result.toString();\n }\n\n public static void main(final String args[]) \n throws FileNotFoundException, InputErrorException {\n if (args.length != 1) {\n System.err.println(\"Missing parameter.\");\n return;\n }\n\n final File inputFile = new File(args[0]);\n final Fightsopa fsopa = new Fightsopa();\n final String result = fsopa.handle(inputFile);\n System.out.println(result);\n }\n}\n</code></pre></li>\n<li><p>The <code>main</code> method should be in a separate class (because of the Single Responsibility Principle again) and it should catch the exceptions. Instead of printing the full stacktrace, prints only the message and log (with a logger) the details to a log file.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T21:29:35.987",
"Id": "11398",
"Score": "2",
"body": "One word,about your's- Awesome \nSo i should improve \n\n1) Naming conventions \n2) Loose coupling \n3) Normalization logic should be run only once(better to be in constructor) \n4) Using Guard Clauses \n5) Closing scanner's etc., \n \nThanks for taking time and breaking down into parts, that helped me a lot. \n\nI just wrote the code ,thinking only to solve. But for a programmer that's not only thing, he should be able to write clean,and best code :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:32:34.450",
"Id": "11401",
"Score": "0",
"body": "can we do anything about reducing\nCyclomatic Complexity 7.000"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T23:29:04.500",
"Id": "11404",
"Score": "0",
"body": "7000? Which method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T05:35:27.427",
"Id": "11412",
"Score": "0",
"body": "not 7000, it's 7 for whole program,it's mostly because of encrypt method i think"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:36:32.487",
"Id": "11460",
"Score": "0",
"body": "7 isn't too much. Anyway, I agree, `encrypt` definitely isn't the most beautiful part of the code. I thought that you will rewrite it as Landei suggested, so didn't care too much about this method."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T20:45:19.813",
"Id": "7284",
"ParentId": "7241",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:28:28.940",
"Id": "7241",
"Score": "3",
"Tags": [
"java",
"optimization",
"algorithm",
"cryptography",
"programming-challenge"
],
"Title": "Rot -n algorithm in Java"
}
|
7241
|
<p>It is known a <code>Revealing Module Pattern</code> in javascript, and here it is a little example.</p>
<pre><code>var Module = (function(){
var a = 3,
init = function(a_user){ a = a_user; },
update = function(){},
get = function(){return a},
set = function(a_user){ a = a_user; };
return {
init : init,
update : update,
get : get,
set : set
}
})();
</code></pre>
<p>It's good for lots of uses. But I modified it in 2 steps, and some people tell me that I've overloaded it, and my new variations take lots of memory. So I ask, if my variations are really bad, and I shouldn't use it?</p>
<h2>Variation 1</h2>
<p>I like to separate public and private logic. It's useful, because I separate methods, which I allow to users of my module (in the client code).</p>
<p>For example:</p>
<pre><code>var MyModule = (function(){
var
pr = {}, // Private Scope
PU = {}; // Public Scope
pr.fetch = function(){}; // fetching data
pr.build = function(){}; // building DOM of module
pr.show = function(){}; // showing our object
pr.hide = function(){}; // hiding our object
//... Other private methods
// Public methods
PU.init = function(){
pr.fetch().build().show();
return PU; // for making chains
}
PU.update = function(){};
//... other Public methods
return PU;
})();
</code></pre>
<p>I know, that in usual <code>Revealing Module Pattern</code> methods that are in last <code>return</code> are public, but other - private. But when you calling private method there, you just type it name, and it's unknown if it is a private method of this module, or it's a global function, that's why I have separated object - <code>pr</code> and <code>PU</code>.</p>
<h2>Variation 2:</h2>
<p>Sometimes I had need to insert some of modules twice on a page (or maybe more). So, I understand that it's not a module anymore, because Module can't have instances, Module is just a bundle of related functions. But I've decided to make a Module that can generate instances of itself.
I've used my code from <code>Variation 1</code> with a little fix:</p>
<pre><code>var MyModule = function(){
var
pr = {}, // Private Scope
PU = {}; // Public Scope
pr.fetch = function(){}; // fetching data
pr.build = function(){}; // building DOM of module
pr.show = function(){}; // showing our object
pr.hide = function(){}; // hiding our object
//... Other private methods
// Public methods
PU.init = function(){
pr.fetch().build().show();
return PU; // for making chains
}
PU.update = function(){};
//... other Public methods
// Constructor
PU.__construct = function() {
// constructor code
return PU;
}
return PU.__construct.apply(this, arguments);
};
// Usage:
var m1 = new MyModule(/* some options*/);
m1.init();
var m2 = new MyModule(/* other options */);
m2.init();
</code></pre>
<p>Are these variation really bad? Should I avoid them, as some people have said to me some time earlier...</p>
|
[] |
[
{
"body": "<p>There's nothing really wrong with variation 1, but there's also no point in putting things in <code>pr</code>. Sure you can chain it, but why chain something where <code>this</code> only refers to half the stuff you need (the private stuff)? You might as well just use function declarations. And you can get rid of <code>PU</code>, since it's kind of a meaningless variable name:</p>\n\n<pre><code>var MyModule = (function(){\n function fetch(obj){}; // fetching data\n function build(obj){}; // building DOM of module\n function show(obj){}; // showing our object\n function hide(obj){}; // hiding our object\n //... Other private methods\n return {\n // Public methods\n init: function(){\n show(build(fetch(this)));\n return this; // for making chains\n },\n update: function(){}\n // ... other Public methods\n };\n})();\n</code></pre>\n\n<p>The problem with variation two is that you create those functions whenever the constructor is called (so, more than once).</p>\n\n<p>The normal way to avoid this is to do something like</p>\n\n<pre><code>var MyModule = (function(){\n\n function fetch(obj){}; // fetching data\n function build(obj){}; // building DOM of module\n function show(obj){}; // showing our object\n function hide(obj){}; // hiding our object\n\n function MyModule(){ \n // constructor code\n };\n\n MyModule.prototype.init = function(){\n show(build(fetch(this)));\n return this;\n }; \n\n MyModule.prototype.update = function(){};\n //... other Public methods\n\n return MyModule;\n\n}());\n</code></pre>\n\n<p>Does that make sense?</p>\n\n<p>This is not really a \"module\" anymore, by the way, just a normal constructor with some function properties attached to the prototype. But it looks like that's what you want, since you need multiple instances of it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T02:55:33.500",
"Id": "7247",
"ParentId": "7242",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7247",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T01:46:24.493",
"Id": "7242",
"Score": "1",
"Tags": [
"javascript",
"design-patterns"
],
"Title": "More Revealing Module Patter in Javascript"
}
|
7242
|
<p>I am creating a Minecraft-like terrain engine in XNA to learn HLSL and more XNA. The problem is my lighting algorithm. Whenever a block which emits light is placed, it takes about half a second to calculate it. I have implemented the lighting in a recursive way.</p>
<pre><code>public void DoLight(int x, int y, int z, float light)
{
Vector3i xDecreasing = new Vector3i(x - 1, y, z);
Vector3i xIncreasing = new Vector3i(x + 1, y, z);
Vector3i yDecreasing = new Vector3i(x, y - 1, z);
Vector3i yIncreasing = new Vector3i(x, y + 1, z);
Vector3i zDecreasing = new Vector3i(x, y, z - 1);
Vector3i zIncreasing = new Vector3i(x, y, z + 1);
if (light > 0)
{
light--;
world.SetLight(x, y, z, (int)light);
Blocks.Add(new Vector3(x, y, z));
if (world.GetLight(yDecreasing.X, yDecreasing.Y, yDecreasing.Z) < light &&
!world.GetBlock(yDecreasing.X, yDecreasing.Y, yDecreasing.Z).IsSolid &&
world.InBounds(yDecreasing.X, yDecreasing.Y, yDecreasing.Z))
DoLight(x, y - 1, z, light);
if (world.GetLight(yIncreasing.X, yIncreasing.Y, yIncreasing.Z) < light &&
!world.GetBlock(yIncreasing.X, yIncreasing.Y, yIncreasing.Z).IsSolid &&
world.InBounds(yIncreasing.X, yIncreasing.Y, yIncreasing.Z))
DoLight(x, y + 1, z, light);
if (world.GetLight(xDecreasing.X, xDecreasing.Y, xDecreasing.Z) < light &&
!world.GetBlock(xDecreasing.X, xDecreasing.Y, xDecreasing.Z).IsSolid &&
world.InBounds(xDecreasing.X, xDecreasing.Y, xDecreasing.Z))
DoLight(x - 1, y, z, light);
if (world.GetLight(xIncreasing.X, xIncreasing.Y, xIncreasing.Z) < light &&
!world.GetBlock(xIncreasing.X, xIncreasing.Y, xIncreasing.Z).IsSolid &&
world.InBounds(xIncreasing.X, xIncreasing.Y, xIncreasing.Z))
DoLight(x + 1, y, z, light);
if (world.GetLight(zDecreasing.X, zDecreasing.Y, zDecreasing.Z) < light &&
!world.GetBlock(zDecreasing.X, zDecreasing.Y, zDecreasing.Z).IsSolid &&
world.InBounds(yDecreasing.X, yDecreasing.Y, zDecreasing.Z))
DoLight(x, y, z - 1, light);
if (world.GetLight(zIncreasing.X, zIncreasing.Y, zIncreasing.Z) < light &&
!world.GetBlock(zIncreasing.X, zIncreasing.Y, zIncreasing.Z).IsSolid &&
world.InBounds(zIncreasing.X, zIncreasing.Y, zIncreasing.Z))
DoLight(x, y, z + 1, light);
}
}
</code></pre>
<p>Does anyone see what is costing me so much performance? And if so, could you please suggest any way to fix it?</p>
<p>Especially when I try to update only a single light every frame, I get a depressingly low FPS of 4 (maybe the recursion is the problem). Does anyone know if a iterative would increase performance ? If so, how would I implement it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T15:25:21.860",
"Id": "11348",
"Score": "1",
"body": "It's always a little surprising when people expect to get decent performance out of voxel rendering engines. Voxels just never caught on in a big enough way for graphics hardware vendors to optimize for them. Expecting voxels to perform like polygons is like expecting a software renderer to perform like a hardware renderer. =/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T21:27:11.250",
"Id": "11397",
"Score": "0",
"body": "The problem in this case is the lighting algorythm, not anything else, without it I get like 1440 FPS on average."
}
] |
[
{
"body": "<p>Did you try using performance profiler with this code? Usually profiler can tell you where the problem is or at least show you the whole picture and give a starting point. Here's a <a href=\"http://www.jetbrains.com/profiler/\" rel=\"nofollow\">decent profiler</a> with 10 days trial period.</p>\n\n<p>On the other hand I see several issues with your code. Every time DoLight is called a bunch of vectors are created. If recursion is deep it can lead to creating a lot of objects. Try placing all those vectors in an container object and pass that object as a parameter of DoLight function.</p>\n\n<p>It is also very suspicious that you do not return from DoLight function after performing recursive DoLight function call. (I do not know the algorithm, so its hypothetical advice).\nI mean instead of if's use if else constructs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T06:18:03.140",
"Id": "11727",
"Score": "0",
"body": "Well, in this case if else statements will not work because the algorythim needs to check every block adjacent to it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T08:24:58.257",
"Id": "7251",
"ParentId": "7244",
"Score": "1"
}
},
{
"body": "<p>Building upon Vadym's answer - the vector instantiation could probably be eliminated entirely. It appears they are only created to provide nice groupings of x,y,z coordinates, as they are only ever referenced by pulling the x,y,z values back out.</p>\n\n<p>If performance is really an issue, I would suggest keeping individual values instead for xincreasing, xdecreasing, etc. and using those. It saves on the object creation <em>and</em> the property getter calls. (edit: and, to me at least, it is a little easier to read)</p>\n\n<pre><code>public void DoLight(int x, int y, int z, float light)\n{\n int xDecreasing = x - 1;\n int xIncreasing = x + 1;\n int yDecreasing = y - 1;\n int yIncreasing = y + 1;\n int zDecreasing = z - 1;\n int zIncreasing = z + 1;\n\n if (light > 0)\n {\n light--;\n\n world.SetLight(x, y, z, (int)light);\n Blocks.Add(new Vector3(x, y, z));\n\n if (world.GetLight(x, yDecreasing, z) < light &&\n !world.GetBlock(x, yDecreasing, z).IsSolid &&\n world.InBounds(x, yDecreasing, z))\n DoLight(x, yDecreasing, z, light);\n if (world.GetLight(x, yIncreasing, z) < light &&\n !world.GetBlock(x, yIncreasing, z).IsSolid &&\n world.InBounds(x, yIncreasing, z))\n DoLight(x, yIncreasing, z, light);\n if (world.GetLight(xDecreasing, y, z) < light &&\n !world.GetBlock(xDecreasing, y, z).IsSolid &&\n world.InBounds(xDecreasing, y, z))\n DoLight(xDecreasing, y, z, light);\n if (world.GetLight(xIncreasing, y, z) < light &&\n !world.GetBlock(xIncreasing, y, z).IsSolid &&\n world.InBounds(xIncreasing, y, z))\n DoLight(xIncreasing, y, z, light);\n if (world.GetLight(x, y, zDecreasing) < light &&\n !world.GetBlock(x, y, zDecreasing).IsSolid &&\n world.InBounds(x, y, zDecreasing))\n DoLight(x, y, zDecreasing, light);\n if (world.GetLight(x, y, zIncreasing) < light &&\n !world.GetBlock(x, y, zIncreasing).IsSolid &&\n world.InBounds(x, y, zIncreasing))\n DoLight(x, y, zIncreasing, light);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T20:23:22.987",
"Id": "11396",
"Score": "0",
"body": "Wow, yes, such a simple fix! Thanks! Makes the code look heaps better! :). But it didn't really do anything to performance... Any other suggestions?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T18:41:37.950",
"Id": "7281",
"ParentId": "7244",
"Score": "2"
}
},
{
"body": "<p>You should really profile the application (as others already suggested), without that nobody knows which are the slow parts.</p>\n\n<p>Anyway, two ideas:</p>\n\n<p>1, Try reordering the conditions:</p>\n\n<pre><code>if (world.GetLight(x, yDecreasing, z) < light &&\n !world.GetBlock(x, yDecreasing, z).IsSolid &&\n world.InBounds(x, yDecreasing, z))\n</code></pre>\n\n<p>You use short-circuit operators (<code>&&</code>), so if <code>world.GetLight(x, yDecreasing, z) < light</code> is <code>false</code> the remaining two conditions don't run. The fastest condition should be the first and so on... Of course, without profiling usually hard to tell which is the fastest/slowest method.</p>\n\n<p>2, Maybe you can cache the results of the <code>world.GetLight</code>, <code>world.GetBlock</code> and <code>world.InBounds</code> calls.</p>\n\n<p>Let's say you call <code>DoLigh(0, 0, 0, 0)</code>. It calls the following methods when it runs the <code>if</code>s:</p>\n\n<pre><code>world.GetLight( 0, 1, 0)\nworld.GetLight( 0, -1, 0) #2\nworld.GetLight(-1, 0, 0)\nworld.GetLight( 1, 0, 0)\nworld.GetLight( 0, 0, -1)\nworld.GetLight( 0, 0, 1)\n</code></pre>\n\n<p>If the first <code>if</code> is <code>true</code>, it calls</p>\n\n<pre><code>DoLight(0, -1, 0, light);\n</code></pre>\n\n<p>which calls</p>\n\n<pre><code>world.GetLight( 0, 0, 0)\nworld.GetLight( 0, -1, 0) #2\nworld.GetLight(-1, -1, 0)\nworld.GetLight( 1, -1, 0)\nworld.GetLight( 0, -1, -1)\nworld.GetLight( 0, -1, 1)\n</code></pre>\n\n<p>In this case the #2 call is the same. I don't know that it is cacheable or not. If it is, a cache could make it faster. The same is true for the other two methods. Anyway, first profile it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T01:06:44.370",
"Id": "11405",
"Score": "0",
"body": "OK, I have done the first optomisation, and it runs pretty much the same, but the second, I really don't know, if you cache the results you would still have to search for them in the cache. Also I have tryed to add support to remove a light source (this takes about 2 seconds to calculate), and am no longer performing lighting calculations every frame, only when nessercary, but when it is nessercary, there is still alot of lag."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T21:39:15.950",
"Id": "7285",
"ParentId": "7244",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T02:09:51.817",
"Id": "7244",
"Score": "4",
"Tags": [
"c#",
"performance",
"algorithm",
"xna",
"minecraft"
],
"Title": "Optimizing lighting algorithm for a voxel engine"
}
|
7244
|
<p>Please point out every problem you see with this code. Any fundamental flaws, naming conventions, design decisions, you name it.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <vector>
class SieveHelper {
public:
SieveHelper() : cur(2) {}
bool operator()(unsigned int i) {
return i != cur && i % cur == 0;
}
unsigned int cur;
};
void sieve(std::vector<unsigned int>& arr) {
SieveHelper helper;
auto it = arr.begin();
while (it != arr.end()) {
helper.cur = *it;
auto last = std::remove_if(it, arr.end(), helper);
arr.erase(last, arr.end());
it++;
}
}
int main() {
int n;
std::cin >> n;
std::vector<unsigned int> arr(n);
for (int i = 2; i <= n; i++)
arr[i-2] = i;
sieve(arr);
std::for_each(arr.begin(), arr.end(), [](unsigned int i) {
std::cout << i << " ";
});
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T15:23:49.953",
"Id": "11347",
"Score": "2",
"body": "A classical prime sieve is probably not implemented in terms of erasing from a vector. http://ideone.com/8yKTK is an example, optimized for minimizing memory usage. sieve_vec is a table of booleans where indexes correspond to odd values 1, 3, 5, 7, ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T15:31:40.630",
"Id": "11349",
"Score": "2",
"body": "As to difference in speed compare http://ideone.com/MB3VJ (primes up to 10,000,000 in 0.08 seconds) and http://ideone.com/BKQXd (up to 200,000 in 2.5 seconds)."
}
] |
[
{
"body": "<ul>\n<li>I sort includes alphabetically, making it easier to keep track of which headers are included in long lists.</li>\n</ul>\n\n<p>I would write:</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <vector>\n</code></pre>\n\n<p>In a long, unsorted list of includes it's hard to see if a header is included twice:</p>\n\n<pre><code>#include <vector>\n#include <list>\n#include <algorithm>\n#include <new>\n#include <fstream>\n#include <set>\n#include <stdexcept>\n#include <list>\n#include <cstdlib>\n</code></pre>\n\n<p>Imagine this problem increasing if you have a couple dozen includes!</p>\n\n<ul>\n<li><code>arr</code> is very undescriptive, and in this case even misleading. This isn't an array, it's a <code>std::vector</code>. <code>vec</code> would be slightly better, but try to describe what the data structure contains or does rather than what kind of data structure it is. Even something as simple as <code>numbers</code> is better than <code>vec</code> (or <code>arr</code>), and you can probably improve that even further. Naming is very important to ensure readability.</li>\n<li>Consider using <a href=\"http://publib.boulder.ibm.com/infocenter/comphelp/v9v111/index.jsp?topic=/com.ibm.xlcpp9.aix.doc/standlib/header_cstdint.htm\" rel=\"nofollow\"><cstdint></a> to control the size of numbers. This makes porting a whole lot easier.</li>\n<li>In C++, it's a good habit to prefer prefix increment- and decrement-operators, because they are usually more efficient for non-built-in types. It doesn't really matter for built-in types, but consistency is nice.</li>\n<li>Consider using <code>using</code>-declarations, i.e. <code>using std::vector;</code> and so on, to make the code more readable.</li>\n<li>I'd usually make <code>SieveHelper::cur</code> private and control access to it, but I presume you know that and did it this way on purpose. It's fine for a small program, but remember that programs grow.</li>\n<li>Use <code>std::vector::at()</code>, which is bounds-checked, whenever array indexing is not in the speed-critical path. The exception is when you're 110 % sure you can never, ever go out of bounds - but better safe than sorry!</li>\n<li>Consider making <code>sieve()</code> take and return an argument, rather than just manipulate an output argument. This is definitely a trade-off, so use your own judgement, but output parameters are generally less readable.</li>\n</ul>\n\n<p>On the plus side, this is mostly good. Extra points for using built-in algorithms, lambda and other juicy C++11 stuff :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T02:36:58.137",
"Id": "11408",
"Score": "1",
"body": "don't agree with using at() as default. I would prefer operator[] as default using at() only when data comes from user (unvalidated input). If you can't guarantee the values on validated code then you have bigger problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T08:32:07.620",
"Id": "11421",
"Score": "0",
"body": "@LokiAstari I agree that you should never actually have an exception thrown from `at()` - but that means even more reason to use it, because its cost is then practically the same as `operator[]`. However, if you *do* get an exception from `at()`, then it's much easier to debug. Also, we should swallow our hubris and write robust code when we can ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T08:55:40.890",
"Id": "7255",
"ParentId": "7245",
"Score": "6"
}
},
{
"body": "<p>Why are you adding <code>1</code> to your array?</p>\n\n<p>I can give a simple performance hint. You know that every even number except 2 is composite, so in initialization of <code>arr</code> do not add even numbers (and of course you should not check for 2 in your <code>sieve</code> function). Something like this:</p>\n\n<pre><code>std::vector<unsigned int> arr(n/2+1);\narr[0] = 2;\nfor (int i = 3; i <= n; i+=2)\n arr[i/2] = i;\n</code></pre>\n\n<p>or you can go further and do not add multiples of 2 and 3. For walking over numbers which are not multiples of 2 and 3, you should first take a step of size 2 and then take a step of size 4 and again 2 and again 4 and ...</p>\n\n<pre><code>std::vector<unsigned int> arr(n/3+1);\narr[0] = 2;\narr[1] = 3;\nint t = 2;\nfor (int i = 5; i <= n; i+=t, t=6-t)\n arr[i/3+1] = i;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T16:39:41.213",
"Id": "11353",
"Score": "0",
"body": "Thank you for pointing out the 1. I removed that from the above code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T10:05:55.317",
"Id": "7259",
"ParentId": "7245",
"Score": "4"
}
},
{
"body": "<p>Where you use <code>while()</code> I would prefer to use <code>for(;;)</code> (and use pre-increment).<br>\nNot a big deal but I like to keep all the loop control in one place</p>\n\n<pre><code>auto it = arr.begin();\n\nwhile (it != arr.end()) {\n // STUFF\n\n it++;\n}\n\n// I prefer (though not much different)\n\nfor(auto it = arr.begin(); it != arr.end(); ++it)\n{\n // STUFF\n}\n</code></pre>\n\n<p>Rather than have SieveHelper being declared once and then updated each time through the loop. Just create a new one each iteration. The actual cost of construction will be optimized to zero and it becomes easier to read.</p>\n\n<pre><code> helper.cur = *it;\n\n auto last = std::remove_if(it, arr.end(), helper);\n\n// I would do this (note it requires slight modifications to SieveHelper (see below)).\n\n auto last = std::remove_if(it, arr.end(), SieveHelper(*it));\n</code></pre>\n\n<p>Keeping const correct is a good habit to get into. You need to apply this to your SieveHelper. Also for simple helper functions like this I like to make them structs</p>\n\n<pre><code>struct SieveHelper\n{\n bool operator()(unsigned int i) const // object not changed by method => const\n // ^^^^^\n {\n return i != cur && i % cur == 0;\n }\n\n // Use a reference (as we don't need to store state in the helper)\n SieveHelper(unsigned int const& c) : cur(c) {}\n private:\n unsigned int const& cur;\n};\n</code></pre>\n\n<p>Since you are using C++11 we can even simplify this to a lambda</p>\n\n<pre><code>auto last = std::remove_if(it, arr.end(), \n [&it](unsigned int i){ return i != (*it) && i % (*it) == 0;}\n );\n</code></pre>\n\n<p>As an optimization (probably not a big one) you don't need to call erase after each iteration:</p>\n\n<pre><code>void sieve(std::vector<unsigned int>& arr)\n{\n SieveHelper helper;\n auto it = arr.begin();\n auto last = arr.end()\n\n while (it != arr.end()) {\n helper.cur = *it;\n\n last = std::remove_if(it, last, helper);\n\n it++;\n }\n arr.erase(last, arr.end());\n}\n</code></pre>\n\n<p>Now if we apply all these (apart from lambda)</p>\n\n<pre><code>void sieve(std::vector<unsigned int>& arr)\n{\n auto last = arr.end()\n\n for(auto it = arr.begin(); it != arr.end(); ++it)\n {\n last = std::remove_if(it, last, SieveHelper(*it));\n }\n arr.erase(last, arr.end());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T08:37:22.557",
"Id": "11422",
"Score": "0",
"body": "Good comments, and I also prefer `for` over `while`. While `while` may be more readable, it spills a variable into the surrounding scope, and with `while` it's easier to neglect the incrementing statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T17:43:56.867",
"Id": "11446",
"Score": "0",
"body": "Wow, I'm really glad you came in and replied even after I already chose an answer because this is really great! Any chance you could point me to an article about the particular compiler optimization on constructing each iteration?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:03:32.650",
"Id": "11450",
"Score": "0",
"body": "Sorry I don;t have an article. You should be able to see it by generating and examining the assembly produced."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T02:51:36.147",
"Id": "7296",
"ParentId": "7245",
"Score": "6"
}
},
{
"body": "<p>I like closing <em>for</em> and <em>if</em> one liners just to prevent accidental addition of code that doesn't get executed or put the entire thing on one line, but that may just be me.</p>\n\n<pre><code>for (int i = 2; i <= n; i++) {arr[i-2] = i;}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (int i = 2; i <= n; i++) {\n arr[i-2] = i;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T06:45:41.993",
"Id": "7439",
"ParentId": "7245",
"Score": "3"
}
},
{
"body": "<p>Since this still gets listed near the top rank under \"Sieve of Eratosthenes\": the code under review does <strong>not</strong> implement the Sieve of Eratosthenes at all, it is <strong>trial division</strong> pure and simple.</p>\n\n<p>The real Sieve of Eratosthenes avoids division, and that makes it orders of magnitude faster. Even millions of times when numbers get big enough. </p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">wikipedia article for SoE</a> explains it well, and there are <a href=\"http://rosettacode.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">plenty of code examples for it at Rosetta Code</a> in many languages. A couple more are on <a href=\"http://c2.com/cgi/wiki?SieveOfEratosthenesInManyProgrammingLanguages\" rel=\"nofollow\">this page</a>. </p>\n\n<p>The best overview from a programmer's perspective is probably <a href=\"http://wwwhomes.uni-bielefeld.de/achim/prime_sieve.html\" rel=\"nofollow\">Achim Flammenkamp's page</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-14T00:59:18.413",
"Id": "69795",
"ParentId": "7245",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7255",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T02:38:18.593",
"Id": "7245",
"Score": "10",
"Tags": [
"c++",
"c++11",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes in C++11"
}
|
7245
|
<p>Struggling to write a simple tool to quickly sum up the last reported versions in a <a href="http://static.dabase.com/count-stats.tar.gz" rel="nofollow">bunch of files</a>. I'm using a <a href="http://mywiki.wooledge.org/BashFAQ/024" rel="nofollow">named pipe</a> to get the count out the loop for the final value, but the $version isn't populated which I don't understand.</p>
<pre><code>mkfifo mypipe
for i in stats/*
do
tail -1 $i
done | sort -n > mypipe &
while read version
do
if test "$version" = "$last"
then
count=$(($count + 1))
else
echo $last $count
count=1
last=$version
fi
done < mypipe
# $version is not printed, what's the workaroud?
echo version $version count $count
</code></pre>
<p>Perhaps people can suggest a better cleaner more suck less solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T03:30:50.900",
"Id": "11336",
"Score": "0",
"body": "I don't quite understand what your script tries to accomplish, I see you're getting the last line of each file in stats, sorting them numerically and then? that second loop is weird, also notice you're comparing $last before it's assigned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T03:31:34.677",
"Id": "11337",
"Score": "0",
"body": "oh and use `[[` in bash instead of `test` or `[` and don't forget to quote the variables! especially when they contain filenames."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T04:08:49.440",
"Id": "11338",
"Score": "0",
"body": "I prefer test. Square brackets are for losers. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T05:07:35.267",
"Id": "11340",
"Score": "0",
"body": "`[` and `test` are identical but `[[` is an improved version, read this: http://mywiki.wooledge.org/BashFAQ/031"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T07:15:12.953",
"Id": "11341",
"Score": "0",
"body": "@Samus_ but `[[` is not POSIX (and portable)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:47:28.153",
"Id": "11402",
"Score": "0",
"body": "as I've said \"use `[[` in bash\" if you're writing POSIX-sh there's lots of other considerations but bash is present on all the current Linux distros so it's posrtable to some extent too."
}
] |
[
{
"body": "<p>This shell works:</p>\n\n<pre><code>while IFS= read -r line\ndo\n test -z \"$line\" && continue\n version=$line # only assign version to line once we know it has a value for L23\n if test \"$version\" = \"$last\"\n then\n count=$((count + 1))\n else\n test \"$last\" && echo \"$last $count\"\n count=1\n last=$version\n fi\ndone < <(\nfor f in stats/*\ndo\n tail -1 \"$f\"\ndone | sort -n\n)\n\necho $version $count\n</code></pre>\n\n<p>However it's quite slow compared to a awk line a user \"mute\" on #bash came up with:</p>\n\n<p><code>awk 'FNR==1&&NR!=1{a[latest]++}1{latest=$0}END{a[latest]++;for (v in a)printf(\"%5s %s\\n\", v, a[v]);}' stats/* | sort -n</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T09:01:57.313",
"Id": "7256",
"ParentId": "7246",
"Score": "0"
}
},
{
"body": "<p>From Patrick Haller off email:</p>\n\n<pre><code>for i in stats/*; do tail -1 $i; done | sort | uniq -c\n</code></pre>\n\n<p>Superb!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T09:31:03.710",
"Id": "7257",
"ParentId": "7246",
"Score": "0"
}
},
{
"body": "<p>Your immediate problem is that the exit condition of the loop is when <code>read version</code> returns an error status. This happens when the loop reaches the end of its input file. This call to <code>read</code> also sets <code>version</code> to the empty string.</p>\n\n<p>You can salvage this code by keeping the last known-good value of <code>version</code> in another variable — which you already do here, in <code>last</code>. So change the last line to <code>echo version $last count $count</code>. But there are simpler ways of doing this; <a href=\"https://codereview.stackexchange.com/a/7257\"><code>uniq -c</code>, which has already been suggested</a> being the simplest, and <a href=\"https://codereview.stackexchange.com/a/7256\"><code>awk</code> as a general purpose text processing tool</a> being something to keep in mind as well.</p>\n\n<p>While I'm at it, some general notes on shell programming.</p>\n\n<ul>\n<li><strong>Always put double quotes around variable substitutions and command substitutions</strong>, unless you can explain why it is safe to leave them off in a particular instance. For example, <code>tail -1 $i</code> should be <code>tail -1 \"$i\"</code>: if you leave off the quotes, this command will fail if the file name contains whitespace or globbing characters.</li>\n<li><p>In fact, this line should be</p>\n\n<pre><code>tail -n 1 -- \"$i\"\n</code></pre>\n\n<p>The <code>--</code> is there in case <code>$i</code> begins with a <code>-</code>; without the <code>--</code> it would be treated as an option to <code>tail</code>. In this specific case <code>$i</code> always begins with <code>s</code> so the <code>--</code> is unnecessary, but it's a good habit to get into.<br>\nThe form <code>-1</code> is obsolete, and some modern implementations of <code>tail</code> don't support it. <code>-n 1</code> is the <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/utilities/tail.html\" rel=\"nofollow noreferrer\">standard</a> form.</p></li>\n<li>To read a line from a file, don't use plain <code>read</code>, but <code>IFS= read -r</code>. See <a href=\"https://unix.stackexchange.com/questions/9784/how-can-i-read-line-by-line-from-a-variable-in-bash/9831#9831\">How can I read line by line from a variable in bash?</a> Plain <code>read</code> expands backslashes (expecting a continuation line if a line ends with a <code>\\</code>), and strips off leading and trailing whitespace.</li>\n<li><p>Using a named pipe requires a lot of management: you need to create it with a unique name (use <code>mktemp</code>) and make sure the permissions are correct. You may have tried and failed with the following structure:</p>\n\n<pre><code>for i in stats/*; do … done | while read version; do … count=…; done\necho $count\n</code></pre>\n\n<p>In most shells (Bourne, ash, bash, pdksh), each component of a pipe is executed in its own subshell, so any assignment to <code>count</code> in the while loop doesn't affect the parent shell. Only in a few shells (ATT ksh, zsh) does the rightmost command in a pipeline run in the parent shell. There's a simple workaround for that: run all the code that depends on the assignments performed by a pipeline component inside that pipeline component.</p>\n\n<pre><code>for i in stats/*; do … done | sort -n | {\n while read version; do … count=…; done;\n echo $count\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T17:48:19.623",
"Id": "7278",
"ParentId": "7246",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T02:55:15.130",
"Id": "7246",
"Score": "1",
"Tags": [
"bash"
],
"Title": "Counting last reported version in shell"
}
|
7246
|
<p>Is it possible to shorten this, or to improve the code in any way? I know it's just a simple if-statement, but it's always fun to learn a shorter way of doing things.</p>
<pre><code>if self.citizenship == 'ES'
@identification_type = IDENTIFICATION_TYPES[0]
elsif self.country == 'ES'
@identification_type = IDENTIFICATION_TYPES[1]
end
</code></pre>
|
[] |
[
{
"body": "<p>You could remove a little duplication like this:</p>\n\n<pre><code>@identification_type = if self.citizenship == 'ES'\n IDENTIFICATION_TYPES[0]\nelsif self.country == 'ES'\n IDENTIFICATION_TYPES[1]\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T13:28:23.720",
"Id": "11436",
"Score": "2",
"body": "In other words: the way to shorten this `if`-statement is to realize that is *isn't* an `if`-statement, it's an *`if`-expression*! In fact, there *are no statements* in Ruby, *everything* is an expression."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T10:28:37.310",
"Id": "7261",
"ParentId": "7252",
"Score": "3"
}
},
{
"body": "<p>You could replace the <code>if</code> with <code>case</code>. Normally, the <code>case</code>-statement contains a variable and the <code>when</code>-statements contain constant or variables. But you may do it the other was:</p>\n\n<pre><code>#Some code to make it executable\nIDENTIFICATION_TYPES = [1,2]\nclass MyObject\n def citizenship; 'ES';end\n def country; 'ES';end\n attr_reader :identification_type\n\n def test\n #The code:\n @identification_type = case 'ES'\n when self.citizenship\n IDENTIFICATION_TYPES[0]\n when self.country\n IDENTIFICATION_TYPES[1]\n end\n end\nend\n\np MyObject.new.test\n</code></pre>\n\n<p>Advantage: you don't need to repeat the <code>== 'ES'</code>.</p>\n\n<p>Disadvantage: Mixed checks (<code>ES</code> or <code>AS</code>...) is not possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:45:43.040",
"Id": "11461",
"Score": "0",
"body": "Now things like `1.citizenship` and `[].country` are possible. Don't do this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:59:45.447",
"Id": "11463",
"Score": "0",
"body": "The modification of Object was only a quick possibility to make the example executable - it wasn't meant to be 'real' code. In real case, the code should be embedded in a Object.- I adapted the example to avoid a change of Object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T18:53:13.650",
"Id": "7282",
"ParentId": "7252",
"Score": "0"
}
},
{
"body": "<p>I don't know Ruby, so I'm not sure this is at all idiomatic. However, you can do something like this (if you're looking for a one-liner):</p>\n\n<pre><code>@identification_type = IDENT_TYPES[[@citizenship, @country].index('ES')]\n</code></pre>\n\n<p>Just so this makes some sort of sense (in case I didn't understand your code), here is some context:</p>\n\n<pre><code>IDENT_TYPES = {0 => :citizen, 1 => :country}\n\nclass Foo\n attr_accessor = :citizenship, :country, :identification_type\n\n def initialize(citizenship, country)\n @citizenship = citizenship\n @country = country\n @identification_type = IDENT_TYPES[[@citizenship, @country].index('ES')]\n puts @identification_type\n end\nend\n\nfoo = Foo.new('ES', 'EN')\nfoo = Foo.new('EN', 'ES')\nfoo = Foo.new('EN', 'EN')\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>citizen\ncountry\nnil\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T09:10:59.723",
"Id": "11423",
"Score": "0",
"body": "Interesting approach, but I don't think this code communicates very well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T23:59:00.203",
"Id": "7294",
"ParentId": "7252",
"Score": "0"
}
},
{
"body": "<p>Based on your code (somewhat like @AdamWagner's answer), here's a way without a case statement (though self.country is always evaluated):</p>\n\n<pre><code>criteria=[self.citizenship, self.country]\n@identification_type=\n IDENTIFICATION_TYPES.at criteria.index{|e| 'ES'==e}\n</code></pre>\n\n<p>And a way with a case statement:</p>\n\n<pre><code>k=case 'ES'\n when self.citizenship then 0\n when self.country then 1\n end\nend\n@identification_type=\n IDENTIFICATION_TYPES.at k\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T19:39:10.743",
"Id": "8227",
"ParentId": "7252",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7261",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T08:35:18.817",
"Id": "7252",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Ruby if-statement, possible to shorten it further?"
}
|
7252
|
<p>For digital electronic circuit simulation, i wanted to implement Three states. i.e <strong>High</strong>, <strong>Low</strong> and <strong>Undefined</strong> in C++.</p>
<p>I saw <code>Boost::tribool</code>, and they implement it using <code>enum</code></p>
<p>Now for conserving some memory i have implemented it using 1 Byte Int</p>
<pre><code>#ifdef _WINDOWS
typedef __int8 State;
#elif
typedef int8_t State;
#endif
const State kLow = 0;
const State kHigh = 1;
const State kUndefined = 2;
</code></pre>
<ol>
<li>Do you see any potential problem with it?</li>
<li>And why would one <em>waste</em> 4 bytes instead of a single byte for 3 values only</li>
<li>Do you have a still better way?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T16:13:21.913",
"Id": "11518",
"Score": "0",
"body": "That's an 8-bit int, not a 1-byte int."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T06:00:34.593",
"Id": "11546",
"Score": "0",
"body": "Of course, but I was more concerned about memory usage, that's why byte. Ha, I would have loved to do this in 2 bits instead!"
}
] |
[
{
"body": "<p>The <strong>main</strong> reason there is no accidental conversion (type safety is one of the keys to using C++ correctly).</p>\n\n<pre><code>enum Tri { Yes, No, Maybe };\n\nint main()\n{\n Tri y = Yes;\n y= 1; // Fails to compile.\n}\n</code></pre>\n\n<p>Secondly you are using three bytes to hold the different states here</p>\n\n<pre><code>const State kLow = 0;\nconst State kHigh = 1;\nconst State kUndefined = 2;\n</code></pre>\n\n<p>With an enum there is no space taken up (though potentially the above may be optimized out).</p>\n\n<p>C++11 also allows you to specify the size of an enum:</p>\n\n<pre><code>enum class Tri : char { Yes, No, Maybe };\n// ^^^^ Uses a char sized object\n</code></pre>\n\n<blockquote>\n <p>Do you see any potential problem with it?</p>\n</blockquote>\n\n<p>Yes. Not type safe</p>\n\n<blockquote>\n <p>And why would one waste 4 bytes instead of a single byte for 3 values only</p>\n</blockquote>\n\n<p>Why not. Does it really matter in any modern PC.<br>\nOK for embedded systems maybe (but you obviously are using WINDOWS)</p>\n\n<blockquote>\n <p>Do you have a still better way?</p>\n</blockquote>\n\n<p>Yes. Use enum in C++11</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T02:04:40.420",
"Id": "11407",
"Score": "0",
"body": "I got a kick out of pushing you over the 5K border ^^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T06:26:48.497",
"Id": "11416",
"Score": "0",
"body": "every time one reminds me of good habit (here not ditching enum) i +1 :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T23:55:50.920",
"Id": "7292",
"ParentId": "7262",
"Score": "5"
}
},
{
"body": "<p>I would definitely recommend using enumerations. As this is December 2011, I would imagine your compiler supports an explicit underlying type on enumerations (GCC supported this since 4.4 and Visual C++ now supports it in 11.0). As a side note, <code><cstdint></code> is supported by visual c++ now (as of 10.0).</p>\n\n<p>As an addenum to traditional c-style enumerations:</p>\n\n<pre><code>enum state : std::int8_t {\n S_UNKNWON,\n S_HIGH,\n S_LOW\n};\n</code></pre>\n\n<p>Or adding scope to the enumeration's memebers (avoid polluting global scope):</p>\n\n<pre><code>enum class state : std::int8_t {\n unknown,\n high,\n low\n};\n\nstate status = state::unknown;\n</code></pre>\n\n<p>Of course, after looking at <code>boost::tribool</code>, I would recommend that over anything -- unless you really need to ensure that <code>state</code> is exactly 1 byte.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T06:25:24.473",
"Id": "11415",
"Score": "0",
"body": "+1 for informing about cstdint. no more #ifdef required. And yeah i wanted some savings, so enum state : int8_t solved the problem, with type safety!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T23:57:13.033",
"Id": "7293",
"ParentId": "7262",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7293",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T10:45:41.713",
"Id": "7262",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Implementing Tribool with int8_t"
}
|
7262
|
<p>I have the following code that loops through a collection of objects and dumps different properties out to Excel. The whole <code>j++</code> on every other line doesn't seem very elegant. Is there a more elegant way to have this functionality where I loop through objects in a collection and dump out properties?</p>
<pre><code>int rowIndex = 2;
foreach (BookInfo book in books)
{
int j = 1;
excelExport.SetCell(j, rowIndex, book.BookId);
j++;
excelExport.SetCell(j, rowIndex, book.Book);
j++;
excelExport.SetCell(j, rowIndex, book.System);
j++;
excelExport.SetCell(j, rowIndex, book.Age);
j++;
excelExport.SetCell(j, rowIndex, book.StartDate);
j++;
excelExport.SetCell(j, rowIndex, book.Pages);
rowIndex++;
}
</code></pre>
<p>I am constantly adding new columns at the beginning and middle, so I want to avoid hard coding column names.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:48:45.563",
"Id": "11356",
"Score": "6",
"body": "You're basically hard-coding it. You could just as easily write each line in the format, \"excelExport.SetCell(1, rowIndex, book.BookId)\" etc. and accomplish the same thing with 1/2 the lines of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:55:54.963",
"Id": "11357",
"Score": "0",
"body": "@Moozhe - but the code is more flexible for change and i am constantly adding new columns at the beginnign"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:59:28.173",
"Id": "11358",
"Score": "5",
"body": "Won't excelExport.SetCell(j++, rowIndex, book.BookId); get you where you want to be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T15:39:19.483",
"Id": "11359",
"Score": "0",
"body": "You say in other comments that you want to easily add columns, but that is a dangerous thing to do. You change the meaning of columns all the time. This is why it is better to use constants for the column index. What if you want to keep a column empty? I would certainly create a method that performs the SetCell operations on a single book as well. This method is bound to grow in time, so keep it neat."
}
] |
[
{
"body": "<p>This </p>\n\n<pre><code>excelExport.SetCell(j, rowIndex, book.BookId);\nj++;\n</code></pre>\n\n<p>is equivalent to this:</p>\n\n<pre><code>excelExport.SetCell(j++, rowIndex, book.BookId);\n</code></pre>\n\n<p><code><sarcasm></code> Now you have one line doing two things! <code></sarcasm></code></p>\n\n<p>Now admittedly this is not a great solution but it does address your concerns of appearance. Like Eric Lippert noted, there are reasons you shouldn't do this.</p>\n\n<p>In your comments, you've noted that these values are evolving. With that in mind, consider the Open-Closed Principle where your export code should be <em><strong>open</strong> for extension but <strong>closed</strong> for modification</em>. Since you are \"constantly adding to the export,\" you're obviously violating the <strong>closed</strong> part of the principle.</p>\n\n<p>A better solution might be to have the BookInfo define what it exports. </p>\n\n<pre><code>foreach(var book in books) \n{\n var columnIndex = 1;\n\n foreach(var exportValue in book.ExportValues)\n {\n excelExport.SetCell(columnIndex, rowIndex, exportValue);\n columnIndex += 1;\n }\n\n rowIndex++; \n}\n</code></pre>\n\n<p>With the code above, the Exporter is now closed for modification (no reason to change) but open for extension (<code>book.ExportValues</code> can grow/contract as needed).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:47:59.767",
"Id": "11360",
"Score": "0",
"body": "is your point that your suggestion isn't recommended ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:48:35.717",
"Id": "11361",
"Score": "4",
"body": "And one line doing two things is *worse*. One statement should do *one thing*; statements that do multiple things are harder to understand, harder to refactor, and harder to debug than statements that do one thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:32:47.993",
"Id": "12179",
"Score": "1",
"body": "I would use the \"excelExport.SetCell(j++, rowIndex, book.BookId)\" solution. I obviosuly agree that you shouldn't do things at once just for the sake of it, but seriously, I think \"applying a function to the next column\" is simpler than \"applying a function to the current column\" and then \"incrementing the column\". It's a shame that there's no excellent syntax for this, but (a) I think using a list is probably too complicated and (b) hardcoding the numbers makes it harder to change the order of lines later. I still think \"excelExport.SetCell(j++, rowIndex, book.BookId)\" is simplest and best."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:46:54.790",
"Id": "7265",
"ParentId": "7264",
"Score": "8"
}
},
{
"body": "<p>Since you're redeclaring <code>j</code> on every iteration, its values are effectively <em>static</em>. So a \"more elegant\" way to do this would be:</p>\n\n<pre><code>foreach (BookInfo book in books)\n{\n excelExport.SetCell(1, rowIndex, book.BookId);\n excelExport.SetCell(2, rowIndex, book.Book);\n excelExport.SetCell(3, rowIndex, book.System);\n excelExport.SetCell(4, rowIndex, book.Age);\n excelExport.SetCell(5, rowIndex, book.StartDate);\n excelExport.SetCell(6, rowIndex, book.Pages);\n\n rowIndex++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:51:25.300",
"Id": "11367",
"Score": "1",
"body": "because i am constantly adding columns at the front and i don't want to have to shift the column number of every other column around every time i need to inject a new column in the middle\\"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:53:53.000",
"Id": "11368",
"Score": "5",
"body": "@leora Then that additional requirement should go in the question. We can't read your mind - as far as readers of the question can tell, there's no reason to have a variable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:49:58.273",
"Id": "7267",
"ParentId": "7264",
"Score": "2"
}
},
{
"body": "<p>I think your code is perfectly understandable as it is.</p>\n\n<p>Here's an idea though. (In case it is not clear: the suggestions here are more for amusement and edification than a serious suggestion. The original procedural code is just fine, but it is interesting to see how it might be done in a functional style.)</p>\n\n<pre><code>var funcs = new List<Func<BookInfo, object>>()\n{\n info=>info.BookId,\n info=>info.Book,\n info=>info.System // etc.\n}\nint rowIndex = 2;\nforeach (BookInfo bookInfo in books)\n{\n int columnIndex = 1;\n foreach(var func in funcs)\n {\n excelExport.SetCell(columnIndex, rowIndex, func(bookInfo));\n columnIndex += 1;\n }\n rowIndex += 1;\n}\n</code></pre>\n\n<p>However, this still has a disappointingly large number of variable mutations. Why do we need to have local variables to track the rows and columns at all? That's the inelegant part that you want to eliminate.</p>\n\n<blockquote>\n <p>Can't tell if trolling...or just addicted to lambdas </p>\n</blockquote>\n\n<p>Oh, we're just getting started here. <strong>I have barely yet even begun to use lambdas.</strong> How about this?</p>\n\n<pre><code>var funcs = new List<Func<BookInfo, object>>()\n{\n info=>info.BookId,\n info=>info.Book,\n info=>info.System // etc.\n}\nvar cells = bookInfos.SelectMany(\n (bookInfo, row)=>\n funcs.Select(\n (func, col)=>\n new {row, col, item = func(bookInfo)}));\nforeach(var cell in cells)\n excel.SetCell(cell.col, cell.row, cell.item);\n</code></pre>\n\n<p>There, now we've got a selector that contains a lambda that contains a selector that contains a lambda that iterates over a list of lambdas. We've also gotten rid of every index mutation.</p>\n\n<p>That of course has far too many explanatory local variables. We should be able to do this without mutating <em>any</em> variable except the loop variable. Let's eliminate all the variable mutations except one:</p>\n\n<pre><code>foreach(var cell in \n bookInfos.SelectMany(\n (bookInfo, row)=>\n new List<Func<BookInfo, object>>()\n {\n info=>info.BookId,\n info=>info.Book,\n info=>info.System // etc.\n }.Select(\n (func, col)=>\n new {row, col, item = func(bookInfo)})))\n excel.SetCell(cell.col, cell.row, cell.item);\n</code></pre>\n\n<p>And now we've illustrated the old saying: every programming language eventually resembles Lisp -- badly. </p>\n\n<p>As Scott Rippey points out in his answer, we actually don't need to be capturing the properties as lambdas at all; we could just capture the values:</p>\n\n<pre><code>foreach(var cell in \n bookInfos.SelectMany(\n (bookInfo, row)=>\n new object[]\n {\n bookInfo.BookId,\n bookInfo.Book,\n bookInfo.System // etc.\n }.Select(\n (item, col)=>\n new {row, col, item})))\n excel.SetCell(cell.col, cell.row, cell.item);\n</code></pre>\n\n<p>Which is actually not too bad.</p>\n\n<p>But like I said, <strong>your original code is just fine</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:00:17.173",
"Id": "11371",
"Score": "8",
"body": "Can't tell if trolling...or just addicted to lambdas"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:06:12.910",
"Id": "11372",
"Score": "7",
"body": "@cHao: Oh we're just getting started here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:38:41.767",
"Id": "11374",
"Score": "2",
"body": "@EricLippert My answer is the same as yours ... except without the crazy addiction to lambdas. Crazy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:44:12.823",
"Id": "11375",
"Score": "0",
"body": "Wow I like the (bookInfo, row)=> new List<Func<BookInfo, object>>(). Nice. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:45:16.213",
"Id": "11376",
"Score": "0",
"body": "@OmegaMan: Because you know, why not re-allocate that list every time through?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:52:40.763",
"Id": "11377",
"Score": "0",
"body": "@EricLippert you wrote elsewhere that your office is like a ghost town today. I can see now that you were not kidding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:57:16.460",
"Id": "11378",
"Score": "5",
"body": "@phoog: Hey, I'm being totally productive here. I just added a new error message to overload resolution and... that's about it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:54:24.723",
"Id": "7269",
"ParentId": "7264",
"Score": "30"
}
},
{
"body": "<p>I, personally, would avoid using <code>j++</code> to populate <code>Excel</code> cells, and instead would use constants. Something like this:</p>\n\n<pre><code>foreach (BookInfo book in books)\n{\n excelExport.SetCell(Constants.BookIdCellIndex, rowIndex, book.BookId);\n excelExport.SetCell(/*index of other cell*/ .....);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:57:26.473",
"Id": "11379",
"Score": "2",
"body": "I wouldn't. Too enterprisey. Makes for one more place to have to look to figure out what exactly the code's doing. This really shouldn't be that complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:02:05.060",
"Id": "11380",
"Score": "0",
"body": "@cHao: consider that one day you decide to reorganize the columns in `Excel`. How you gonna handle it inthis cycle code in \"easy\" way. ?? In case of index declaration, **the only thing** you need to change, is the index of the constant. The code is much robust and scallable then that one which uses a loop var."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:06:45.727",
"Id": "11381",
"Score": "0",
"body": "Except for that part about having to go halfway across the app to figure out what `Constants.BookIdCellIndex` is or what it's for. If you want it hard-coded, then hard-code it. If you want it flexible, then pass an array with stuff in the order you want. Not this. This looks like it was cooked up by a Java junkie. (BTW, not my downvote.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:08:50.917",
"Id": "11382",
"Score": "0",
"body": "Absolutely unclear, wrong and confusing downvote on the question where top rated answer says **exactly** the same what is written here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:10:02.463",
"Id": "11383",
"Score": "0",
"body": "@cHao: please, explain me difference between top most rated answer and mine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:14:10.610",
"Id": "11384",
"Score": "0",
"body": "@cHao: push constants on separate class or declare them inside the scope of the function or whatever else is absolutely architectual decision, which has to be made by developer by subjective decisions made against current project. So it could wrong, could be right. I didn't pay attention on *that*, cause it's not relevant, imo, in this question. Good luck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:17:58.843",
"Id": "11385",
"Score": "0",
"body": "The top voted answer (1) includes the simplest, most straightforward way (just hard-coding it), and (2) even for the version that uses constants, includes them right near where the values will be used. Not in some whole other class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:28:39.597",
"Id": "11386",
"Score": "1",
"body": "@cHao: bah!... What if I have a function which *reads* the data from the same `Excel`. Like a good developer you will move the constants declaration *out*. just an example, to say that, the issue you pointing out is context dependent, so irrelevant for *this* question. Good luck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T06:05:47.757",
"Id": "11388",
"Score": "2",
"body": "*If* you need those constants in two distinct places, then go for it. But til then, YAGNI. And if i'm going to be using the same constants for reading and writing, i don't want them easily modifiable, especially from halfway across the app. I want those suckers etched in stone, lest some schmuck decide to move some columns around and break backward compatibility."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:54:56.923",
"Id": "7270",
"ParentId": "7264",
"Score": "2"
}
},
{
"body": "<p>I would advocate the column-index constant approach suggested by Bryan, but with a change. The change makes it easier for you to support the requirement of easy maintainability when inserting columns near the front:</p>\n\n<pre><code> const int BOOK_ID = 1; \n const int BOOK = BOOK_ID + 1; \n const int SYSTEM = BOOK + 1; \n const int AGE = SYSTEM + 1; \n const int START_DATE = AGE + 1; \n const int PAGES = PAGES + 1; \n</code></pre>\n\n<p>Adding a column between book and system? No problem:</p>\n\n<pre><code> const int BOOK_ID = 1; //unchanged line\n const int BOOK = BOOK_ID + 1; //unchanged line\n const int NEW_COLUMN = BOOK + 1; //new line\n const int SYSTEM = NEW_COLUMN + 1; //changed line\n const int AGE = SYSTEM + 1; //unchanged line\n const int START_DATE = AGE + 1; //unchanged line\n const int PAGES = PAGES + 1; //unchanged line\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:57:11.203",
"Id": "7271",
"ParentId": "7264",
"Score": "0"
}
},
{
"body": "<p>Since it appears as though your column definitions are static, I would create contants for your column indexes</p>\n\n<pre><code>const int BookIdColumn = 1;\nconst int BookColumn = 2;\nconst int SystemColumn = 3;\nconst int AgeColumn = 4;\nconst int StartDateColumn = 5;\nconst int PagesColumn = 6;\n\nint rowIndex = 2;\nforeach (BookInfo book in books)\n{\n excelExport.SetCell(BookIdColumn, rowIndex, book.BookId);\n excelExport.SetCell(BookColumn, rowIndex, book.Book);\n excelExport.SetCell(SystemColumn, rowIndex, book.System);\n excelExport.SetCell(AgeColumn, rowIndex, book.Age);\n excelExport.SetCell(StartDateColumn, rowIndex, book.StartDate);\n excelExport.SetCell(PagesColumn, rowIndex, book.Pages);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:02:15.183",
"Id": "7272",
"ParentId": "7264",
"Score": "0"
}
},
{
"body": "<p>This is super simple; use an array and a for-loop: </p>\n\n<pre><code>int rowIndex = 2;\nforeach (BookInfo book in books)\n{\n var columns = new object[]{\n book.BookId,\n book.Book,\n book.System,\n book.Age,\n book.StartDate,\n book.Pages,\n };\n for (int j = 0; j < columns.Length; j++) {\n excelExport.SetCell(j + 1, rowIndex, columns[j]);\n }\n rowIndex++;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:32:45.793",
"Id": "7273",
"ParentId": "7264",
"Score": "24"
}
},
{
"body": "<p>One can use reflection to avoid having to hard code the properties of the book. I take the direction that all the public properties need to be shown. Then I use the index of the book to define the row and the index of the property to define the <code>j</code> in your example.</p>\n\n<p>Note: I commented out the actual call to excel which would be your actual call; but left it out so it can run.</p>\n\n<p>This teaches Linq, which I feel separates the mid level C# developers from the senior level because they now think in terms of <code>IEnumerable</code>/<code>IQuerable</code> on all data structures.</p>\n\n<p>The below will run in LinqPad:</p>\n\n<pre><code>void Main()\n{\n var books = new List<BookInfo>() { new BookInfo() { BookId = 1, Book=\"War N Peace\", StartDate= DateTime.Now },\n new BookInfo() { BookId = 2, Book=\"Visual Basic .NET Code Security Handbook\", StartDate=DateTime.Now.AddYears(1) }};\n\n\n var publicProps = typeof(BookInfo).GetProperties( BindingFlags.Instance | BindingFlags.Public );\n\n books.Select ((bk, index) => new { Book = bk, BookIndex = index} )\n .ToList()\n .ForEach(bk => publicProps.Select ((prp, index) => new {Prop = prp, Index = index } )\n .ToList()\n .ForEach(pp => //excelExport.SetCell(bk.BookIndex, pp.Index, pp.Prop.GetValue(bk.Book, null)); \n Console.WriteLine (\"RowIndex as ({0}) J as ({1}) reflected value as ({2})\", bk.BookIndex, pp.Index, pp.Prop.GetValue(bk.Book, null)))\n );\n\n/* Output\nRowIndex as (0) J as (0) reflected value as (1)\nRowIndex as (0) J as (1) reflected value as (War N Peace)\nRowIndex as (0) J as (2) reflected value as (12/28/2011 3:33:15 PM)\nRowIndex as (1) J as (0) reflected value as (2)\nRowIndex as (1) J as (1) reflected value as (Visual Basic .NET Code Security Handbook)\nRowIndex as (1) J as (2) reflected value as (12/28/2012 3:33:15 PM)\n*/ \n\n\n}\n\n// Define other methods and classes here\n\npublic class BookInfo\n{\n public int BookId { get; set; }\n public string Book { get; set; }\n public DateTime StartDate { get; set; }\n\n}\n</code></pre>\n\n<p>EDIT: Removed redundant tolist. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-09T04:14:29.203",
"Id": "93546",
"Score": "0",
"body": "@jamal I am honored that you would consider my answer enough to edit it to its proper verbiage. The only thing which was in doubt was the change of `tack` to `task`. My original intent was `tack` as to \"tack into the wind\", as a direction or really course. 'Task' as your change would have worked per-se, but I knew the original meaning and changed it to `direction` for a better understanding. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-09T04:19:05.510",
"Id": "93548",
"Score": "0",
"body": "Thanks for the clarification. I changed it as it seemed like a typo, and I just wanted to be sure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T22:41:38.953",
"Id": "7274",
"ParentId": "7264",
"Score": "0"
}
},
{
"body": "<p>Every time you're confronted with code that doesn't feel quite right, try to imagine <em>what you'd like the code to look like</em>. Often, you can create an abstraction that better communicates the <em>intent</em> of the code, easing readability and future maintainability. </p>\n\n<p>In this case, encapsulate the tedious code in a higher abstraction to have this result:</p>\n\n<pre><code>var row = new RowFiller(excelExport, startRowIndex: 2, startColumnIndex: 1);\nforeach (BookInfo book in books) {\n row.Put(book.BookId);\n row.Put(book.Book);\n row.Put(book.System);\n row.Put(book.Age);\n row.Put(book.StartDate);\n row.Put(book.Pages);\n row.Skip();\n} \n</code></pre>\n\n<p>I thought it would be good to have an object that represents a row that I can <em>put</em> values on, that I can also <em>skip</em> to start putting values in the next row, always correctly taking care of rows and column indexes for me. The resulting code is easier to write, read and change.</p>\n\n<hr>\n\n<p>This is the needed <code>RowFiller</code> class:</p>\n\n<pre><code>public class RowFiller {\n\n private readonly Excel excelExport;\n private readonly int startColumnIndex;\n private int currentRowIndex;\n private int currentColumnIndex;\n\n public RowFiller(Excel excelExport, int startRowIndex, int startColumnIndex) {\n this.excelExport = excelExport;\n this.currentRowIndex = startRowIndex;\n this.startColumnIndex = startColumnIndex;\n this.currentColumnIndex = startColumnIndex;\n }\n\n public void Put(object value) {\n excelExport.SetCell(currentColumnIndex, currentRowIndex, value);\n currentColumnIndex++;\n }\n\n public void Skip() {\n currentRowIndex++;\n currentColumnIndex = startColumnIndex;\n }\n\n}\n</code></pre>\n\n<p>(Note: I don't know the type of <code>excelExport</code>, so I just assumed it was <code>Excel</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T14:49:34.430",
"Id": "7275",
"ParentId": "7264",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T21:44:59.597",
"Id": "7264",
"Score": "26",
"Tags": [
"c#",
"excel",
"collections"
],
"Title": "Exporting information on a collection of books to Excel"
}
|
7264
|
<p>This is based on <a href="http://careers.stackoverflow.com/nevermind">Alexey Drobyshevsky's</a> excellent article, <a href="http://www.codeproject.com/KB/cs/safe_enumerable.aspx" rel="nofollow">"Problems with Iteration"</a>. With Alexey's suggestion, I implemented his solution using a <code>ReaderWriterLockSlim</code>. Then I fleshed out a <code>ThreadSafeList<T> : IList<T></code> implementation. </p>
<p>The idea here is to have a collection that multiple threads can iterate over, execute Linq queries against, and modify at the same time without data inconsistencies, <code>InvalidOperationException</code>s, or deadlocks.</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace ThreadSafeEnumeration
{
public class SafeEnumerator<T> : IEnumerator<T>
{
private readonly ReaderWriterLockSlim _readerWriterLock;
private readonly IEnumerator<T> _innerCollection;
public SafeEnumerator(IEnumerator<T> innerCollection, ReaderWriterLockSlim readerWriterLock)
{
_innerCollection = innerCollection;
_readerWriterLock = readerWriterLock;
_readerWriterLock.EnterReadLock();
}
public void Dispose()
{
_readerWriterLock.ExitReadLock();
}
public bool MoveNext()
{
return _innerCollection.MoveNext();
}
public void Reset()
{
_innerCollection.Reset();
}
public T Current
{
get { return _innerCollection.Current; }
}
object IEnumerator.Current
{
get { return Current; }
}
}
public class ThreadSafeList<T> : IList<T>
{
private readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private readonly List<T> _innerList = new List<T>();
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
_readerWriterLock.EnterReadLock();
try
{
return new SafeEnumerator<T>(_innerList.GetEnumerator(), _readerWriterLock);
}
finally
{
_readerWriterLock.ExitReadLock();
}
}
public IEnumerator GetEnumerator()
{
return (this as IEnumerable<T>).GetEnumerator();
}
public void Add(T item)
{
try
{
_readerWriterLock.EnterWriteLock();
_innerList.Add(item);
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
public void Clear()
{
try
{
_readerWriterLock.EnterWriteLock();
_innerList.Clear();
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
public bool Contains(T item)
{
try
{
_readerWriterLock.EnterReadLock();
return _innerList.Contains(item);
}
finally
{
_readerWriterLock.EnterReadLock();
}
}
public void CopyTo(T[] array, int arrayIndex)
{
try
{
_readerWriterLock.EnterWriteLock();
_innerList.CopyTo(array, arrayIndex);
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
public bool Remove(T item)
{
try
{
_readerWriterLock.EnterWriteLock();
return _innerList.Remove(item);
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
public int Count
{
get
{
try
{
_readerWriterLock.EnterReadLock();
return _innerList.Count;
}
finally
{
_readerWriterLock.ExitReadLock();
}
}
}
bool ICollection<T>.IsReadOnly
{
get
{
try
{
_readerWriterLock.EnterReadLock();
return ((ICollection<T>)_innerList).IsReadOnly;
}
finally
{
_readerWriterLock.ExitReadLock();
}
}
}
public int IndexOf(T item)
{
try
{
_readerWriterLock.EnterReadLock();
return _innerList.IndexOf(item);
}
finally
{
_readerWriterLock.ExitReadLock();
}
}
public void Insert(int index, T item)
{
try
{
_readerWriterLock.EnterWriteLock();
_innerList.Insert(index, item);
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
public void RemoveAt(int index)
{
try
{
_readerWriterLock.EnterWriteLock();
_innerList.RemoveAt(index);
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
public T this[int index]
{
get
{
try
{
_readerWriterLock.EnterReadLock();
return _innerList[index];
}
finally
{
_readerWriterLock.ExitReadLock();
}
}
set
{
try
{
_readerWriterLock.EnterWriteLock();
_innerList[index] = value;
}
finally
{
_readerWriterLock.ExitWriteLock();
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T14:51:24.873",
"Id": "11622",
"Score": "0",
"body": "I believe this implementation may be prone to deadlocks. I have a unit test that starts 300 CRUD threads against a collection of 1,000,000 objects in a random fashion. 90% of the time the test returns within 10 seconds (8 core cpu) with all assertions passing. However, about 1 in 10 runs hangs indefinitely and throws no errors. My attempts to try to observe or log the deadlock come up empty. It never hangs in debug mode, and any writing to disk appears to change the timing just enough for the deadlock case to never occur. Your experience in solving deadlocks would be appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T10:26:50.570",
"Id": "11685",
"Score": "0",
"body": "I think that having concurrent threads reading & writing the collection without inconsistencies or deadlocks cannot be achieved. There has to be a compromise somewhere; regarding either data integrity or locking policy. Anyway, I find your question and Alexey's article very interesting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:16:54.530",
"Id": "11698",
"Score": "0",
"body": "I'm certainly finding out that it's very hard and may not be worth the effort. However, I'm still under the impression that it's theoretically possible to safely implement a collection that can be read and written to by multiple threads. I believe I should be able to avoid deadlocks while locking only on one resource. I think at this point I need a tool that will help me do a StackTrace dump of all the running threads. This is proving to be an extremely challenging exercise in Windows 7 with x64 .Net 4."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T20:34:33.840",
"Id": "11830",
"Score": "0",
"body": "I finally managed to create .dmp files that i can actually debug. (had to use procdump.exe because of 32 bit process on an x64 issues) I discovered some very odd behavior that occurs only when running in ReSharper test runner, and only when in run mode (not in debug mode). Very strangely the threads seem to hang at _readerWriterLock.ExitWriteLock(); why would RELEASING a lock be blocked!? What is it waiting for!? When running in as a console app, or even in R# test runner in debug mode, this bizarre blocking does not occur and it works perfectly as designed. R# must be doing something weird."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T20:32:24.137",
"Id": "12197",
"Score": "0",
"body": "I think that your CopyTo method only requires a read lock, not a write lock."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-24T05:49:01.560",
"Id": "199597",
"Score": "0",
"body": "Your implementation of contains enters the lock twice..."
}
] |
[
{
"body": "<p>Debugging multi threaded apps, for me, has always had the affect of aligning the threads and hiding deadlocks. This experience is mostly in native code, however, I could imagine the same thing could happen in managed. I'm not exactly sure why, but I think it has to do with introducing a delay on context switching in the debugger introspecting the stack and running it with symbols loaded. Depending on what the test is doing (<code>Console.Write</code>), running in console may have a similar affect aligning the thread while waiting for I/O.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T20:42:16.167",
"Id": "12198",
"Score": "0",
"body": "I wonder if [Visual Studio's Intellitrace feature](http://msdn.microsoft.com/en-us/library/dd264915.aspx) (Ultimate edition only, for now) would make it easier to debug multi-threading issues. If I understand it, one can use the dump file to effectively step through an already completed execution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T20:27:00.123",
"Id": "7724",
"ParentId": "7276",
"Score": "1"
}
},
{
"body": "<p>I see that you're using the <code>ReaderWriterLockSlim</code> constructor with the <code>SupportsRecursion</code> <code>LockRecursionPolicy</code>. </p>\n\n<p>Notice this line in the <a href=\"http://msdn.microsoft.com/en-us/library/bb355025.aspx\" rel=\"nofollow\">documentation for <code>ReaderWriterLockSlim</code></a>:</p>\n\n<blockquote>\n <p>Regardless of recursion policy, a thread that initially entered read mode is not allowed to upgrade to upgradeable mode or write mode, because that pattern creates a strong probability of deadlocks.</p>\n</blockquote>\n\n<p>However, I don't see anything in your code that makes me think that this is causing you a problem. In fact, calls to the <code>EnterWriteLock</code> method will throw a <code>SynchronizationLockException</code> if you have previously called <code>EnterReadLock</code>, so I'm sure you would have noticed that happening.</p>\n\n<hr>\n\n<p>I see that there are multiple places in your code where you are doing this:</p>\n\n<pre><code> try\n {\n _readerWriterLock.EnterWriteLock();\n // ...\n }\n finally\n {\n _readerWriterLock.ExitWriteLock();\n }\n</code></pre>\n\n<p>You should keep the call to <code>EnterWriteLock</code> outside of the <code>try</code> block, because if it fails for some reason, you don't want to call <code>ExitWriteLock</code>. The same goes for calls to <code>EnterReadLock</code>. It should be like this:</p>\n\n<pre><code> _readerWriterLock.EnterWriteLock();\n try\n {\n // ...\n }\n finally\n {\n _readerWriterLock.ExitWriteLock();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T21:23:35.413",
"Id": "7726",
"ParentId": "7276",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T16:42:24.993",
"Id": "7276",
"Score": "5",
"Tags": [
"c#",
"linq",
"thread-safety",
"concurrency",
"collections"
],
"Title": "Reader-writer collection"
}
|
7276
|
<blockquote>
<p><strong>Puzzle:</strong></p>
<p>For two strings A and B, we define the similarity of the strings to be
the length of the longest prefix common to both strings. For example,
the similarity of strings "abc" and "abd" is 2, while the similarity
of strings "aaa" and "aaab" is 3. Calculate the sum of similarities of
a string S with each of its suffixes.</p>
<p><strong>Explanation:</strong></p>
<p>For ababaa the suffixes of the string are "ababaa", "babaa", "abaa",
"baa", "aa" and "a". The similarities of each of these strings with
the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6
+ 0 + 3 + 0 + 1 + 1 = 11.</p>
</blockquote>
<p>How can I improve execution time of this (when larger testcases are provided)?</p>
<pre><code>import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner;
Solution sr = new Solution();
scanner = new Scanner(System.in);
int no_cases = scanner.nextInt();
for (int i = no_cases; --i >=0; ) {
String to_proc = scanner.next();
sr.solve(to_proc);
}
}
private void solve(String to_proc) {
String str=to_proc;
int len=to_proc.length();
int count=0;
int total=0;
for(int i=1;i<len;i++)
{
count=0;
for(int j=i;j<len;j++)
{
// System.out.println(str.charAt(j)+" , "+str.charAt(j-i));
if(str.charAt(j-i)==str.charAt(j))
{
count++;
}
else
{
break;
}
}
total=total+count;
}
System.out.println(total+len);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:01:56.017",
"Id": "11399",
"Score": "2",
"body": "I tried hard to find a way to make it faster, but I couldn't. I give up. Do you have reasons to believe that it can be made faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:11:44.513",
"Id": "11400",
"Score": "0",
"body": "@MikeNakis \n One more approach of solving it is by making an arrays of suffixes and compare each with the main one and writing the similarity to output.Donno it might reduce some time.\n\nAs u know here, what i did here is getting the string and comparing suffixes on the run.\n\nThe puzzle where it's shown, shows me this\n_Time Limit Exceeded_ \n_7/10 testcases passed_\nSo, it ran out of time while executing testcases. And time limit of puzzle execution time for java is 5secs."
}
] |
[
{
"body": "<p>Converting the input <code>String</code> to <code>char[]</code> helps a little bit but I cannot profile it now.</p>\n\n<pre><code>private void solve2(final String input) {\n int total = 0;\n final char[] inputArray = input.toCharArray();\n for (int i = 1; i < inputArray.length; i++) {\n int count = 0;\n for (int j = i; j < inputArray.length; j++) {\n if (inputArray[j - i] != inputArray[j]) {\n break;\n }\n count++;\n }\n total = total + count;\n }\n System.out.println(total + inputArray.length);\n}\n</code></pre>\n\n<p><code>String.charAt</code> does some index checks, so I suppose the cause of the performance improvement is the missing checks.</p>\n\n<pre><code>public char charAt(int index) {\n if ((index < 0) || (index >= count)) {\n throw new StringIndexOutOfBoundsException(index);\n }\n return value[index + offset];\n}\n</code></pre>\n\n<p>Anyway, profile the code. Modern IDEs usually have profiler.</p>\n\n<p>Another idea is using multiple threads.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T07:04:47.157",
"Id": "11418",
"Score": "0",
"body": "I am pretty sure that what you need is an algorithmic optimization, and not a little hack, which is bound to yield an improvement that gets factored out (doesn't register) in terms of big-oh notation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:32:03.873",
"Id": "7288",
"ParentId": "7283",
"Score": "4"
}
},
{
"body": "<p>I think you need a suffix tree.</p>\n\n<p>Its a data structure that puts all the prefixes of a string in a tree. This makes a number of operations faster, and I think you can make your similarity metric qualify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T07:01:15.940",
"Id": "11417",
"Score": "1",
"body": "Doch! I thought of this, and then I thought that the time you'd spend building this tree would be larger than the time you'd spend to just answer the question the straightforward way, but now that I am thinking about it again, I realize this: your 'solve' function can save the prefix tree of each string it sees, so as to reuse it later if it gets invoked with the same string! And I'll bet you that they make the test last 5 seconds largely by feeding it the same string over and over again, instead of producing a new string every time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T23:47:18.327",
"Id": "7290",
"ParentId": "7283",
"Score": "5"
}
},
{
"body": "<h2>Efficiency</h2>\n\n<p>Your <code>solve()</code> is O(<em>n<sup>2</sup></em>), where <em>n</em> is the length of the input string.</p>\n\n<p>As it turns out, there is an O(<em>n</em>) algorithm to produce exactly the lengths of the common prefixes you want, called the Z Algorithm. In the standard terminology used to describe the algorithm, each of those common prefixes is called a \"Z-box\". A full explanation of the algorithm is beyond the scope of this review, but you should be able to find some <a href=\"https://www.cs.umd.edu/class/fall2011/cmsc858s/Lec02-zalg.pdf\" rel=\"nofollow noreferrer\">online resources</a> that illustrate it well. The basic idea is that information about previously analyzed Z-boxes can be used for shortcuts.</p>\n\n<p>Here is a <a href=\"https://codereview.stackexchange.com/a/53969/9357\">Python implementation</a>, which translates very easily into Java.</p>\n\n<h2>Driver</h2>\n\n<p>I suggest writing <code>main()</code> this way:</p>\n\n<pre><code>public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in)) {\n int numCases = scanner.nextInt();\n while (numCases-- > 0) {\n System.out.println(sum(z(scanner.next())));\n }\n }\n}\n</code></pre>\n\n<p>Note the following improvements:</p>\n\n<ul>\n<li>Open the <code>Scanner</code> using a try-with-resources block.</li>\n<li>Use static methods. <code>new Solution()</code> is pointless, since the object keeps no state.</li>\n<li>Rename the <code>no_cases</code> variable according to <code>javaConventions</code>.</li>\n<li>Eliminate the <code>i</code> variable.</li>\n<li>Separate concerns, such that finding the prefix lengths, summing, and printing are done in separate functions.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-20T06:39:58.800",
"Id": "60549",
"ParentId": "7283",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7288",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T20:21:01.633",
"Id": "7283",
"Score": "6",
"Tags": [
"java",
"optimization",
"performance",
"strings",
"programming-challenge"
],
"Title": "Calculating sum of similarities of strings"
}
|
7283
|
<p>I'm writing a (nearly-)single-page app using Ruby on Rails 3.1 and Backbone.js. Thus, most of my controllers return rootless JSON, courtesy this setting as per the Backbone.js docs:</p>
<pre><code>ActiveRecord::Base.include_root_in_json = false
</code></pre>
<p>So the returned JSON for an account, say, looks like this:</p>
<pre><code>{
"created_at":"2011-12-27T22:23:17Z",
"id":1,"name":"My Happy Account",
"updated_at":"2011-12-27T22:23:17Z"
}
</code></pre>
<p>I'm testing that this works in the following way:</p>
<pre><code>it 'returns the account associated with the current user' do
get :current, :format => :json
assert_response(:success)
account = JSON.parse(response.body)
account['name'].should == @account_one.name
account['id'].should == @account_one.id
end
</code></pre>
<p>The spec passes but I can't help feel that it's a bit icky and not very idiomatic perhaps. Could someone please suggest a nicer way of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T06:04:39.933",
"Id": "11413",
"Score": "0",
"body": "What in particular feels icky or non-idiomatic about this? My app is also a single-page Backbone/Rails 3.1 app, and my tests are similar to this. My tests are a bit more broken down -- generally just one assertion per it/specify block -- but otherwise it amounts to the same thing: parse the response, make assertions on the key-value pairs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T06:12:37.253",
"Id": "11414",
"Score": "0",
"body": "I guess you should also ask yourself what an idiomatic test would look like if you were testing a multi-page, non-Backbone app. You might check assigned values or that a specific is rendered. In this case there is no template to render, so that's out, but checking assigns seems analogous to what you're testing. There's just less syntactic sugar in your case."
}
] |
[
{
"body": "<p><strong>I think your method of testing is fine.</strong> </p>\n\n<p>My app is also a single-page Backbone/Rails 3.1 app, and my tests are similar to yours. My tests are a bit more broken down -- I generally aim for one assertion per <code>it</code> / <code>specify</code> block -- but the substance of the tests amounts to the same thing: make a request, parse the response, and make assertions based on what the response contains versus what I expect that it should contain.</p>\n\n<p>The crucial question to ask yourself here is what idiomatic controller tests might look like in a more traditional, multi-page, non-Backbone app. You're generally checking a few things in those tests:</p>\n\n<ol>\n<li>A particular value is assigned</li>\n<li>A particular template is rendered, or that you've redirected to a particular URL</li>\n<li>The response code matches your expectation</li>\n</ol>\n\n<p>For item 1, I think that amount to parsing the response and looking for a particular value. RSpec-Rails gives you the nice sugar of the <code>assigns</code> statement, which makes things look a bit cleaner, but in my mind the intent is the same as what you're doing. You could pretty easily write your own sugar to wrap the parsed JSON response body, if you wanted, so you could write something like <code>json_response(:name).should == @account_one.name</code>, where <code>json_response</code> is the name of the helper method you would write. (The implementation basically amounts to parsing the response body and looking up the value for the key passed as a method argument.) Do that and the tests look a lot more like those for a non-Backbone app.</p>\n\n<p>Item 2 doesn't apply to a single-page Backbone app, since you're always on the same page. So that's out.</p>\n\n<p>Item 3 is the same as in a non-Backbone app. You have <code>assert_response(:success)</code>, which is fine. I like to do something like <code>response.status.should eq(200)</code>, or whatever is appropriate for the status code I expect. I find that I check status codes more often in my Backbone app's tests than in a more \"traditional\" multi-page app, just because I like to return appropriate HTTP status codes when possible as error response in Ajax apps, whereas in a multi-page app I might be returning a 200 status with some error message on the page like \"Email address is mandatory.\" YMMV, in this regard.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T00:17:09.057",
"Id": "7476",
"ParentId": "7287",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7476",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T22:20:11.850",
"Id": "7287",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails",
"json"
],
"Title": "Testing Backbone.js"
}
|
7287
|
<p>Is this implementation of AES for Android safe? Is it 128 bit encryption? How can I strengthen this implementation? Please help me, all suggestions are welcome :)</p>
<pre><code>import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryption {
private static final String SecretKey = "9081726354fabced";
private static final String Salt = "03xy9z52twq8r4s1uv67";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String KEY_ALGORITHM = "AES";
private static final String SECRET_KEY_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
private static final String RANDOM_ALGORITHM = "SHA-512";
private static final int PBE_ITERATION_COUNT = 100;
private static final int PBE_KEY_LENGTH = 256;
private static final int IV_LENGTH = 16;
private Cipher cipher;
public AESEncryption() {
try {
cipher = Cipher.getInstance(CIPHER_ALGORITHM);
}
catch (NoSuchAlgorithmException e) {
cipher = null;
}
catch (NoSuchPaddingException e) {
cipher = null;
}
randomInt = new Random();
}
public SecretKey getSecretKey(String password) {
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), Salt.getBytes("UTF-8"), PBE_ITERATION_COUNT, PBE_KEY_LENGTH);
SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
SecretKey tmp = factory.generateSecret(pbeKeySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), KEY_ALGORITHM);
return secret;
}
catch (Exception e) {
return null;
}
}
public String encrypt(String text) {
Thread.sleep(randomInt.nextInt(100));
if (text == null || text.length() == 0) {
return null;
}
byte[] encrypted = null;
try {
byte[] iv = generateIV();
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(SecretKey), ivspec);
encrypted = cipher.doFinal(text.getBytes("UTF-8"));
}
catch (Exception e) {
return null;
}
return Base64.encodeToString(iv, Base64.DEFAULT)+Base64.encodeToString(encrypted, Base64.DEFAULT);
}
public String decrypt(String code) {
Thread.sleep(randomInt.nextInt(100));
if(code == null || code.length() == 0) {
return null;
}
byte[] decrypted = null;
try {
String iv64 = code.substring(0, IV_LENGTH*2);
String encrypted64 = code.substring(IV_LENGTH*2);
byte[] iv = Base64.decode(iv64, Base64.DEFAULT);
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(SecretKey), ivspec);
decrypted = cipher.doFinal(Base64.decode(encrypted64, Base64.DEFAULT));
}
catch (Exception e) {
return null;
}
return new String(decrypted, "UTF-8");
}
private byte[] generateIV() {
try {
SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
byte[] iv = new byte[IV_LENGTH];
random.nextBytes(iv);
return iv;
}
catch (Exception e) {
return null;
}
}
/*public static String bytesToHex(byte[] data) {
String HEXES = "0123456789ABCDEF";
if (data == null) {
return null;
}
final StringBuilder hex = new StringBuilder(2*data.length);
for (final byte b : data) {
hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}*/
/*public static byte[] hexToBytes(String str) {
if (str == null) {
return null;
}
else if (str.length() < 2) {
return null;
}
else {
int len = str.length()/2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}*/
}
</code></pre>
<p>Thanks a lot in advance!</p>
<p><strong>Edit:</strong> The code throws an exception because Android can't find "PBEWithSHA256And256BitAES-CBC-BC". This is when I run the code on my phone, at least. What algorithm can I take now to replace this unknown one? The algorithm for SecretKeyFactory must be compatible to AES and the key size, right?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-13T13:39:41.603",
"Id": "31328",
"Score": "0",
"body": "Hi pal, not to sound like a bad sport, but does this class come with any license restriction to it? You don't specify in the headers and i would like to know. Thanks in advance"
}
] |
[
{
"body": "<p>I observe the following deficiencies:</p>\n\n<ul>\n<li>Use of strings to store the key, which is then extracted using <code>getBytes()</code>. This has multiple problems:\n<ul>\n<li>The character encoding used to convert the string to bytes can vary between Java implementations (so while the Android spec forces UTF-8 to be the default character encoding, your code won't be portable to J2SE, even though it will compile - dangerous). <code>String.getBytes()</code> should be deprecated if it isn't already; you should always supply an argument specifying the character encoding to use (and 99% of the time it should be <code>\"UTF-8\"</code>).</li>\n<li>Certain character encodings (including UTF-8) place additional constraints on the valid values of bytes which mean that you lose some of the keyspace. It would be better to base-64 encode it (and use <code>android.util.Base64</code> to decode) or hex-encode it (using the static methods which you've posted - although see below).</li>\n</ul></li>\n<li>Bad padding. If you look at that code carefully you'll see that it pads with spaces on encryption and doesn't unpad on decryption. So you'll have to unpad in the next layer up, and if the encrypted string ends in one or more spaces you'll unpad incorrectly. I would remove <code>padString</code> and the call to it, and change the cipher algorithm to <code>AES/CBC/PKCS7</code> (assuming that it's supported; if not, try <code>AES/CBC/PKCS5</code>).</li>\n<li>Reuse of IV. In certain applications this is excusable, but as a general rule you should use a different, randomly generated, IV for each message and send it (unencrypted) along with the message. Otherwise if your messages start out with the same text then an eavesdropper can get information on where they diverge.</li>\n<li>Whoever wrote <code>bytesToHex</code> is probably more experienced with PHP than Java, because otherwise they would know that building a string in a loop like that is inexcusable for someone who's been programming Java for more than two weeks. Given that the size of the output is known from the start, I'd be inclined to just build it into a <code>char[]</code> and then call the <code>String(char[])</code> constructor rather than use a <code>StringBuilder</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T03:30:13.760",
"Id": "11472",
"Score": "0",
"body": "Thank you very much, Peter! I tried to implement all your suggestions (except for the IV reuse, which I want to retain). Did I succeed? The class should be more secure now, isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T11:21:58.650",
"Id": "11483",
"Score": "0",
"body": "@MarcoW., is there a reason for using PBE rather than generating a key with full entropy and hex-coding it? Also, I didn't pay enough attention to the asymmetry between encode and decode. Probably both `encrypt` and `decrypt` should take strings and return strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T11:53:49.040",
"Id": "11485",
"Score": "0",
"body": "Thanks, I've changed both methods to return strings. But concerning PBE, I thought this would be a safe way of retrieving a 256 bit key. Is it not? I need the fixed-length key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T12:04:29.290",
"Id": "11486",
"Score": "0",
"body": "@MarcoW., it's not bad per se, but it's a bit overkill if you're hard-coding the key. What do you mean by \"fixed-length\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T13:10:42.670",
"Id": "11488",
"Score": "0",
"body": "So you could call the class safe now? Is this a secure implementation if ignore the hard-coded key, salt and IV? What I wanted to say is that you need a key with 256 bit length. Right? So I can't take a string such as \"my_secure_key7\" as the key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T13:41:33.103",
"Id": "11489",
"Score": "0",
"body": "@MarcoW., depends on your threat model - there may still be timing attacks - but it at least avoids some of the simpler errors. You could take a random 64-character hex string as the key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T14:24:56.297",
"Id": "11490",
"Score": "0",
"body": "Thank you, you helped me so much! My last two questions: Can I prevent timing attacks by adding a sleep() with a short random sleep time in the encryption and decryption functions? And, if you see my edit in the question: Does this way of implementing IV enhance security? The IV is now randomly generated on encryption and then added to the beginning of the result string. On deryption, the IV is extracted from the beginning of the encrypted text and used for decryption."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T02:42:55.593",
"Id": "11506",
"Score": "0",
"body": "@MarcoW., random sleep could help, yes, although it depends on whether the resolution of the sleep is fine enough. (If you can sleep in multiples of 50ms and the timing information is much finer grained, it may not gain you anything; but in a software implementation on unknown hardware there's not much else you can do); this is the way IV is intended to be used, and avoids correlation between messages. Although I'd use base-64 rather than base-16 for converting the messages back to strings. Or character encoding \"ISO-8859-1\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T00:52:08.493",
"Id": "11533",
"Score": "0",
"body": "I've added the random sleep to the code now. Is it implemented in a correct way? I thought maybe it doesn't improve anything at all, as CPU load will decrease in the sleep phase and make the duration of sleep obvious. Is this so? And why would you use base-64 instead of hex? Just because it produces shorter strings?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:32:52.273",
"Id": "11564",
"Score": "1",
"body": "True, there's still power analysis, but that requires fairly direct access to the device whereas timing attacks don't always. Yes, the base-64 is just to produce shorter strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T01:17:19.843",
"Id": "11787",
"Score": "0",
"body": "I've replaced the hex format by base 64 now (I hope I did it right). Is there any (stupid) mistake left in the code now? And when creating the PBEKeySpec, is reading the bytes from the salt enough? Or should I convert it to base 64 first, as well? Same with the password which is converted to a char array."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:50:14.390",
"Id": "7311",
"ParentId": "7297",
"Score": "15"
}
},
{
"body": "<p>Two more points:</p>\n\n<ol>\n<li>No separator between iv and cipher text. </li>\n</ol>\n\n<p>From <code>Base64</code>'s name, you can derive that its base is 64, ie <code>2**6</code>, so for your iv length(16 * 8) can't be divided with no reminder, so <code>encodeToString()</code> will add padding to you iv. To split two parts of base64 of iv and cipher text conveniently, you may add a separator char larger than 63(<code>]</code>, for example) and not special char of regex(for in java <code>split()</code> receive a regex string) so that you can easily split them.</p>\n\n<ol start=\"2\">\n<li>Use sub-string to get iv. </li>\n</ol>\n\n<p>As upper item has explained, I can't get why you use <code>2 * IV_LENGTH</code> to get iv which is wrong. For example, use a iv of 16 bytes, which is 128 bits and <code>encodingToString()</code> change it to 24 bytes(128 / 6 = 22 + 2 paddings, for reasons see <a href=\"https://en.wikipedia.org/wiki/Base64\" rel=\"nofollow\">here</a>). So it is obvious not <code>2 * IV_LENGTH</code>. Try to change to split, see details at item one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-16T14:27:28.567",
"Id": "107779",
"ParentId": "7297",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7311",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T03:20:46.830",
"Id": "7297",
"Score": "8",
"Tags": [
"java",
"security",
"android",
"aes"
],
"Title": "Secure AES encryption and decryption in Android"
}
|
7297
|
<p>I have an MD5 hash string:</p>
<pre><code>_hash = '743a0e0c5c657d3295d347a1f0a66109'
</code></pre>
<p>I want to write function that splits passed string to path in nginx cache format:</p>
<pre><code>print hash2path(_hash, [1, 2, 3])
# outputs '7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'
</code></pre>
<p>This is my variant:</p>
<pre><code>def hash2path(_hash, levels):
hash_copy = _hash
parts = []
for level in levels:
parts.append(_hash[:level])
_hash = _hash[level:]
parts.append(hash_copy)
return '/'.join(parts)
</code></pre>
<p>How could this be improved?</p>
|
[] |
[
{
"body": "<p>Why you can't just hardcode cache path calculation?</p>\n\n<pre><code>>>> _hash = '743a0e0c5c657d3295d347a1f0a66109'\n>>> def hash2path(_hash):\n... return \"%s/%s/%s/%s\" % (_hash[0], _hash[1:3], _hash[3:6], _hash)\n... \n>>> hash2path(_hash)\n'7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'\n</code></pre>\n\n<p>UPDATE: If you really need to pass level array there is a little bit faster version:</p>\n\n<pre><code>def hash2path(_hash, levels):\n prev = 0\n parts = []\n for level in levels:\n parts.append(_hash[prev:prev + level])\n prev += level\n parts.append(_hash)\n return \"/\".join(parts)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T07:49:34.160",
"Id": "11419",
"Score": "0",
"body": "The point is to pass level array to function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T18:30:46.267",
"Id": "11447",
"Score": "0",
"body": "Thank you, Dmitry. But it doesn't work correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T18:38:16.480",
"Id": "11448",
"Score": "0",
"body": "Works if `prev += level` is in 6th line"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T22:21:41.810",
"Id": "11466",
"Score": "0",
"body": "Ah, you're right. I didn't test it thoroughly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T07:34:33.657",
"Id": "7299",
"ParentId": "7298",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T05:58:48.010",
"Id": "7298",
"Score": "1",
"Tags": [
"python",
"cryptography"
],
"Title": "Nginx cache path function"
}
|
7298
|
<p>I have an increasing table which already has records of 50,000+.
So in a combo box I have to load it, so that it shows which one is selected and its a main record which need to be selected and based on that it spread other relational records. But when I load it the whole web browser freeze.</p>
<p>How do you handle it?</p>
<p>My controllers:</p>
<pre><code>$sql = "select name,name from countryCity";
$secondResult = $this->db->fetchPairs($sql);
$this->view->selectitems = array(''=>'') + $secondResult;
</code></pre>
<p>My view file:</p>
<pre><code><?for($i=0; $i<10; $i++):?>
<?=$this->formSelect("a",
"select one",
array('class'=>'largetosmall'),
$this->selectitems)?>
<?endfor;?>
</code></pre>
<p>Output:</p>
<pre><code><select class=largetosmall id=a>
<option>...</option>
<option>50,000+++... records</option>
</select>
</code></pre>
<p>More than 10 times I have a huge <code>select</code> element in one page. Never working.</p>
|
[] |
[
{
"body": "<p>50k is simply too many for a drop-down list. Use AJAX-based autocomplete input boxes or split the list to smaller parts, for example by state. I think the users also don't like it, it's really hard to scroll or search in a so huge drop-down list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T11:31:07.580",
"Id": "7303",
"ParentId": "7301",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7303",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T10:02:52.733",
"Id": "7301",
"Score": "1",
"Tags": [
"php",
"javascript",
"html",
"zend-framework"
],
"Title": "Browser freeze - How to handle or optimize 50,000 rows in one HTML select element more than several times?"
}
|
7301
|
<p>I want to build a small newsletter like tool which sends mails in pre-defined timespans. First after registration, second 14 days later, third 7 days later etc.</p>
<p>I came across for two database designs and those two queries:</p>
<ol>
<li><p>Create a separate table (dispatch) and put the next mails into it (can be done by cronjob):</p>
<pre><code>SELECT
m.campaign_id,
s.name,
s.email,
m.subject,
m.body
FROM sp_dispatch AS d
INNER JOIN sp_subscribers AS s
ON s.id = d.recipient_id
INNER JOIN sp_mailings AS m
ON m.id = d.mailing_id
WHERE d.time
BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 31 DAY)
LIMIT 0, 500
</code></pre></li>
<li><p>Without a separate table and search through all mails when sending.</p>
<pre><code>SELECT
r.campaignID,
DATE_ADD(r.startDate, INTERVAL t.timeOffset DAY) AS sendDate,
r.name,
r.email,
t.subject,
t.textMail
FROM cw_recipients AS r
INNER JOIN cw_triggerMails AS t
ON r.campaignID = t.campaignID
WHERE DATE_ADD(r.startDate, INTERVAL t.timeOffset DAY)
BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 31 DAY)
LIMIT 0, 500
</code></pre></li>
</ol>
<p>What do you think is the better/faster/more reliable solution?</p>
<ul>
<li>DB Design <a href="https://i.stack.imgur.com/FQsUL.png" rel="nofollow noreferrer">#1</a></li>
<li>DB Design <a href="https://i.stack.imgur.com/Tuu6A.png" rel="nofollow noreferrer">#2</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:12:02.413",
"Id": "11425",
"Score": "3",
"body": "Use `explain query` to see what it is using how many keys are involved. You can analyze it and show us the output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T12:11:16.073",
"Id": "13517",
"Score": "0",
"body": "You should write description about the tables (include the cardinality between them too)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-05T18:23:20.753",
"Id": "13586",
"Score": "0",
"body": "No one here who can help and explain what the \"explain results\" mean?"
}
] |
[
{
"body": "<ol>\n<li>Use <code>EXPLAIN</code> in the sql console to determine what the query optimizer is doing with each query. This will give you clues as to how each query performs, and may also help you optimize further, for example by indicating places where adding an index will speed the query up. </li>\n<li>Run each of the queries in a loop and benchmark how long they take! If you're using PHP just wrap the query execution in a for loop and execute it 100 times or so. Record the <code>microtime()</code> before you start and do it again at the end. Subtract the start time from the end time and you'll have your benchmark. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T20:30:31.180",
"Id": "12853",
"Score": "0",
"body": "Thanks for this hint! Sorry, couldn't answer earlier – was on vacation. EXPLAIN gives me following results for …"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T20:39:49.060",
"Id": "12854",
"Score": "0",
"body": "EXPLAIN gives me following results for …\n\n1) \n2) \n\nI really don't know how to tell which one is better. Hope you can help?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T10:27:27.277",
"Id": "7483",
"ParentId": "7302",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T10:30:13.493",
"Id": "7302",
"Score": "2",
"Tags": [
"php",
"performance",
"sql",
"mysql"
],
"Title": "Newsletter SQL query optimization"
}
|
7302
|
<p>I was searching for a way to get all active log4net logfiles (if any) at runtime without adding a reference to the project. </p>
<p>This is the solution I came up with: </p>
<pre><code>private static IEnumerable<AbstractReportInformation> GetLog4NetLogfiles()
{
var type = Type.GetType("log4net.LogManager,log4net");
if(null == type)
return new List<AbstractReportInformation>();
dynamic[] repositories = type.GetMethod("GetAllRepositories").Invoke(null, null) as dynamic[];
IEnumerable<FileInfo> files = repositories
.SelectMany<dynamic, dynamic>(repos => repos.GetAppenders())
.Where(appender => Type.GetType("log4net.Appender.FileAppender,log4net").IsAssignableFrom(appender.GetType()))
.Select(appender => new FileInfo(appender.File));
return files.Select(
file => new FilesystemInformation(file)).Cast<AbstractReportInformation>().ToList();
}
</code></pre>
<p>It makes use of the <code>dynamic</code> keyword instead of doing it all with reflection. </p>
<ul>
<li>Are there any obvious errors in my code? </li>
<li>Are there better ways to
achieve the same result?</li>
</ul>
<p>I feel a bit unsure about leaving the safety of the otherwise strongly typed language / framework.</p>
<p><strong>Update to explain why no references shall be used / why <code>dynamic</code> is used</strong></p>
<p>The above code is used to "detect" whether log4net is present and then gathers the logfiles. The same will later be implemented for NLog and possibly other frameworks of that sort. The project I'm using this code in is a application health monitoring framework and I don't want to add a lot of references.</p>
|
[] |
[
{
"body": "<p>Well, that seems a strange solution to me. Despite the fact you don't have a formal reference in References folder of a VS project you still have a dependency on the log4net library. And if in runtime the log4net library won't be available, your code will fail. Moreover, somebody has to remember about that dependency and copy log4net.dll manually to you bin folder, so the code could be executed.</p>\n\n<p>From my point of view, it is always better to have a visible dependency rather than having invisible one. The only exception comming to my mind is when you need to have a modular architecture where modules can be safely plugged and unplugged. And, as far as I can understand, it is not your requirement.</p>\n\n<p>I would recommend you to create a separate project that would have a normal reference to log4net and which would be used by your main project. In that case you will have your main project unaware of log4net, but in the same time you would have all compile-time checks and every benefit of strongly typed language / framework.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T15:54:19.370",
"Id": "11443",
"Score": "0",
"body": "Thanks for your review. The above code is used to \"detect\" whether log4net is present and then gathers the logfiles. The same will later be implemented for NLog and possibly other frameworks of that sort. The project I'm using this code in is a application health monitoring framework and I don't want to add a lot of references."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T08:53:31.097",
"Id": "11511",
"Score": "0",
"body": "@yas it would be great if you could add that note to the original question ;-) it's a very good explanation of why using `dynamic` here makes sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:24:12.537",
"Id": "7309",
"ParentId": "7304",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T11:34:43.697",
"Id": "7304",
"Score": "4",
"Tags": [
"c#",
".net",
"reflection"
],
"Title": "Find log4net logfiles at runtime without adding dependency to project"
}
|
7304
|
<p>I'm working on a game for iOS devices and this is the function we use to create server-loaded buildings. The server loading is in another function and everything works just fine, but I was wondering if this function could be prettier? This function runs every 60 seconds as we reload the whole base (with the buildings in) frequently, maybe I should reuse the buildings if nothing has changed server-side?</p>
<p>There's another function that just clears all the subviews in the UIView "sandbox" to reset the base upon reload.</p>
<pre><code>-(void)loadBuilding:(BuildingButton *)building
{
//building.backgroundColor = [UIColor blackColor];
if(building.buildUpgrading > 0 && building.buildLevel == 1) //Building is being built
{
HJManagedImageV *constructionImage = [[HJManagedImageV alloc] init];
constructionImage.url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mysite.com/img/base/construction/%@",building.buildConstrImg]];
constructionImage.greyscale = greyscale;
constructionImage.resize = 1;
constructionImage.reloadSuperview = 1;
constructionImage.animateSetImage = YES;
constructionImage.delegate = building;
//[constructionImage showLoadingWheel];
[appDelegate.objManager manage:constructionImage];
constructionImage.frame = CGRectMake(0, 0, constructionImage.image.size.width, constructionImage.image.size.height);
[building addSubview:constructionImage];
[building bringSubviewToFront:constructionImage];
[building setNeedsDisplay];
[constructionImage release];
} else { //Building is normal!
//---------------------------------------------------------------------------------------------------------
//ANIMATED IMAGES IMPLEMENTS HERE -------------------------------------------------------------------------
if([building.buildImage isEqualToString:@"oil_refinery_desert.gif"]) //Images that need animating, use ID instead?
{
UIImage *image1 = [UIImage imageNamed:@"oil_refinery_desert01.png"];
UIImage *image2 = [UIImage imageNamed:@"oil_refinery_desert02.png"];
UIImage *image3 = [UIImage imageNamed:@"oil_refinery_desert03.png"];
UIImage *image4 = [UIImage imageNamed:@"oil_refinery_desert04.png"];
UIImage *image5 = [UIImage imageNamed:@"oil_refinery_desert05.png"];
//Make GREY!
if (greyscale) {
image1 = [self convertImageToGrayScale:image1];
image2 = [self convertImageToGrayScale:image2];
image3 = [self convertImageToGrayScale:image3];
image4 = [self convertImageToGrayScale:image4];
image5 = [self convertImageToGrayScale:image5];
}
NSArray *images = [[NSArray alloc] initWithObjects:image1, image2, image3, image4, image5, nil];
UIImageView *animationSequence = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image1.size.width, image1.size.height)];
animationSequence.animationImages = images;
[images release];
[building addSubview:animationSequence];
[building bringSubviewToFront:animationSequence];
[building setNeedsDisplay];
//[building setBackgroundColor:[UIColor redColor]];
[building setFrame:CGRectMake(building.frame.origin.x, building.frame.origin.y, image1.size.width, image1.size.height)];
animationSequence.animationDuration = 0.75;
animationSequence.animationRepeatCount = 0;
[animationSequence startAnimating];
[animationSequence release];
} else {
//[building setImage:imageLoader.image forState:UIControlStateNormal];
HJManagedImageV *imageLoader = [[HJManagedImageV alloc] initWithFrame:CGRectMake(0,0,0,0)];
imageLoader.url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mysite.com/img/base/%@",building.buildImage]];
imageLoader.greyscale = greyscale;
imageLoader.resize = 1;
imageLoader.reloadSuperview = 1;
imageLoader.animateSetImage = YES;
imageLoader.delegate = building;
//[imageLoader showLoadingWheel];
[appDelegate.objManager manage:imageLoader];
[building addSubview:imageLoader];
[imageLoader release];
//[building setBackgroundColor:[UIColor blackColor]];
}
//Is the building upgrading?
if(building.buildUpgrading > 0)
{
HJManagedImageV *constructionImage = [[HJManagedImageV alloc] init];
constructionImage.url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mysite.com/img/base/upgrade/%@",building.buildUpgradeImg]];
constructionImage.greyscale = greyscale;
constructionImage.resize = 1;
constructionImage.reloadSuperview = 1;
constructionImage.animateSetImage = YES;
constructionImage.delegate = building;
//[constructionImage showLoadingWheel];
[appDelegate.objManager manage:constructionImage];
constructionImage.frame = CGRectMake(0, 0, building.frame.size.width, building.frame.size.height);
[building addSubview:constructionImage];
[building bringSubviewToFront:constructionImage];
[building setNeedsDisplay];
[constructionImage release];
}
}
if(building.buildID == 999) { //Road is disabled!
building.userInteractionEnabled = FALSE;
}
NSLog(@"Loaded: %@", building);
if(greyscale == 0) {
[building addTarget:self action:@selector(playButtonSound) forControlEvents:UIControlEventTouchDown];
[building addTarget:self action:@selector(loadWindow:) forControlEvents:UIControlEventTouchUpInside];
}
[sandbox addSubview:building];
}
</code></pre>
|
[] |
[
{
"body": "<p>You should rewrite <code>convertImageToGrayScale:</code> to <code>grayScaled</code> in a category on UIImage</p>\n\n<pre><code> image1 = [self grayScaled];\n</code></pre>\n\n<p>in the following block you should add the images to array first, and then loop through it, to perform <code>for(UIImage *image in images){image = [image grayScaled];}</code></p>\n\n<pre><code> UIImage *image1 = [UIImage imageNamed:@\"oil_refinery_desert01.png\"];\n UIImage *image2 = [UIImage imageNamed:@\"oil_refinery_desert02.png\"];\n UIImage *image3 = [UIImage imageNamed:@\"oil_refinery_desert03.png\"];\n UIImage *image4 = [UIImage imageNamed:@\"oil_refinery_desert04.png\"];\n UIImage *image5 = [UIImage imageNamed:@\"oil_refinery_desert05.png\"];\n //Make GREY!\n if (greyscale) {\n image1 = [self convertImageToGrayScale:image1];\n image2 = [self convertImageToGrayScale:image2];\n image3 = [self convertImageToGrayScale:image3];\n image4 = [self convertImageToGrayScale:image4];\n image5 = [self convertImageToGrayScale:image5];\n }\n NSArray *images = [[NSArray alloc] initWithObjects:image1, image2, image3, image4, image5, nil];\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code> UIImage *image1 = [UIImage imageNamed:@\"oil_refinery_desert01.png\"];\n UIImage *image2 = [UIImage imageNamed:@\"oil_refinery_desert02.png\"];\n UIImage *image3 = [UIImage imageNamed:@\"oil_refinery_desert03.png\"];\n UIImage *image4 = [UIImage imageNamed:@\"oil_refinery_desert04.png\"];\n UIImage *image5 = [UIImage imageNamed:@\"oil_refinery_desert05.png\"];\n\n NSArray *images = [[NSArray alloc] initWithObjects:image1, image2, image3, image4, image5, nil];\n\n if (greyscale) {\n for(UIImage *image in images){\n image= [image grayScaled];\n }\n }\n</code></pre>\n\n<p>can you confirm, that this is necessary:</p>\n\n<pre><code> [building addSubview:animationSequence];\n [building bringSubviewToFront:animationSequence];\n [building setNeedsDisplay];\n</code></pre>\n\n<p>I think, <code>[building addSubview:animationSequence];</code> should be sufficient.</p>\n\n<p>BTW: IMHO Class names for Views should end with the word View, i.e. Building becomes BuildingView. Same for Controllers.</p>\n\n<p><code>if(building.buildID == 999) { //Road is disabled!</code> looks a bit suspicious to me. Adding a meta information to an object shouldn't be necessary in a OO environment. I assume a RoadModel to be a subclass of an BuildingModel (or FacilityModel,…), so the better check would be <code>if([building isKindOfClass:[Road class]])</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T13:12:37.860",
"Id": "11434",
"Score": "0",
"body": "please see my addition"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T13:22:20.827",
"Id": "11435",
"Score": "0",
"body": "and another edit"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T13:02:44.767",
"Id": "7312",
"ParentId": "7305",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7312",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:08:19.363",
"Id": "7305",
"Score": "2",
"Tags": [
"game",
"objective-c",
"ios",
"cocoa"
],
"Title": "Server-loaded buildings function for an iOS game"
}
|
7305
|
<p>In one of our project with 3 tier architecture (tightly coupled), there's a bad code smell and it doesn't follow the DRY principle. I want to refactor it with design possible design pattern. I don't want to write this project from scratch.</p>
<p>Here's one of the class in BLL:</p>
<pre><code>namespace BAL
{
public class NotificationSettings
{
public readonly bool SignUPFBPost;
public readonly bool SignUPEmails;
public readonly bool SignUPPushNotification;
public readonly bool SignUPFCActivity;
public readonly bool SignUPBubbleNotification;
public readonly bool SignUPGlobeNotification;
public NotificationSettings()
{
NotificationSettingsBAL objNotificationSettings = new NotificationSettingsBAL();
DataTable dtblNotifList = objNotificationSettings.GetNotificationList();
SignUPFBPost = (Convert.ToInt16(dtblNotifList.Rows[0]["FBWallPost"]) == 1) ? true : false;
SignUPEmails = (Convert.ToInt16(dtblNotifList.Rows[0]["Emails"]) == 1) ? true : false;
SignUPPushNotification = (Convert.ToInt16(dtblNotifList.Rows[0]["PushNotification"]) == 1) ? true : false;
SignUPFCActivity = (Convert.ToInt16(dtblNotifList.Rows[0]["FCActivity"]) == 1) ? true : false;
SignUPBubbleNotification = (Convert.ToInt16(dtblNotifList.Rows[0]["BubbleNotification"]) == 1) ? true : false;
SignUPGlobeNotification = (Convert.ToInt16(dtblNotifList.Rows[0]["GlobNotification"]) == 1) ? true : false;
}
}
}
</code></pre>
<p>We're getting various user related settings db from database and checking at different places as per the need and displaying messages or sending push notification.</p>
<pre><code>if (objSqlResult.IsSuccess)
{
FavorBAL.Favor objFavorStatus = (FavorBAL.Favor)objFavorBAL.Status;
switch (objFavorStatus)
{
case FavorBAL.Favor.Initiated:
break;
case FavorBAL.Favor.Accepted:
strTitle = "Accept";
strMessage = MsgSuccess.GetMsg(Successes.FBPostFavorAccept).Replace("{%RecMemberName%}", objMemberBAL.FirstName + " " + objMemberBAL.LastName).Replace("{%ReqMemberName%}", Convert.ToString(dtblFavor.Rows[0]["ReqMemberName"]));
strEmailMessage = MsgSuccess.GetMsg(Successes.FBPostFavorAccept).Replace("{%RecMemberName%}", objMemberBAL.FirstName + " " + objMemberBAL.LastName).Replace("{%ReqMemberName%}", "you");
Common.DisplayMessageFavor(divMsg, MsgSuccess.GetMsg(Successes.FriendFavorAccept), Common.ErrorMsgType.Success);
if (new NotificationSettings().FavorAcceptFBPost)
{
Response.Write(Javascript.ScriptStartTag + "PostOnFBWall(\"" + strMessage + "\",\"" + Config.FacebookAppUrl + "\",\"" + Config.WebSiteUrl + "images/logo.png\",\"Favor in Progress!\",\"\",\"Message\");" + Javascript.ScriptEndTag);
}
if (new NotificationSettings().FavorAcceptEmails)
{
IsNotificationMailAllowed = true;
}
if (new NotificationSettings().FavorAcceptPushNotification)
{
objPushNotification.Push(strMessage, strUDID);
}
break;
//Other Cases
}
}
</code></pre>
<p>How can we refector the code with or without a design pattern? There's replication of second code listing or similar to it. I am reading one of the <a href="http://www.simple-talk.com/dotnet/.net-framework/designing-c-software-with-interfaces/" rel="nofollow">article</a> on interface to make it loosely coupled so that system can adapt changes easily. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T08:40:36.230",
"Id": "11427",
"Score": "1",
"body": "repeated stuff like `(Convert.ToInt16(dtblNotifList.Rows[0][\"GlobNotification\"]) == 1) ? true : false` looks like a candidate for my favorite [Extract method pattern](http://martinfowler.com/refactoring/catalog/extractMethod.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T11:05:13.303",
"Id": "11428",
"Score": "0",
"body": "@gnat\nFor brevity I've not posted complete code. Constructor is having total 15 boolean variables (e.g signup) which are assigned values based on table index. How could we extract method in that case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:03:54.620",
"Id": "11429",
"Score": "0",
"body": "for example of extracted method in your case, see `TryParseBool` in [an answer from Kane](http://programmers.stackexchange.com/posts/127679/edit) - _\"main focus being replacing the `Convert.ToInt16` repetition with a method\"_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T04:53:05.633",
"Id": "11543",
"Score": "0",
"body": "Even if I replace Convert.ToInt16 with TryParseBool, I am repeatedly calling TryParseBool for converting datatable value to boolean value, so what difference does it make?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:36:55.887",
"Id": "11565",
"Score": "0",
"body": "As of now there are only six notification settings for each kind of activity (total 15 means total 90 fields) as displayed in code. If at all tomorrow one more setting will be added user wise, I might have to change the code. I think that has to be changed using Design Pattern and Reflection, can anybody throw some light?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:58:21.887",
"Id": "11629",
"Score": "0",
"body": "Well to me, this makes a critical difference in readability. While this code isn't extracted, I find it hard to focus on any other refactoring / pattern. It's like... like you know trying to tune a car which simply lacks one of wheels."
}
] |
[
{
"body": "<p>I would start with those steps:</p>\n\n<ul>\n<li>Create an <code>enum</code> for your flags 'FBWallPost', 'Emails', and so on. </li>\n<li>Put yor \"signs\" into an boolean array indexed by values of that <code>enum</code> (instead of individual booleans), then you can easily create a loop around that. </li>\n</ul>\n\n<p>After that replacement I would check how much of the second part of your code can be refactored to general methods. Then I would look at the remaining parts and how much code duplication is still in there. Eventually I would try to apply strategy pattern, having classes <code>FBWallPostStrategy</code>, <code>EmailsStrategy</code> etc. with a common base class. Those classes may later replace the <code>enum</code> I have introduced first (you won't need it then anymore), keep only the individual code parts that are special for the particular case. The common code goes either to the common base class or a separate class applying \"template method\" pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T11:17:58.680",
"Id": "11430",
"Score": "0",
"body": "NotificationSetting class fetches total 5 boolean values for each of the application activities like\n\n- FacebookWallPost\n- Emails\n- PushNotification\n- DisplayActivityOnWebSiteWall\n- FacebookGlobNotification.\n\nWhenever any activity performed on website, settings for this variable checked for given user and particular action gets performed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T07:16:42.843",
"Id": "7307",
"ParentId": "7306",
"Score": "1"
}
},
{
"body": "<p>I would look at replacing the BLL code with the following. With the main focus being replacing the <code>Convert.ToInt16</code> repetition with a method. The other area of concern is the inability to mock your BAL code. To overcome this I have written a quick and dirty interface which allows better unit testing.</p>\n\n<pre><code>namespace BAL\n{\n // interfaces allow the class ot be easily mocked\n internal interface ICustomDataColumnTryParse\n {\n bool TryParseBool(string columnName);\n }\n\n // interfaces allow the class ot be easily mocked\n internal interface INotificationSettingsDomain\n {\n DataTable GetNotificationList();\n }\n\n // sample implementation of the interface\n internal class NotificationSettingsBAL : INotificationSettingsDomain\n {\n public DataTable GetNotificationList()\n {\n // do whatever you need to return information from your data repository\n throw new System.NotImplementedException();\n }\n }\n\n internal class NotificationSettings : ICustomDataColumnTryParse\n {\n // properties are more widely accepted for consumers of this class over\n // traditional fields / variables, but it really depends on 'what' you want\n // to use these values for?\n internal bool SignUPFBPost { get; private set; }\n internal bool SignUPEmails { get; private set; }\n internal bool SignUPPushNotification { get; private set; }\n internal bool SignUPFCActivity { get; private set; }\n internal bool SignUPBubbleNotification { get; private set; }\n internal bool SignUPGlobeNotification { get; private set; }\n\n private DataTable m_notificationListDataTable;\n\n internal NotificationSettings()\n : this(new NotificationSettingsBAL())\n { }\n\n // using an interface allows mocking of the 'NotificationSettingsBAL' object\n public NotificationSettings(INotificationSettingsDomain notificationSettingsDomain)\n {\n // prefer suffixes over prefixes for naming conventions\n m_notificationListDataTable = notificationSettingsDomain.GetNotificationList();\n\n SignUPFBPost = TryParseBool(\"FBWallPost\");\n SignUPEmails = TryParseBool(\"Emails\");\n SignUPPushNotification = TryParseBool(\"PushNotification\");\n SignUPFCActivity = TryParseBool(\"FCActivity\");\n SignUPBubbleNotification = TryParseBool(\"BubbleNotification\");\n SignUPGlobeNotification = TryParseBool(\"GlobNotification\");\n }\n\n // this can be a method on this class, extension method (my preference) or a static method\n // i have opted for an internal class method coded against an interface so the data table \n // isn't passed around. \n public bool TryParseBool(string columnName)\n {\n // this can allow for additional logic if we wanted to get a different row index\n var row = m_notificationListDataTable.Rows[0];\n var value = row[columnName];\n\n if (value == null)\n {\n return false;\n }\n\n int valueAsInt = 0;\n int.TryParse(value.ToString(), out valueAsInt);\n return valueAsInt == 1;\n }\n }\n}\n</code></pre>\n\n<p>As for replacing the switch statement you might be over-using an architectural pattern. I would only choose something like a strategy pattern if the business logic is <code>likely</code> to change or that additional switch statements will be <code>added / removed</code> with a high frequency in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:45:31.257",
"Id": "11545",
"Score": "0",
"body": "You're right Kane, that I've to use Strategy Pattern to replace my long swith..case. But I am not sure how should I go about replacing it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T06:53:19.680",
"Id": "11549",
"Score": "0",
"body": "I might be able to instantiate the NotificationSettings but won't be able to access properties as they're set Internal."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T09:00:09.203",
"Id": "7308",
"ParentId": "7306",
"Score": "5"
}
},
{
"body": "<p>I'm not really sure what you're trying to do but I think the purpose of your code is to check what kind of notifications are enabled and perform them accordingly. Assuming that the notification settings are on a per-user basis (as a setting for example) and not something that can be enabled/disabled application wide I would make the following changes:</p>\n\n<p>Create a general INotification-interface and subclass from that interface </p>\n\n<pre><code>//depending on how different the messages are per type of notification\n//you might only need one message\npublic interface INotification\n{\n public String NotificationMailMessage { get; };\n public String NotificationPushMessage { get; };\n //add more types here\n}\n\n//you might only need one concrete implementation, dependings on how complex the logic is\n//using the INotification-interface gives you the flexibility to create specific\n//notification classes for more complex notifications\npublic class SimpleNotification: INotification\n{\n //you could replace this with a general message and some parameters if applicable\n public SimpleNotification(String mailMessage, String pushMessage)\n {\n NotificationMailMessage = mailMessage;\n NotificationPushMessage = pushMessage;\n }\n\n //implement properties here\n}\n</code></pre>\n\n<p>Something you could do is:</p>\n\n<pre><code>public class FavorAcceptedNotification : INotification\n{\n private String _firstName;\n private String _lastName;\n private String _reqMemberName;\n\n public FavorAcceptedNotification(String firstName, String lastName, String reqMembername)\n {\n _firstName = firstName;\n //and so on\n }\n\n public String NotificationMailMessage\n {\n get\n {\n return MsgSuccess.GetMsg(Successes.FBPostFavorAccept).Replace(\"{%RecMemberName%}\", _firstName + \" \" + _lastName).Replace(\"{%ReqMemberName%}\", \"you\");\n }\n }\n}\n</code></pre>\n\n<p>Which means you simplify the switch to:</p>\n\n<pre><code>case FavorBAL.Favor.Accepted:\n strTitle = \"Accept\";\n var notification = new FavorAcceptedNotification(objMemberBAL.FirstName, objMemberBAL.LastName, Convert.ToString(dtblFavor.Rows[0][\"ReqMemberName\"]));\n var notificationSettings = new NotificationSettings();\n notificationSettings.Push(notification);\n</code></pre>\n\n<p>Your NotificationSettings class (might need to rename that one since it now does more then wrap settings) can deal with determining what notifications are enabled and what needs to be sent. Use Kane's suggestion to refactor with TryParseBool.</p>\n\n<p>It all depends on what you're trying to achieve really.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:36:31.583",
"Id": "11544",
"Score": "0",
"body": "Thanks JDT for replying. You're right that Notification Settings are stored user wise and not application wise. I think I need to use Strategy pattern for switch..case. Notificatin Setting class just get the settings user wise from DB. I think I need to create one more class which will pull System message from XML file and will be displayed based on action performed and user setting for Notification. But bit confused from Where should I start?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T05:28:29.793",
"Id": "11585",
"Score": "0",
"body": "If you mean the class that will actually do the work - just create a class with a methode that takes INotification objects and acts on them based on the NotificationSettings."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T12:49:50.147",
"Id": "7310",
"ParentId": "7306",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7310",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T06:57:10.600",
"Id": "7306",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"asp.net"
],
"Title": "How can the below code can be refactored with design pattern?"
}
|
7306
|
<p>I have a unit test that needs to compare two arrays but it shouldn't care about the order of the arrays. I didn't see anything in the Test:Unit docs that provided this so I wrote my own. I really don't want to use this code if I don't have to (want to avoid Not Invented Here syndrome). </p>
<p>If you can give me some feedback on the following points it would be a huge help, thanks!</p>
<ol>
<li>Should I even use this? Is there a built-in Test:Unit assertion I can use?</li>
<li>I've refactored this as much as I can but any further improvements are encouraged and welcome.</li>
<li>I've included my tests for this custom assertion, can you see any cases that I may be missing? </li>
</ol>
<p>Here is the custom assertion:</p>
<pre><code>def assert_have_same_items(expected, actual, message = nil)
full_message = build_message(message, "<?> was expected to contain the same collection of items as \n<?> but did not.\n", actual, expected)
test = expected | actual
assert_equal expected.size, actual.size, full_message
assert_equal expected.size, test.size, full_message
end
</code></pre>
<p>And the tests:</p>
<pre><code>test "assert_have_same_items with two arrays with same items in same order reports success" do
assert_have_same_items [1,2,3], [1,2,3]
end
test "assert_have_same_items with two arrays with same items in different order reports success" do
assert_have_same_items [1,2,3], [2,1,3]
end
test "assert_have_same_items with actual missing an item, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3], [2,1]
end
end
test "assert_have_same_items with actual having more items, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3], [2,1,3,4,5,6]
end
end
test "assert_have_same_items with actual having duplicates, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3], [2,1,3,2,1,3]
end
end
test "assert_have_same_items with actual having duplicates and expected having same number of items, reports failure" do
assert_should_fail do
assert_have_same_items [1,2,3,4,5,6], [2,1,3,2,1,3]
end
end
protected
def assert_should_fail
begin
yield if block_given?
flunk "Expected failure but assertion reported success"
rescue Test::Unit::AssertionFailedError
assert true
end
end
</code></pre>
|
[] |
[
{
"body": "<p>You have adequate test coverage for integers, and probably this will extend to floating points as well (although you really should test those as well, IMO). However you should also test for objects. Also, try a couple combinations of objects, numbers, and strings to be really sure that your assertion is correct.</p>\n\n<p>If you only need to test for integer arrays, you should make it clear that the assert only works for them and its behavior with other arrays is undefined. In that case maybe you should change the name to <code>assert_same_items_integer</code> or something similar for clarity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T15:13:17.830",
"Id": "11440",
"Score": "0",
"body": "good point, the intent is for it to handle arrays of anything so I'll add some tests for each case. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T14:21:24.257",
"Id": "7314",
"ParentId": "7313",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7314",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T13:23:37.510",
"Id": "7313",
"Score": "3",
"Tags": [
"ruby",
"unit-testing"
],
"Title": "Can this custom Test:Unit assert be replaced/refactored? Am I missing test cases?"
}
|
7313
|
<p>I decided to build my own fade-in fade-out function, since that is all I need on my page.</p>
<p>Please comment on things I can make better.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div>
<span id="fade_in">Fade In</span> |
<span id="fade_out">Fade Out</span></div>
<div id="fading_div" style="display:none;height:100px;background:#f00">Fading Box</div>
</div>
</div>
<script type="text/javascript">
// global varibles
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value, fade_in_or_fade_out) { // fade_in_or_out - 0 = fade in, 1 = fade out
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
if (fade_in_or_fade_out == 'in' && opacity_value == 1) {
fading_div.style.display = 'block';
}
if (fade_in_or_fade_out == 'in' && opacity_value == 100) {
done = true;
}
if (fade_in_or_fade_out == 'out' && opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout("function_opacity(" + i + ",'in')", i * 5);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 100; i >= 1; i--) {
setTimeout("function_opacity(" + i + ",'out')", (i - 100) * -1 * 5);
}
}
};
alert (test);
</script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T00:34:23.240",
"Id": "11467",
"Score": "6",
"body": "You could skip all of this and let css transitions do the work for you. http://css3.bradshawenterprises.com/transitions/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T10:33:55.703",
"Id": "11482",
"Score": "0",
"body": "GGG, maybe it's a good idea. People will be updating there browsers more often in 2012."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T17:54:31.423",
"Id": "11498",
"Score": "1",
"body": "Yeah, I think it's fine for something like a fade (progressive enhancement). People who's browsers don't support it won't see the fade, but the thing will still appear/disappear, so they're just missing out on a visual effect, and you get to save 50 or 60 lines of javascript."
}
] |
[
{
"body": "<p>Just some generic notes about the JavaScript code: I'd extract out a <code>setOpacity</code> function and create a <code>fadeOut</code> and a <code>fadeIn</code> function too.</p>\n\n<pre><code>function setOpacity(opacity) {\n fading_div.style.opacity = opacity / 100;\n fading_div.style.filter = 'alpha(opacity=' + opacity + ')';\n}\n\nfunction fadeOut(opacity) {\n setOpacity(opacity);\n if (opacity == 1) {\n fading_div.style.display = 'none';\n done = true;\n }\n}\n\nfunction fadeIn(opacity) {\n setOpacity(opacity);\n if (opacity == 1) {\n fading_div.style.display = 'block';\n }\n if (opacity == 100) {\n done = true;\n }\n}\n\n...\nsetTimeout(\"fadeIn(\" + i + \")\", i * 5);\n...\n</code></pre>\n\n<p>It eliminates the <code>in</code> and <code>out</code> magic constants and lots of conditions which checks their values. </p>\n\n<p>Using variable name suffixes like <code>opacity_value</code> looks a little bit redundant (since variables stores values), so I've renamed them. The same is true for the <code>function_opacity</code> function.</p>\n\n<p>I've changed the second for loop too to use fewer arithmetic operations, I think the following is easier to read:</p>\n\n<pre><code>for (var i = 1; i <= 100; i++) {\n setTimeout(\"fadeOut(\" + (100 - i) + \")\", i * 5);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:58:42.930",
"Id": "11462",
"Score": "2",
"body": "Please don't pass strings to `setTimeout`! It `eval`s them. Pass a function. `setTimeout((function(x){ return function(){ fadeOut(100-x); }; })(i), i * 5);` It's in a closure because `i` changes in the `for` loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T22:08:36.633",
"Id": "11465",
"Score": "0",
"body": "Thanks, @Rocket! Could you give me an example or link with some explanation why is it better? I'm not a JavaScript guru. (Maybe you want to write it as an answer since in the question there is the same string passing, and we will be able to upvote it.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:15:17.460",
"Id": "7323",
"ParentId": "7315",
"Score": "6"
}
},
{
"body": "<p>This is just an extension to @palacsint's answer. You shouldn't pass strings to <code>setTimeout</code>, it uses <code>eval</code>, which is inefficient and insecure. You should pass a function.</p>\n\n<p>Problem is, in the <code>for</code> loop <code>i</code> changes, so you'll have to use a closure.</p>\n\n<p>Don't do this:</p>\n\n<pre><code>for (var i = 100; i >= 1; i--) {\n setTimeout(\"function_opacity(\" + i + \",'out')\", (i - 100) * -1 * 5);\n}\n</code></pre>\n\n<p>Instead do:</p>\n\n<pre><code>for (var i = 100; i >= 1; i--) {\n setTimeout((function(x){\n return function(){\n function_opacity(x, 'out')\n };\n })(i), (i - 100) * -1 * 5);\n}\n</code></pre>\n\n<p>This may look a little messy. I suggest declaring a function that returns a function separately.</p>\n\n<pre><code>function call_opacity(i, d){\n return function(){\n function_opacity(i, d);\n };\n}\n</code></pre>\n\n<p>Then do:</p>\n\n<pre><code>for (var i = 100; i >= 1; i--) {\n setTimeout(call_opacity(i, 'out'), (i - 100) * -1 * 5);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T09:14:11.713",
"Id": "11479",
"Score": "1",
"body": "Thanks Rocket! Here is a link on the subject to back up your answer. Thanks for shring! http://stackoverflow.com/questions/6232574/is-it-bad-practice-to-pass-a-string-to-settimeout-if-yes-why"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T22:13:27.530",
"Id": "7329",
"ParentId": "7315",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7323",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T15:55:34.197",
"Id": "7315",
"Score": "14",
"Tags": [
"javascript",
"animation"
],
"Title": "Fade-in and fade-out in pure JavaScript"
}
|
7315
|
<blockquote>
<p><strong>Puzzle Description</strong></p>
<p>Given \$N\$ numbers, \$N <= 10^5\$, count the total pairs of numbers \$(N_i, N_j)\$ that have a difference of \$K = N_i - N_j\$ where \$0 < K < 10^9\$.</p>
<p>Input Format:</p>
<ul>
<li><p>1st line contains \$N\$ and \$K\$ (integers).</p></li>
<li><p>2nd line contains \$N\$ numbers of the set. All the \$N\$ numbers are assured to be distinct.</p></li>
</ul>
<p>Output Format:</p>
<ul>
<li>One integer saying the number of pairs of numbers that have a difference \$K\$.</li>
</ul>
<p>Time limit is 5 seconds.</p>
<pre class="lang-none prettyprint-override"><code>Sample Input : 5 2
1 5 3 4 2
Sample Output: 3
</code></pre>
</blockquote>
<p>First I've tried using <code>ArrayList</code>s and later tried using arrays. The code is bad and does not at all follow normal conventions of Java. But I'm not looking at that because execution time doesn't depend on it, right?</p>
<p>But to achieve the puzzle description I couldn't see any better logic than this:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
public class k_diff {
public int process() {
Scanner scanner = new Scanner(System.in);
int total_nums = scanner.nextInt();
int diff = scanner.nextInt();
int ary_nums[] = new int[total_nums];
for (int i = 0; i < total_nums; i++) {
ary_nums[i] = scanner.nextInt();
}
int len = ary_nums.length;
int count = 0;
for (int j = 0; j < len - 1; j++) {
for (int k = j + 1; k < len; k++) {
if (Math.abs(ary_nums[j] - ary_nums[k]) == diff) {
count++;
}
}
}
return count;
}
public static void main(String args[]) {
k_diff kdiff = new k_diff();
System.out.println(kdiff.process());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T17:09:56.267",
"Id": "11444",
"Score": "0",
"body": "What is N and K in your sample?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T17:15:27.137",
"Id": "11445",
"Score": "0",
"body": "First two nums - 5(N) 2(K)"
}
] |
[
{
"body": "<p>Some things which just jump into my eyes (even if not asked, I'll tell you anyway):</p>\n\n<ul>\n<li><strong>Whitespaces</strong>: Use whitespaces were appropriate, f.e. <code>for(int i=0;i<nums;i++)</code> is harder to rad then <code>for(int i = 0; i < nums; i++)</code>.</li>\n<li><strong>Meaningful names:</strong> Name your variables after what they are, not what type they are. This especially includes simple <code>for</code> loops. It might be taught or standard to use <code>i</code>, but I consider it bad practice because you never know what exactly <code>i</code> is at first glance. Give your variables <em>meaningful</em> names, please, they deserve love too! Same goes for your classes.</li>\n<li><strong>Split up where appropriate:</strong> if you've got only one function (<code>main</code>) you're most likely doing something wrong. Split it into Input, Processing and Output.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:01:49.357",
"Id": "7322",
"ParentId": "7316",
"Score": "4"
}
},
{
"body": "<p>Other than comparing the numbers as they are given (in order), sorting them and comparing would take fewer cycles and run much faster.</p>\n\n<p>So the above code can be optimized to this:</p>\n\n<pre><code>Arrays.sort(ary_nums);\n\nfor (int i = total_nums - 1; i > 0; i--) {\n for (int j = i - 1; j >= 0; j--) {\n if (ary_nums[i] - ary_nums[j] == diff) {\n count++;\n j = 0;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T01:22:40.133",
"Id": "462460",
"Score": "0",
"body": "This is still an \\$O(n^2)\\$ loop. The optimized form needs a single loop decreasing either i or j as appropriate."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-25T08:54:21.493",
"Id": "9406",
"ParentId": "7316",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "9406",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T17:02:08.103",
"Id": "7316",
"Score": "4",
"Tags": [
"java",
"optimization",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "k_diff challenge in Java"
}
|
7316
|
<p>This started as a hacked-together tool to remove annoyances I was facing with experimenting with code on live remote servers, then getting that code into my development environment after experimenting. I thought others might be able to benefit from the tool, so I cleaned it up and released it as open source on <a href="https://github.com/joshdick/pytograph" rel="nofollow">GitHub</a>.</p>
<p>The code in its current state appears below in its ~250 SLOC entirety. I'd appreciate any and all comments--correctness, style, best practices, logging, error handling, etc.</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python
"""
pytograph - Reflect local filesystem changes on a remote system in real time, automatically.
<https://github.com/joshdick/pytograph>
Requires Python 2.7, and the third-party Python packages config, pysftp, and watchdog.
"""
__author__ = 'Josh Dick <joshdick.net>'
__email__ = 'josh@joshdick.net'
__copyright__ = '(c) 2011-2012, Josh Dick'
__license__ = 'Simplified BSD'
from config import Config
from watchdog.observers import Observer
from watchdog.events import *
import argparse, getpass, logging, paramiko, posixpath, pysftp, sys, time
logFormat='%(levelname)s: %(message)s'
logging.basicConfig(format=logFormat)
logger = logging.getLogger('pytograph')
logger.setLevel(logging.INFO)
class PytoWatchdogHandler(PatternMatchingEventHandler):
"""
Watchdog event handler.
Triggers appropriate actions on a remote server via a RemoteControl when
specific Watchdog events are fired due to local filesystem changes.
"""
def __init__(self, remote_control = None, **kw):
super(PytoWatchdogHandler, self).__init__(**kw)
if (remote_control == None):
raise Exception('remote_control is a required parameter')
elif not isinstance(remote_control, RemoteControl):
raise Exception('remote_control must be an instance of RemoteControl')
self._remote_control = remote_control
def on_created(self, event):
if isinstance(event, DirCreatedEvent):
# Ignoring this event for now since directories will automatically
# be created on the remote server by transfer_file()
logger.debug('Ignoring DirCreatedEvent')
else:
self._remote_control.transfer_file(event.src_path)
def on_deleted(self, event):
self._remote_control.delete_resource(event.src_path)
def on_modified(self, event):
if isinstance(event, DirModifiedEvent):
logger.debug('Ignoring DirModifiedEvent')
else:
self._remote_control.transfer_file(event.src_path)
def on_moved(self, event):
self._remote_control.move_resource(event.src_path, event.dest_path)
class RemoteControl:
"""
Performs filesystem manipulations on a remote server,
using data from the local machine's filesystem as necessary.
"""
def __init__(self, sftp_connection = None, local_base = None, remote_base = None):
if (sftp_connection == None):
raise Exception('sftp_connection is a required parameter')
elif not isinstance(sftp_connection, SFTPConnection):
raise Exception('sftp_connection must be an instance of SFTPConnection')
self._connection = sftp_connection.connection
self._ssh_prefix = sftp_connection.ssh_prefix
self._local_base = local_base
self._remote_base = remote_base
# Given a full canonical path on the local filesystem, returns an equivalent full
# canonical path on the remote filesystem.
def get_remote_path(self, local_path):
# Strip the local base path from the local full canonical path to get the relative path
remote_relative = local_path[len(self._local_base):]
return self._remote_base + remote_relative
def transfer_file(self, src_path):
dest_path = self.get_remote_path(src_path)
logger.info('Copying\n\t%s\nto\n\t%s:%s' % (src_path, self._ssh_prefix, dest_path))
try:
# Make sure the intermediate destination path to this file actually exists on the remote machine
self._connection.execute('mkdir -p "' + os.path.split(dest_path)[0] + '"')
self._connection.put(src_path, dest_path)
except Exception as e:
logger.error('Caught exception while copying:')
logger.exception(e)
def delete_resource(self, src_path):
dest_path = self.get_remote_path(src_path)
logger.info('Deleting %s:%s' % (self._ssh_prefix, dest_path))
try:
self._connection.execute('rm -rf "' + dest_path + '"')
except Exception as e:
logger.error('Caught exception while deleting:')
logger.exception(e)
def move_resource(self, src_path, dest_path):
logger.info('Moving\n\t%s:%s\nto\n\t%s:%s' %
(self._ssh_prefix, self.get_remote_path(src_path), self._ssh_prefix, self.get_remote_path(dest_path)))
try:
# Make sure the intermediate destination path to this file actually exists on the remote machine
self._connection.execute('mkdir -p "' + os.path.split(dest_path)[0] + '"')
self._connection.execute('mv "' + src_path + '" "' + dest_path + '"')
except Exception as e:
logger.error('Caught exception while moving:')
logger.exception(e)
class SFTPConnection:
"""
Maintains a persistent SSH connection to a remote server via pysftp.
"""
def __init__(self, host = None, username = None, password = None):
self._ssh_prefix = None
self._connection = None
if (username == ''):
username = getpass.getuser()
logger.debug('No username configured; assuming username %s' % username)
else:
logger.debug('Using configured username %s' % username)
self._ssh_prefix = '%s@%s' % (username, cfg.remote_host)
if (password == ''):
try:
logger.debug('No password specified, attempting to use key authentication')
self._connection = pysftp.Connection(host, username = username)
except Exception:
logger.debug('Key authentication failed; prompting for password')
password = getpass.getpass('Password for %s: ' % self._ssh_prefix)
try:
self._connection = pysftp.Connection(host, username = username, password = password)
except Exception as e:
logger.error('Could not successfully connect to %s\nCause: %s' % (self._ssh_prefix, e))
sys.exit(1)
else:
logger.debug('Using configured password')
try:
self._connection = pysftp.Connection(host, username = username, password = password)
except Exception as e:
logger.error('Could not successfully connect to %s\nCause: %s' % (self._ssh_prefix, e))
sys.exit(1)
logger.debug('Successfully connected to %s' % self._ssh_prefix)
@property
def ssh_prefix(self):
"""
(Read-only)
String containing the username and host information for the remote server.
"""
return self._ssh_prefix
@property
def connection(self):
"""
(Read-only)
A pysftp Connection object representing the active connection to the remote server.
"""
return self._connection
if __name__ == "__main__":
# Cannot use argparse.FileType with a default value since the help message will not display if pytograph.cfg
# doesn't appear in the default location. Could subclass argparse.FileType but the following seems more intuitive.
# See http://stackoverflow.com/questions/8236954/specifying-default-filenames-with-argparse-but-not-opening-them-on-help
parser = argparse.ArgumentParser(description='Reflect local filesystem changes on a remote system in real time, automatically.')
parser.add_argument('-c', '--config-file', default='pytograph.cfg', help='location of a pytograph configuration file')
args = parser.parse_args()
try:
config_file = file(args.config_file)
except Exception as e:
logger.error('Couldn\'t read pytograph configuration file!\n\
Either place a pytograph.cfg file in the same folder as pytograph.py, or specify an alternate location.\n\
Run \'%s -h\' for usage information.\nCause: %s' % (os.path.basename(__file__), e))
sys.exit(1)
try:
cfg = Config(config_file)
except Exception as e:
logger.error('Pytograph configuration file is invalid!\nCause: %s' % e)
sys.exit(1)
# Read configuration
local_root_path = os.path.abspath(os.path.expanduser(cfg.local_root_path))
if not os.path.isdir(local_root_path):
logger.error('Invalid local_root_path configured: %s is not a valid path on the local machine' % cfg.local_root_path)
sys.exit(1)
else:
logger.debug('Using local root path: ' + local_root_path)
# Create persistent SSH connection to remote server
sftp_connection = SFTPConnection(cfg.remote_host, cfg.remote_username, cfg.remote_password)
logger.debug('Initializating path mappings...')
# If this is still true when the loop below completes, no valid mappings are configured.
no_valid_mappings = True
observer = Observer()
for mapping in cfg.path_mappings:
# Create an absolute local path from the local root path and this mapping's local relative path
local_base = os.path.join(local_root_path, mapping.local)
if not os.path.isdir(local_base):
logger.warn('Invalid path mapping configured: %s is not a valid path on the local machine' % local_base)
continue
# If we got this far, we have at least one valid mapping
no_valid_mappings = False
# Create an absolute remote path from the remote root path and this mapping's remote relative path
# Use explicit posixpath.join since the remote server will always use UNIX-style paths for SFTP
# TODO: Validate this, expand tilde notation, etc.
remote_base = posixpath.join(cfg.remote_root_path, mapping.remote)
logger.info('Path mapping initializing:\nChanges at local path\n\t%s\nwill be reflected at remote path\n\t%s:%s'
% (local_base, sftp_connection.ssh_prefix, remote_base))
# Create necessary objects for this particular mapping and schedule this mapping on the Watchdog observer as appropriate
remote_control = RemoteControl(sftp_connection = sftp_connection, local_base = local_base, remote_base = remote_base)
event_handler = PytoWatchdogHandler(ignore_patterns = cfg.ignore_patterns, remote_control = remote_control)
observer.schedule(event_handler, path=local_base, recursive=True)
if no_valid_mappings:
logger.error('No valid path mappings were configured, so there\'s nothing to do. Please check your pytograph configuration file.')
sys.exit('Terminating.')
# We have at least one valid mapping, so start the Watchdog observer - filesystem monitoring actually begins here
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
</code></pre>
|
[] |
[
{
"body": "<pre><code>#!/usr/bin/env python\n\n\"\"\"\npytograph - Reflect local filesystem changes on a remote system in real time, automatically.\n\n<https://github.com/joshdick/pytograph>\n\nRequires Python 2.7, and the third-party Python packages config, pysftp, and watchdog.\n\"\"\"\n\n__author__ = 'Josh Dick <joshdick.net>'\n__email__ = 'josh@joshdick.net'\n__copyright__ = '(c) 2011-2012, Josh Dick'\n__license__ = 'Simplified BSD'\n\nfrom config import Config\nfrom watchdog.observers import Observer\nfrom watchdog.events import *\nimport argparse, getpass, logging, paramiko, posixpath, pysftp, sys, time\n\nlogFormat='%(levelname)s: %(message)s'\nlogging.basicConfig(format=logFormat)\nlogger = logging.getLogger('pytograph')\nlogger.setLevel(logging.INFO)\n\nclass PytoWatchdogHandler(PatternMatchingEventHandler):\n\n \"\"\"\n Watchdog event handler.\n Triggers appropriate actions on a remote server via a RemoteControl when\n specific Watchdog events are fired due to local filesystem changes.\n \"\"\"\n\n def __init__(self, remote_control = None, **kw):\n super(PytoWatchdogHandler, self).__init__(**kw)\n\n if (remote_control == None):\n</code></pre>\n\n<p>Check for None using <code>is None</code> rather then <code>== None</code>. You don't need those parens.</p>\n\n<pre><code> raise Exception('remote_control is a required parameter')\n</code></pre>\n\n<p>Rather then checking for None, just make remote_control not have a default value.</p>\n\n<pre><code> elif not isinstance(remote_control, RemoteControl):\n raise Exception('remote_control must be an instance of RemoteControl')\n</code></pre>\n\n<p>Checking the types of arguments is frowned upon in python. You shouldn't do this check, just assume the user did the correct thing. Also, if you must raise an error, use TypeError.</p>\n\n<pre><code> self._remote_control = remote_control\n\n def on_created(self, event):\n if isinstance(event, DirCreatedEvent):\n # Ignoring this event for now since directories will automatically\n # be created on the remote server by transfer_file()\n logger.debug('Ignoring DirCreatedEvent')\n</code></pre>\n\n<p>I might include detail about the directory in the log file</p>\n\n<pre><code> else:\n self._remote_control.transfer_file(event.src_path)\n\n def on_deleted(self, event):\n self._remote_control.delete_resource(event.src_path)\n</code></pre>\n\n<p>Why resource? You seem to switch randomnly between resource and file.</p>\n\n<pre><code> def on_modified(self, event):\n if isinstance(event, DirModifiedEvent):\n logger.debug('Ignoring DirModifiedEvent')\n else:\n self._remote_control.transfer_file(event.src_path)\n\n def on_moved(self, event):\n self._remote_control.move_resource(event.src_path, event.dest_path)\n\n\nclass RemoteControl:\n\n \"\"\"\n Performs filesystem manipulations on a remote server,\n using data from the local machine's filesystem as necessary.\n \"\"\"\n\n def __init__(self, sftp_connection = None, local_base = None, remote_base = None):\n if (sftp_connection == None):\n raise Exception('sftp_connection is a required parameter')\n elif not isinstance(sftp_connection, SFTPConnection):\n raise Exception('sftp_connection must be an instance of SFTPConnection')\n</code></pre>\n\n<p>Again, don't check types, and if its a required parameter don't provide a default value</p>\n\n<pre><code> self._connection = sftp_connection.connection\n self._ssh_prefix = sftp_connection.ssh_prefix\n self._local_base = local_base\n self._remote_base = remote_base\n\n # Given a full canonical path on the local filesystem, returns an equivalent full\n # canonical path on the remote filesystem.\n def get_remote_path(self, local_path):\n # Strip the local base path from the local full canonical path to get the relative path\n remote_relative = local_path[len(self._local_base):]\n return self._remote_base + remote_relative\n</code></pre>\n\n<p>Python has a number of functions like os.path.relpath and os.path.join which would probably be a better choice then string manipulation. They'll handle the funky corner cases.</p>\n\n<pre><code> def transfer_file(self, src_path):\n dest_path = self.get_remote_path(src_path)\n logger.info('Copying\\n\\t%s\\nto\\n\\t%s:%s' % (src_path, self._ssh_prefix, dest_path))\n try:\n # Make sure the intermediate destination path to this file actually exists on the remote machine\n self._connection.execute('mkdir -p \"' + os.path.split(dest_path)[0] + '\"')\n self._connection.put(src_path, dest_path)\n except Exception as e:\n logger.error('Caught exception while copying:')\n logger.exception(e)\n</code></pre>\n\n<p>Here you catch any exception. But that includes exceptions caused by mispelling function names. That'll make it harder to find bugs. I'd recommend narrowing the scope to catch just whatever errors you really expect.</p>\n\n<pre><code> def delete_resource(self, src_path):\n dest_path = self.get_remote_path(src_path)\n logger.info('Deleting %s:%s' % (self._ssh_prefix, dest_path))\n try:\n self._connection.execute('rm -rf \"' + dest_path + '\"')\n except Exception as e:\n logger.error('Caught exception while deleting:')\n logger.exception(e)\n</code></pre>\n\n<p>These functions look very similar. This suggests that you should refactor them to combine the common elements.</p>\n\n<pre><code> def move_resource(self, src_path, dest_path):\n logger.info('Moving\\n\\t%s:%s\\nto\\n\\t%s:%s' %\n (self._ssh_prefix, self.get_remote_path(src_path), self._ssh_prefix, self.get_remote_path(dest_path)))\n try:\n # Make sure the intermediate destination path to this file actually exists on the remote machine\n self._connection.execute('mkdir -p \"' + os.path.split(dest_path)[0] + '\"')\n self._connection.execute('mv \"' + src_path + '\" \"' + dest_path + '\"')\n except Exception as e:\n logger.error('Caught exception while moving:')\n logger.exception(e)\n\n\nclass SFTPConnection:\n\n \"\"\"\n Maintains a persistent SSH connection to a remote server via pysftp.\n \"\"\"\n</code></pre>\n\n<p>Extra space between class and docstring.</p>\n\n<pre><code> def __init__(self, host = None, username = None, password = None):\n\n self._ssh_prefix = None\n self._connection = None\n\n if (username == ''):\n</code></pre>\n\n<p>Parens not needed</p>\n\n<pre><code> username = getpass.getuser()\n logger.debug('No username configured; assuming username %s' % username)\n else:\n logger.debug('Using configured username %s' % username)\n\n self._ssh_prefix = '%s@%s' % (username, cfg.remote_host)\n\n if (password == ''):\n try:\n logger.debug('No password specified, attempting to use key authentication')\n self._connection = pysftp.Connection(host, username = username)\n except Exception:\n logger.debug('Key authentication failed; prompting for password')\n password = getpass.getpass('Password for %s: ' % self._ssh_prefix)\n try:\n self._connection = pysftp.Connection(host, username = username, password = password)\n except Exception as e:\n logger.error('Could not successfully connect to %s\\nCause: %s' % (self._ssh_prefix, e))\n sys.exit(1)\n</code></pre>\n\n<p>Again, I'd narrow the exceptions being caught. I'd also shut down the program by throwing my own exception which I'd then print just before exiting.</p>\n\n<pre><code> else:\n logger.debug('Using configured password')\n try:\n self._connection = pysftp.Connection(host, username = username, password = password)\n except Exception as e:\n logger.error('Could not successfully connect to %s\\nCause: %s' % (self._ssh_prefix, e))\n sys.exit(1)\n</code></pre>\n\n<p>These two blocks are the same except for the way in which the password was fetched. You should rearrange the code so that the common bits aren't repeated.</p>\n\n<pre><code> logger.debug('Successfully connected to %s' % self._ssh_prefix)\n\n @property\n def ssh_prefix(self):\n \"\"\"\n (Read-only)\n String containing the username and host information for the remote server.\n \"\"\"\n return self._ssh_prefix\n\n @property\n def connection(self):\n \"\"\"\n (Read-only)\n A pysftp Connection object representing the active connection to the remote server.\n \"\"\"\n return self._connection\n</code></pre>\n\n<p>Where's the <code>execute</code> and <code>put</code> function you were calling before?</p>\n\n<pre><code>if __name__ == \"__main__\":\n</code></pre>\n\n<p>I'd put the following in main function and call it from here. </p>\n\n<pre><code> # Cannot use argparse.FileType with a default value since the help message will not display if pytograph.cfg\n # doesn't appear in the default location. Could subclass argparse.FileType but the following seems more intuitive.\n # See http://stackoverflow.com/questions/8236954/specifying-default-filenames-with-argparse-but-not-opening-them-on-help\n parser = argparse.ArgumentParser(description='Reflect local filesystem changes on a remote system in real time, automatically.')\n parser.add_argument('-c', '--config-file', default='pytograph.cfg', help='location of a pytograph configuration file')\n args = parser.parse_args()\n\n try:\n config_file = file(args.config_file)\n except Exception as e:\n logger.error('Couldn\\'t read pytograph configuration file!\\n\\\nEither place a pytograph.cfg file in the same folder as pytograph.py, or specify an alternate location.\\n\\\nRun \\'%s -h\\' for usage information.\\nCause: %s' % (os.path.basename(__file__), e))\n sys.exit(1)\n</code></pre>\n\n<p>When handling an exception, you should try to get as much information about the error for user display.</p>\n\n<pre><code> try:\n cfg = Config(config_file)\n except Exception as e:\n logger.error('Pytograph configuration file is invalid!\\nCause: %s' % e)\n sys.exit(1)\n\n # Read configuration\n local_root_path = os.path.abspath(os.path.expanduser(cfg.local_root_path))\n if not os.path.isdir(local_root_path):\n logger.error('Invalid local_root_path configured: %s is not a valid path on the local machine' % cfg.local_root_path)\n sys.exit(1)\n else:\n logger.debug('Using local root path: ' + local_root_path)\n\n # Create persistent SSH connection to remote server\n sftp_connection = SFTPConnection(cfg.remote_host, cfg.remote_username, cfg.remote_password)\n\n logger.debug('Initializating path mappings...')\n\n # If this is still true when the loop below completes, no valid mappings are configured.\n no_valid_mappings = True\n\n observer = Observer()\n\n for mapping in cfg.path_mappings:\n\n # Create an absolute local path from the local root path and this mapping's local relative path\n local_base = os.path.join(local_root_path, mapping.local)\n if not os.path.isdir(local_base):\n logger.warn('Invalid path mapping configured: %s is not a valid path on the local machine' % local_base)\n continue\n</code></pre>\n\n<p>I generally avoid continue in favor of else. I think its easier to read.</p>\n\n<pre><code> # If we got this far, we have at least one valid mapping\n no_valid_mappings = False\n\n # Create an absolute remote path from the remote root path and this mapping's remote relative path\n # Use explicit posixpath.join since the remote server will always use UNIX-style paths for SFTP\n # TODO: Validate this, expand tilde notation, etc.\n remote_base = posixpath.join(cfg.remote_root_path, mapping.remote)\n\n logger.info('Path mapping initializing:\\nChanges at local path\\n\\t%s\\nwill be reflected at remote path\\n\\t%s:%s'\n % (local_base, sftp_connection.ssh_prefix, remote_base))\n\n # Create necessary objects for this particular mapping and schedule this mapping on the Watchdog observer as appropriate\n remote_control = RemoteControl(sftp_connection = sftp_connection, local_base = local_base, remote_base = remote_base)\n event_handler = PytoWatchdogHandler(ignore_patterns = cfg.ignore_patterns, remote_control = remote_control)\n</code></pre>\n\n<p>Why always keyboard rather then positional arguments?</p>\n\n<pre><code> observer.schedule(event_handler, path=local_base, recursive=True)\n</code></pre>\n\n<p>I'd divide this loop into two parts. The first would filter the list of mappings to only include those we are actually interested in. The second would actually process them. Then you wouldn't need the flag variable: no_valid_mappings. I think it would be a bit simpler. </p>\n\n<pre><code> if no_valid_mappings:\n logger.error('No valid path mappings were configured, so there\\'s nothing to do. Please check your pytograph configuration file.')\n sys.exit('Terminating.')\n\n # We have at least one valid mapping, so start the Watchdog observer - filesystem monitoring actually begins here\n observer.start()\n\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n observer.stop()\n observer.join()\n</code></pre>\n\n<p>What if an exception besides KeyboardInterrupt is thrown. Should you call observer.stop() then? Perhaps the .stop and .join should be in a finally clause.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T20:04:19.753",
"Id": "11455",
"Score": "0",
"body": "Thanks for your comments, addressing them now!\n\nThe naming discrepancy between transfer_file() and delete_resource()/move_resource() was actually on purpose; it's because transfer_file() is only used with files, while the others can work with both files and directories. I may change these names to be more clear.\n\nThanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T18:07:42.743",
"Id": "7320",
"ParentId": "7317",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "7320",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T17:29:20.723",
"Id": "7317",
"Score": "8",
"Tags": [
"python",
"python-2.x",
"file-system"
],
"Title": "Keeping remote folders in sync with local ones"
}
|
7317
|
<p>I am optimizing the variable parser for <a href="http://code.google.com/p/hack-programming-language/" rel="nofollow">my programming language</a>, and also trying to make it more readable and concise (precedence: readable and concise > efficient). What is the best way to improve this code and make the best out of each line, and make it easier to understand for contributors?</p>
<pre><code>namespace pro_compiler
{
/* Handles all the variable declarations */
public class VarParser : Parser
{
public VarParser( )
: base()
{
}
public string Parse(ref string line)
{
CheckVariable(ref line);
return line;
}
public void CheckVariable(ref string line)
{
/* Check current line for the "var" keyword */
if (line.StartsWith("var"))
{
string decl = line;
decl += ';';
line = decl;
CheckFunctions(ref line);
}
}
/* check if the var declaration contains any functions
* e.g var input = readln; */
public string CheckFunctions(ref string line)
{
var words = line.Split(' '); //check wether each word is a function
line = ""; // clear the current line
foreach (var word in words)
{
string w = word.Trim(); //trim all leading and trailing spaces.
foreach(var pair in FuncTable.Instance.NormSet)
{
if (w.StartsWith(pair.Key)) // if the word is a function
{
w = w.Replace(pair.Key, pair.Value + "( )"); // replace it with the C# equivalent
}
}
w = ((w == words[0]) ? "" : " ") + w; // reinsert trailing and leading spaces
line += w; // add the words back to the current line
}
return line;
}
}
}
</code></pre>
<p>Also, I have used a lot of the C# standard library methods, since I figured that the people who wrote those have 10 times more skills than me and wrote them as efficiently as possible. Is this good? Or is it better to implement my own string functions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T08:13:32.590",
"Id": "11476",
"Score": "1",
"body": "I'd use a parser generator instead of writing your own from scratch. It will be a lot easier to define and maintain your grammar and code."
}
] |
[
{
"body": "<h1>A few observations...</h1>\n\n<h2>General</h2>\n\n<ul>\n<li>It would be great if you could include a syntax snippets of how a line in your programming language would look so we can test our solutions against the expected output. I had to go to your Google Code project and search for an actual syntax example in your source files </li>\n<li>Your parsing functionality is still very rudimentary. (I didn't change that.) It can't yet handle function arguments and it doesn't work if there are no spaces in between words. Also, if there are spaces in front of the variable declaration, the function will not get translated at all (this I fixed)</li>\n<li>It's usually advisable to stick with library functions and <em>not</em> to reinvent the wheel, <em>especially</em> since you have stated that readability trumps efficiency in your scenario. .NET's string functions are mostly fine</li>\n<li>There's no need to explicitly specify the default constructor as it (along with it's call to the argument-less constructor of <code>Parser</code>) will be automatically generated by the compiler. Leaving it out means one less thing for your readers and contributors to worry about</li>\n</ul>\n\n<h2>Naming issues</h2>\n\n<p><ul>\n<li>According to the comment just above the class definition, <code>VarParser handles all the variable declarations</code>. Although this makes sense, I'd suggest you ponder on finding a more <em>descriptive</em> name, such as <code>VariableDeclarationParser</code> or at least <code>VariableParser</code></li>\n<li>The function name <code>CheckVariable</code> is lacking at best, or misinformation at worst. It tells us it is \"checking a variable\" but in reality it isn't - it's checking if the current line <em>contains a variable and, if it does, it will process the line - otherwise it will do nothing</em>. An adequate name for that would be <code>ParseLineIfItContainsAVariableDeclaration</code>. Of course we <strong>don't</strong> use that, but rather we realize that the function needs to be split up to separate the check from the processing, so we choose two names for our new functions:\n<ul>\n<li><code>ContainsVariableDeclaration(string line)</code> will return a <code>bool</code> indicating if we should process the line</li>\n<li><code>ParseLine(string line)</code> will return a string containing the parsed line</li>\n</ul></li>\n<li><code>FuncTable</code> is a very vague name for your Singleton containing the (also vague) <code>NormSet</code> - consider something like <code>HackToCSharpMapper</code> (or just <code>LanguageMapper</code>) and <code>FunctionMappings</code> or something along those lines instead of <code>NormSet</code></li>\n<li><code>CheckFunctions</code> <em>doesn't <strong>check</strong> anything</em>, rather it seems to parse functions. Therefore, name it <code>ParseFunctionsIn(string line)</code> </li>\n<li>I'm not saying you should choose the exact names I recommended, just try to think of the name that captures what the function does best and don't imply a function is doing something it doesn't do</li>\n<li><strong>Naming is important</strong> because it forces us to define what a given function, variable or class <em>should</em> do. When we end up with long names (see example above), we know that our code isn't well-structured and needs to be changed so that we follow the principles of OOP.</p>\n\n<blockquote>\n <p>A function should do <strong>one thing</strong>. It should do it <strong>well</strong>. It should do it <strong>only.</strong><br>\n — Robert C. Martin in <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\">Clean Code: A Handbook of Agile Software Craftsmanship</a></li>\n </ul></p>\n \n <h2>Comments</h2>\n</blockquote>\n\n<p>Almost all of your comments can be made obsolete by choosing proper names and generally making the code as expressive as possible. IMHO, we should avoid comments that tell us <em>what</em> a particular statement does, rather we should use them <strong>only</strong> to clarify <strong>why</strong> we have made an unusal decision.<br>\nOr, to put it like <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\">Uncle Bob</a>, <em>I view every comment I write as a <strong>failure</strong> to express myself in code</em>.<br>\nSo I deleted most of your comments from the refactored version below because the names now stand for themselves, without the need for further clarification.</p>\n\n<h2>Dangerous and unusual things</h2>\n\n<ul>\n<li>Are you sure there won't be any whitespace before the <code>var</code> keyword? I've added a call to <code>String.TrimStart()</code> to make sure we don't stumble over this edge case</li>\n<li>In your class, I see <strong>absolutely no reason</strong> to pass the <code>line</code> parameter <em>by reference</em>. This should be avoided because it makes your code more unpredictable - one can no longer be sure whether the function has a side effect on the input parameter\n<ul>\n<li><code>CheckFunctions</code> returns a string, but the return value is never used because you rely on the <code>ref</code> parameter - be consistent!</li>\n</ul></li>\n<li>Why are <code>CheckVariable</code> and <code>CheckFunctions</code> <code>public</code>? Too me, it looks like they <em>should only ever be accessed from within that class</em></li>\n<li>What if someone passes in a line that doesn't contain a variable declaration? At the moment, there will be no warning at all, the result will just be the same as the input - I suggest changing your program to throw an <code>ArgumentException</code> if it is not passed a valid declaration</li>\n</ul>\n\n<h2>Loops</h2>\n\n<ul>\n<li>Your nested <code>foreach</code> loop is unnecessary and bad for performance because it loops over all possibilities. As further investigation of the rest of your source code on Google Code shows, <code>FuncTable.Instance.NormSet</code> is a <code>Dictionary<string,string></code> and therefore suitable for <strong>fast access by key</strong>. </li>\n<li>Note that in your original code, you kept going through further possible function matches <em>even after you have already replaced the current word with it's C# function!</em></li>\n</ul>\n\n<p>After quite a bit of refactoring, we arrive at the below solution. If anything needs to be clarified, go ahead and ask.</p>\n\n<h1>Refactored example</h1>\n\n<p>All methods could have been made static, however I suspect you will change the base class - to which VariableDeclarationParser has <strong>no dependency</strong> at the moment - to a more useful one that provides a <code>virtual Parse()</code> method that can be overridden.</p>\n\n<pre><code>public class VariableDeclarationParser : Parser\n{\n public string Parse(string line)\n {\n if (ContainsVariableDeclaration(line))\n {\n return ParseLine(line);\n }\n throw new ArgumentException(\"Invalid declaration: \" + line);\n }\n\n private bool ContainsVariableDeclaration(string line)\n {\n return line.TrimStart().StartsWith(\"var\");\n }\n\n private string ParseLine(string line)\n {\n string parsedLine = string.Empty;\n foreach (string word in line.Split(' '))\n {\n parsedLine += GetFunctionOrVariable(word);\n }\n return parsedLine.TrimEnd() + \";\";\n }\n\n private string GetFunctionOrVariable(string candidate)\n {\n string key = candidate.Trim();\n var mappings = HackToCSharpMapper.Instance.FunctionMappings;\n if (mappings.ContainsKey(key)) return mappings[key] + \"() \";\n return candidate + \" \";\n }\n}\n</code></pre>\n\n<p>If you're into LINQ, consider this alternative <code>ParseLine</code> function. It's more concise, but it sacrifices some readability - I think the above <code>foreach</code> is the better solution.</p>\n\n<pre><code>private string ParseLine(string line)\n{\n string parsedLine = line.Split(' ').Aggregate(\n string.Empty, (parsed, word) => parsed + GetFunctionOrVariable(word));\n return parsedLine.TrimEnd() + \";\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T11:32:27.930",
"Id": "11484",
"Score": "1",
"body": "+1, Thank You. Wish I could upvote this answer a million times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T21:34:17.497",
"Id": "11715",
"Score": "1",
"body": "Great answer. As an alternative to making the Parse method virtual, you might consider putting abstract ShouldParseLine (replaces ContainsVariableDeclaration) and ParseLine methods on the Parser base class. Then, implement the Parse method as a non-virtual method also on the Parser base class. This would enforce all classes derived from the Parser class to follow the same implementation pattern."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T00:28:19.627",
"Id": "7330",
"ParentId": "7318",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "7330",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T17:34:09.163",
"Id": "7318",
"Score": "3",
"Tags": [
"c#",
".net",
"performance",
"parsing"
],
"Title": "Variable parser for the Hack programming language"
}
|
7318
|
<p>I have a model with a number of complex/simple properties that has a corresponding strongly typed view, that calls <code>EditorFor</code> to a custom editor template view for the model.</p>
<p>One of the form's requirements is to auto fill the form based on a choose of values from a database.</p>
<p>Previously, I had the selectors on the selection popup do a post back to an action with the additional value needed to <code>prepopulate</code> the model, and then the model is bound like normal.</p>
<p>I wanted to see if I could alter the form to do the prefill with Ajax:</p>
<p>I have a <code>JsonResult</code> Action that accepts a unique Id, and returns the JSON version of the model.</p>
<p>When you click the selection button this action is invoked via jQuery <code>$.ajax</code> post.</p>
<p>Each input on the form has an Id in the form <code>Id="ModelName_PropertyName"</code> so parse the keys in the JSON object, using the keys to look up the field in a given selector, and set the values from JSON.</p>
<p>Here is how I invoke from Ajax in CoffeeScript (<strong>I can post the JavaScript if requested</strong>):</p>
<pre><code>$.ajax
type: "POST"
url: $("#SelectFromPolicyContainer").data "url"
data: vin
success: (response) ->
$("#PropertyInfo").bindFormToJson response.Data.Vehicle, true
$("#SelectFromPolicyResponse").dialog "close"
</code></pre>
<p>The Action looks like this:</p>
<pre><code>[HttpPost]
public JsonResult VehicleByVIN(string VinNumber)
{
return AjaxJsonResponse.Create(UserNotice.NoNotice, new
{
Vehicle = Policy.Vehicles.SingleOrDefault(p=>p.Info.Vin.Number==VinNumber)
});
}
</code></pre>
<p>And the definition of <code>bindFormToJson</code>:</p>
<pre><code>$ -> $.fn.bindFormToJson = (JsonObject, OverwritePopulatedFields) ->
selector = $(this).selector
iterateJson = (JSonObject, FullKey, Seperator, func) ->
for key, value of JSonObject
newKey = ""
if FullKey == ""
newKey = key
else
newKey = FullKey + Seperator + key
if typeof(value) == "object"
iterateJson value, newKey, Seperator, func
else
func newKey, value
iterateJson JsonObject, "", "_", (key,value) ->
field = $(selector + " #" + key)
currentValue = field.val()
if (currentValue and OverwritePopulatedFields) or not currentValue
field.val(value)
</code></pre>
<p>Any tips, or things I may have missed or potential problems I might have overlooked would be wonderful. In my test environment right now though, this is working beautifully.</p>
|
[] |
[
{
"body": "<p>Not a JavaScript pitfall <em>per se</em>, but I'd stay away from using two variable names that are only differentiated by the case of the second letter in a single lexical scope like that. (<code>JsonObject</code> vs <code>JSonObject</code>)</p>\n\n<p>Also, the bindFormToJson function is re-defining the iterateJson function every time it is called, which a waste of cycles (not egregious, but less than ideal). Using coffeescripts <code>do</code> notation is a handy way to create a closure and return a value from it:</p>\n\n<pre><code>$ -> $.fn.bindFormToJson = do ->\n\n iterateJson = (Source, FullKey, Seperator, func) ->\n for key, value of Source\n newKey = \"\"\n if FullKey == \"\"\n newKey = key\n else\n newKey = FullKey + Seperator + key\n\n if typeof(value) == \"object\" \n iterateJson value, newKey, Seperator, func \n else \n func newKey, value\n\n return (JsonObject, OverwritePopulatedFields) ->\n selector = $(this).selector\n iterateJson JsonObject, \"\", \"_\", (key, value) -> \n field = $(selector + \" #\" + key)\n currentValue = field.val()\n if (currentValue and OverwritePopulatedFields) or not currentValue\n field.val(value)\n</code></pre>\n\n<p>The return is unnecessary, but I figured it can't hurt to be explicit about what's happening there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T13:07:49.560",
"Id": "12832",
"Score": "0",
"body": "Thank you for the feedback, and I have made the suggested changes. I hadn't use `do` before, that is very useful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T07:57:46.957",
"Id": "8050",
"ParentId": "7321",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T18:45:15.680",
"Id": "7321",
"Score": "0",
"Tags": [
"coffeescript",
"asp.net-mvc-3"
],
"Title": "Model with complex/simple properties"
}
|
7321
|
<blockquote>
<p><strong>Puzzle Description:</strong></p>
<p>You are given 'n' strings w1, w2, ......, wn. Let Si denote the set of strings formed by considering all unique substrings of the string wi. A substring is defined as a contiguous sequence of one or more characters in the string. More information on substrings can be found here. Let 'S' = {S1 U S2 U .... Sn} .i.e 'S' is a set of strings formed by considering all the unique strings in all sets S1, S2, ..... Sn. You will be given many queries and for each query and an integer 'k'. Your task is to output the lexicographically kth smallest string from the set 'S'.</p>
<p><strong>Input:</strong></p>
<p>The first line of input contains a single integer 'n', denoting the number of strings. Each of the next 'n' lines consists of a string. The string on the ith line (\$1 <= i<= n\$) is denoted by wi and has a length mi. The next line consists of a single integer 'q', denoting the number of queries. Each of the next 'q' lines consists of a single integer 'k'.
Note: The input strings consist only of lowercase English alphabets 'a' - 'z'.</p>
<p><strong>Output:</strong></p>
<p>Output 'q' lines, where the ith line consists of a string which is the answer to the ith query. If the input is invalid ('k' > |S|), output "INVALID" (quotes for clarity) for that case.</p>
<p>Constraints:</p>
<ul>
<li>\$1 <= n <= 50\$</li>
<li>\$1 <= mi <= 2000\$</li>
<li>\$1 <= q<= 500\$</li>
<li>\$1 <= k<= 1000000000\$</li>
</ul>
<p>Sample Input:</p>
<pre><code>2
aab
aac
3
3
8
23
</code></pre>
<p>Sample Output:</p>
<pre><code>aab
c
INVALID
</code></pre>
<p><em>Explanation:</em></p>
<p>For the sample test case, we have 2 strings "<code>aab</code>" and "<code>aac</code>".</p>
<p><code>S1 = {"a", "aa", "aab", "ab", "b"}</code> . These are the 5 unique substrings of "<code>aab</code>".</p>
<p><code>S2 = {"a", "aa", "aac", "ac", "c" }</code> . These are the 5 unique substrings of "<code>aac</code>".</p>
<p>Now, <code>S = {S1 U S2} = {"a", "aa", "aab", "aac", "ab", "ac", "b", "c"}</code>. Totally, 8 unique strings are present in the set 'S'.</p>
<p>The lexicographically 3rd smallest string in 'S' is "<code>aab</code>" and the lexicographically 8th smallest string in 'S' is "<code>c</code>". Since there are only 8 distinct substrings, the answer to the last query is "<code>INVALID</code>".</p>
<p><strong>Time-limit:</strong> 5 secs</p>
</blockquote>
<hr>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
public class find_str {
private static final String INVALID = "INVALID";
private TreeSet<String> mainset = new TreeSet<String>();
private ArrayList<String> array = new ArrayList<String>();
private String[] main_ary;
private int length;
public static void main(String args[]) {
find_str fin = new find_str();
Scanner scanner = new Scanner(System.in);
int num_of_strings = scanner.nextInt();
for (int i = num_of_strings; --i >=0;) {
fin.process(scanner.next());
}
fin.initialize();
int num_of_queries = scanner.nextInt();
for (int i = num_of_queries; --i >=0;) {
System.out.println(fin.query(scanner.nextInt()-1));
}
}
private String query(int index) {
if (index < length) {
return main_ary[index];
} else {
return INVALID;
}
}
private void process(String input) {
int len = input.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
mainset.add(input.substring(i, j + 1));
}
}
}
private void initialize() {
length=mainset.size();
main_ary=(String[]) mainset.toArray(new String[length]);
// array.addAll(mainset);
}
}
</code></pre>
<ol>
<li>This was written to solve puzzle only</li>
<li>First I thought of creating separate sets for each string and then later unionize all them to get final mainset and then sort them using custom comparator if necessary and later can be retrieved with index.</li>
<li>Later without doing all this nonsense, created tree-set which is populated with substrings on the run, thus combined process of unionizing and sorting. </li>
<li>For retrieving through index I had to make an <code>ArrayList</code> with contents of mainset. I guess this doesn't take much time or memory than other process.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:36:52.770",
"Id": "11452",
"Score": "2",
"body": "You been asking all the question for recruitment from interviewstreet.com"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:47:21.023",
"Id": "11453",
"Score": "0",
"body": "I wouldn't have asked if i didn't solve it, the reason i'm asking is to improvise the code, it wouldn't be good if i asked to solve a puzzle and steal charm myself right? :)\nFYI, that recruitment is way too beyond me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:50:11.457",
"Id": "11454",
"Score": "0",
"body": "Anyway, i'm still a beginner and trying to solve puzzles , so i could gain some knowledge and to improvise myself in domain :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T22:05:15.103",
"Id": "11464",
"Score": "2",
"body": "@Pheonix, see http://meta.codereview.stackexchange.com/questions/429/online-contest-questions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T06:45:49.170",
"Id": "11474",
"Score": "0",
"body": "how can i make the process of making substring of each given string,into separate thread ? thus it does parallel functioning and take lesser execution time."
}
] |
[
{
"body": "<p>Just formal way :</p>\n\n<p>Use <code>TreeSet<String> ts</code> to store <code>S = {S1 U S2}</code> : </p>\n\n<ul>\n<li>if String is already stored, it returns <code>false</code>,</li>\n<li>you can use <code>ts.toString()</code> to print all values of the Set, separated by '<code>,</code> ' between '<code>[]</code>'</li>\n<li>you have <code>addAll(..), containsAll(..), retainAll(..), ...</code> ready made [and optimized] other tools.</li>\n<li>You can put in <code>Collections.synchronizedSet(s)</code> if you have multi threaded concurrrent jobs.</li>\n</ul>\n\n<p>You can rebuilt/combine your code from JVM, not only from mathematical constraints. ... wheels exist from long time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T07:34:25.877",
"Id": "13926",
"ParentId": "7324",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:19:36.060",
"Id": "7324",
"Score": "3",
"Tags": [
"java",
"optimization",
"strings",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Output strings from a set in lexicographical order"
}
|
7324
|
<p>This is for a page where it displays some social media information for that user.</p>
<p>I would like to improve the following code that I posted below. It does the job perfectly, but I just feel like it could definitely be improved. I could easily leave it the way it is but I am trying to learn and that's why I would like to get suggestions from experienced programmers.</p>
<pre><code><?php
if($facebook && !$twitter_username || !$facebook && $twitter_username) {
$width = "490";
} else {
$width = "930";
}
?>
<div id="content">
<div style="width:<?=$width;?>px;margin:auto;">
<?php if($facebook) { ?><div class="buttons"><img src="images/facebook_icon.png" class="fb" /> <p><em>Like Us</em><br />on Facebook</p></div><?php } ?>
<?php if($twitter_username) { ?><div class="buttons"><img src="images/twitter_icon.png" class="twitter" /> <p><em>Follow Us</em><br />on Twitter</p><span>@<?=$twitter_username;?></span></div><?php } ?>
</div>
<br class="clear" />
<?php
if($twitter_username) {
if($display_tweets) {
?>
<div class="tweet">
<h2 class="twitter_feed white_textshadow">Latest Tweet</h2>
<div class="feed"></div>
</div>
<?php
}
}
if(!$display_tweets || !$twitter_username) {
if($website_url) {
?>
<h2 class="visit white_textshadow center"><em>Visit Our Website</em><br>www.<?=$website_url;?></h2>
<?php
}
}
?>
</div>
</code></pre>
<p>In the database there are 4 fields: </p>
<ul>
<li>Facebook (NULL or 1)</li>
<li>Twitter username (NULL or username)</li>
<li>display_feed (NULL or 1)</li>
<li>Website URL (NULL or URL domain.com format)</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T12:28:30.220",
"Id": "11487",
"Score": "1",
"body": "Consider using a templating engine like twig: http://twig.sensiolabs.org/"
}
] |
[
{
"body": "<p><strong>Style (PHP)</strong></p>\n\n<ul>\n<li><p>At the beginning, the test seems pretty weird but in any case, I usually prefer </p>\n\n<pre><code>$var = (condition) ? val1 : val2;\n</code></pre>\n\n<p>over </p>\n\n<pre><code>if(condition) {\n $var = val1;\n} else {\n $var = val2;\n}\n</code></pre></li>\n<li><p>You can replace</p>\n\n<pre><code>if(condition1) {\n if(condition2) {\n stuff();\n }\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>if(condition1 && condition2) {\n stuff();\n}\n</code></pre></li>\n</ul>\n\n<p>On top of that, the <code>if(!$display_tweets || !$twitter_username)</code> test would then be useless as it would correspond to the <code>else</code> case.</p>\n\n<ul>\n<li>There's no point in closing php tags just before reopening them. Remove the <code>? > < ? php</code> tags.</li>\n</ul>\n\n<p><strong>Style (HTML)</strong></p>\n\n<ul>\n<li>Do you really want to use the em markup inside the <code>h2</code> one?</li>\n</ul>\n\n<p><strong>What you are actually doing/trying to do</strong></p>\n\n<ul>\n<li><p>The code at the beginning seems to be assuming that we have a least facebook or twitter (sometimes both).</p>\n\n<ul>\n<li>If this is indeed the case, the\n<code>$width = ($facebook && !$twitter_username || !$facebook && $twitter_username) ? \"490\" : \"930\";</code>\nat the beginning could become\n<code>$width = ($facebook && $twitter_username) ? \"930\" : \"490\";</code></li>\n<li>If it is not the case, could the beginning be behind an <code>if (twitter || facebook)</code> test as creating an empty <code>div</code> (and giving it an arbitrary width) might not be relevant. If you want to keep it, for the definition of the width, I'd rather have someting like : \n<code>$width = ($facebook && $twitter_username) ? \"930\" : (($facebook || $twitter_username) ? \"490\" : \"1\");</code></li>\n</ul></li>\n<li><p>It might be interesting to use <code><a href=\"<?= $website_url; ?>\" ></code> or something like that to display the url as an actual link to make things easier from a user point of view (here I assumed that the input has been sanitized properly). On top of that, I don't understand why you hardcode the <code>www.</code> string (have a look at your current adress bar for more details). If there was anything to be hardcoded (and I personally wouldn't go for that), it's more likely to be the <code>http://</code> part.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:27:56.647",
"Id": "11459",
"Score": "0",
"body": "Thanks so much for your help. For the em inside the h2, I needed that part to be italics and then also that italicized part has a little bigger font size then the bottom part, so I can target it with CSS to increase the font size. Is there a better way to do it? And for the www, I am storing the domains as domain.com in the database and this screen will be shown on TV's so there are no clickable links or anything. I just figured it would be best to display the website URL as www.domain.com - should I do it differently?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-07T10:07:47.170",
"Id": "34352",
"Score": "0",
"body": "I would use a <span> or a <p> tag in the place of the em. Then apply a class to the new element rather than using em."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:03:16.657",
"Id": "7327",
"ParentId": "7325",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7327",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T19:36:30.377",
"Id": "7325",
"Score": "1",
"Tags": [
"php",
"twitter",
"facebook"
],
"Title": "Displaying a user's social media information"
}
|
7325
|
<p>Edit - <code>decl</code> smokes <code>dojo.declare</code> - <a href="http://jsperf.com/dojo-declare-vs-decl" rel="nofollow">http://jsperf.com/dojo-declare-vs-decl</a></p>
<p>The code has been updated a bit. <code>decl</code> now accepts object literals as well, although I still like "declaration functions" better.</p>
<hr>
<p>I'm looking for some feedback on an approach I've been taking to provide simple inheritance for my javascript code. </p>
<p>Usually when working with constructors in javascript, you create the constructor function first, and add properties to its prototype. </p>
<p>With this approach, you instead write a single function (we'll call it the "declaration function") which is invoked using <code>new</code>. The properties of the resulting object instance (the "declaration object") are copied to the <code>prototype</code> of your new constructor. The <code>constructor</code> property of the declaration object (if any) is the constructor itself; otherwise a new empty function or wrapper for the parent constructor is used as the constructor.</p>
<p>Before your declaration function is invoked, it is given a <code>prototype</code> providing it with a few useful function properties. So far these include <code>extend</code>, for extending another constructor, and <code>augment</code>, for continuing a partial declaration. Because the declaration function is invoked with <code>new</code>, these functions are available as properties of <code>this</code> in the declaration function. Note that these function properties <em>only</em> exist in the transient "declaration object," not in your constructor or its prototype.</p>
<p>Here is the code:</p>
<pre><code>/** decl
Create a prototype object and return its constructor.
@param {Function|Object} declaration
*/
function decl (declaration) {
if (!declaration) {
declaration = {};
}
else if (declaration.call) {
declaration.prototype=decl.proto;
declaration.prototype[decl.dataKey]={};
}
return decl.getCtor(declaration);
}
// Name of property where declaration objects' metadata will be stored.
// If you want to pass objects to decl instead of functions,
// put the metadata (parent, partial, etc.) in this property.
decl.dataKey = 'decl-data';
// This object is used as a prototype for declaration objects,
// so everything here is available as properties of `this`
// inside the body of each declaration function.
decl.proto = {
extend: function (ctor) {
return (this[decl.dataKey].parent=ctor).prototype;
},
augment: function (ctor) {
return (this[decl.dataKey].partial=ctor).prototype;
}
};
// Create a copy of a simple object
decl.clone = function (obj) {
return this instanceof decl.clone ? this :
new decl.clone(decl.clone.prototype=obj);
};
// Merge src object's properties into target object
decl.merge = function (target, src) {
for (var k in src) {
if (src.hasOwnProperty(k) && k!='prototype' && k!=decl.dataKey) {
target[k] = src[k];
}
}
};
// Generate empty constructor
decl.empty = function () {
return function(){};
};
// Generate wrapper for parent constructor
decl.wrap = function (parent) {
return function(){ parent.apply(this, arguments); };
};
// Prepare a constructor to be returned by decl
decl.getCtor = function (declaration) {
var oldProto, p = 'prototype', c = 'constructor',
declFn = declaration.call ? declaration : null,
declObj = declFn ? new declFn(declFn) : declaration,
data = declObj[decl.dataKey] || {},
parent = data.parent, partial = data.partial,
ctor =
declObj.hasOwnProperty(c) ? declObj[c] : // ctor is user-defined
partial ? partial : // ctor is already defined (partial)
parent ? decl.wrap(parent) : // ctor is generated wrapper for parent ctor
decl.empty(); // ctor is generated empty function
// If there's a parent constructor, use a clone of its prototype
// and copy the properties from the current prototype.
if (parent) {
oldProto = ctor[p];
ctor[p] = decl.clone(parent[p]);
decl.merge(ctor[p], oldProto);
}
// Merge the declaration function's properties into the constructor.
// This allows adding properties to `this.constructor` in the declaration function
// without defining a constructor, or before defining one.
decl.merge(ctor, declFn);
// Merge the declaration objects's properties into the prototype.
decl.merge(ctor[p], declObj);
// Have the constructor reference itself in its prototype, and return it.
return (ctor[p][c]=ctor);
};
</code></pre>
<p>Here are some simple examples.</p>
<pre><code>// super, implicit ctor
var Animal = decl(function(){
this.test = function(){
console.log('ok');
};
});
// sub, implicit ctor
var Dog = decl(function(){
this.extend(Animal);
this.legs = 4;
this.bark = function(){
console.log('woof');
};
});
// super, explicit ctor
var Foo = decl(function(){
this.constructor = function(x){
this.x = x;
};
});
// sub, auto ctor
var Bar = decl(function(){
this.extend(Foo);
});
// partial prototype (the rest of Foo)
decl(function(){
this.augment(Foo);
this.test = function(){
console.log('{'+this.x+'}');
};
});
// tests
console.log (new Foo(24), new Bar(13), new Animal(), new Dog());
</code></pre>
<p>I feel like this solution allows for a pretty clean and straightforward coding style, but I haven't really seen it used. Is there something out there that already takes this approach? Or is it a bad idea for some reasons I'm missing?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T20:52:15.487",
"Id": "11457",
"Score": "1",
"body": "Doing it wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T21:09:27.640",
"Id": "11458",
"Score": "2",
"body": "Since that doesn't really add much and I'm already talking to you in the javascript room I won't bother addressing it ;)"
}
] |
[
{
"body": "<p>From a onceover:</p>\n\n<ul>\n<li><code>instanceof</code> works, so bonus points there</li>\n<li>Some terrible names : <code>decl</code>, <code>getCtor</code>, <code>declFn</code>, <code>declObj</code>, just type the full name</li>\n<li>You have an unmaintainable/undocumented nested ternary in <code>getCtor()</code></li>\n</ul>\n\n<p>It is a neat idea to define the constructor and auto-magically move the functions to prototype, but in the end I find vanilla OO still the best approach. It seems tricky now to add legs to the prototype of Dog.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T00:41:02.670",
"Id": "66024",
"Score": "0",
"body": "`getCtor`, `declFn`, `declObj` are only used internally; I saw no reason to be extra verbose with those (IMO the names are doing their job, I still remember what they mean and this code is pretty old now). `decl` is supposed to be the name of the \"library,\" so it should probably stay. Which nested ternary is undocumented? Surely you don't mean the one documented with comments on every line? Why is it hard to modify Dog's prototype? `Dog.prototype.legs = 3` should do it. The `augment` method was supposed to make this even easier, but I ditched it in a more recent version, figuring YAGNI."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T16:30:06.050",
"Id": "39397",
"ParentId": "7326",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-30T20:40:10.303",
"Id": "7326",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"constructor",
"prototypal-class-design"
],
"Title": "\"metaconstructors\" for inheritance in js?"
}
|
7326
|
<p>I have the following <code>Student</code> class:</p>
<pre><code>class Student {
public $user_id;
public $name;
public function __construct($user_id) {
$info = $this->studentInfo($user_id);
$this->name = $info['name'];
$this->is_instructor = $info['is_instructor'];
$this->user_id = $info['id'];
}
public function studentInfo($id) {
global $db;
$u = mysql_fetch_array(mysql_query("SELECT * FROM $db[students] WHERE id='$id'"));
if($u) {
return $u;
}
}
public function getCoursesByInstructor() {
global $db;
return mysql_query("SELECT courses.*, course_types.name FROM $db[courses] as courses
JOIN $db[course_types] as course_types ON courses.course_type_id=course_types.id
WHERE instructor_id='$this->user_id'");
}
}
</code></pre>
<p>Ideally, I'd do:</p>
<pre><code>$u = new Student(1);
$courses = $u->getCoursesByInstructor();
</code></pre>
<p>Does anyone have any critiques on this class? Also, how would you recommend me adding functionality to "add" a student? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T01:25:28.833",
"Id": "11468",
"Score": "0",
"body": "PDO http://php.net/manual/en/book.pdo.php and Dependency Injection http://fabien.potencier.org/article/11/what-is-dependency-injection"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-21T05:47:26.783",
"Id": "19157",
"Score": "0",
"body": "please try to have \"descriptive\" title."
}
] |
[
{
"body": "<p>From an OOP standpoint, I dont think your properties should be public.</p>\n\n<p>I think <code>studentInfo</code> should be renamed <code>getStudentInfo</code></p>\n\n<p>For database access its good to look at a ORM framework. I suggest <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow\">Doctrine</a>. If you want to use pure PHP, I think use PDO or MySQLi at least. <a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\" rel=\"nofollow\">Why use PDO on Nettuts</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T01:22:09.110",
"Id": "7332",
"ParentId": "7331",
"Score": "0"
}
},
{
"body": "<p><strong>mysql_* functions</strong></p>\n\n<p>Stop using them, immediately! They are essentially deprecated, as they refer to MySQL before version 4.1. They are not removed as to not brake backward compatibility, but there's no point in using them.</p>\n\n<p>The drop in replacement is <a href=\"http://www.php.net/manual/en/intro.mysqli.php\" rel=\"nofollow noreferrer\">myslqi_* functions</a>, which are based around a newer MySQL driver that works better with MySQL 5.x. You can easily replace most references to myslq_* functions by just adding the extra <strong>i</strong>. </p>\n\n<p>But a far better solution is <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a>, an object oriented database agnostic interface. Since you are starting out in object oriented PHP you'll definitely appreciate the object orient part, and as for the database agnostic part, it means that you can easily switch databases (with minor modifications).</p>\n\n<p>I would advise against an <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM solution</a> at this point, ORM's are extremely useful but can be easily abused if you aren't 100% certain on what you are doing.</p>\n\n<p><strong>global $db;</strong></p>\n\n<p>Never ever do that again. Forget about the <code>global</code> keyword completely. It has its uses, but in most situations it's an extremely bad habit. The object oriented way to achieve the same effect would be: </p>\n\n<pre><code>class Student {\n private $db;\n\n public function __construct($db, $user_id) {\n $this->db = $db;\n\n ... \n }\n}\n</code></pre>\n\n<p>That's a minor example of <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a>. In sort, you should feed your object what it needs, and not depend on something being available in the global namespace. You can't always be absolutely sure of that.</p>\n\n<p><strong>Public properties</strong></p>\n\n<p>Public properties violate the object oriented concept of <a href=\"http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29\" rel=\"nofollow noreferrer\">encapsulation</a>. You really don't want to do that, trust me :)</p>\n\n<p>The most common object oriented workaround are setters and getters: </p>\n\n<pre><code>class Student {\n private $user_id;\n private $name;\n\n ...\n\n public function setUserID($user_id) {\n if( !is_int($user_id) ) {\n throw new InvalidArgumentException();\n }\n\n $this->user_id = $user_id;\n\n return $this;\n }\n\n public function setName($name) {\n if( !is_string($name) ) {\n throw new InvalidArgumentException();\n }\n\n $this->name = $name;\n\n return $this;\n } \n\n public function getUserID() {\n return $this->user_id;\n }\n\n public function getName() {\n return $this->name;\n }\n\n ...\n\n}\n</code></pre>\n\n<p>Wow! So much more code for such a simple thing! Before you get discouraged, notice that I also validate the input on the setters and I'm throwing <a href=\"http://php.net/manual/en/language.exceptions.php\" rel=\"nofollow noreferrer\">exceptions</a> if something is wrong. That's a very good reason to use setters instead of public properties, that way you have the ability of checking what the parameter is, and if it's not the one you are expecting you can deal with it accordingly. </p>\n\n<p>In the instances above I'm throwing an <a href=\"http://www.php.net/manual/en/class.invalidargumentexception.php\" rel=\"nofollow noreferrer\">InvalidArgumentException</a>, which is one of the many <a href=\"http://www.php.net/manual/en/spl.exceptions.php\" rel=\"nofollow noreferrer\">pre-built SPL extensions</a>. Learn about the <a href=\"http://www.php.net/manual/en/book.spl.php\" rel=\"nofollow noreferrer\">SPL</a>, it offers quite a few core object oriented interfaces and classes, such as <a href=\"http://www.php.net/manual/en/spl.iterators.php\" rel=\"nofollow noreferrer\">iterators</a>. </p>\n\n<p>A far better way to validate common datatypes is the <a href=\"http://www.php.net/manual/en/book.filter.php\" rel=\"nofollow noreferrer\">filter functions</a>, I'm not using them in the example above to not confuse you any further. And, when you feel confident enough, you can minimize the code via magic <a href=\"http://php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow noreferrer\">Property overloading</a>. Fair warning, don't go there unless you know exactly what you're doing. </p>\n\n<p>But never ever again have public properties, always write getters and setters. And of course, the <code>$db</code> property from my previous example should have its own setter. No need for a getter, unless of course you actually need to pass around the database connection object.</p>\n\n<p>Lastly, notice how I return <code>$this</code> on the setters? This isn't something you have to do, it's a trick to allow <a href=\"https://stackoverflow.com/questions/3724112/php-method-chaining\">method chaining</a>: </p>\n\n<pre><code>$student = new Student( ... );\n$student->setUserID(1)->setName(\"Yannis\");\n</code></pre>\n\n<p>Or, if you prefer a slightly more readable version:</p>\n\n<pre><code>$student->setUserID(1)\n ->setName(\"Yannis\"); \n</code></pre>\n\n<p><strong>Naming</strong></p>\n\n<p>As @jiewmeng writes, <code>studentInfo</code> should be renamed <code>getStudentInfo</code>. You should be very consistent on how you name functions, prefixing functions that return results with <code>get</code> and those that set info in the class with <code>set</code> is a very common practice, and one that will be familiar to most programmers, as it alludes to the concept of getters and setters I've described above.</p>\n\n<p><strong>Always return something</strong></p>\n\n<p>I don't really like it when functions don't return something:</p>\n\n<pre><code>public function studentInfo($id) {\n global $db;\n\n $u = mysql_fetch_array(mysql_query(\"SELECT * FROM $db[students] WHERE id='$id'\"));\n if($u) {\n return $u;\n }\n} \n</code></pre>\n\n<p>Here, of course you <code>return $u;</code>, but only <code>if($u)</code>. For that function, I would probably return <code>false</code> as well:</p>\n\n<pre><code>public function studentInfo($id) {\n global $db;\n\n $u = mysql_fetch_array(mysql_query(\"SELECT * FROM $db[students] WHERE id='$id'\"));\n if($u) {\n return $u;\n }\n\n return false;\n} \n</code></pre>\n\n<p>Of course <code>null</code> is returned by default when you don't return something explicitly, but I find it a lot better when I know exactly what I should expect from a function return, and <code>false</code> will tell me that something failed long after I totally forget what goes on in the function. If you are in a situation where you can't think of something obvious to return, that might be a good place to throw an exception instead.</p>\n\n<p><strong>Adding a student</strong></p>\n\n<p>You could do a <code>save()</code> function: </p>\n\n<pre><code>class Student {\n\n ...\n\n public function save() {\n if(!this->validate()) {\n return false; \n }\n\n return $this->store(); \n }\n\n private function validate() {\n // check all properties\n // if the required ones are filled and valid, return true,\n // else return false\n }\n\n private function store() {\n if($this->userExists()) {\n return $this->insert();\n }\n\n return $this->update();\n }\n\n private function userExists() {\n // determine if user already exists in the database\n }\n\n private function insert() {\n // insert user in the database\n }\n\n private function update() {\n // update existing user\n } \n\n ... \n}\n</code></pre>\n\n<p>Of course that's more pseudo code, than code. But more or less, that's the common workflow. I'm assuming each function returns either <code>true</code> or <code>false</code>. Notice how the return value propagates from <code>insert()</code> or <code>update()</code> to <code>save()</code>?</p>\n\n<p><strong>In conclusion</strong></p>\n\n<p>You need to do a lot of research into the fundamental object orient concepts. The <a href=\"http://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">wikipedia article</a> is as a good place to start as any, and most articles on the specific concepts have PHP examples. Your code is clean, and you do quite a few things correctly, but you are starting out in a new programming paradigm, one that is extremely useful and extremely vague. More often than not \"best practices\" are not obvious, and you'll need quite solid conceptual foundations to write object oriented code.</p>\n\n<p>And please, consider writing <a href=\"http://www.google.gr/url?sa=t&rct=j&q=phpdoc&source=web&cd=2&ved=0CDUQFjAB&url=http://www.phpdoc.org/tutorial.php&ei=tAD_TpqQBdCM4gSHwuQe&usg=AFQjCNG5KtCfGxDBBKcj2ensgvsERBAtxg&sig2=6E0Xt8O-xvy0_qI7YUlS4w&cad=rja\" rel=\"nofollow noreferrer\">phpDoc comments</a>. </p>\n\n<p>Happy new year!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T15:29:33.963",
"Id": "11495",
"Score": "0",
"body": "-1 spoon-feeding [/proactive comment]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T12:28:56.367",
"Id": "7337",
"ParentId": "7331",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "7337",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T01:01:44.387",
"Id": "7331",
"Score": "4",
"Tags": [
"php",
"object-oriented"
],
"Title": "What would be a better way of adding the functionality to \"add\" a student?"
}
|
7331
|
<p><strong>Background</strong>:</p>
<p>I'm a member of my high school's robotics club (and in charge of the
programming team). The robot is going to be written in C++, but I'm mostly
a Python coder and want to make sure I don't have any fundamental gaps in my
knowledge.</p>
<p>In preparation for the start of the competition in just a few days, I've
quickly written up the bare minimum required for a robot to drive around
(included below). I was hoping to get feedback and criticism at this stage
to nip any problems/misconceptions I have before they get serious.</p>
<p>As previously stated, I'm unfamiliar with C++ so don't know many of its best
practices/idioms/etc. What I'm looking for is a bit vague, but in essence,
<strong>how can I make my code more professional/better? Am I making any errors?</strong></p>
<p>Any feedback would be welcome.</p>
<p>There are three files:</p>
<ul>
<li>MainRobot.h</li>
<li>MainRobot.cpp</li>
<li>typedefs.h</li>
</ul>
<p><strong>MainRobot.h</strong></p>
<pre><code>#ifndef MAINROBOT_H_
#define MAINROBOT_H_
// 3rd-party modules
#include "WPILib.h"
// Modules created by us
#include "typedefs.h"
class MainRobot : public SimpleRobot
{
public:
// Required methods (for robot to run)
MainRobot(void);
void Autonomous(void);
void OperatorControl(void);
// Objects (provided by WPILib.h)
RobotDrive robotDrive;
Joystick *leftStick;
Joystick *rightStick;
Timer timer;
// Motor ports (hardware)
static const UINT32 kLeftFrontMotor = kPWMPort_1;
static const UINT32 kRightFrontMotor = kPWMPort_2;
static const UINT32 kLeftBackMotor = kPWMPort_3;
static const UINT32 kRightBackMotor = kPWMPort_4;
// Joystick ports (hardware)
static const UINT32 kRightJoystickPort = kUSBPort_1;
static const UINT32 kLeftJoystickPort = kUSBPort_2;
// Delay to prevent spamming motors with input
static const float kDelayValue = 0.01;
};
#endif /*MAINROBOT_H_*/
</code></pre>
<p><strong>MainRobot.cpp</strong></p>
<pre><code>#include "MainRobot.h"
/**
* The constructor.
*
* Initializes the motors, drivetrain, joysticks, safety devices, etc.
*/
MainRobot::MainRobot(void):
robotDrive(kLeftFrontMotor,
kRightFrontMotor,
kLeftBackMotor,
kRightBackMotor)
{
MainRobot::GetWatchdog().SetExpiration(0.1); // In seconds
MainRobot::leftStick = new Joystick(kLeftJoystickPort);
MainRobot::rightStick = new Joystick(kRightJoystickPort);
return;
}
/**
* Initializes the autonomous period when called
* (robot performs a task without human intervention)
*
* Currently left blank.
*/
void MainRobot::Autonomous(void) {
while(MainRobot::IsAutonomous()) {
MainRobot::GetWatchdog().Feed();
Wait(kDelayValue);
// Do nothing.
}
return;
}
/**
* Initializes the teleoperated period when called.
* (robot is driven by humans using two joysticks)
*/
void MainRobot::OperatorControl(void) {
MainRobot::GetWatchdog().SetEnabled(true);
MainRobot::timer.Reset();
MainRobot::timer.Start();
while(MainRobot::IsOperatorControl()) {
MainRobot::robotDrive.TankDrive(MainRobot::leftStick,
MainRobot::rightStick);
MainRobot::GetWatchdog().Feed();
Wait(kDelayValue);
}
return;
}
</code></pre>
<p><strong>typedefs.h</strong></p>
<pre><code>#ifndef TYPE_DEFS_H_
#define TYPE_DEFS_H_
// The available ports for any motors
typedef enum {
kPWMPort_1 = 1,
kPWMPort_2 = 2,
kPWMPort_3 = 3,
kPWMPort_4 = 4,
kPWMPort_5 = 5,
kPWMPort_6 = 6,
kPWMPort_7 = 7,
kPWMPort_8 = 8,
kPWMPort_9 = 9,
kPWMPort_10 = 10
} PWMPorts;
// The available ports for USB drives (for joysticks, etc)
typedef enum {
kUSBPort_1 = 1,
kUSBPort_2 = 2,
kUSBPort_3 = 3,
kUSBPort_4 = 4
} USBPorts;
#endif
</code></pre>
|
[] |
[
{
"body": "<p>Do you plan to replace the Joystick object?</p>\n\n<pre><code>Joystick *leftStick;\nJoystick *rightStick;\n</code></pre>\n\n<p>If not then declare them as</p>\n\n<pre><code>Joystick leftStick;\nJoystick rightStick;\n</code></pre>\n\n<p>If you are going to replace them then you should be using smart pointers rather than a RAW pointer (if you want to do it manually then learn the rule of three) But I would go with smart pointers (but that is a second option to normal objects).</p>\n\n<p>If you must have pointer use smart pointers:</p>\n\n<pre><code>std::unique_ptr<Joystick> leftStick;\nstd::unique_ptr<Joystick> rightStick;\n</code></pre>\n\n<p>There is no need declare these as static (unless you want to get the address or something) so just use enum:</p>\n\n<pre><code>// Motor ports (hardware)\nstatic const UINT32 kLeftFrontMotor = kPWMPort_1;\nstatic const UINT32 kRightFrontMotor = kPWMPort_2;\nstatic const UINT32 kLeftBackMotor = kPWMPort_3;\nstatic const UINT32 kRightBackMotor = kPWMPort_4;\n</code></pre>\n\n<p>Prefer:</p>\n\n<pre><code>enum { kLeftFrontMotor = kPWMPort_1, kRightFrontMotor = kPWMPort_2, kLeftBackMotor = kPWMPort_3, kRightBackMotor = kPWMPort_4};\n</code></pre>\n\n<p>No need to explicitly return from a constructor:</p>\n\n<pre><code>MainRobot::MainRobot(void)\n{\n ...\n\n return; // No need\n}\n</code></pre>\n\n<p>There is nothing wrong with prefixing functions with the class name but personally I would not.</p>\n\n<pre><code>while(MainRobot::IsAutonomous()) {\n MainRobot::GetWatchdog().Feed();\n Wait(kDelayValue);\n // Do nothing.\n}\n</code></pre>\n\n<p>Easier to write:</p>\n\n<pre><code>while(IsAutonomous())\n{\n GetWatchdog().Feed();\n Wait(kDelayValue);\n // Do nothing.\n}\n</code></pre>\n\n<p>The file name \"typedefs.h\" is relatively common. You may want to avoid it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T07:30:51.780",
"Id": "7335",
"ParentId": "7334",
"Score": "2"
}
},
{
"body": "<p>If this is C++, you do not need to typedef enums; <code>enum USBPorts { /* values */ };</code> will do. There's also no need to place <code>return;</code> at the end of a function that returns <code>void</code>, or <code>void</code> in the parameter list of functions that take no parameters.</p>\n\n<p>As Loki Astari remarked, you should not <code>new</code> the joysticks unless you have a good reason to; even if you do, though, and don't use smart pointers, you should make a destructor that deletes the two pointers, and should either implement or make private the copy-constructor and assignment operator.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:55:28.353",
"Id": "7367",
"ParentId": "7334",
"Score": "1"
}
},
{
"body": "<p>It's better style, whenever possible, to initialize members like leftStick and rightStick in the constructor's comma-separated initializer list before the body of the constructor vs. assigning inside the constructor.</p>\n\n<p>If you decide to switch to Joystick objects rather than Joystick pointers, this may be anywhere from slightly more efficient to the only legal option, depending on what Joystick defines for constructor(s) and operators. </p>\n\n<p>If you do make that change, I don't know how your compiler will express it's requirement for pointers in the call to:</p>\n\n<pre><code> robotDrive.TankDrive(&leftStick, &rightStick);\n</code></pre>\n\n<p>but it will almost certainly complain somehow, and the syntax shown here will be what it wants.</p>\n\n<p>And, yes, really, you don't want to habitually use prefixes like 'MainRobot::'. \nSuch prefixing is usually optional and meaningless, except in a few cases:</p>\n\n<ul>\n<li><p>It associates member definitions (usually functions, but sometimes static data members) with their defining class, so you have to use it there. This is the only one of these cases that applies to your code above.</p></li>\n<li><p>When a class is being used as a namespace-like container for types and enums and statics AND these definitions need to be referenced from OUTSIDE the class' methods, they must be prefixed like this.</p></li>\n<li><p>Important! when such a prefix is applied to an object method (virtual member function) call, it means \"call the method non-virtually\" which is not what you normally want or expect. This is normally used to \"chain up\" from a member function refinement to its counterpart in a base class -- rather than infinitely recurse. Python has a similar idiom for this: </p>\n\n<pre><code>BaseClassName.methodname(self, arguments) \n</code></pre></li>\n</ul>\n\n<p>to make a non-virtual call to the specified class' implementation in place of the normal virtual-by-default-because-it's-Python syntax:</p>\n\n<pre><code> self.methodname(arguments)\n</code></pre>\n\n<p>Finally, you might want to take better advantage of the implementation hiding features of C++. </p>\n\n<p>I was planning to advise you to declare \"private:\" as much of your class content as possible, but I've reconsidered. I think that the best way to hide the implementation details of the MainRobot class may be to move as much of the class content as possible into the .cpp file. You might be able to move the whole class and eliminate the .h file.</p>\n\n<p>At a minimum, I don't see any benefit (though you might be able to anticipate benefits as your implementation grows) for the static class members (or enums) to be defined inside the class vs. module-scoped static non-class-members at the top of the MainRobot.cpp -- unless they are needed in other .cpp files.</p>\n\n<p>There must be some entry point that creates one or more MainRobot objects, and the details of how this works is likely to have been determined by the WPILib / SimpleRobot framework providers -- do you get to define \"main\" or some special initialization callback function? If you can implement any such hooks within MainRobot.cpp, there may not be sufficient justification for a separate header file. If you need to implement helper objects for MainRobot, it may make more sense to have MainRobot call out to them through the methods in THEIR header files rather than have them call into MainRobot. There's an attractive aspect to having each of them focus on a slice of the problem and not need visibility to the \"bigger picture\" represented by MainRobot.</p>\n\n<p>Once you move a class completely into its .cpp file, so long as you reasonably limit\nthe content of that .cpp file to class members and possibly a minimal \"main\" function,\nthere's not a lot of point to the public/private distinction -- the callers are restricted by the strictly local scope of the class definition.</p>\n\n<p>If this is too radical, then certainly fall back to using \"private:\" with as many class members as you can -- any that aren't needed by the MainRobot creation code path or by MainRobot helper objects.</p>\n\n<p>The desire to have a MainRobot-based class hierarchy would be another reason to keep the .h separate. In that case, you might want to use \"protected\" instead of private but only for the minimum content that the derived classes need to call directly. You should still consider hiding as much implementation detail as possible in the .cpp</p>\n\n<p>You might consider using protected or private inheritance depending on whether anything outside of MainRobot needs to know that a MainRobot is a SimpleRobot. That's a useful idiom if not a very popular one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T12:46:20.023",
"Id": "7414",
"ParentId": "7334",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7335",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T06:50:22.833",
"Id": "7334",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Allowing a robot to drive around"
}
|
7334
|
<p>Some code im working with for a stock system , i have two ways to do this, looking for review on if any of them are correct and if so which one is better OO than the other</p>
<pre><code>public interface Order {
public void processed(AllocationResponse response);
}
</code></pre>
<p>the two solutions i have in my head are</p>
<pre><code>public class Warehouse {
public void allocate(Order order){
AllocationResponse response = calculateAllocation(order.getQuantity());
order.processed(response)
}
private AllocationResponse calculateAllocation(int quantity){
// code
}
}
public class AllocationResponse {
int quantityAllocated = 0;
int quantityBackOrdered = 0;
}
Order order = // get order
new Warehouse().allocate(order)
</code></pre>
<p>or</p>
<pre><code>public class Warehouse {
public AllocationResponse allocate(int quantity){
return calculateAllocation(quantity);
}
private AllocationResponse calculateAllocation(int quantity){
// code to generate response object
}
}
Order order = // get order
AllocationResponse response = new Warehouse().allocate(order.getQuantity());
order.processed(response)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T09:03:42.563",
"Id": "11477",
"Score": "0",
"body": "please add a tag to show us what language you are using - C#? Java?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T09:12:46.783",
"Id": "11478",
"Score": "2",
"body": "\"If you *think* you understand quantum mechanics, you *don't* understand quantum mechanics.\" --Richard Feynman."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T09:24:02.500",
"Id": "11480",
"Score": "0",
"body": "@Mike did I miss something? The language wasn't obvious to me after looking at the code... although the use of camelCase can count as a hint.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T10:33:09.313",
"Id": "11481",
"Score": "1",
"body": "@codesparkle my comment was not referring to you. It was just a humorous (albeit mischievous) remark for the OP. When you do OOP right, you know that you are doing it right. If you are wondering whether you are doing it right, most probably you are not doing it right. This can usually be said without looking at the code. In any case, the code included in the post is not enough to be able to tell. What we actually need is a diagram of the design, not a listing of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T17:24:41.103",
"Id": "11496",
"Score": "0",
"body": "Impossible to answer with the information given. Creating a new warehouse is a little weird, though, if a \"warehouse\" is supposed to represent an actual warehouse. Unless you build a lot of warehouses."
}
] |
[
{
"body": "<p>A partial answer to the partial question (with no partiality to C#, Java, or quantum mechanics):</p>\n\n<p>The invariants:</p>\n\n<ul>\n<li><p>Some unnamed caller needs to effectively call:</p>\n\n<pre><code>order.processed(warehouse.calculateAllocation(order.getQuantity()));\n</code></pre>\n\n<p>where calculateAllocation is private (so, presumably invisible to the caller).</p></li>\n</ul>\n\n<p>[So, let's imagine the int getQuantity() method in the Order interface.]</p>\n\n<ul>\n<li><p>The Warehouse implementation depends on AllocationResponse.</p></li>\n<li><p>The unnamed caller must minimally depend on the existence of Order and Warehouse and needs some way to call calculateAllocation \"for an order\".</p></li>\n</ul>\n\n<p>Comparison of the variants:</p>\n\n<p>Option 1 pros: </p>\n\n<ul>\n<li>The unnamed caller has no further dependencies beyond the above minimum.</li>\n</ul>\n\n<p>Option 1 cons: </p>\n\n<ul>\n<li>Warehouse now depends on Order, Order.getQuantity and Order.processed.</li>\n</ul>\n\n<p>Option 2 pros: </p>\n\n<ul>\n<li>Warehouse has no further dependencies.</li>\n</ul>\n\n<p>Option 2 cons: </p>\n\n<ul>\n<li><p>calculateAllocation is now completely exposed to abusive calling (via allocate) with not so much as an Order in sight. They might as well be one public function. Yet calculateAllocation was likely defined private for good reason -- otherwise:</p>\n\n<pre><code>order.processed(new Warehouse().calculateAllocation(order.getQuantity()));\n</code></pre>\n\n<p>would have been Option 0.</p></li>\n<li><p>The unnamed caller now depends on Order.getQuantity, Order.processed, and AllocationResponse. </p></li>\n</ul>\n\n<p>Note: The dependency on AllocationResponse could be reduced (at least in one sense) at some cost of readability (you judge?) and unique line numbers for breakpoints (typically just where and when you need one) with:</p>\n\n<pre><code> order.processed(new Warehouse().allocate(order.getQuantity()))\n</code></pre>\n\n<p>Now, those are just the apparent trade-offs, but they may well be outweighed by how these design options fit in with other present and foreseeable code.</p>\n\n<p>For example,</p>\n\n<p>Option 1 would be more favorable in a wider system that might:</p>\n\n<ul>\n<li><p>define Warehouse-based classes that specifically refine the behavior of allocate(order),\npossibly with no change or a different change to calculateAllocation(int). That is, refining allocate(order) SOLELY indirectly by refining calculateAllocation(int) would be the same deal between Options 1 and 2.</p></li>\n<li><p>have many different callers of the exact same idiom:</p>\n\n<pre><code>warehouse.allocate(order)\n</code></pre></li>\n<li><p>require other exposure to Order, Order.getQuantity and Order.processed in the Warehouse module (helping to justify/amortize the dependency cost).</p></li>\n</ul>\n\n<p>Option 2 would be more favorable in a wider system that might:</p>\n\n<ul>\n<li><p>require or desire other exposure to Order.getQuantity and Order.processed, and possibly AllocationResponse in the unnamed caller (to justify/amortize the dependency cost) other than just using the idiom:</p>\n\n<pre><code>order.processed(warehouse.allocate(order.getQuantity()))\n</code></pre></li>\n</ul>\n\n<p>Repeated use of this idiom would argue for giving it its own method -- under Option 2, a local method of the unnamed caller, so that would be pretty much the same deal between Options 1 and 2. </p>\n\n<p>In some \"binary\" sense, the Order interface is already imported by the unnamed caller, so the exposure to the methods is implicitly already there \"for free\" or more like \"for better or worse\". Here \"binary\" has BOTH its meanings of \"either on or off\" and \"down to the compiled bits\". This \"binary\" distinction is important when designing interfaces for libraries intended for public consumption \"to be supported forever\". But in a subtler practical sense, for an interface that's only used experimentally or in a small \"in house\" code base, isolating function calls to a small fraction of even the modules that import the interface can make it considerably less painful to \"break the contract\" later by evolving those functions. In this sense, calls to each distinct Order method from the unnamed caller is a \"deeper\" dependency than merely importing the Order interface.</p>\n\n<ul>\n<li>require or desire other exposure to calculateAllocation/allocate(int) outside Warehouse. That seems unlikely. Otherwise, calculateAllocation would not have been declared private, or it would have been changed to public as a knee-jerk Option 0 solution as soon as this design problem arose, with none the wiser -- now THAT's what I'd call \"doing it all wrong\".</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T02:39:55.037",
"Id": "7350",
"ParentId": "7336",
"Score": "3"
}
},
{
"body": "<p>My preference:</p>\n\n<pre><code>public class Warehouse {\n\n public void allocate(int quantity){\n // code\n }\n}\n\npublic class Order {\n\n public void process(Warehouse warehouse)\n {\n processed(warehouse.allocate(getQuantity());\n }\n}\n</code></pre>\n\n<p>Basically, you need to call:</p>\n\n<pre><code>order.processed(warehouse.allocate(order.getQuantity()))\n</code></pre>\n\n<p>I suggest that this belong in order. </p>\n\n<p>Why?</p>\n\n<ol>\n<li>Tell Don't Ask: It is preferable to ask Order to process rather then extracting the information and then processing it somewhere else</li>\n<li>Coupling: Two of the three calls are to order. This suggests that the code is coupled to order and probably belongs in Order.</li>\n<li>Minimize interface: The processed and getQuantity() functions become internal to Order (as long as they aren't used elsewhere), thereby simplifying the interface of those objects.</li>\n</ol>\n\n<p>Possible issues:</p>\n\n<ol>\n<li>Order may already be too complicated, adding <code>process(Wharehouse)</code> may bloat that. I'd suggest that is probably a better way to split that code.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T05:26:07.223",
"Id": "7351",
"ParentId": "7336",
"Score": "0"
}
},
{
"body": "<p>Both methods look too convoluted.</p>\n\n<p>I guess that your problem is that the warehouse sometimes miss some capacity to fulfill the full order and can only partially fill the order.</p>\n\n<p>I would decouple your code:</p>\n\n<p>I guess you have the clients calling a <code>submit(order)</code> method somewhere, but you should have them check the capacity first, e.g. <code>wareHouse.checkCapacity()</code> (and maybe obtain a lock on some specified capacity if many clients are placing orders concurrently). It's important that your interface should let the clients know what is going on instead of just returning a partial order. The client code should decide what to do when there is not enough capacity; in both your solutions it's a mismatch between the warehouse and the order.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T18:49:12.797",
"Id": "7360",
"ParentId": "7336",
"Score": "0"
}
},
{
"body": "<p>I love being downvoted :) There is no correct OO design for this problem. The problem cannot fit into the OO structure because it involves relationships. It isn't possible to have two abstractions such as \"warehouse\" and \"order\" interact by a method such as \"place\" (which places an order on a particular warehouse). This is proven so don't waste your time arguing. The issue is known as the \"covariance problem\".</p>\n\n<p>To solve this problem properly you must de-abstract one of the entities: either the warehouse or orders must become invariant (fixed data types). You can still use information hiding but you cannot derive new instances.</p>\n\n<p>In this kind of problem in the real world BOTH concepts would always be de-abstracted.</p>\n\n<p>The classical solution, and the most commonly used, is known as a relational database. Here all the data structures are tables of concrete data.</p>\n\n<p>That is the correct solution. Throw out the OO. It's useless here: a whole lot of mumbo jumbo religious garbage. Just use plain old data structures and the program will be done in one tenth the time, it will work, it will be easy to maintain, and it will operate quickly.</p>\n\n<p>I hope it's clear: you've been lied to in School by a bunch of pseudo academics that don't know any theory and try to teach ideas that theoreticians threw out two decades ago. If you want to learn about abstraction and good programming, learn a language like Ocaml or Haskell designed by people with a good knowledge of the mathematics underlying it, not someone that could barely design a toaster that works.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T06:32:49.323",
"Id": "7907",
"ParentId": "7336",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T08:48:26.040",
"Id": "7336",
"Score": "2",
"Tags": [
"java",
"object-oriented"
],
"Title": "looking for OO input , is any of this code good OO or am i doing it all wrong?"
}
|
7336
|
<p>I have applied some optimizations like storing only odd values
and starting to mark off from square of the number.</p>
<p>Can it be optimized further?</p>
<pre><code>bool * isPrime = new bool [n/2];
for (int i=0; i < n/2; ++i)
isPrime [i] = true;
cout<< 2 << "\n";
for (int i = 3; i < n; i += 2) {
if (isPrime [i / 2]) {
cout<< i << "\n";
for (int j = i * i; j < n; j += 2 * i)
isPrime [j / 2] = false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T13:10:09.580",
"Id": "11514",
"Score": "0",
"body": "You can get less memory usage (one bit per bool) by using `std::vector<bool>`. Possibly downside, indexing is a bit harder. But in any case a `vector<char>` would be better over dynamically allocating an array of bools."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T15:20:51.300",
"Id": "11568",
"Score": "0",
"body": "why is vector better than array of bools..what is the need for dynamic array like vector"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-06T21:58:58.673",
"Id": "36330",
"Score": "0",
"body": "Because the C++ language says vector<bool> is specialized to only use one bit per bool. That is probably the worst idea in the standard, if you ask me - it means a[0] cannot be a bool&."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T16:54:25.670",
"Id": "283248",
"Score": "0",
"body": "It's always good to [test a hypothesis](http://codereview.stackexchange.com/questions/117880/comparing-stdvectorbool-to-stdvectorchar) regarding the relative performance of code in C++."
}
] |
[
{
"body": "<p>Before starting to optimize, a few questions to be asked :</p>\n\n<ul>\n<li>does you code compile ? (I find the way you use isPrime pretty weird)</li>\n<li>is your code working properly ? (I think the initialization of isPrime with \"false\" is wrong)</li>\n</ul>\n\n<p>And then, once you have a yes for the 2 previous questions, you can ask yourself :</p>\n\n<ul>\n<li>why do I want to optimize ?</li>\n<li>what do I want to optimize ?</li>\n</ul>\n\n<p>And finally, once the code changed :</p>\n\n<ul>\n<li>do I have a way to test that my code is still working ?</li>\n<li>do I have a way to see if the code is actually working better than it used to be ? </li>\n</ul>\n\n<blockquote>\n <p>\"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil\" from Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268. <a href=\"http://en.wikipedia.org/wiki/Program_optimization\" rel=\"nofollow\">From wikipedia</a></p>\n</blockquote>\n\n<p>Anyway, a few details : </p>\n\n<ul>\n<li>First detail I noticed : it seems like the first element of isPrime is never used (it's initialised but never read).</li>\n<li>Also, I am not really sure about the actual implementation of arrays of booleans but it might be interesting to have a look at bitfields to do what you are trying to do (depending on what you want to optimize).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T15:15:39.340",
"Id": "11491",
"Score": "0",
"body": "I have updated the question. Yes, i think i am trying to optimize the memory space here. I have left first element unused to save additional computations to arrive at the correct index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T15:18:25.140",
"Id": "11492",
"Score": "0",
"body": "At first glance, the code seems better now :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T15:21:50.563",
"Id": "11493",
"Score": "0",
"body": "Actually, the loop \"for (int i = 3; i < n; ++i) {\" is still weird. Don't you want to do \"i+=2\" instead of \"i++\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T15:24:43.117",
"Id": "11494",
"Score": "0",
"body": "oops again! i wrote correct but typed wrong"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T13:05:19.783",
"Id": "11513",
"Score": "0",
"body": "The question is obviously about *algorithmic* optimizations and finding primes can never be too fast, so that questioning the question seems a bit out of place."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T14:43:33.280",
"Id": "7339",
"ParentId": "7338",
"Score": "5"
}
},
{
"body": "<p>You can go further by not processing multiples of 3 together with multiples of 2 (even numbers, which you already not process). For stepping on numbers not multiple of 2 and 3, you should take steps of size 2 and 4 alternatively. 5 (+2) 7 (+4) 11 (+2) 13 (+4) 17 ...</p>\n\n<p>This way you will also save space (from <code>n/2</code> to <code>n/3</code>). You can change your loops like below:</p>\n\n<pre><code>for (int i = 5, t = 2; i < n; i += t, t = 6 - t) {\n\n if (isPrime [i / 3]) {\n\n cout<< i << \"\\n\";\n\n for (int j = i * i, v = t; j < n; j += v * i, v = 6 - v)\n isPrime [j / 3] = false; \n }\n}\n</code></pre>\n\n<p>a little hint is that if don't want to print the prime numbers and want just to generate <code>isPrime</code> array, you can change your outer loop condition to <code>i*i<n</code>, because composite numbers are turned to false by their factor less than their square root.</p>\n\n<p>Another good optimization is that you can use a single bit for storing <code>isPrime</code> flag of each number. This way you can save space by a factor of <code>1/8</code>, and what is great about this method is that you are increasing your locality of reference and your code will use cache better (when I first wrote sieve by this optimization, amazingly I achieved about 20% speed improvement).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T09:38:57.270",
"Id": "32338",
"Score": "0",
"body": "I guess a link to the [wheel factorization](http://en.wikipedia.org/wiki/Wheel_factorization) which is looks like this algorithm comes from might be handy. You can go further and make wheel bigger than `6`, but you'll have to store your sectors sequence in a general form rather than `+2, +4, +2...`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T17:54:17.623",
"Id": "7342",
"ParentId": "7338",
"Score": "9"
}
},
{
"body": "<p>The algorithm hinges on tracking the effect of each \"prime less than i\" on each \"odd value less than n\" as i ranges to n.</p>\n\n<p>The current implementation tracks this effect per \"odd value less than n\", suggesting a required peak memory footprint of n/2 bits.</p>\n\n<p>An alternative whose memory use scales better is to track the effect per \"prime less than i\" (as i ranges up to n), which requires more storage (like sizeof(n)) per entry but for fewer entries by far, especially for larger values of n. In other words, there's less to remember when you determine the effect of prior primes (all at once) on each odd number (taken one at a time).</p>\n\n<p>Edited to add requested detail:</p>\n\n<p>To 100% sacrifice cpu for memory, preallocate or \"grow\" an int vector for primes (p) from 3 to sqrt(n).</p>\n\n<pre><code> for each i from 3 to n,\n for each p so far,\n if (i % p == 0) break;\n if (i % p == 0) continue;\n print i \n if i <= sqrt(n) add i as next p\n\n// The vector of all PRIMEs <= sqrt(n) can be small, for respectable-sized n.\n// That's < 60 elements (bytes or shorts) for n < 2^16, \n// and < 7000 elements (shorts or ints) for n < 2^32, \n\n// That beats n/16 bytes.\n\n// SO for speed, use a vector of p,m (prime,multiple) int pairs:\n\n for each i from 3 to n,\n for each p,m entry so far,\n if (i>m) m=((i/p)+1)*p; // m is lowest multiple of p >= i\n if (i==m) break;\n if (i==m) continue;\n print i\n if i <= sqrt(n) add i,3*i as next p,m\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T19:01:45.917",
"Id": "11500",
"Score": "0",
"body": "can you explain it in detail..i understand that you want to store result in an integer instead of bool"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T18:45:56.397",
"Id": "7343",
"ParentId": "7338",
"Score": "0"
}
},
{
"body": "<p>You can optimize the initialization of the array:</p>\n\n<pre><code>bool * isPrime = new bool [n/2]; // Array of random states\n\n// But\n\nbool * isPrime = new bool [n/2](); // Array of zero-initialized members\n // For bool this means initialization to false\n</code></pre>\n\n<p>If you inverse your logic (ie treat false as true and true as false)</p>\n\n<pre><code>// These two lines can be removed.\nfor (int i=0; i < n/2; ++i)\n isPrime [i] = true;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T19:02:09.457",
"Id": "11501",
"Score": "0",
"body": "yes, very nice hack"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T18:52:23.823",
"Id": "7344",
"ParentId": "7338",
"Score": "5"
}
},
{
"body": "<p>Initialize the boolean array to true, then from 2 to the square root of the upper bound, if the number is prime, eliminate all multiples of that number. </p>\n\n<p>So, start with 2... so 2*i should all be set to false. </p>\n\n<p>Then if 3 isPrime , do 3*i and set all of those to false. </p>\n\n<p>Continue up the the sqrt of the upper bound. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T04:19:39.387",
"Id": "283137",
"Score": "0",
"body": "This answer implies that the OP's code does not do these things, but the OP's code does do them.... and does them better than what's suggested here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T02:38:10.847",
"Id": "150460",
"ParentId": "7338",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7342",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T13:47:20.310",
"Id": "7338",
"Score": "8",
"Tags": [
"c++",
"optimization",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes optimization"
}
|
7338
|
<p>Being new to <code>Node.js</code>, I'd like to know of a better way of implementing this:</p>
<pre><code>server = http.createServer( function(req, res) {
if (req.url === '/') {
fs.readFile('index.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
else if (req.url == '/new.html') {
fs.readFile('new.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
});
server.listen(8080);
</code></pre>
<p>Using something like this:</p>
<pre><code>var Url = require('url')
...
// In request handler
var uri = Url.parse(req.url);
switch (uri.pathname) {
case "/":
..
case "/new.html":
..
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T17:33:26.297",
"Id": "11497",
"Score": "0",
"body": "Use a router like express."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T23:30:27.647",
"Id": "11503",
"Score": "1",
"body": "Other than using a framework..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T10:48:38.290",
"Id": "11512",
"Score": "0",
"body": "If you want static routing you can write a naive static router"
}
] |
[
{
"body": "<p>Whether you wanna implement a static server?\nIf so, you can just use <a href=\"http://senchalabs.github.com/connect/\" rel=\"nofollow\">connect</a> and its built-in <em>static</em> middlewave. With it, you just need to write the following code to implement a static server:</p>\n\n<pre><code>var connect = require(\"connect\");\n\nconnect(\n connect.static(__dirname)\n).listen(3000);\n</code></pre>\n\n<p>That's it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T07:07:02.050",
"Id": "7522",
"ParentId": "7341",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7522",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T16:57:00.497",
"Id": "7341",
"Score": "2",
"Tags": [
"javascript",
"node.js"
],
"Title": "How can I improve this Node.js file's routing?"
}
|
7341
|
<p>This code performs 301 redirects based on the taxonomy terms associated with the node, as 301 redirects can adversely effect page load time. How could this be best optimized?</p>
<pre><code> <?php
/**
* Implementation of hook_init().
*calling this hook causes the code below to execute before the page is loaded
*/
function region_filter_init() {}
//hook "nodeapi" is called when we are doing something to the node, in this "case" we are "viewing" the node.
function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
switch ($op) {
case 'view':
if( (arg(1) == 0)){ } //do not execute on homepage. if there are no aruments after the base url in arument one is thedelimagazine.com/argument1, if this is 0 then do nothing.
else {
$region = getRegion(); //get current region from deli.mmodule
$national = 'national'; //store string 'national' in variable
$count = count($node->taxonomy);//nstores number of key/value pairs in array, if two terms are selected with the node/post then count == 2
$terms = array();//initialize terms to array
foreach($node->taxonomy as $term) {
$terms[$term->name] = $term->name; //prints array of individual terms
}
/*case 1 new england*/
//if there are less than 9 terms and more than 2 and new england is in the array redirect to new england
if( $count < 9 && $count > 2 && in_array('newengland', $terms) && $region != 'newengland')
{
$link = 'http://newengland.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');
drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);
}
/*END case 1 new england*/
/*case 2*/
if($count == 2 && in_array('national', $terms) && is_numeric(arg(1))) { //if there are 2 terms in taxonomy && national is one of them & the first argument in url is a number such as thedelimagazine.com/12345 (before alias redirect)
unset($terms['national']); //remove national from array
$value = array_shift($terms) ;//set value to the other term left. in array
if($value == 'los angeles') {//fix for los angelas, because in deli module taxonomy term and subdomain are different only for los angeles
$value = 'la';
}
if($region != $value) { //if region does not already = term (would cause redirect loop)
$link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//go to term left in $value
drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);//drupal redirect function
}
}
/* ++ END case 2++*/
/* ++case 3 national+++*/
else {
if($count > 10 && in_array('national', $terms) && $region != 'national' ) { //if there are moer than 10 terms and national is in the array $terms, and the current region does not already =national
$link = 'http://national.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//then set $link to national.thedelimagazine.com. drupl get path alias gets the path to the node and node id and converts it to clean readable urls that i implemented last year.
drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301); //go to the $link
}
/* ++ END case 3 national++*/
}
}
break;
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code> function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {\n\n switch ($op) {\n\n case 'view':\n\n\n if( (arg(1) == 0)){ } //do not execute on homepage. if there are no aruments after the base url in arument one is thedelimagazine.com/argument1, if this is 0 then do nothing.\n</code></pre>\n\n<p>You get an extra pair of parens, and it would be easier to to check for <code>arg(1) ~= 0</code> rathern the have an empty if block.</p>\n\n<pre><code> else {\n\n $region = getRegion(); //get current region from deli.mmodule\n\n $national = 'national'; //store string 'national' in variable\n</code></pre>\n\n<p>Don't write dumb comments. Assume the reader understands PHP. Your comment should explain why you want to do that, not reiterate the code.</p>\n\n<pre><code> $count = count($node->taxonomy);//nstores number of key/value pairs in array, if two terms are selected with the node/post then count == 2\n\n $terms = array();//initialize terms to array\n foreach($node->taxonomy as $term) { \n $terms[$term->name] = $term->name; //prints array of individual terms\n\n\n\n\n }\n</code></pre>\n\n<p>That was a lot of pointless empty lines.</p>\n\n<pre><code> /*case 1 new england*/\n\n //if there are less than 9 terms and more than 2 and new england is in the array redirect to new england\n if( $count < 9 && $count > 2 && in_array('newengland', $terms) && $region != 'newengland')\n</code></pre>\n\n<p>Again, your comment simply tells me what I could have already gotton from the code. But I'm left thinking: WHAT? What's the deal with the number of terms? What am I checking in the array? What has <code>$region</code> got to do with it?</p>\n\n<pre><code> {\n $link = 'http://newengland.thedelimagazine.com/' . drupal_get_path_alias(\"node/$node->nid\", $path_language = '');\n drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);\n</code></pre>\n\n<p>Keep your indentation consistent.\n }\n /<em>END case 1 new england</em>/</p>\n\n<p>Don't put end comment like that. I can already see the case is ending thanks to the } and your indentation. </p>\n\n<pre><code> /*case 2*/\n if($count == 2 && in_array('national', $terms) && is_numeric(arg(1))) { //if there are 2 terms in taxonomy && national is one of them & the first argument in url is a number such as thedelimagazine.com/12345 (before alias redirect)\n</code></pre>\n\n<p>Again, don't repeat your code in the comments. Explain why your code is doing that.</p>\n\n<pre><code> unset($terms['national']); //remove national from array\n $value = array_shift($terms) ;//set value to the other term left. in array \n if($value == 'los angeles') {//fix for los angelas, because in deli module taxonomy term and subdomain are different only for los angeles\n</code></pre>\n\n<p>See those are the comments that are helpful, because it explains what so special about los agenles.</p>\n\n<pre><code> $value = 'la';\n } \n\n if($region != $value) { //if region does not already = term (would cause redirect loop)\n</code></pre>\n\n<p>Here I'd just say <code>// avoid redirect loop</code> </p>\n\n<pre><code> $link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias(\"node/$node->nid\", $path_language = '');//go to term left in $value\n\n drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);//drupal redirect function\n</code></pre>\n\n<p>This looks pretty much the same as the last case. You should refactor the code.\n }<br>\n }</p>\n\n<pre><code> /* ++ END case 2++*/\n\n\n /* ++case 3 national+++*/ \n else {\n\n if($count > 10 && in_array('national', $terms) && $region != 'national' ) { //if there are moer than 10 terms and national is in the array $terms, and the current region does not already =national \n $link = 'http://national.thedelimagazine.com/' . drupal_get_path_alias(\"node/$node->nid\", $path_language = '');//then set $link to national.thedelimagazine.com. drupl get path alias gets the path to the node and node id and converts it to clean readable urls that i implemented last year.\n drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301); //go to the $link\n }\n /* ++ END case 3 national++*/\n\n\n\n }\n }\n break;\n }\n }\n</code></pre>\n\n<p>It's been so long so I read the matching pieces of code that I have no idea what these pieces much up to. That a sign that your code is overly complicated.</p>\n\n<p>Here is a quick reworking of the code:</p>\n\n<pre><code><?php\n // return the region that the user should be on for this node\n function determine_region($node)\n {\n\n $taxonomy_count = count($node->taxonomy);\n\n // I doubt this is neccesary, I don't know what\n // $node->taxonomy is, but perhaps you can use that rather\n // then copying the data into an array.\n $terms = array();\n foreach($node->taxonomy as $term) { \n $terms[$term->name] = $term->name; \n }\n\n // I really have no idea what the logic behind the region is\n if($taxonomy_count == 2 && in_array('national', $terms) && is_numeric(arg(1))) \n { \n $region = array_shift($terms);\n // los ageneles needs special case\n if($region == \"los angeles\")\n {\n $region = 'la';\n }\n return $region;\n }\n else if($taxonomy_count > 2 && $taxonomy_count < 9 && in_array('newengland', $terms)\n {\n return 'newengland';\n }\n else if($taxonomy_count > 10 && in_array('national', $terms) )\n {\n return 'national';\n }\n else\n {\n // none of the cases fit, we'll just keep the current region\n return getRegion();\n }\n\n }\n\n // redirect the user to a particular region and node\n function send_redirect($region, $node)\n {\n $link = 'http://' . $region . '.thedelimagazine.com/' . drupal_get_path_alias(\"node/$node->nid\", $path_language = '');//go to term left in $value\n drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);\n }\n\n function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {\n // if viewing something other then the home page, consider redirecting\n if($op == 'view' && arg(1) != 0)\n {\n $correct_region = determine_region($node);\n // redirect to correct region if necessary.\n if( getRegion() != $correct_region )\n {\n send_redirect($correct_region, $node);\n }\n }\n }\n?>\n</code></pre>\n\n<p>I think you'll find my version easier to follow. I've divided to task into pieces so that each piece can be simpler.</p>\n\n<blockquote>\n <p>This code performs 301 redirects based on the taxonomy terms\n associated with the node, as 301 redirects can adversely effect page\n load time, how could this be best optimized.</p>\n</blockquote>\n\n<p>The solution is not to do 301 redirects. Telling the browser to go download another page will make loading the page slower. Nothing you can do in your code will change that. All you can do is not tell them to go download another page. Do you really need to redirect the user to a different subdomain? Maybe you do, but if you can get away without doing it, don't do it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T16:19:20.857",
"Id": "11521",
"Score": "0",
"body": "`arg(1) ~= 0` ??? What am I missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T16:50:23.317",
"Id": "11524",
"Score": "0",
"body": "@YannisRizos, language confusion. ~= means != in some languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T21:28:20.463",
"Id": "11572",
"Score": "0",
"body": "sorry the comments were written for a non technical person to read"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T21:29:50.820",
"Id": "11573",
"Score": "0",
"body": "this doesn't really make sense to what I need to do, but thanks for taking a look"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T23:12:30.873",
"Id": "7347",
"ParentId": "7345",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7347",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T19:06:19.877",
"Id": "7345",
"Score": "3",
"Tags": [
"php",
"optimization"
],
"Title": "Performing redirects based on taxonomy terms associated with nodes"
}
|
7345
|
<p>Below is a set of extensions that I use in unit tests. </p>
<p>The basic idea is that when creating or modifying some sort of user output type of string, I want to eyeball the output to see that it makes sense, even though it might be 'correct' in a unit test sense. But when doing almost any other tests and certainly when regression testing, I don't want the added noise or time it takes to do so.</p>
<p>For example:</p>
<pre><code>[TestCase("US1")]
[TestCase("123")]
[TestCase("E$R")]
public void Get_From_IsoAlphaCode_IfThreeLetterCodeIsNotAllAlpha_Error(string val)
{
var ex = Assert.Throws<IsoAlphabeticCodeFormatException>(() => Currency.Get(val));
ex.Look(); // *** eyeball the whole exception using extension ***
Assert.That(ex.Message, Is.StringStarting(IsoAlphabeticCodeFormatException.Not3AlphaCharsMessage));
Assert.That(ex.ParamName, Is.StringMatching("isoAlphaCode"));
Assert.That(ex.ActualValue, Is.EqualTo(val));
}
// OUTPUT
IsoAlphabeticCodeFormatException: Badly formed ISO 4217 Aplhabetic Code.
The passed code was not three (3) alphabetic characters.
Parameter name: isoAlphaCode
Actual value was bubba.
at Support.Guard.AgainstBadIsoAlphaCodeFormat(String paramName, String value) in C:\Support\Guard.cs:line 26
at Currency.Get(String isoAlphaCode) in C:\Currency.cs:line 731
at Tests.Currencies.CurrencyTests.<>c__DisplayClass6.<Get_From_IsoAlphaCode_IfThreeLetterCodeIsWrongSize_Error>b__5() in C:.Tests\Currencies\CurrencyTests.CacheFetching.cs:line 95
at NUnit.Framework.Assert.Throws(IResolveConstraint expression, TestDelegate code, String message, Object[] args)
21 passed, 0 failed, 0 skipped, took 4.71 seconds (NUnit 2.5.10).
</code></pre>
<p>So, the design goals here are:</p>
<ol>
<li>be short and easy to use</li>
<li>be configurable</li>
</ol>
<p>And I have two concerns about the class as is:</p>
<ol>
<li>Am I rewriting some existing functionality (ie, does Trace, Debug, NUnit, log4net, etc already do this?</li>
<li>What is a better way to configure the verbosity level?</li>
</ol>
<p>Here's my code:</p>
<pre><code>/// <summary>
/// Helpers to 'eyeball' artifacts of a unit test
/// </summary>
public static class UnitTestLoggingExtensions
{
private enum OutputOption { OFF, VERBOSE, TERSE, }
private static OutputOption option = OutputOption.TERSE;
/// <summary>Writes the passed string and any passed format arguments.</summary>
public static void Look(this string msg, params object[] args)
{
if (msg == null) {
Debug.Write("");
return;
}
switch (option)
{
case OutputOption.OFF:
break;
case OutputOption.VERBOSE:
Debug.WriteLine(_createVerboseMessage(msg, args), "INFO");
break;
case OutputOption.TERSE:
Debug.WriteLine(string.Format(msg, args), "INFO");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>Writes the passed exception's message.</summary>
public static void Look(this Exception ex) { Look(ex.Message); }
/// <summary>Writes the passed object, invoking ToString().</summary>
public static void Look(this object o) { Look(o.ToString()); }
/// <summary>Writes the passed items, invoking ToString().</summary>
public static void Look<T>(this IEnumerable<T> items)
{
foreach (var o in items)
{
o.Look();
}
}
/// <summary>Writes the passed items along with a header.</summary>
public static void Look<T>(this IEnumerable<T> items, string header)
{
header.Look();
items.Look();
}
private static string _createVerboseMessage(string format, params object[] args)
{
return string.Format("[{0}]{1}-> {2}",
DateTime.Now.ToString("o"),
Environment.NewLine,
string.Format(format, args));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I use log4net in my test code along with the <a href=\"https://github.com/drewburlingame/ObjectPrinter\" rel=\"nofollow\">ObjectPrinter</a> library and the log4net ConsoleAppender. </p>\n\n<p>When I'm actively working on a test where I want to see additional output I just crank up my logging level in my log4net config file so I can see the additional debug information in my ReSharper test runner console window.</p>\n\n<pre><code>private static readonly ILog Log = LogManager.GetLogger(typeof (MyTestFixture));\n\n[TestCase(\"US1\")]\n[TestCase(\"123\")]\n[TestCase(\"E$R\")]\npublic void Get_From_IsoAlphaCode_IfThreeLetterCodeIsNotAllAlpha_Error(string val)\n{\n var ex = Assert.Throws<IsoAlphabeticCodeFormatException>(() => Currency.Get(val));\n Log.Debug(ex); // <-- only prints when log4net is configured to log DEBUG msgs\n Assert.That(ex.Message, Is.StringStarting(IsoAlphabeticCodeFormatException.Not3AlphaCharsMessage));\n Assert.That(ex.ParamName, Is.StringMatching(\"isoAlphaCode\"));\n Assert.That(ex.ActualValue, Is.EqualTo(val));\n}\n</code></pre>\n\n<p>ObjectPrinter isn't required, but it outputs more information into the log by reflecting over the passed in objects public properties. The Log.Debug statement outputs something like this in the console window.</p>\n\n<pre>\n2012-01-01 19:38:26,362 [7] DEBUG NUnitTestHarness1.MyTestFixture [IsoAlphabeticCodeFormatException]: hashcode { 11076195 }\n{\n Message : Badly formed ISO 4217 Aplhabetic Code.\n StackTrace : at Currency.Get(String val) in d:\\source\\spikes\\NUnitTestHarness1\\NUnitTestHarness1\\Class1.cs:line 31\n at NUnitTestHarness1.MyTestFixture.c__DisplayClass1.b__0() in d:\\source\\spikes\\NUnitTestHarness1\\NUnitTestHarness1\\Class1.cs:line 18\n at NUnit.Framework.Assert.Throws(IResolveConstraint expression, TestDelegate code, String message, Object[] args)\n Source : NUnitTestHarness1\n TargetSite : Int32 Get(System.String)\n HelpLink : {NULL}\n ParamName : {NULL}\n ActualValue : {NULL}\n Data : {}\n InnerException : {NULL}\n}\n</pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T22:19:49.580",
"Id": "11528",
"Score": "0",
"body": "Can you please show me a sample usage to that would be the equivalent of my 'exception.Look()' extension? I want to decide if it is worth spending some quality time with log4net and learning the ObjectPrinter library. Cheers"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T20:13:08.950",
"Id": "7361",
"ParentId": "7346",
"Score": "2"
}
},
{
"body": "<p>I like Sneal's suggestion lots and I may go that route at some point. </p>\n\n<p>For now, I just don't have time or inclination to learn the ObjectPrnter library or rewrite existing code that uses; so the path of least resistance is just to use a VisualStudio Setting. </p>\n\n<p>It's easy, provides a single point of configuration change, doesn't require a build.</p>\n\n<p>Cheers,<br>\nBerryl</p>\n\n<h1>changes in UnitTestLoggingExtensions</h1>\n\n<pre><code>#region Configuration\n\npublic enum VerbosityLevel\n{\n OFF = 0,\n VERBOSE,\n TERSE,\n}\n\npublic static readonly VerbosityLevel Verbosity;\n\nstatic TestingOutputExtensions() { \n Verbosity = (VerbosityLevel) Properties.Settings.Default.UnitTestOutputVerbosityLevel; }\n\n#endregion\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T16:56:26.743",
"Id": "7590",
"ParentId": "7346",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T20:44:14.643",
"Id": "7346",
"Score": "2",
"Tags": [
"c#",
".net",
"unit-testing"
],
"Title": "Trace-like extensions for unit testing"
}
|
7346
|
<p>I know that Facebook has an algorithm to filter out posts that may be irreverent, but I'm building a very simple yet functional algorithm to improve on it.</p>
<p>It's getting complicated to maintain, and I want to know how to organize the code in one specific way, have patterns, use shortcuts etc...</p>
<p>Please don't hesitate to criticize this code heavily.</p>
<pre><code>#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <limits>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
// TO DO: Add ignoring case and white space
// Make it so that the user doesn't have to enter each post from FB to this script to see if it's okay or not
// Add GUI to this script (wxWidgets?)
using namespace std;
vector<string> explode(const string& str, const char& ch) {
string next = "";
vector<string> result;
// For each character in the string
for (string::const_iterator it = str.begin(); it != str.end(); it++) {
// If we've hit the terminal character
if (*it == ch) {
// If we have some characters accumulated
if (next.length() > 0) {
// Add them to the result vector
result.push_back(next);
next = "";
}
} else {
// Accumulate the next character into the sequence
next += *it;
}
}
return result;
}
bool overuse_of_caps(int percentage, string this_message) {
string ac[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
string otherChars[] = {" ", ",", ".", "-"};
float x = 0; // Counter
float y = 1; // Inverse Counter
for (int i = 0; i < this_message.size(); i++) {
for (int ii = 0; ii < 26; ii++) {
for (int iii = 0; iii < 4; iii++) {
if (!(this_message[i] == ' ')) {
stringstream ss;
string s;
char c = this_message[i];
ss << c;
ss >> s;
if (s == ac[ii]) {
x++;
}
}
stringstream ss;
string s;
char c = this_message[i];
ss << c;
ss >> s;
if (s == otherChars[iii]) {
y++;
}
}
}
}
if ( floor ( (x / ( ( this_message.size() ) - y) ) * 100) > percentage) {
return true;
} else {
return false;
}
}
int main (int argc, const char * argv[]) {
// INITIALIZE
bool is_true = false;
bool master_switch = false;
bool is_true_II = false;
bool true_III = false;
string alphabetLower = "abcdefghijklmnopqrstuvwxyz";
string alphabetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int questionMarkCounter = 0;
int exclemMarkCounter = 0;
string conditionals[] = {"like this", "my status", "like this status", "inbox", "bad mood", "r.i.p", "rip", "rest in peace", "cool beans", "im bored", "S I N G L E or N O T", "Single or not", "[ ]", "[", "]", "[]", "[x]", "shut up", "what the", ":(", ":'(", ":*", "((", "war", "MW", "MW2", "attack", "kill", "one person in this world", "iloveyou", "i love you", "idiot", "brotips", "tips", "ohgodlol", "Ill Tell You", "What I Think Of You", ".)", "if beauty were inches, you'd go on for miles.", "profile", "cracked", "drugs", "weed", "aint", "ain't", "Pokemon", "Lyrics", "jonas brothers", ":#", "heartbreaking", "</3", "<3", "SAVE", "survey", "purchase", "butt", "mediafire", "text it", "phone broken", "phones broke", "phone not working", "dont text", "don't text", "angrey", "sorrow", "on Twitter", "arrested", "watching", "farmvile", "21 questions", "profile view", "poop", "profile counter", "gurl", "girl", "hating", "haters", "hatin", "macdonalds", "mac donalds", "mcdonalds", "kiss", "LMFAO", "live webcam", "facebook video", "facebook", "PLEASE SHARE, THANKS!", "repost", "Barbie", "homework", "depress", "dog", "cat", "female", "thb", "tbh", "niggle", "ngl", "ho", "hoe", "hate", "dont", "hate", "dislike", "recreate", "disallow", "forget", "relationship", "relationship", "broke", "break", "respect", "forever", "never", "live", "life", "inbox", "status", "bored", "wtf", "wft", "wtfz", "hahahah", "hahha", "hahahahah", "hahaaah", "frigger", "effing", "eff", "bed"};
// This is where the first test string is initialized.
std::string this_message_RAW = "like my status because its awesome.";
// Explode the string into words.
std::vector<std::string> this_message = explode(this_message_RAW, ' ');
// TEST ONE: Detect if the message is shorter or equal to 3 letters.
if (this_message.size() <= 3) {
master_switch = true;
}
// TEST TWO: Keyword matching
for (int i = 0; i < this_message.size(); i++) {
string this_item = this_message[i];
for (int ii = 0; ii < 130; ii++) { // 130 needs to be updated to however many items are in the list.
// Messing around with conditionals goes here.
if (this_item == conditionals[ii]) {
printf("A MATCH WAS FOUND.");
master_switch = true;
}
}
}
// TEST THREE: Check if the first item starts with a number.
if (isdigit(this_message_RAW[0])) {
bool FAILED_TEST = true;
printf("Test three failed!");
master_switch = true;
}
// TEST FOUR: Detect excessive use of question marks or exclementation marks.
for (int i = 0; i < this_message_RAW.size(); i++) {
if (this_message_RAW[i] == '?') {
questionMarkCounter++;
}
if (this_message_RAW[i] == '!') {
exclemMarkCounter++;
}
}
if ((questionMarkCounter > 3)||(exclemMarkCounter > 3)) {
printf("The question mark or exclem test failed.");
master_switch = true;
}
// TEST FIVE: Overuse_of_caps
if (overuse_of_caps(80, this_message_RAW)) {
printf("Overuse of caps DETECTED! Test failed.");
master_switch = true;
}
// CONCLUSION
if (is_true||is_true_II||true_III||master_switch) {
printf("A test failed. Not safe for public use.");master_switch = true;
return false;}
else{
return true;
}
if (master_switch = true) {
printf("One or more of the tests failed. This means that this status is not good.");
} else {
printf("Passed! The status is approved, and is okay.");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>I haven't really tried to understand your code but I have a few remarks :</p>\n\n<ul>\n<li><p>There's a much better way than using an array to get the i-th letter of the alphabet.</p>\n\n<pre><code>string ac[] = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"};\n// ...\nif (s == ac[ii])\n</code></pre>\n\n<p>Can be rewritten /</p>\n\n<pre><code> if (s == ii+'A')\n</code></pre></li>\n<li><p>You can improve readibility of your code by writing :</p>\n\n<pre><code>if (this_message[i] != ' ')\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>if (!(this_message[i] == ' '))\n</code></pre></li>\n<li><p>Use <code>else</code> between 2 conditions that cannot be <code>true</code> in the same time. By doing do, you won't evaluate the second condition when the first one is true (it's slighty better from a performance point of view but it's also much easier for the code-reader to follow the flow). Instead of:</p>\n\n<pre><code>if (this_message_RAW[i] == '?') { foo(); }\nif (this_message_RAW[i] == '!') { bar(); }\n</code></pre>\n\n<p>Write</p>\n\n<pre><code>if (this_message_RAW[i] == '?') { foo(); }\nelse if (this_message_RAW[i] == '!') { bar(); }\n</code></pre></li>\n<li><p>There's no point in having this :</p>\n\n<pre><code>if ( floor ( (x / ( ( this_message.size() ) - y) ) * 100) > percentage)\n{ return true; }\nelse \n{ return false; }\n</code></pre>\n\n<p>When you can write:</p>\n\n<pre><code>return ( floor ( (x / ( ( this_message.size() ) - y) ) * 100) > percentage);\n</code></pre></li>\n<li><p>Please take into account your own comments before asking for code review. You can easily use the length of your list instead of a hardcoded value in </p>\n\n<pre><code>for (int ii = 0; ii < 130; ii++) { // 130 needs to be updated to however many items are in the list.\n</code></pre></li>\n<li><p>Please take into account the compiler warnings before asking for code review. I'm pretty sure that the code after </p>\n\n<pre><code>if (is_true||is_true_II||true_III||master_switch) {\n printf(\"A test failed. Not safe for public use.\");master_switch = true;\n return false;}\nelse{\n return true;\n}\n</code></pre>\n\n<p>will never be reached and that should be said by the compiler.</p></li>\n<li><p>I don't get the point of having <code>bool is_true = FALSE;</code>. But there are many things to be said here:</p>\n\n<ul>\n<li>This could be const</li>\n<li>You can use false in lowercase</li>\n<li>This variable is useless (this might also be detected by your compiler)</li>\n<li>The bool name is really really confusing</li>\n</ul></li>\n</ul>\n\n<p>Same remarks apply to most of the other variables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T12:05:46.980",
"Id": "7352",
"ParentId": "7349",
"Score": "6"
}
},
{
"body": "<p>Use the C++ versions of the header file.<br>\nThis way everything is put in the std namespace.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n\n// Change to:\n\n#include <cstdio>\n#include <cstdlib>\n#include <cctype>\n</code></pre>\n\n<p>Prefer not to import the whole std namespace into global namespace.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>It is not that hard to use the full name.</p>\n\n<pre><code>std::vector\n</code></pre>\n\n<p>Alternatively you can selectively import the bits you want with</p>\n\n<pre><code>using std::vector;\n</code></pre>\n\n<p>Not this is bound the current scope this you can limit its affect to just a function.</p>\n\n<p>There is an easier way to write explode():<br>\nThis example breaks the string into words using white space as the delimiter.<br>\nIf you want to use another delimiter that is relatively easy; just use a type that reads words by delimiter when using the operator>>.</p>\n\n<pre><code>std::vector<std::string> explode(std::string const& str)\n{\n std::stringstream stream(str);\n std::vector<std::string> result;\n\n std::copy(std::istream_iterator<std::string>(stream),\n std::istream_iterator<std::string>(),\n std::back_inserter(result)\n );\n return result;\n}\n</code></pre>\n\n<p>There is no need to have a triple nested loop:</p>\n\n<pre><code>for (int i = 0; i < this_message.size(); i++) {\n for (int ii = 0; ii < 26; ii++) {\n for (int iii = 0; iii < 4; iii++) {\n</code></pre>\n\n<p>Basically you are testing each character to see if it is uppercase or a special. This is much easier by doing an explicit test on each character.</p>\n\n<p>This is a very bad way of extracting a single character into a string.</p>\n\n<pre><code> stringstream ss;\n string s;\n char c = this_message[i];\n ss << c;\n ss >> s;\n</code></pre>\n\n<p>The equivalent of the above code is:</p>\n\n<pre><code> this_message.substr(i,1);\n</code></pre>\n\n<p>But what you really want is:</p>\n\n<pre><code> char c = this_message[i];\n</code></pre>\n\n<p>The test for uppercase letters would be much easier written as:</p>\n\n<pre><code> isupper(this_message[i])\n</code></pre>\n\n<p>The test for a specific character in a set you can use:</p>\n\n<pre><code> strchr(\" ,.-\", this_message[i]) != NULL\n</code></pre>\n\n<p>Using these two we could reduce your code too:</p>\n\n<pre><code>bool overuse_of_caps(int percentage, string this_message)\n{\n float x = 0; // Counter\n float y = 1; // Inverse Counter\n\n for (int i = 0; i < this_message.size(); i++)\n {\n if (isupper(this_message[ii]))\n {\n x++;\n }\n if (strchr(\" ,.-\", this_message[i]) != NULL)\n {\n y++;\n }\n }\n\n return ( floor ( (x / ( ( this_message.size() ) - y) ) * 100) > percentage);\n}\n</code></pre>\n\n<p>You don't need to write a manual search the standard already has one:</p>\n\n<pre><code>std::find(iterator, iterator, thingToFind)\n</code></pre>\n\n<p>So this:</p>\n\n<pre><code> for (int ii = 0; ii < 130; ii++) { // 130 needs to be updated to however many items are in the list.\n\n // Messing around with conditionals goes here.\n if (this_item == conditionals[ii]) {\n printf(\"A MATCH WAS FOUND.\");\n master_switch = true;\n }\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>master_switch = std::find(conditionals.begin(), conditionals.end(), this_item) != conditionals.end();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:54:34.170",
"Id": "7366",
"ParentId": "7349",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "7366",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T02:13:54.813",
"Id": "7349",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"beginner"
],
"Title": "HappyBook algorithm for filtering out posts"
}
|
7349
|
<p>What is the best way to considerably decrease the size of the following code without sacrificing functionality, and to make it more readable, and well, make it look professional?</p>
<pre><code>class Compiler
{
public string Compile(TextReader src)
{
string rtn = SourceTemplate.Top;
var preprocessor = new PreProcessor();
Parser[] ParserRounds = {
new PredefinedConstantParser(),
new VariableDeclarationParser(),
new ConditionalExpressionParser(),
new FunctionCallParser()//,
//new FunctionParser
};
foreach (var l in preprocessor.Process(src))
{
var line = l;
foreach (var parser in ParserRounds)
{
line = parser.Parse(line);
}
rtn += "\t\t\t" + line + "\n";
}
return rtn + SourceTemplate.Bottom;
}
public static void Start(string[] args)
{
TextReader src = File.OpenText(args[0]);
var com = new Compiler();
var source = com.Compile(src);
string target = args[0].TrimEnd(".hack".ToCharArray());
target += ".cs";
}
public void SaveToFile(string source, string target)
{
TextWriter wsrc = File.CreateText(target);
wsrc.WriteLine(source);
wsrc.Close();
}
}
</code></pre>
<p>In my personal opinion, the above code looks like a mess at this stage. Also, please suggest good and expressive variable names instead of <code>rtn</code> , <code>src</code> etc. Should I also make this class generic?</p>
|
[] |
[
{
"body": "<p>Just some generic notes since I'm not too familiar with C#:</p>\n\n<ol>\n<li><p><a href=\"https://stackoverflow.com/questions/73883/string-vs-stringbuilder\"><code>rtn</code> should be <code>StringBuilder</code></a></p></li>\n<li><p>I'd change the <code>preprocessor</code> and <code>ParserRounds</code> variables to fields and pass their values to the constructor of the class. It makes testing easier (you can test only one parser at a time, you can test with a mocked preprocessor etc.) and it results looser coupling.</p></li>\n<li><p>Using <code>SourceTemplate.Top</code> and <code>SourceTemplate.Bottom</code> also tight coupling, pass these values to the constructor too, store them in a field and use these fields in the <code>Compile</code> method. (Maybe it's worth creating a <code>SourceTemplate</code> interface with <code>GetTop()</code> and <code>GetBottom()</code> methods and passing a proper instance to the <code>Compiler</code> class.)</p></li>\n<li><p>I'm really missing the input validation. For example, if the <code>Compile</code> method get a <code>null</code> as a value of <code>TextReader</code> you should throw an exception immediately. It helps debugging a lot. Why would you do any compiling if it will throw an exception later since the <code>TextReader</code> is <code>null</code>?</p>\n\n<p>The <code>Start</code> method also should check the input values.</p></li>\n<li><p>Some variable naming ideas:</p>\n\n<ul>\n<li><code>src</code> -> <code>sourceReader</code> or <code>srcReader</code></li>\n<li><code>com</code> -> <code>compiler</code></li>\n<li><code>target</code> -> <code>targetFileName</code></li>\n<li><code>rtn</code> -> <code>result</code></li>\n<li><code>wsrc</code> -> <code>targetWriter</code></li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T16:24:10.710",
"Id": "7354",
"ParentId": "7353",
"Score": "8"
}
},
{
"body": "<p><code>ParserRounds</code> should not start with a capital since it is an instance. </p>\n\n<p>But much worse is that it should not exist at all: you are straying very far from OO. Instead of the for-loop that calls the members of parserRounds you should think of some OO pattern to use, where the <code>line</code> goes through some \"automatic\" chain of processing. There are probably many different ways to proceed, but I can think of passing the line to some instance of <code>Parser</code> that itself contains the other subclasses of <code>Parser</code> in order.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T18:26:24.580",
"Id": "7359",
"ParentId": "7353",
"Score": "1"
}
},
{
"body": "<p>Building on the great answers provided by @palacsint and @toto2 I have put together a quick sample of what could be done to improve your application.</p>\n\n<p>For me code speaks louder than words so here goes:</p>\n\n<pre><code>// SOLID: Interface Segregation Principle\n// Use an interface to allow better / easier unit testing \n// through mocking.\n internal interface ICompiler\n{\n string Compile(string textFileContents);\n}\n\n// SOLID: Interface Segregation Principle\n// Once again using an interface will allow the preprocessor \n// to be mocked in unit testing.\ninterface ITextPreProcessor\n{\n IEnumerable<string> Process(string lines);\n}\n\n// SOLID: Interface Segregation Principle\n// Use an interface to allow better / easier unit testing \n// through mocking.\ninternal interface ITextParser\n{\n string Parse(string line);\n}\n\n// SOLID: Single Responsibility Principle\n// This class is responsible for the parsing of text files.\n// The class is NOT responsible for loading or pesisting the\n// parsed response.\ninternal class Compiler : ICompiler\n{\n public Compiler()\n : this(new PreProcessor())\n { }\n\n // other text parsers have been omitted from this code sample\n public Compiler(ITextPreProcessor textPreProcessor)\n : this(textPreProcessor, new ITextParser[] { new PredefinedConstantParser(), new VariableDeclarationParser() }\n )\n { }\n\n // using this constructor allows for better object mocking and unit testing.\n public Compiler(ITextPreProcessor textPreProcessor, IEnumerable<ITextParser> parserRounds)\n {\n // depending on your business logic you may want to check for null value objects \n // and throw an exception here\n if (textPreProcessor == null) throw new ArgumentNullException(\"textPreProcessor\");\n if (parserRounds == null) throw new ArgumentNullException(\"parserRounds\");\n\n TextPreProcessor = textPreProcessor;\n ParserRounds = parserRounds;\n }\n\n /// <summary>\n /// Gets the text pre processor.\n /// </summary>\n public ITextPreProcessor TextPreProcessor { get; private set; }\n\n /// <summary>\n /// Gets the parser rounds.\n /// </summary>\n public IEnumerable<ITextParser> ParserRounds { get; private set; }\n\n public string Compile(string textFileContents)\n {\n // depending on your business rules you may want to throw an\n // exception if the textFileContents variable is null???\n if (string.IsNullOrEmpty(textFileContents)) throw new ArgumentNullException(\"textFileContents\");\n\n var builder = new StringBuilder();\n\n builder.AppendLine(SourceTemplate.Top);\n builder.AppendLine(\"\\t\\t\\t\");\n\n foreach (var line in TextPreProcessor.Process(textFileContents))\n {\n foreach (var parser in ParserRounds)\n {\n // depending on your business rules you may want to either use a \n // try catch exception block here if the returnv value from \"Parse\"\n // is null or empty by letting the exceptions bubble up\n // to the layer responsible for doing something with the exception???\n builder.AppendLine(parser.Parse(line));\n }\n\n builder.AppendLine(\"\\n\");\n }\n\n builder.AppendLine(SourceTemplate.Bottom);\n return builder.ToString();\n }\n}\n\n// SOLID: This class is responsible for the management\npublic class ParseManager\n{\n public static void Start(string[] args)\n {\n var sourceFileContents = File.ReadAllText(args[0]);\n\n try\n {\n ICompiler compiler = new Compiler();\n var parsedContents = compiler.Compile(sourceFileContents);\n\n string destinationPath = string.Format(\"{0}.cs\", args[0].TrimEnd(\".hack\".ToCharArray()));\n\n // writing text files can be done in 1 line so there\n // is no need to wrap this in a seperate method\n File.WriteAllText(destinationPath, parsedContents);\n\n // sample \n Console.WriteLine(\"Parsed file saved: {0}\", destinationPath);\n }\n catch (Exception exception)\n {\n Console.WriteLine(exception.ToString());\n }\n\n Console.Read();\n }\n}\n</code></pre>\n\n<p>Below are some sample class implementations to show how this improvement could be used</p>\n\n<pre><code>// sample class implementation\ninternal class PreProcessor : ITextPreProcessor\n{\n public IEnumerable<string> Process(string lines)\n {\n throw new NotImplementedException();\n }\n}\n\n// sample parser implementation\ninternal class PredefinedConstantParser : ITextParser\n{\n public string Parse(string line)\n {\n var builder = new StringBuilder();\n return builder.ToString();\n }\n}\n\n// sample parser implementation\ninternal class VariableDeclarationParser : ITextParser\n{\n public string Parse(string line)\n {\n var builder = new StringBuilder();\n return builder.ToString();\n }\n}\n</code></pre>\n\n<p>With naming standards I tend to use those offered by <a href=\"http://idesign.net/idesign/download/IDesign%20CSharp%20Coding%20Standard.zip\" rel=\"nofollow\">IDesign</a> as they take out any personal preference and are in line with best practice suggested by Microsoft. </p>\n\n<p>For details on the SOLID principles refer to <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">here</a> and <a href=\"http://dimecasts.net/Casts/ByTag/SOLID%20Principle\" rel=\"nofollow\">here</a>. IMHO SOLID is one of the most important aspects in writing good software applications.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:37:21.203",
"Id": "7365",
"ParentId": "7353",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7354",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T14:14:23.087",
"Id": "7353",
"Score": "2",
"Tags": [
"c#",
"parsing"
],
"Title": "Cleaning up Compiler class"
}
|
7353
|
<p>I have a keyup function that expands an input field as text is added. There are a lot of fields where this code will be applied, what is the best way to write this for best performance?</p>
<p>Here is a working demo: <a href="http://jsfiddle.net/J9Ner/" rel="nofollow">http://jsfiddle.net/J9Ner/</a></p>
<pre><code>$('input.name','#bakery').live('keyup', function() {
var el = $(this);
var len = el.val().length;
if (len < 20) {
el.width('200px');
return;
} else if (len > 56) {
return;
}
el.width((len * 10) + 'px');
});
</code></pre>
|
[] |
[
{
"body": "<p>You can rearrange the if/else to be a little more efficient.</p>\n\n<p>You can retrieve the length a little more efficiently.</p>\n\n<p>And, use <code>.delegate()</code> (pre jQuery 1.7) or <code>.on()</code> (jQuery 1.7+) with a selector of a parent object close to the elements. That will perform much better than <code>.live()</code> for large numbers of elements.</p>\n\n<p>It could look something like this:</p>\n\n<pre><code>$('#bakery').on('keyup', 'input.name', function() {\n var el = $(this);\n var len = this.value.length;\n\n if (len < 20) {\n el.width('200px');\n } else if (len <= 56) {\n el.width((len * 10) + 'px');\n }\n});\n</code></pre>\n\n<p>If you don't actually need <code>.live()</code> or <code>.on()</code> type behavior, it's even more performant to avoid the need for event propagation and bind the event handlers directly to the input elements themselves so no selector matching must be done on each key event:</p>\n\n<pre><code>$('#bakery input.name').keyup(function() {\n var el = $(this);\n var len = this.value.length;\n\n if (len < 20) {\n el.width('200px');\n } else if (len <= 56) {\n el.width((len * 10) + 'px');\n }\n});\n</code></pre>\n\n<p>And, then removing the jQuery <code>.width()</code> call would speed it up some more:</p>\n\n<pre><code>$('#bakery').on('keyup', 'input.name', function() {\n var len = this.value.length;\n\n if (len < 20) {\n this.style.width = '200px';\n } else if (len <= 56) {\n this.style.width = (len * 10) + 'px';\n }\n});\n</code></pre>\n\n<p>You can see this last one working here: <a href=\"http://jsfiddle.net/jfriend00/7Pb8b/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/7Pb8b/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T17:09:54.100",
"Id": "7357",
"ParentId": "7356",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7357",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T16:52:32.317",
"Id": "7356",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "Increase performance for this keyup function?"
}
|
7356
|
<p>I wrote a Hangman game to try out some of the new features in C++11. I'm pretty new to C++, and I would like some good advice on how I can improve this code (in terms of conventions, bad/good practices, ...):</p>
<pre><code>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
#include <random>
#include <algorithm>
const unsigned initial_number_of_lives = 5;
// Returns a random word from the given words file.
std::string pick_word(const std::string& words_filename) {
std::vector<std::string> words;
std::ifstream words_file(words_filename.c_str());
if (!words_file) {
throw std::runtime_error("Couldn't open file.");
}
std::string word;
do {
std::getline(words_file, word);
words.push_back(word);
} while (!words_file.eof());
std::uniform_int_distribution<uintmax_t> random_distribution(0, words.size() - 1);
std::mt19937 random_engine(static_cast<std::mt19937::result_type>(std::time(nullptr)));
uintmax_t word_index = random_distribution(random_engine);
return words[word_index];
}
int main(int argc, const char *argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " <words-file>\n";
return 1;
}
std::string word;
try {
word = pick_word(argv[1]);
} catch(...) {
std::cerr << argv[0] << ": couldn't open words file: " << argv[1] << '\n';
return 1;
}
#if DEBUG
std::cout << "(debug) word: " << word << "\n\n";
#endif
std::cout << "Welcome to hangman!"; // Newline in main loop below.
unsigned lives = initial_number_of_lives;
std::vector<char> guessed_letters;
for (;;) {
bool won = true;
for (char &letter : word) {
if (std::find(guessed_letters.begin(),
guessed_letters.end(),
letter) == guessed_letters.end()) {
won = false;
}
}
if (won) {
std::cout << "You won the game!!1\n";
return 0;
}
std::cout << "\n\nLives left: " << lives;
std::cout << "\nAlready guessed: ";
for (char &letter : guessed_letters) {
std::cout << letter << ' ';
}
std::cout << '\n';
for (char &letter : word) {
if (std::find(guessed_letters.begin(),
guessed_letters.end(),
letter) != guessed_letters.end()) {
std::cout << letter;
} else {
std::cout << '_';
}
}
char guess;
std::cout << "\nEnter a letter: ";
std::cin >> guess;
guess = std::tolower(guess);
// Don't allow player to enter the same letter twice.
if (std::find(guessed_letters.begin(),
guessed_letters.end(),
guess) != guessed_letters.end()) {
std::cout << "You have already guessed that letter!\n";
continue;
}
// Don't allow player to enter anything but letters.
if (!std::isalpha(guess)) {
std::cout << "That is not a letter!\n";
continue;
}
guessed_letters.push_back(guess);
bool word_contains_letter = false;
for (char &letter : word) {
if (letter == guess) {
word_contains_letter = true;
break;
}
}
if (word_contains_letter) continue;
--lives;
if (lives == 0) {
std::cout << "Game over! The right word was: " << word << '\n';
break;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T21:35:37.967",
"Id": "18132",
"Score": "0",
"body": "missing include `#include <ctime>`"
}
] |
[
{
"body": "<p>A few thoughts:</p>\n\n<p>Instead of </p>\n\n<pre><code>do {\n std::getline(words_file, word);\n words.push_back(word);\n} while (!words_file.eof());\n</code></pre>\n\n<p>You should do</p>\n\n<pre><code>while(std::getline(words_file, word))\n words.push_back(word);\n}\n</code></pre>\n\n<p>Otherwise, the read which causes the stream to go into an invalid state will still be pushed.</p>\n\n<p>Also, why not include the filename that cannot be opened in the exception text and then output the exception text instead of the hard-coded text you have now. As things are, you may be ignoring other exceptions (although I don't see when one would happen). Perhaps output the exception.what() in addition to what you have now.</p>\n\n<p>I would also advise splitting some of the game logic into functions -- you don't need them in multiple places as things are, but it could be easier to follow. Things like the piece setting <code>word_contains_letter</code> would look better as function calls, in my opinion.</p>\n\n<p>Oh, another thing: you may want to use <code>#ifndef NDEBUG</code> rather than <code>#ifdef DEBUG</code>, as that is the default way to check whether debugging is enabled or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:57:34.197",
"Id": "11529",
"Score": "2",
"body": "Its not probably. He must. Your version works his version is broken and will push the last word into the list twice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T00:02:32.913",
"Id": "11530",
"Score": "0",
"body": "Removed the probably. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:28:34.017",
"Id": "7363",
"ParentId": "7362",
"Score": "10"
}
},
{
"body": "<ol>\n<li><p>Consider using conventional <code>ALL_CAPS</code> for constant <code>initial_number_of_lives</code>.</p></li>\n<li><p>Consider moving the definition of <code>initial_number_of_lives</code> into its minimal scope \n(inside <code>main</code>, just before using it). The file preamble is really better only for constants that are used in multiple functions.</p></li>\n<li><p>Consider scalability of <code>pick_word</code>. It doesn't really need to hold every word in the word file in memory at the same time just to fairly pick one. It could use an iterative process with repeated random picks among the words seen so far. Fairness could be maintained by giving the prior pick added weighting equal to the total number of entries it is \"replacing\" so far.</p>\n\n<p>This is guaranteed to be fair by the rules of conditional probability.\nIn theory, this process only requires 2 strings in memory at a time, if you don't mind doing n-1 weighted random picks. A reasonable performance compromise, still fair and just slightly more complex, would be to keep small batches of strings in memory (plus the one \"weighted\" word picked from all of the prior batches) and do fewer random picks, (n-1)/m, where m is the (constant or average) batch size.</p></li>\n<li><p>Consider unit testability -- it would be easier to unit test the code if <code>pick_word</code> delegated to simple functions like:</p>\n\n<ul>\n<li>a separately testable (mockable) random number generator</li>\n<li>a separately testable (mockable) word picker that operated on an abstract \ninput stream (testable without requiring file access)</li>\n</ul></li>\n<li><p>Instead of:</p>\n\n<pre><code>std::vector<char> guessed_letters;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (std::find(guessed_letters.begin(),\n guessed_letters.end(),\n letter) == guessed_letters.end()) {\n</code></pre>\n\n<p>consider</p>\n\n<pre><code>std::string guessed_letters;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (guessed_letters.find(letter) != std::string::npos) {\n</code></pre>\n\n<p>and even so, consider factoring THAT bit of ugliness into a bool test function. If you took Anton's advice and have a <code>word_contains_letter</code> function,\nit's already there, ready to be called! And that can be unit tested, too.</p>\n\n<p>Aside: I try to avoid or at least isolate into a one-liner wrapper function\nany idiom of the form</p>\n\n<pre><code>std::METHOD(CONTAINER.begin(), CONTAINER.end(), ARGS) COMPARATOR CONTAINER.end())\n</code></pre>\n\n<p>Yes, the idioms are so common that experienced STL users can write \nand read them in their sleep, but still it's ugly! Cxx11 is especially helpful in providing ways to avoid these idioms using higher order programming or to wrap them generically with your own function templates like:</p>\n\n<pre><code>bool contains(const C& container, const T& element)\n</code></pre>\n\n<p>I don't know why I can't find sugar like this is in the standard \ncontainer or algorithm library (have I missed something?).</p></li>\n<li><p>Consider placing the test for a non-alpha guess BEFORE the check for a repeated guess, just because as it stands it made me think, when I needn't have.</p></li>\n<li><p>Consider replacing the \"forever\" loop with the more indicative</p>\n\n<pre><code>while (lives) {\n</code></pre>\n\n<p>and extracting the \"Game Over\" code path from the loop, so</p>\n\n<pre><code> if (word_contains_letter) continue;\n --lives;\n if (lives == 0) {\n std::cout << \"Game over! The right word was: \" << word << '\\n';\n break;\n }\n}\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code> if (! word_contains_letter) {\n --lives;\n }\n}\n\nstd::cout << \"Game over! The right word was: \" << word << '\\n';\n</code></pre></li>\n<li><p>Consider defending against unwinnable games. If the guesser is restricted to guessing letters, it seems only sporting that the word chosen from the word file be guaranteed to include only guessable letters. Actually, more flexible variant of the game might allow non-letters (spaces, punctuation) in the words (phrases, really) and just reveal them with no effect on the guessing or scoring.</p>\n\n<p>Any uppercase letters in the words file poses a similar issue, but suggests that you might want to keep a lowercase version of the word for matching guesses but use the original mixed case word for the purposes of showing the guessed letters and revealing the answer at the end. Even if you go with more flexibility in the word list, words that contain an '_' should not be allowed!</p></li>\n<li><p>Consider keeping yet another version of the word string, a \"display\" copy, initially filled with '<em>'s. This is more for clarity than performance. It just seems counter-intuitive to be repeating the work of re-filtering the word for display each time through the loop, even when the state of <code>guessed_letters</code> hasn't changed. Each '</em>' in the display copy can be replaced exactly once when that letter is guessed, based on the guessed letter's position(s) in other copy of the word. </p>\n\n<p>This may lead to the question \"Is it OK that word_contain_element calls find, tests the returned position and discards it, and if the test succeeds returns to code that immediately re-executes find with the same arguments (this time at the head of a loop that finds each position of the letter)?\" I think the answer is \"Yes, because readability is more important than performance, here.\"</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T03:33:18.577",
"Id": "7401",
"ParentId": "7362",
"Score": "5"
}
},
{
"body": "<p>Here's my inline edits. The most conspicuous result is </p>\n\n<ul>\n<li>less manual work</li>\n<li>20%-25% shorter (in lines, words, and characters). Less code means less bugs and less maintenance burden (if not obfuscating)</li>\n</ul>\n\n<p>Notes</p>\n\n<ol>\n<li>removed some not very valuable error handling</li>\n<li>don't pass filename as std::string for no reason (pass <code>const char*const</code>)</li>\n<li>added input checking (just alpha-only words)</li>\n<li>removed silly uniform distribution on a one-shot random selection</li>\n<li>lowercase picked word</li>\n<li>made <code>word</code> const (see below)</li>\n<li>replace all range-based fors with the corresponding algorithm (<code>std::copy</code>, <code>std::set::find</code>, <code>std::transform</code>, <code>std::all_of</code>)</li>\n<li>use a <code>set</code> for guessed letters</li>\n<li><p>shortened form; I think e.g.</p>\n\n<pre><code>if (std::string::npos != word.find(guess))\n continue;\n</code></pre>\n\n<p>is by definition more readable than</p>\n\n<pre><code>bool word_contains_letter = false;\nfor (char &letter : word) {\n if (letter == guess) {\n word_contains_letter = true;\n break;\n }\n}\n\nif (word_contains_letter) continue;\n</code></pre></li>\n<li><p>there was the matter of style on loops (like the for-loop just above). Consider doing <code>for (const auto&letter : word)</code> or <code>for (char letter : word)</code> so as to make it clear that letter shall not be modified by the loop.</p></li>\n</ol>\n\n<blockquote>\n <p><strong>Note</strong> I'm not saying my code is (much) better, but it should give you food for thought, which, I think, is the objective of the game.</p>\n</blockquote>\n\n<pre><code>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <stdexcept>\n#include <random>\n#include <algorithm>\n#include <ctime>\n#include <iterator>\n#include <set>\n\n\nconst unsigned initial_number_of_lives = 5;\n\n// Returns a random word from the given words file.\nstd::string pick_word(const char* const words_filename)\n{\n std::vector<std::string> words;\n std::ifstream words_file(words_filename);\n std::string word;\n while(std::getline(words_file, word))\n if (std::all_of(word.begin(), word.end(), [](char c) { return std::isalpha(c); }))\n words.push_back(word);\n\n std::mt19937 random_engine(std::time(nullptr));\n word = words[random_engine() % words.size()];\n std::for_each(word.begin(), word.end(), [](char&c) { c = std::tolower(c); });\n return word;\n}\n\nint main(int argc, const char *argv[])\n{\n if (argc != 2)\n {\n std::cerr << \"usage: \" << argv[0] << \" <words-file>\\n\";\n return 1;\n }\n\n const std::string word = pick_word(argv[1]);\n std::string result(word.size(), '_');\n\n std::cout << \"Welcome to hangman!\"; // Newline in main loop below.\n\n std::set<char> guessed;\n unsigned lives = initial_number_of_lives;\n\n for (;;)\n {\n std::transform(word.begin(), word.end(), result.begin(), [&] (char c) \n { return guessed.end()==guessed.find(c)? '_':c; });\n\n if (result == word)\n {\n std::cout << \"\\nYou won the game!! \\n\";\n return 0;\n }\n\n std::cout << \"\\n\\nLives left: \" << lives;\n\n std::cout << \"\\nAlready guessed: \";\n std::copy(guessed.begin(), guessed.end(), std::ostream_iterator<char>(std::cout, \" \"));\n std::cout << '\\n' << result << \"\\nEnter a letter: \";\n\n char guess;\n std::cin >> guess;\n guess = std::tolower(guess);\n\n // Don't allow player to enter anything but letters.\n if (!std::isalpha(guess))\n {\n std::cout << \"That is not a letter!\\n\";\n continue;\n }\n\n // Don't allow player to enter the same letter twice.\n if (guessed.find(guess) != guessed.end())\n continue;\n\n guessed.insert(guess);\n\n if (std::string::npos == word.find(guess) // word doesn't contain letter\n && !lives--) // no more lives\n {\n std::cout << \"Game over! The right word was: \" << word << '\\n';\n break;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T23:37:11.983",
"Id": "18134",
"Score": "0",
"body": "Your `pick_word` is reusing a variable (`word`). I’d flag that in a code review. Also, the implicit `int` => `char` coercion in the last conditional is evil and should be replaced by an explicit comparison (`lives-- == 0`). C++’ habit of treating numbers and logical values identical is annoying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T00:03:10.997",
"Id": "18135",
"Score": "0",
"body": "@KonradRudolph You meant `int => bool`? And C++ doesn't treat numbers and logical values as identical. It just does implicit conversions (and stays compatible with C). My stance is, the usual idioms are widely recognized and hence, the 'simpler' code will be easier to grok (and verify). Of course, don't use this in wildly complicated settings involving bit masks etc. Footshooting material there"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T00:03:38.640",
"Id": "18136",
"Score": "0",
"body": "Good point about the 'word' reuse. I wouldn't flag it, but hey, I wouldn't object if anyone else did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:42:49.960",
"Id": "62105",
"Score": "1",
"body": "You can usually use std::any_of if you're not actually going to use the iterator returned from find."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-28T23:01:24.193",
"Id": "11287",
"ParentId": "7362",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "7363",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:12:09.220",
"Id": "7362",
"Score": "12",
"Tags": [
"c++",
"beginner",
"c++11",
"hangman"
],
"Title": "Testing new C++11 features with Hangman"
}
|
7362
|
<p>I am attempting to optimize a piece of C code which aims to multiply a series of pairs of unsigned shorts and add the result. I am only concerned about the high 16 bits of the result, and I can guarantee that the sum of the multiples will fit in a 32-bit value. I initially coded this in C, and then rewrote it to use SSE2 intrinsics (slowest), and then rewrote it in SSE2 assembler (fastest). I am not an expert at x86 assembler and would appreciate any recommendations on how to speed this code up. Speed is the priority, this is a tight inner loop. It is OK to assume that input will be valid. In addition, portability is not a major concern, this code will only be used on computers with Intel i5 or i7 processors. Attend:</p>
<p><strong>C</strong></p>
<pre><code>register int i;
uint16_t* iw_ptr = n->iw;
uint16_t* nw_ptr = n->nw;
register uint32_t accvalue = 0;
if (id < 2 * I_CNT) {
for (i = 0; i < I_CNT; i++) {
accvalue += (uint32_t) i_ptr[i] * (uint32_t) iw_ptr[i];
}
}
for (i = 0; i < id; i++) {
accvalue += (uint32_t) n_ptr[i] * (uint32_t) nw_ptr[i];
}
value = (uint16_t) (accvalue >> 16);
</code></pre>
<p><strong>C SSE2</strong></p>
<pre><code>#define SSE2_I ((INPUT_COUNT+7)/8)
#define SSE2_N ((NEURON_COUNT+7)/8)
register int i;
__m128i mm_sums;
__m128i mm_arg1;
__m128i mm_arg2;
__m128i mm_accum = _mm_setzero_si128();
__m128i* mm_iptr = (__m128i*) i_ptr;
__m128i* mm_nptr = (__m128i*) n_ptr;
__m128i* mm_iwptr = (__m128i*) n->iw_ptr;
__m128i* mm_nwptr = (__m128i*) n->nw_ptr;
int id_8 = (id + 7)/8; // Round up to nearest multiple of 8
if (id < 2 * I_CNT) {
for (i = 0; i < SSE2_I; i++) {
mm_arg1 = _mm_loadu_si128(mm_iptr+i);
mm_arg2 = _mm_loadu_si128(mm_iwptr+i);
mm_sums = _mm_mulhi_epu16(mm_arg1, mm_arg2);
mm_accum = _mm_adds_epu16(mm_accum, mm_sums);
}
}
for (i = 0; i < id_8; i++) {
mm_arg1 = _mm_loadu_si128(mm_nptr+i);
mm_arg2 = _mm_loadu_si128(mm_nwptr+i);
mm_sums = _mm_mulhi_epu16(mm_arg1, mm_arg2);
mm_accum = _mm_adds_epu16(mm_accum, mm_sums);
}
_mm_storeu_si128(mm_accum_mem, mm_accum);
for (i = 0; i < 8; i++) {
value += *(((uint16_t*) mm_accum_mem) + i);
}
</code></pre>
<p><strong>SSE2 and x86 Assembler</strong></p>
<pre><code>#define SSE2_I ((I_CNT+7)/8)
#define SSE2_N ((N_CNT+7)/8)
__m128i* mm_iptr = (__m128i*) i_ptr;
__m128i* mm_nptr = (__m128i*) n_ptr;
__m128i* mm_iwptr = (__m128i*) n->iw_ptr;
__m128i* mm_nwptr = (__m128i*) n->nw_ptr;
int id_8 = (id + 7)/8; // Divide by 8, round up
asm(
"MOVL %5, %%eax \n\t" // Current ID
"MOVL %6, %%ebx \n\t" // 2*I_CNT
"CMP %%eax, %%ebx \n\t" // If ID >= 2 * input count
"JGE Nstart1 \n\t" // Skip the first step
"MOVL %1, %%eax \n\t"
"MOVL %3, %%ebx \n\t"
"MOVDQA (%%eax), %%xmm0 \n\t"
"MOVDQA (%%ebx), %%xmm1 \n\t"
"PMULHUW %%xmm1, %%xmm0 \n\t"
#if SSE2_I > 1
"MOVDQA 0x10(%%eax), %%xmm1 \n\t"
"MOVDQA 0x10(%%ebx), %%xmm2 \n\t"
"PMULHUW %%xmm1, %%xmm2 \n\t"
"PADDUSW %%xmm2, %%xmm0 \n\t"
#endif
#if SSE2_I > 2
"MOVDQA 0x20(%%eax), %%xmm1 \n\t"
"MOVDQA 0x20(%%ebx), %%xmm2 \n\t"
"PMULHUW %%xmm1, %%xmm2 \n\t"
"PADDUSW %%xmm2, %%xmm0 \n\t"
#endif
#if SSE2_I > 3
"MOVDQA 0x30(%%eax), %%xmm1 \n\t"
"MOVDQA 0x30(%%ebx), %%xmm2 \n\t"
"PMULHUW %%xmm1, %%xmm2 \n\t"
"PADDUSW %%xmm2, %%xmm0 \n\t"
#endif
"JMP Nstart2 \n\t"
"Nstart1: \n\t" // This is our first multiplication
"MOVL %2, %%edi \n\t"
"MOVL %4, %%esi \n\t"
"MOVDQA (%%edi), %%xmm0 \n\t"
"MOVDQA (%%esi), %%xmm1 \n\t"
"PMULHUW %%xmm1, %%xmm0 \n\t"
"JMP Nstart3 \n\t"
"Nstart2: \n\t" // This is not our first multiplication
"MOVL %2, %%edi \n\t"
"MOVL %4, %%esi \n\t"
"MOVDQA (%%edi), %%xmm1 \n\t"
"MOVDQA (%%esi), %%xmm2 \n\t"
"PMULHUW %%xmm1, %%xmm2 \n\t"
"PADDUSW %%xmm2, %%xmm0 \n\t"
"Nstart3: \n\t"
"MOVL %7, %%ebx \n\t" // Current ID, divided by 8, rounded up.
// The number of rounds we have to do
"DEC %%ebx \n\t" // If it is now 0 or -1
"JLE Endloop \n\t" // We don't have to do any more rounds
"MOVL $0x10, %%eax \n\t" // The offset
"Loop: \n\t"
"MOVDQA (%%edi, %%eax), %%xmm1 \n\t"
"MOVDQA (%%esi, %%eax), %%xmm2 \n\t"
"PMULHUW %%xmm1, %%xmm2 \n\t"
"PADDUSW %%xmm2, %%xmm0 \n\t"
"ADDL $0x10, %%eax \n\t"
"DEC %%ebx \n\t" // The round we just did
"JNE Loop \n\t" // If not zero, do it again
"Endloop: \n\t"
/**
* PREPARE FOR THE ADDING OF THE WORDS
* xmm0 3 2 1 0
* xmm1 0 0 3 2 0b00001110
* xmm0 X X 1+3 0+2 PADDUSW
* xmm1 X X X 1+3 0b00000001
* xmm0 X X X sum PADDUSW
* This however is still two words - we were shuffling doublewords...
* But that's not all we can shuffle!
* Shuffle lowwords 0b00000001
* PADDUSW
* Extract to register as a 16-bit word
*/
"PSHUFD $0x0E, %%xmm0, %%xmm1 \n\t"
"PADDUSW %%xmm1, %%xmm0 \n\t"
"PSHUFD $0x01, %%xmm0, %%xmm1 \n\t"
"PADDUSW %%xmm1, %%xmm0 \n\t"
"PSHUFLW $0x01, %%xmm0, %%xmm1 \n\t"
"PADDUSW %%xmm1, %%xmm0 \n\t"
"PEXTRW $0x01, %%xmm0, %%eax \n\t"
: "=d" (value) // Outputs
: "g" (mm_iptr), "g" (mm_nptr),
"g" (mm_iwptr), "g" (mm_nwptr),
"g" (id), "g" (2*INPUT_COUNT), "g" (id_8) // Inputs
: "%xmm0", "%xmm1", "%xmm2",
"%eax", "%ebx", "%edi", "%esi" // Clobbered
);
</code></pre>
<p><strong>I have tried to:</strong></p>
<p>Use the <code>prefetchnta</code> instruction on a few of the pointers (like %2 and %4), this has only increased the execution time.</p>
<p>Use more of the XMM registers by grouping the <code>MOVDQA, MOVDQA</code> and <code>PMULHUW, PADDUSW</code> to up to three iterations at a time. I expected this to be at least a little useful by grouping the reads from memory together and slightly increasing the number of instructions between a read and the corresponding use of that data. This provided no speedup.</p>
<p>I would like to be able to skip the <code>PMULHUW, PADDUSW</code> sequence if either of the operands is all-zeroes. However, MOVDQA does not set the zero register and I can't see any easy way to test that. Is it possible to jump if an XMM register is all zeroes?</p>
<p>Did I screw up any of the assembly loop code?</p>
<p>Any other ways to get one of these running faster?</p>
|
[] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li><p>forget asm (for now at least) and stick with SSE intrinsics - you can concentrate on optimisation and let the compiler worry about the implementation details like register allocation, instruction scheduling and loop unrolling</p></li>\n<li><p>use a decent compiler - e.g. Intel ICC typically generates better code than gcc in most cases, and Visual Studio typically generates worse code (this is just based on empirical evidence - try as many different compilers as is practical to see which gives best results)</p></li>\n<li><p>use x86-64 if you can - this gives you twice as many SSE registers to play with (16 versus 8) which enables more loop unrolling etc</p></li>\n<li><p>if your data contains a lot of zeroes such that it's worth the cost of testing and branching to avoid redundant multiplies then you can use <code>_mm_testz_si128</code> (<code>PTEST</code>) to handle this case - make sure you time with/without this optimisation as its potential benefit is highly data-dependent</p></li>\n<li><p>you are doing very little computation relative to the number of loads and stores so you may hit an optimisation brick wall due to finite memory bandwidth (you may have hit this already) - if possible try combining some other operations from before/after this loop so that you can mitigate the cost of loads and stores</p></li>\n<li><p>try and ensure that your data is 16 byte aligned and use only aligned loads/stores if you possibly can - even though Core i7 supposedly has zero performance penalty for misaligned loads in practice there is still an overhead (probably due to increased cache footprint)</p></li>\n<li><p>don't mess with prefetch instructions (for now at least) - it's hard to beat the automatic prefetch in Core i7 and you may well end up reducing performance rather then improving it</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T02:09:01.147",
"Id": "11788",
"Score": "1",
"body": "Thanks for the advice. I tried with the SSE intrinsics but they were actually slower, and I had heard that GCC was not great at optimizing them. (Here's some proof: `paddusw %xmm1, %xmm0; movdqa %xmm0, %xmm1`.) I'm downloading ICC right now (very slowly) and I'll try it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:59:06.423",
"Id": "7489",
"ParentId": "7364",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7489",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T23:31:18.920",
"Id": "7364",
"Score": "4",
"Tags": [
"c",
"assembly",
"sse"
],
"Title": "SSE2 assembly optimization - multiply unsigned shorts and add the result"
}
|
7364
|
<p>I was experimenting with lists, sets, and finally maps when I spotted a pattern in my code to make it recursive. Now I haven't used recursion much in the past or at work and I was very excited to have something that does recursion.</p>
<p>I have this recursive method that takes in an <code>Integer</code> and returns a string representation of the <code>Integer</code> by reading two <code>HashMap</code>s.</p>
<p>For example representation(11) will be Eleven OR representation(89) will be Eighty-Nine, ect.</p>
<p>I have arranged to handle up to 999,999. Are there any improvements I could make to this current implementation to handle things more efficiently/speedily?</p>
<pre><code>public String representation(Integer num) {
StringBuffer numRep = new StringBuffer();
StringBuffer hundred = new StringBuffer("Hundred");
StringBuffer thousand = new StringBuffer("Thousand");
//The case for anything less than 20; 0-19
if (num < 20) {
numRep.append(genNumMap.get(num));
//The case for any integer less than 100; 20-99
} else if (num < 100) {
int temp = num % 10;
if (temp == 0) {
numRep.append(greaterNumMap.get(num));
} else {
numRep.append(greaterNumMap.get(num - temp) + "-"
+ representation(temp));
}
//The case for any integer less than 1000, covers the hundreds; 100-999
} else if (num < 1000) {
int temp = num % 100;
if (temp == 0) {
numRep.append(representation(num / 100) + "-" + hundred);
} else {
numRep.append(representation((num - temp) / 100) + "-" + hundred
+ "-" + representation(temp));
}
//The case for any integer less that one million, covers the thousands; 1,000 - 999,999
} else if (num < 1000000) {
int temp = num % 1000;
if (temp == 0) {
numRep.append(representation(num / 1000) + "-" + thousand);
} else {
numRep.append(representation((num - temp) / 1000) + "-" + thousand
+ "-" + representation(temp));
}
} else if (num > 1000000){
numRep.append("Sorry, this number is too large");
JOptionPane.showMessageDialog(null, "Sorry, this number is too large\n"+"Integers 0 through 999,999 are exceptable.");
}
return numRep.toString();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T02:57:38.037",
"Id": "11538",
"Score": "2",
"body": "in last else if should be num>1000000, not '<'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T03:02:50.530",
"Id": "11540",
"Score": "3",
"body": "If you are trying to convert an integer into an english word presentation then I think you are doing too much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T03:08:22.120",
"Id": "11541",
"Score": "0",
"body": "i solved euler problem -17 in python,which is similar to your problem ,take a look at it.might be of help to you!!!https://github.com/srinivasreddy/euler/blob/master/src/17.py"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T03:44:56.477",
"Id": "11542",
"Score": "0",
"body": "You may not need to optimize your recursion but may need to optimize what you are doing during the recursion. Or you may need to do the operation iteratively, or you may have memory issue, or you may have.........the list goes on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T15:09:17.427",
"Id": "11690",
"Score": "1",
"body": "Use `StringBuilder` instead of `StringBuffer`, that is a little bit faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:24:46.867",
"Id": "12094",
"Score": "0",
"body": "Landei is right. It almost never makes sense to use StringBuffer rather than StringBuilder."
}
] |
[
{
"body": "<p>By all means, implement your code iteratively -- recursion is probably never the most efficient way to do something, because you do indeed make multiple copies of the local variables. If your method allocates a 256 byte buffer on the stack, that 256 byte buffer is allocated every method call, and eventually, you'll run out of stack space.</p>\n\n<p>What's more significantly expensive with a function call is allocating memory for it's internal procedures. If you have an iterative function -- one which exits before it is called again -- the allocation only needs to happen ONCE, the same region of memory will be reused. With a recursive function, however, allocation has to happen at each level of recursion. So the only good time to use recursion is when, for example, you need to compound data, in which case an iterative function would be allocating and returning data each time, or else there is no clear and easy iterative method. Main reasons to use recursion:</p>\n\n<ul>\n<li>Because it's cool.</li>\n<li>Because it will be fewer lines of code.</li>\n</ul>\n\n<p>Method calling is slower then looping for several reasons. you have to unroll the stack, return, and remove variables passed into the function from the stack for every function call. Not to mention saving and restoring the stack pointer, it has several instructions associated with it, and difficult branch prediction as well </p>\n\n<p>Loops, on the other hand, don't have to deal with half that stuff. most will fit completely in the icache. they allocate space for needed variables once, and they have no return pointer pushed on the stack with each function call. In short, they are the best option for anything that involves repeating a step.</p>\n\n<blockquote>\n <p>As most programmers know, the solutions to many problems can be expressed very elegantly using recursion. However, it is also true that any recursive algorithm can be converted into an iterative one, and traditional wisdom suggests that iterative algorithms are preferred from the standpoint of performance and scalability. <a href=\"http://www.ahmadsoft.org/articles/recursion/index.html\" rel=\"nofollow\">See</a>.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T03:31:08.990",
"Id": "7370",
"ParentId": "7369",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Such an algorithm is very rarely used, so it is <em>extremely unlikely</em> that its performance matters. So, most chances are you do not need to optimize it <em>at all</em>. But if you insist:</p></li>\n<li><p>Do <em>not</em> pre-initialize the 'hundred' and 'thousand' <code>StringBuffer</code>s. Only initialize them if they are needed. As a matter of fact, it is good practice (though it does not have anything to do with performance) to not even <em>declare</em> them outside of <em>the narrowest possible scope in which they will be used</em>. By the way, I do not understand why 'hundred' and 'thousand' are <code>StringBuffer</code>s instead of <code>String</code>s.</p></li>\n<li><p>You do not need <code>HashMap</code>s for this job; just use arrays of <code>String</code>. They will be faster.</p></li>\n<li><p>It seems like the kind of recursion you are using is <code>tail recursion</code>, so you can trivially convert your function to work iteratively, which will probably yield better performance. I am not saying it will <em>necessarily</em> perform better, so write both versions and <em>benchmark</em> one against the other if you <em>really</em> care about performance. But if you do not, then <em>keep</em> the recursive version, it is way cooler, and even easier to read.</p></li>\n<li><p>When you append to a <code>StringBuffer</code>, never append multiple strings concatenated with <code>+</code>. Always use a separate call to <code>append()</code> for each string. Otherwise, the compiler will very likely be creating more temporary <code>StringBuffer</code>s behind your back in order to optimize your string append operations.</p></li>\n<li><p>Considering that any number minus zero is still the same number, you can optimize this:</p>\n\n<pre><code>int temp = num % 1000;\nif (temp == 0) {\n numRep.append(representation(num / 1000) + \"-\" + thousand);\n} else {\n numRep.append(representation((num - temp) / 1000) + \"-\" + thousand\n + \"-\" + representation(temp));\n}\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code>int temp = num % 1000;\nnumRep.append( representation( (num - temp) / 1000) );\nnumRep.append( \"-\" );\nnumRep.append( thousand );\nif( temp != 0 ) \n{\n numRep.append( \"-\" );\n numRep.append( representation( temp ) );\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:29:37.230",
"Id": "7381",
"ParentId": "7369",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7381",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T02:49:02.090",
"Id": "7369",
"Score": "6",
"Tags": [
"java",
"strings",
"recursion",
"converting",
"integer"
],
"Title": "Integer to String recursive method"
}
|
7369
|
<p>I decided to put together a quick project using jquery, the Kendo UI HTML 5 framework and JavaScript. </p>
<p>I don't do much JavaScript development and I'd like some input on how to make this look less like a complete spaghetti hack, walking up and down DOM elements, trying to find the right event handler to hook onto.</p>
<pre><code>$(window).load(function(){
var serviceUrl = "http://catalogService.asmx";
var configurationsUrl = serviceUrl + "/Configurations?format=json";
var itemAttributesUrl = serviceUrl + "/GetItemAttributes?format=json";
var updateConsumersUrl = serviceUrl + "/UpdateConsumers?format=json";
var dataSource = kendo.data.DataSource.create({
schema: { model: {id: "ServiceEntityName"} },
transport: {
read: {
url: configurationsUrl,
dataType: "jsonp"
}
},
pageSize: 15
});
$("#grid").kendoGrid({
dataSource: dataSource,
height: 670,
scrollable: true,
pageable: true,
sortable: true,
groupable: true,
detailInit: detailInit,
dataBound: function(e) {
this.element.find(".consumers").each(function() {
// Get the matching grid data row.
var id = $(this).closest("tr").data("id");
var data = dataSource.get(id).data;
var consumers = data.Consumers;
var dd = $(this).kendoDropDownList({
dataSource: consumers,
template: $("#consumerTemplate").html()
}).data("kendoDropDownList");
var lastTarget = document.body;
updateConsumersText(dd, consumers);
// keep track of mouse up element to determine if we should close the dropdown
dd.popup.element.delegate("*", "mouseup", function(e) { lastTarget = e.currentTarget; });
dd.popup.bind("close", function(e) {
if ($.contains(this.element[0], lastTarget)) {
// don't close - we haven't clicked on the dropdown element itself (or outside the dropdown)
this.element.find(".consumerCheckBox").each(function(i, e) {
consumers[i].IsSelected = e.checked;
});
updateConsumersText(dd, consumers);
e.preventDefault();
}
else if (data.ServiceEntityName)
{
updateConsumers(data.ServiceEntityName, dd.text());
}
lastTarget = document.body;
});
});
},
columns: [
{ field: "Namespace" },
{ field: "Name" },
{ field: "Description" },
{
name: "Consumers",
template: $("#consumersTemplate").html()
}
],
selectable: true
});
$.fn.toggleCheckbox = function() {
this.attr('checked', !this.attr('checked'));
}
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
function updateConsumersText(dropDownList, consumers)
{
var text= "";
for (var i = 0; i < consumers.length; i++)
{
var c = consumers[i];
if (c.IsSelected)
{
text+= c.Name + ", ";
}
}
if (text.endsWith(", "))
{
text = text.substring(0, text.length - 2);
}
dropDownList.text(text);
}
function updateConsumers(serviceEntityName, consumersText)
{
var url = updateConsumersUrl + "&serviceEntityName=" + serviceEntityName + "&consumersText=" + consumersText;
$.ajax({
url: url,
error: function(xhr,s,e) {alert("Error updating consumers: " + e); },
tyoe: "GET",
dataType: "JSONP"
});
}
function detailInit(e) {
var itemAttributesDataSourceUrl = itemAttributesUrl + "&serviceEntityName=" + e.data.ServiceEntityName;
var itemAttributesDataSource = kendo.data.DataSource.create({
schema: { model: {id: "ID"} },
transport: {
read: {
url: itemAttributesDataSourceUrl,
dataType: "jsonp"
}
}
});
$("<div/>").kendoGrid({
dataSource: itemAttributesDataSource ,
scrollable: false,
sortable: true,
columns: [ "Name", "DisplayName", "Description" ]
}).appendTo(e.detailCell);
}
});
</code></pre>
|
[] |
[
{
"body": "<p>Here's my approach:</p>\n\n<ol>\n<li>Reduce temporary variables when it makes sense (when they're only used once)</li>\n<li>Reduce string tokens into reusable functions for url generation</li>\n<li>Add comments to increase clarity</li>\n<li>Add whitespace for clarity</li>\n<li>Reduce the duplicate config data structures used by kendo</li>\n<li>Declare variables as late as possible in the source so they are more closely associated with all of their usage (for instance, so you don't have to jump from top to bottom of the page to figure out what initDetail does)</li>\n<li>Refactor logic when better approaches are available (mostly the string concatenation/endsWith stuff)</li>\n</ol>\n\n<p>I also fixed some bugs hidden in the code - always use encodeURIComponent for url parameter data unless the values are constants and do not contain characters that need uri escaping. There was a typo or two in the $.ajax hash keys. </p>\n\n<p>The code didn't reduce too much, though mostly because I'm not very familiar with kendo and don't know what parameters are defaulted to in the config groups (hopefully they contain common use case defaults.) Also, you have a lot of specific behavior mixed inside your data population code. That could probably be isolated across all behaviors in the site, reducing this data population snippet even further. I've added comments for these as TODO:'s in the code. </p>\n\n<p>Since this didn't compile before, and since I don't have the same kendo environment up, I hope it will compile now. I ran it through JS Lint but it complained about a variable not being used when it actually was. The code was reduced to about 120 lines of code (minus comments) so about a 15% reduction in entropic loc's. And imo the clarity and conciseness was increased in the process so overall a net win.</p>\n\n<pre><code>$(function() {\n\n //generate target url for catalog service\n var target = function(page, params) {\n //reduce number of string tokens\n return \"http://catalogService.asmx/\" + page + \"?format=json\" + params;\n };\n\n //generate kendoConfig param structure \n var kendoConfig = function(model, url, params, pageSize) {\n //NOTE: kendo is a big part of your spaghetti code problem\n // this data structure is unecessarily complex...\n return {\n schema : {\n model : {\n id : model\n }\n },\n transport : {\n read : {\n url : target(url, params),\n dataType : 'jsonp'\n }\n },\n pageSize : pageSize //assuming kendo can handle undefined parameters\n };\n };\n\n var updateConsumersText = function (dropDownList, consumers) {\n //TODO: consider using a filter iteratator\n // dropDownList.text(consumers.filter(function(c) { if (c.IsSelected) return c.Name; }).join(\", \"));\n var selected = [];\n for (var i = 0; i < consumers.length; i++) { \n var c = consumers[i];\n if (c.IsSelected) selected.push(c.Name);\n }\n dropDownList.text(selected.join(\", \")); \n };\n\n var configs = kendo.data.DataSource.create(kendoConfig('ServiceEntityName', 'Configurations', \"\", 15);\n\n $('#grid').kendoGrid({\n dataSource : configs,\n height : 670,\n scrollable : true, //TODO: if these equal the kendo defaults remove them\n pageable : true, //ditto\n sortable : true, //ditto\n groupable : true, //ditto\n selectable: true, //ditto\n detailInit : function(e) {\n //Generate the Item Detail Grid\n $('<div/>').kendoGrid({\n dataSource : kendo.data.DataSource.create(\n kendoConfig(\n 'ID',\n 'GetItemAttributes',\n '&serviceEntityName=' + encodeURIComponent(e.data.ServiceEntityName)\n )\n ),\n scrollable : false,\n sortable : true,\n columns : ['Name', 'DisplayName', 'Description']\n }).appendTo(e.detailCell);\n },\n dataBound : function(e) {\n //Implement Main Consumer Binding\n this.element.find(\".consumers\").each(function() {\n // Get the matching grid data row. \n var id = $(this).closest(\"tr\").data(\"id\"); //this is not really that bad\n var data = configs.get(id).data; \n var consumers = data.Consumers; \n\n //Update drop down with list of consumers \n var dd = $(this).kendoDropDownList({ \n dataSource: consumers, \n template: $(\"#consumerTemplate\").html() \n }).data(\"kendoDropDownList\");\n\n updateConsumersText(dd, consumers); \n\n // keep track of mouse up element to determine if we should close the dropdown\n //TODO: this could be abstracted into an evented behavior for any dropdown (the behavior of\n // selecting and closing dropdown lists)\n var lastTarget = document.body;\n\n dd.popup.element.delegate(\"*\", \"mouseup\", function(e) { lastTarget = e.currentTarget; }); \n\n dd.popup.bind(\"close\", function(e) { \n if ($.contains(this.element[0], lastTarget)) { \n // don't close - we haven't clicked on the dropdown element itself (or outside the dropdown) \n this.element.find(\".consumerCheckBox\").each(function(i, e) { \n consumers[i].IsSelected = e.checked; \n }); \n updateConsumersText(dd, consumers); \n e.preventDefault(); \n } \n else if (data.ServiceEntityName) {\n //Update service entity name on the server\n\n //TODO: consider using a toParamString() function on a json object instead of manually\n // compiling the parameters\n var url = target(\n 'UpdateConsumers',\n '&serviceEntityName=' + encodeURIComponent(data.ServiceEntityName) +\n '&consumersText=' + encodeURIComponent(dd.text())\n );\n\n $.ajax({ \n url: url, \n error: function(xhr,s,e) { alert(\"Error updating consumers: \" + e); }, \n type: \"GET\", \n dataType: \"JSONP\" \n }); \n }\n\n lastTarget = document.body; \n });\n });\n },\n columns: [\n { field: \"Namespace\" }, \n { field: \"Name\" }, \n { field: \"Description\" }, \n { \n name: \"Consumers\", \n template: $(\"#consumersTemplate\").html() \n } \n ] \n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:10:27.107",
"Id": "8751",
"ParentId": "7372",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T06:12:25.223",
"Id": "7372",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html5"
],
"Title": "JavaScript code quality"
}
|
7372
|
<p>I'm learning java, although because of work I didn't had much time to go to classes. We had a final work to do but since I'm more familiarised with python I'm not sure if I'm doing java correctly...</p>
<p>I'm also a bit confused about attributes and constructors, I don't really understand the use of it.</p>
<p>For this work we have to do a server class and a client class. We have 4 files, one with times (in seconds) and points for bike female and male, and others with times and points run female and male. We then have a times file where each athlete have the time (minutes) for bike and run. We need to calculate the points for each time with linear interpolation, and then sort then, to see which athlete was the best one.</p>
<p>Where's what I've done at the server class:</p>
<pre><code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Scorer {
private String bike;
private String run;
private ArrayList<ArrayList<Integer>> athletes;
private boolean gender;
public Scorer(String bikeF, String runF, ArrayList<ArrayList<Integer>> athletes) {
this.bike = bikeF;
this.run = runF;
this.athletes = athletes;
}
public Scorer(ArrayList<ArrayList<Integer>> athletes, boolean gender) {
this.athletes = athletes;
this.gender = gender;
if (gender == true) {
this.bike = bike + "F.tab";
this.run = run + "F.tab";
} else {
this.bike = bike + "M.tab";
this.run = run + "M.tab";
}
}
public int[][] valsProximos(String table, ArrayList<ArrayList<Integer>> athletes, int n)
throws FileNotFoundException {
// compare file times and points with array to find distances and points closest to calculate linear interpolation
Scanner tables = new Scanner (new FileReader(table));
int [][] tabPoints = new int [9][2];
// this case, each column has a meaning, 1 athlete 2 points (if equals) 3 athlete 4 difference between times 5 max time 6 max points 7 athlete 8 difference between times 9 min time 10 min points
int [][] values = new int [athletes.size()][10];
for (int i=0; i<tabPoints.length;i++) {
for (int j =0;j<tabPoints[0].length;j++)
tabPoints[i][j]= tables.nextInt();
}
for (int i=0; i<athletes.size(); i++) {
for (int j=0; j<tabPoints.length; j++) {
if (athletes.get(i).get(n) == tabPoints[j][0]) {
values[i][0] = athletes.get(i).get(0);
values[i][1] = tabPoints[j][1];
} else {
if (tabPoints[j][0] > athletes.get(i).get(n)) {
// calculate difference between each time and the time in the table
int dif = tabPoints[j][0] - athletes.get(i).get(n);
if (values[i][2] != athletes.get(i).get(0)) {
values[i][2] = athletes.get(i).get(0);
values[i][3] = dif;
values[i][4] = tabPoints[j][0]; //maxTime
values[i][5] = tabPoints[j][1]; // maxPoint
} else if (dif < values[i][3]) {
values[i][3] = dif;
values[i][4] = tabPoints[j][0];
values[i][5] = tabPoints[j][1];
}
} else {
int dif1 = athletes.get(i).get(n) - tabPoints[j][0];
if (values[i][6] != athletes.get(i).get(0)) {
values[i][6] = athletes.get(i).get(0);
values[i][7] = dif1;
values[i][8] = tabPoints[j][0]; // minTime
values[i][9] = tabPoints[j][1]; // minPoint
} else {
if (dif1 < values[i][7]) {
values[i][7] = dif1;
values[i][8] = tabPoints[j][0];
values[i][9] = tabPoints[j][1];
}
}
}
}
}
}
return values;
}
public double intLinear(int maxTime, int time, int minTime,
int maxPoint, int minPoint) {
// calculate points given time acRunding to linear interpolation
double intLinear = (double)(maxTime - time)/(maxTime - minTime)
* minPoint + (double)(time - minTime)/(maxTime - minTime) * maxPoint;
// round to closest number
double athletePoint = (double)Math.round(intLinear);
return athletePoint;
}
public int[][] Score(int [][] valBike, int [][] valRun,
ArrayList<ArrayList<Integer>> athletes) {
int [][] punctuate = new int [athletes.size()][4];
for (int i=0; i<valBike.length; i++) {
if (athletes.get(i).get(0) == valBike[i][0]){
punctuate[i][0] = athletes.get(i).get(0);
punctuate[i][1] = valBike[i][1];
} else {
int maxTime = valBike[i][4];
int time = athletes.get(i).get(1);
int minTime = valBike[i][8];
int maxPoint = valBike[i][5];
int minPoint = valBike[i][9];
double athletePoint = intLinear(maxTime, time, minTime, maxPoint, minPoint);
punctuate[i][0] = athletes.get(i).get(0);
punctuate[i][1] = (int) athletePoint;
}
if (athletes.get(i).get(0) == valRun[i][0]){
// Verify that we are inserting points at right position
//if (punctuate[i][0] == valRun[i][0]) {
punctuate[i][2] = valRun[i][1];
//}
} else {
int maxTime = valRun[i][4];
int time = athletes.get(i).get(2);
int minTime = valRun[i][8];
int maxPoint = valRun[i][5];
int minPoint = valRun[i][9];
double athletePoint = intLinear(maxTime, time, minTime, maxPoint, minPoint);
//if (punctuate[i][0] == valRun[i][2]) {
punctuate[i][2] = (int) athletePoint;
//}
}
}
for (int i=0; i<punctuate.length; i++) {
// total points
punctuate[i][3] = punctuate[i][1] + punctuate[i][2];
}
return punctuate;
}
public int[][] ScoreF(int [][] order, int colNum) {
for (int row=0; row< order.length; row++){
for (int row2=row+1; row2<order.length; row2++){
// modify acRunding to the column we want to sort
if(order[row][colNum]<order[row2][colNum]){
for(int column=0; column<order[0].length; column++) {
int temp = order[row][column];
order[row][column] = order[row2][column];
order[row2][column] = temp;
}
}
}
}
return order;
}
}
</code></pre>
<p>and the client class:</p>
<pre><code> import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class DualthonProof {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// ask user name of file
Scanner input= new Scanner(System.in);
System.out.println("Enter file name bike female:");
String bikeF = input.nextLine();
System.out.println("Enter file name female run:");
String runF = input.nextLine();
System.out.println("Enter file name male bike:");
String bikeM = input.nextLine();
System.out.println("Enter file name male run:");
String runM = input.nextLine();
String tabBikeF = "bikeF.tab";
String tabRunF = "runF.tab";
String tabBikeM = "bikeM.tab";
String tabRunM = "runM.tab";
// if user didn't wrote anything use file
if (bikeF.equals(""))
bikeF = tabBikeF;
if (runF.equals(""))
runF = tabRunF;
if (bikeM.equals(""))
bikeM = tabBikeM;
if (runM.equals(""))
runM = tabRunM;
Scanner ficheiro = new Scanner (new FileReader ("times.txt"));
// Ignore first line
ficheiro.nextLine();
ArrayList<ArrayList<Integer>> athleteF = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> athleteM = new ArrayList<ArrayList<Integer>>();
while (ficheiro.hasNextLine()) {
String row = ficheiro.nextLine();
String[] section = row.split("\t");
String[] split1 = section[2].split(":");
String[] split2 = section[3].split(":");
// Convert string to integer
int num1 = Integer.parseInt(split1[0]);
int num2 = Integer.parseInt(split1[1]);
int secsBike = num1 * 60 + num2;
int num3 = Integer.parseInt(split2[0]);
int num4 = Integer.parseInt(split2[1]);
int secsRun = num3 * 60 + num4;
if (section[1].equals("F")) {
athleteF.add(new ArrayList<Integer>());
athleteF.get(athleteF.size()-1).add(Integer.parseInt(section[0]));
athleteF.get(athleteF.size()-1).add(secsBike);
athleteF.get(athleteF.size()-1).add(secsRun);
} else if (section[1].equals("M")) {
athleteM.add(new ArrayList<Integer>());
athleteM.get(athleteM.size()-1).add(Integer.parseInt(section[0]));
athleteM.get(athleteM.size()-1).add(secsBike);
athleteM.get(athleteM.size()-1).add(secsRun);
}
}
Scorer ptsF = new Scorer(bikeF, runF, athleteF);
int [][] valBikeF = ptsF.valsProximos(bikeF, athleteF, 1);
int [][] valRunF = ptsF.valsProximos(runF, athleteF, 2);
int [][] pointingF = ptsF.Score(valBikeF, valRunF, athleteF);
int [][] sortedF = ptsF.ScoreF(pointingF, 3);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T12:16:31.030",
"Id": "11557",
"Score": "2",
"body": "I'm not a friend of localized variable names and comments. You might want to consider to keep *everything* in English, especially if you come with your code to an English website to let it be reviewed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T12:30:15.873",
"Id": "11558",
"Score": "0",
"body": "yes, you're right. Normally I program in english but since this was an assignment to school I left it in portuguese and only change the comments. Can you explain your statement about localized variables? I've came here to learn with my mistakes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T12:31:28.943",
"Id": "11559",
"Score": "0",
"body": "That's what I meant with 'localized', read localized to your native language which is not English."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:51:20.547",
"Id": "11566",
"Score": "0",
"body": "I think everything or almost everything is translated now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:55:27.157",
"Id": "11567",
"Score": "1",
"body": "pavid, use the `@` sign before someone's name to make sure they receive a notification about your comment. So, you should prefix your comment with `@Bobby `"
}
] |
[
{
"body": "<p>I haven't read it all, but one thing I picked up:</p>\n\n<pre>\npublic Scorer(ArrayList> athletes, boolean gender) {\n this.athletes = athletes;\n this.gender = gender;\n if (gender == true) {\n this.bike = bike + \"F.tab\";\n this.run = run + \"F.tab\";\n } else { \n this.bike = bike + \"M.tab\";\n this.run = run + \"M.tab\";\n }\n\n}</pre>\n\n<p>When this constructor is called, bike and run are both null. null + \"F.tab \" will either throw a nullpointer or give you \"nullF.tab\", neither of which I think is your intention. You propably want bike=\"F.tab\"; run=\"F.tab\"; etc. </p>\n\n<p>For the record, because this constructor does not declare it's own bike and run variables, this.bike and bike are the same reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:04:02.633",
"Id": "11592",
"Score": "0",
"body": "thank you @Aaron for your answer. actually this is something I don't quite understand. What is the job of attributes here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T13:32:03.007",
"Id": "11618",
"Score": "0",
"body": "What is the job of the attributes? I'm not sure, you wrote it. What job did you intend them to serve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T16:34:32.110",
"Id": "11634",
"Score": "0",
"body": "I think I've understood. it doesn't make sense that way but if I do something like this: private String bike = \"filebike.txt\"; it would be more appropriate @Aaron"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T17:45:55.433",
"Id": "11637",
"Score": "0",
"body": "Yep, that looks fine"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T00:27:27.813",
"Id": "7393",
"ParentId": "7376",
"Score": "1"
}
},
{
"body": "<p>At first sight, the biggest problem is the double generic lists, like:</p>\n\n<pre><code>ArrayList<ArrayList<Integer>> athleteF = new ArrayList<ArrayList<Integer>>();\n</code></pre>\n\n<p>It's really hard to read and error-prone, since the lots of magic numbers which indexes the array. It's easy to mix-up the indexes and hard to remember which index stores which value. Use at least constants instead of the numbers.</p>\n\n<p>Anyway, you should create an <code>Athlete</code> class which stores all data of an athlete and store <code>Athlete</code> objects in the list:</p>\n\n<pre><code>final List<Athlete> athleteF = new ArrayList<Athlete>();\n</code></pre>\n\n\n\n<pre><code>public class Athlete {\n\n // TODO: set a proper name for this field\n private int someDataNeedName;\n private int secsBike;\n private int secsRun;\n\n public Athlete(final int someDataNeedName, final int secsBike, \n final int secsRun) {\n this.someDataNeedName = someDataNeedName;\n this.secsBike = secsBike;\n this.secsRun = secsRun;\n }\n\n public int getSomeDataNeedName() {\n return someDataNeedName;\n }\n\n public void setSomeDataNeedName(final int someDataNeedName) {\n this.someDataNeedName = someDataNeedName;\n }\n\n public int getSecsBike() {\n return secsBike;\n }\n\n public void setSecsBike(final int secsBike) {\n this.secsBike = secsBike;\n }\n\n public int getSecsRun() {\n return secsRun;\n }\n\n public void setSecsRun(final int secsRun) {\n this.secsRun = secsRun;\n }\n}\n</code></pre>\n\n<p>This class stores its data with names (these are the names of the fields).</p>\n\n<p>Usage:</p>\n\n<pre><code>final Athlete athlete = new Athlete(Integer.parseInt(section[0]), secsBike, secsRun);\n\nif (section[1].equals(\"F\")) {\n athleteF.add(athlete);\n} else if (section[1].equals(\"M\")) {\n ...\n}\n</code></pre>\n\n<p>(I hope it helps a little bit and somebody has time for a complete review.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:05:48.947",
"Id": "11593",
"Score": "0",
"body": "thank you @palacsint for your answer. actually at first I tried to use List (without creating a new class) but I didn't something wrong and it didn't work. That's why I moved to arrayList. What is the main difference between those two?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:36:30.257",
"Id": "11601",
"Score": "1",
"body": "`List` is an interface and `ArrayList` is an implementation of the `List` interface. http://www.javabeat.net/qna/9-difference-between-list-and-arraylist-/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T00:31:00.150",
"Id": "7394",
"ParentId": "7376",
"Score": "4"
}
},
{
"body": "<p>I'd strongly suggest to use the same order for parameters in overloaded methods/constructors, this is standard and expected:</p>\n\n<pre><code>public Scorer(ArrayList<ArrayList<Integer>> athletes, String bikeF, String runF)\npublic Scorer(ArrayList<ArrayList<Integer>> athletes, boolean gender)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T09:23:37.203",
"Id": "7988",
"ParentId": "7376",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7394",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T12:09:11.307",
"Id": "7376",
"Score": "2",
"Tags": [
"java",
"homework"
],
"Title": "Is this correct java? Attributes and constructors especially"
}
|
7376
|
<p>I'm kinda worried that the way I did my animation intro is a bit too heavy and is not optimized. Please review and let me know your thoughts.</p>
<pre><code>$(document).ready(function() {
introIconFirst();
function introIconFirst() {
$('h2.ribbon').css({
'marginTop': '+30px',
'opacity': '0'
}).animate({
marginTop: '0',
opacity: '1'
}, 1500, 'easeOutElastic', introIconSecond());
}
function introIconSecond() {
$('#ico_website').rotate('0deg').css({
'top': '+900px',
'opacity': '0'
}).animate({
top: '50px',
opacity: '1'
}, {
queue: false,
duration: 1100,
easing: 'easeOutElastic'
}).animate({
rotate: '-30deg'
}, 1000, 'easeOutElastic', introIconThird());
}
function introIconThird() {
$('#ico_rails').css({
'top': '+900px',
'opacity': '0'
}).delay(300).animate({
top: '145px',
opacity: '1'
}, 1400, 'easeOutElastic', introIconFourth());
}
function introIconFourth() {
$('#ico_plane').css({
'left': '255px',
'top': '90px',
'opacity': '0'
}).delay(800).animate({
top: '18px',
left: '299px',
opacity: '1'
}, 600, 'linear');
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T09:30:01.913",
"Id": "11560",
"Score": "0",
"body": "@JoshSmith Thanks. I didn't know it before. Will do for future post."
}
] |
[
{
"body": "<p>Looks good, though I prefer to keep the $(document).ready() as clean as possible, by only making calls and not definitions. Makes DOM management a bit easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T11:09:38.937",
"Id": "11562",
"Score": "0",
"body": "No problem, I tend to be a bit too obsessive over things like that. Often times my doc readys' don't consist of more than a few lines."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T00:16:13.523",
"Id": "7378",
"ParentId": "7377",
"Score": "1"
}
},
{
"body": "<p>Why the hell you need to declare your functions inside $(document).ready()? :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-01T00:31:39.537",
"Id": "7379",
"ParentId": "7377",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7378",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T18:52:55.450",
"Id": "7377",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html5",
"easing"
],
"Title": "jQuery animation procedural approach, suggestions need"
}
|
7377
|
<p>On ASP.NET MVC, I try to write an async Controller action with the old asynchronous programming model (actually, it is the current one, new one is still a CTP). </p>
<p>Here, I am trying to run 4 operations in parallel and it worked great. Here is the complete code:</p>
<pre><code>public class SampleController : AsyncController {
public void IndexAsync() {
AsyncManager.OutstandingOperations.Increment(4);
var task1 = Task<string>.Factory.StartNew(() => {
return GetReponse1();
});
var task2 = Task<string>.Factory.StartNew(() => {
return GetResponse2();
});
var task3 = Task<string>.Factory.StartNew(() => {
return GetResponse3();
});
var task4 = Task<string>.Factory.StartNew(() => {
return GetResponse4();
});
task1.ContinueWith(t => {
AsyncManager.Parameters["headers1"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task2.ContinueWith(t => {
AsyncManager.Parameters["headers2"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task3.ContinueWith(t => {
AsyncManager.Parameters["headers3"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task4.ContinueWith(t => {
AsyncManager.Parameters["headers4"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task3.ContinueWith(t => {
AsyncManager.OutstandingOperations.Decrement();
}, TaskContinuationOptions.OnlyOnFaulted);
}
public ActionResult IndexCompleted(string headers1, string headers2, string headers3, string headers4) {
ViewBag.Headers = string.Join("<br/><br/>", headers1, headers2, headers3, headers4);
return View();
}
public ActionResult Index2() {
ViewBag.Headers = string.Join("<br/><br/>", GetReponse1(), GetResponse2(), GetResponse3(), GetResponse4());
return View();
}
#region helpers
string GetReponse1() {
var req = (HttpWebRequest)WebRequest.Create("http://www.twitter.com");
req.Method = "HEAD";
var resp = (HttpWebResponse)req.GetResponse();
return FormatHeaders(resp.Headers);
}
string GetResponse2() {
var req2 = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
req2.Method = "HEAD";
var resp2 = (HttpWebResponse)req2.GetResponse();
return FormatHeaders(resp2.Headers);
}
string GetResponse3() {
var req = (HttpWebRequest)WebRequest.Create("http://google.com");
req.Method = "HEAD";
var resp = (HttpWebResponse)req.GetResponse();
return FormatHeaders(resp.Headers);
}
string GetResponse4() {
var req = (HttpWebRequest)WebRequest.Create("http://github.com");
req.Method = "HEAD";
var resp = (HttpWebResponse)req.GetResponse();
return FormatHeaders(resp.Headers);
}
private static string FormatHeaders(WebHeaderCollection headers) {
var headerStrings = from header in headers.Keys.Cast<string>()
select string.Format("{0}: {1}", header, headers[header]);
return string.Join("<br />", headerStrings.ToArray());
}
#endregion
}
</code></pre>
<p>I have also <code>Index2</code> method here which is synchronous and does the same thing.</p>
<p>I compare two operation execution times and there is major difference (approx. 2 seconds)</p>
<p>But I think I am missing lots of things here (exception handling, timeouts, etc). I only implement the exception handling on task3 but I don't think it is the right way of doing that. </p>
<p>What is your opinion on this code? How can it be improved?</p>
|
[] |
[
{
"body": "<p>I would certainly include exception handling in the process. I normally use try catch statements. This at least allows me to catch the exceptions and return a more meaningful and informative message vs letting a method create a silent exception that may not be returned.</p>\n\n<p>Example within the helper methods: </p>\n\n<pre><code> string GetReponse1() {\n try\n {\n var req = (HttpWebRequest)WebRequest.Create(\"http://www.twitter.com\");\n req.Method = \"HEAD\";\n var resp = (HttpWebResponse)req.GetResponse();\n return FormatHeaders(resp.Headers);\n }\n catch (Exception ex)\n c{\n throw new Exception(\"There was a problem creating web request\" + ex.InnerException);\n { \n }\n</code></pre>\n\n<p>Since you are making async calls I would look to handle timeouts or prolonged responses. You could do this by creating a timer (stopwatch class). I would allow this to be configurable by the user or within a config file but I would include a stopwatch object in the method that will cancel the async call and return a timeout response once \"x\" (10 seconds as an example) time was reached. You could include this with the helper methods so that the call will expire after a certain time. </p>\n\n<p>Additional examples of try catch statements or the stopwatch class may be found at:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"nofollow\">Stopwatch class MSDN</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx\" rel=\"nofollow\">Try Catch Statements</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T01:28:48.500",
"Id": "7398",
"ParentId": "7380",
"Score": "1"
}
},
{
"body": "<p>There is a lot of code repetition. I would create a custom class that inherits from Task and make it generic enough so you can have an array of your custom class and just loop through that array to do what you need to do.</p>\n\n<pre><code>class TaskController<T> : Task<T>\n{\n public TaskController(AsyncManager asyncManager, string asyncManagerParameter, Func<T> callback) : base(callback)\n {\n this.ContinueWith(t =>\n {\n //just for demonstration\n Console.WriteLine(t.Result);\n\n // Do some work with your asyncManager\n asyncManager.Parameters[asyncManagerParameter] = t.Result.ToString();\n });\n }\n}\n</code></pre>\n\n<p>I would also have <code>GetResponse</code> take a <code>string uri</code> as parameter instead of making a new <code>GetResponse</code> for each url that you want to use. </p>\n\n<pre><code>public static string GetResponse(string uri)\n{\n HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);\n req.Method = \"HEAD\";\n\n HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n\n return resp.Headers.ToString(); // just changed this for demonstration purposes\n}\n</code></pre>\n\n<p>and finally I would use it like this</p>\n\n<pre><code>AsyncManager asyncManager = new AsyncManager();\n\nTaskController<string>[] taskControllers = {\n new TaskController<string>(asyncManager, \"header1\", () => GetResponse(\"http://google.com\")),\n new TaskController<string>(asyncManager, \"header3\", () => GetResponse(\"http://www.twitter.com\"))\n};\n\nforeach (TaskController<string> tc in taskControllers)\n{\n tc.Start();\n}\n</code></pre>\n\n<p>It is much less code, you can reuse it later, you can very easily add a new TaskController if you want to work with another URL, and it's a lot more readable.</p>\n\n<p>To use this you will need to just edit <code>this.ContinueWith</code> inside <code>TaskController</code> and have it do whatever you want (decrement, etc)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T13:41:14.070",
"Id": "42957",
"ParentId": "7380",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7398",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:24:57.937",
"Id": "7380",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-3",
"asynchronous"
],
"Title": "Old-way of asynchronous programming in ASP.NET MVC 3"
}
|
7380
|
<blockquote>
<p>First number indicates the number of points, followed by N points
(x,y). Then the next number indicates Q num_queries, followed by Q queries:</p>
<ol>
<li>Reflect all points between point i and j both including along the
X axis. This query is represented as "X i j" </li>
<li>Reflect all points between point i and j both including along the Y axis. This query is
represented as "Y i j" </li>
<li>Count how many points between point i and j both including lie in each of the 4 quadrants. This query is
represented as "C i j"</li>
</ol>
<h3>Sample Input</h3>
<pre><code>4
1 1
-1 1
-1 -1
1 -1
5
C 1 4
X 2 4
C 3 4
Y 1 2
C 1 3
</code></pre>
<h3>Sample Output</h3>
<pre><code>1 1 1 1
1 1 0 0
0 2 0 1
</code></pre>
</blockquote>
<p>How can i improve this code for better metrics?</p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author cypronmaya
*/
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Quad_query {
private ArrayList<Point> arrayList;
public Quad_query(int capacity) {
this.arrayList = new ArrayList<Point>(capacity);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int num_of_points = scanner.nextInt();
Quad_query quad_query = new Quad_query(num_of_points);
for (int i = num_of_points; --i >= 0;) {
int x = scanner.nextInt();
int y = scanner.nextInt();
quad_query.add(x, y);
}
int num_of_queries = scanner.nextInt();
for (int i = num_of_queries; --i >= 0;) {
char c = scanner.next().charAt(0);
quad_query.query(c, scanner.nextInt() - 1, scanner.nextInt() - 1);
}
}
public void add(int x, int y) {
Point point = new Point(x, y);
arrayList.add(point);
}
public void query(char c, int i, int j) {
switch (c) {
case 'C':
queryC(i, j);
break;
default:
queryXY(c, i, j);
break;
}
}
public void queryC(int i, int j) {
int quad_1 = 0, quad_2 = 0, quad_3 = 0, quad_4 = 0;
for (int k = i; k <= j; k++) {
Point pnt = arrayList.get(k);
int pnt_x = pnt.x;
int pnt_y = pnt.y;
if (pnt_x > 0 && pnt_y > 0) {
quad_1++;
} else if (pnt_x < 0 && pnt_y > 0) {
quad_2++;
} else if (pnt_x < 0 && pnt_y < 0) {
quad_3++;
} else if (pnt_x > 0 && pnt_y < 0) {
quad_4++;
}
}
System.out.println(quad_1 + " " + quad_2 + " " + quad_3 + " " + quad_4);
}
private void queryXY(char c, int i, int j) {
for (int k = i; k <= j; k++) {
Point pnt = arrayList.get(k);
int pnt_x = pnt.x;
int pnt_y = pnt.y;
if (c == 'X') {
pnt = new Point(pnt_x, -pnt_y);
} else if (c == 'Y') {
pnt = new Point(-pnt_x, pnt_y);
}
arrayList.set(k, pnt);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T22:33:25.333",
"Id": "11578",
"Score": "1",
"body": "Can you add the expected output for the input you gave ?\n\nAs a first quick and useless comment, I would say that variable \"num_of_points\" is not really useful."
}
] |
[
{
"body": "<p>Instead of initializing your arrayList when you create the instance of the class, do it when you have the num_of_points value from the scanner.</p>\n\n<pre><code>arrayList = new ArrayList<Point>(num_of_points);\n</code></pre>\n\n<p>This will mean the array list doesn't need to resize itself (potentially slow operation). In the example you have given with only 4 points it won't make any difference, but if there were a larger number of points you may save some time!</p>\n\n<p>Where you get the value from the scanner <code>char c</code> you trim the value, which you shouldn't need to do as the Scanner should stop when it sees a delimiter (in this case, a space).</p>\n\n<p>In the <code>queryC</code> method, you have a for loop...</p>\n\n<pre><code>for (int b = 0; b < len; b++) {\n pnt = arrayList.get(b);\n}\n</code></pre>\n\n<p>...that does nothing, so you can remove it.</p>\n\n<p>A few notes on code style...</p>\n\n<ul>\n<li>In the main method your for loops go from X down to 0, but in the query methods you go from 0 up to X. Just wondering why?</li>\n<li>You also use <code>(0 - pnt.x)</code> where you could use <code>-pnt.x</code>.</li>\n</ul>\n\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T03:59:06.173",
"Id": "11582",
"Score": "0",
"body": "sorry,i forgot to remove that useless loop before only,regarding (o-pnt.x) -- written simply, loops go down in main method from X->0 because i wouldn't use the loop variable in it,the way i've written loops in main method, would optimized one's"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T04:00:44.000",
"Id": "11583",
"Score": "0",
"body": "those trim, that i've done just for safety purposes,i know scanner would take exactly what to take, but simply, please look at modified version"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T14:49:19.247",
"Id": "11620",
"Score": "0",
"body": "@cypronmaya The only other thing I can see is that you have used variables ``int pnt_x = pnt.x`` I wouldn't bother with this variable as the compiler should inline it anyway. \nIt is coded in a pretty readable manner which as @MikeNakis said, is the main thing to worry about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T14:51:25.190",
"Id": "11621",
"Score": "0",
"body": "Also you say that you write the for loops in the main method that way because you're not using the loop variable inside the loop - why not turn it into a much more readable while loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T14:53:26.813",
"Id": "11623",
"Score": "0",
"body": "Ya, u've given lot of usefull inpur, but still i'm not able to achieve the req thing, execution time failed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:00:35.617",
"Id": "11624",
"Score": "0",
"body": "before i could pass all testcases :(, donno what i'm doing wrong , all these modifications would only increase readability,optimized. May be my implementation is worse, if u've found any simpler form for this solution , i would be greatful"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:27:55.513",
"Id": "11625",
"Score": "0",
"body": "are you supposed to read from standard input? this would take a long time and would have significant effect on the time it takes for your program to complete. Could you read from file instead? It will read quicker from file as it's not waiting for you to type anything in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T16:23:26.340",
"Id": "11631",
"Score": "0",
"body": "no, i can't change rules, they will gimme in STDIN and should give output in STDOUT, they have their own testcases, constraints etc.,"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T16:27:40.290",
"Id": "11632",
"Score": "0",
"body": "Try putting arrayList.add and arrrayList.remove back in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T16:32:11.210",
"Id": "11633",
"Score": "0",
"body": "arrayList.set would combinedly do those right....."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T16:47:37.160",
"Id": "11635",
"Score": "0",
"body": "it should do what you want it to do, but I wonder if it might be the change that has had a sudden performance hit on your code. None of the other changes should have affected it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T17:21:58.350",
"Id": "11636",
"Score": "0",
"body": "changes done to the initial one, done nothing(in metrics).... increased readability, cleaner version."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T23:14:08.680",
"Id": "7392",
"ParentId": "7383",
"Score": "3"
}
},
{
"body": "<p><code>for (int i = num_of_queries; --i >=0;)</code> is cute, but it makes one pause for a moment and think whether it is correct or not before moving on. It is better rewritten as <code>for (int i = num_of_queries; i > 0; i--)</code>.</p>\n\n<p>Your arraylist is allocated once and never changed, (its contents are ganged, but not the object itself,) so it should be declared as <code>final</code>. Right before you start using it, since you know how many items are going to go into it, do <code>arrayList.ensureCapacity(num_of_points);</code> so as to help it to avoid resizing itself as it is discovering its capacity by itself.</p>\n\n<p>Use better names; <code>quad_qu</code> should be <code>quad_queue</code> or perhaps just <code>queue</code>.</p>\n\n<p>In <code>QueryC</code>:</p>\n\n<p>Get rid of the <code>pnt_x</code> and <code>pnt_y</code> variables and simply use <code>pnt.x</code> and <code>pnt.y</code> instead.</p>\n\n<p>Declare <code>pnt</code> inside the loop, not outside it: <code>Point pnt = arrayList.get(k);</code></p>\n\n<p>Rename <code>pnt</code> to <code>point</code>, or <code>pt</code>, or just <code>p</code>.</p>\n\n<p>In <code>QueryXY</code>:</p>\n\n<p>Again, declare <code>pnt</code> inside the loop, not outside it.</p>\n\n<p>Declare <code>new_pnt</code> inside the loop, too, and <em>do not initialize it to null</em>. It is bad practice to initialize things when there is no need. It prevents the compiler from giving you useful warnings. When you do this, the compiler will give you a warning that you may be trying to use <code>new_pnt</code> before you have assigned a value to it. That's because your if statement checks for <code>'X'</code>, and then for <code>'Y'</code>, but there is no <code>else</code> clause to handle any other possibility. So, add an <code>else</code> clause and throw an exception: <code>throw new Exception(\"wtf?\")</code></p>\n\n<p>Get rid of these: <code>int pnt_x = 0, pnt_y = 0;</code> they are not used. Actually, the fact that you have these in your code, and you have not seen a compiler warning about them not being used, tells me that you are not compiling with all warnings enabled. Do yourself a favor and enable all warnings so as to have the compiler help you. That's his job.</p>\n\n<p>Replace this:</p>\n\n<pre><code>arrayList.remove(k);\narrayList.add(k, new_pnt);\n</code></pre>\n\n<p>With simply this: <code>arrayList.set(k, new_pnt);</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:20:12.077",
"Id": "11594",
"Score": "0",
"body": "Speaking of -> for (int i = num_of_queries; --i >=0;) is lot better, it removes useless checks and optimized.\n-> ensureCapacity it's better only if i'm having lots of records, atleast more than 10(initial capacity).As i'm having very few records, i don't it doesn't really matter ....:P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:26:27.527",
"Id": "11597",
"Score": "0",
"body": "Regarding names,un-necessary variables,declarations thanks. BTW i've initialized it to null as compiler thrown me a warning.\nAbout replacing this \"arrayList.remove(k);\narrayList.add(k, new_pnt);\" ----> Here first i'm removing the element at pos-k and then inserting newly modified element at the same position. As u suggested arrayList.set(k, new_pnt); , what it does is , it doesn't replace the existing element, it only checks if an element exists, if so their index will be increased and new_element is inserted at tht position."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:28:14.260",
"Id": "11598",
"Score": "0",
"body": "Regarding `ensureCapacity`, you are right. Regarding the `for` loop, the compiler will optimize it for you anyway, so you don't have to worry about it. Even if the compiler was not going to optimize it, readability is usually far more important than minuscule optimizations. The couple of seconds I wasted looking at it represent a much longer time period than the sum of all the nanoseconds that would ever be saved by this little optimization on all the runs of your application by all the users who will ever see it in all the years that it is going to be in use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:33:34.550",
"Id": "11599",
"Score": "0",
"body": "Regarding ->Get rid of the pnt_x and pnt_y variables and simply use pnt.x and pnt.y instead.-> If i didn't use pnt_x,pnt_y, every time is use pnt.x,pnt.y in if conditional's it has to calculate or get wht is pnt.x and pnt.y from object, so for that, i've assigned them to pnt_x,pnt_y, so that they don't have to be calculated again and again.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:35:17.123",
"Id": "11600",
"Score": "0",
"body": "Can u comment on the approach i've followed? any unnecessary methods, unnecessary loops,is it too obvious or lengthy or lame one?. Can u suggest a good approach to solve this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:44:35.560",
"Id": "11603",
"Score": "0",
"body": "Regarding the initialization to null, the warning, and why you should do it the way I suggested, read this: http://codereview.stackexchange.com/a/6329/8381 starting from \"One more note:\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:46:14.983",
"Id": "11604",
"Score": "1",
"body": "arrayList.set( k, new_pnt ) will do exactly what I intended it to do; don't theorize about it when you can just look it up: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#set(int, E)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:52:05.593",
"Id": "11605",
"Score": "0",
"body": "Regarding pnt_x and pnt_y, studies have shown that when humans try to hand-optimize code at that level, the results are in most cases **worse** than if they had left the compiler do it for them, and in the majority of the remaining cases they are no better than what the compiler would have done by itself, anyway. Declaring your own variables instead of letting the compiler use what is known as \"inference variables\" is a typical example of such a well meant, but ill advised optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:53:52.427",
"Id": "11606",
"Score": "0",
"body": "Sorry about set method, ya it does exactly what u've said,i've forgot to see the name set,it looked like add to me :P to say like that. Regarding initialization , i completely agree"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:55:20.990",
"Id": "11607",
"Score": "1",
"body": "In any case, my advise to you would be to stop worrying about performance so much. The rule in the industry is to code things in the simplest, most readable and most maintainable way possible, then establish performance requirements, then measure the software against these requirements, and if and only if the software fails to meet these requirements, go optimize that 1% of the code which will make the software meet the requirements. And usually, these optimizations turn out to be algorithmic, not hacky."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:55:56.623",
"Id": "11608",
"Score": "1",
"body": "As to the approach you followed, no, I have nothing to say about that, it seems just fine to me."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:05:47.013",
"Id": "7410",
"ParentId": "7383",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T20:00:09.787",
"Id": "7383",
"Score": "3",
"Tags": [
"java",
"homework",
"coordinate-system"
],
"Title": "Reflecting and counting points on a 2D grid"
}
|
7383
|
<p>I'm calling this function from my html (and in some cases from another function in my JavaScript). These type of <code>switch</code> statements are starting to litter my code. Is there a more elegant solution to these <code>if</code> statements? I wish I could pass a reference to the variables I want to modify. I'm finally asking the question because now I have a situation where if I do it this same way, I'm going to have an ugly <code>switch</code> statement with hundreds of cases which I'm guessing not only looks ugly, but will hurt performance.</p>
<pre><code>function incCriteriaStats(exp){
switch (exp) {
case "a":
numOfA++;
break;
case "b":
numOfB++;
break;
case "c":
numOfC++;
break;
case "d":
numOfD++;
break;
case "e":
numOfE++;
break;
case "f":
numOfF++;
break;
case "g":
numOfG++;
break;
}
|
</code></pre>
|
[] |
[
{
"body": "<p>Use an object, with the keys being the letters, and then you can just do:</p>\n\n<pre><code>function incCriteriaStats(exp) {\n if(exp in obj)\n obj[exp]++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T21:34:48.197",
"Id": "11576",
"Score": "0",
"body": "Sorry - looks like your slick answer that beat me by a minute was moved to this black hole. Don't take it too hard, it's happened to me before."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T17:43:31.627",
"Id": "7386",
"ParentId": "7385",
"Score": "12"
}
},
{
"body": "<p>Why not use an object to store the values for <code>a</code>, <code>b</code>, <code>c</code>, etc, rather than using separate <code>numOfA</code>, <code>numOfB</code>, etc variables:</p>\n\n<pre><code>var obj = { \n \"a\": 0,\n \"b\": 0,\n \"c\": 0,\n \"d\": 0,\n \"e\": 0,\n \"f\": 0,\n \"g\": 0\n};\n</code></pre>\n\n<p>This will allow you to do something nice and simple like this:</p>\n\n<pre><code>function incCriteriaStats(exp){\n if (obj[exp] != null)\n obj[exp]++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T17:46:04.967",
"Id": "11574",
"Score": "1",
"body": "Beat you by just a minute :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T17:58:48.293",
"Id": "11575",
"Score": "0",
"body": "@Dhaivat ok +1 - I found [this question](http://stackoverflow.com/a/8703764/352552) so I guess I'm over it :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T17:44:35.653",
"Id": "7387",
"ParentId": "7385",
"Score": "7"
}
},
{
"body": "<pre><code>var obj={};\nfunction incCriteriaStats(exp) {\n if (typeof(obj[exp]==\"undefined\") {\n obj[exp]=1;\n } else {\n obj[exp]++;\n }\n}\n</code></pre>\n\n<p>The object obj will end up like: </p>\n\n<pre><code>{\n \"a\": 4,\n \"b\": 5,\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T17:57:16.797",
"Id": "7388",
"ParentId": "7385",
"Score": "2"
}
},
{
"body": "<p>Obj isn't accessible from global scope, you can only get it by calling <code>incCriteriaStats</code> which increment key <code>exp</code> in <code>obj</code> var and return it </p>\n\n<pre><code>var incCriteriaStats = (function( ) {\n var obj={}\n return function( exp ) { \n exp ? obj[ exp ] = ( obj[ exp ] || 0 ) +1 : 0;\n return obj;\n }\n })();\n\nincCriteriaStats( \"a\" )\nincCriteriaStats( \"a\" )\nincCriteriaStats( \"a\" )[ \"a\" ] // 3\nincCriteriaStats( \"a\" )[ \"a\" ] // 4\nincCriteriaStats( \"b\" );\n\nvar obj = incCriteriaStats() // get the `obj` from inside incCriteriaStatus without modifying it;\nobj.a == 4; //true\nobj.b == 1; //true\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T18:55:18.527",
"Id": "7389",
"ParentId": "7385",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T17:41:40.527",
"Id": "7385",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Looking for a better solution than a bunch of switch statements in my JavaScript"
}
|
7385
|
<p>I would like to simplify to following function as much as possible:</p>
<pre><code>public string[] GetPowerSet(string input)
{
IEnumerable<IEnumerable<string>> seed = new List<IEnumerable<string>>() { Enumerable.Empty<string>() };
return input.Split(',').ToList().Aggregate(seed, (a, b) =>
a.Concat(a.Select(x => x.Concat(new List<string>() { b })))).Select(subset => string.Join(",", subset.ToArray())).Skip(1).ToArray();
}
</code></pre>
|
[] |
[
{
"body": "<p>Can't say I've simplified it much... but I've removed some syntactic extras that were unnecessary in the original version, made the method itself static (no reliance on instance data or methods) and hoisted out the seed to a one-time initialized class-level variable for speed/GC (over multiple calls) sake:</p>\n\n<pre><code>private static readonly IEnumerable<IEnumerable<string>> seed =\n new List<IEnumerable<string>> { Enumerable.Empty<string>() };\n\npublic static string[] GetPowerSet(string input)\n{\n return input.Split(',').Aggregate(\n seed,\n (a, b) => a.Concat(a.Select(x => x.Concat(new[] { b })))).Select(subset => string.Join(\",\", subset)).Skip(1).ToArray();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:23:51.257",
"Id": "7461",
"ParentId": "7390",
"Score": "1"
}
},
{
"body": "<p>Man, it's been quite a while since I've had to deal with powerset. I don't really know what your code is doing, but you could simplify it and make it more readable by creating some general utility functions and with some thoughtful use of whitespace. Below is the best I can come up with:</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string Join(this IEnumerable<string> source, string separator)\n {\n using (var enumerator = source.GetEnumerator())\n {\n if (enumerator.MoveNext())\n {\n StringBuilder builder = new StringBuilder(enumerator.Current);\n\n while (enumerator.MoveNext())\n {\n builder.Append(separator).Append(enumerator.Current);\n }\n\n return builder.ToString();\n }\n }\n\n return null;\n }\n}\n\npublic static class EnumerableExtensions\n{\n public static IEnumerable<T> Append<T>(this IEnumerable<T> first, T second)\n {\n foreach (var item in first)\n {\n yield return item;\n }\n\n yield return second;\n }\n\n public static IEnumerable<T> Append<T>(this IEnumerable<T> first, params T[] second)\n {\n foreach (var item in first)\n {\n yield return item;\n }\n\n foreach (var item in second)\n {\n yield return item;\n }\n }\n}\n\npublic static class PowerSet\n{\n public static string[] GetPowerSet(string input)\n {\n IEnumerable<IEnumerable<string>> seed = new List<IEnumerable<string>>() { Enumerable.Empty<string>() };\n\n return input.Split(',').Aggregate(\n seed,\n (a, b) => a.Concat(\n a.Select(x => x.Append(b))\n )\n ).Select(\n subset => subset.Join(\",\")\n ).Skip(1).ToArray();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:35:36.270",
"Id": "7462",
"ParentId": "7390",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7461",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T21:52:19.830",
"Id": "7390",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Simplify a powerset function in C#"
}
|
7390
|
<p>I recently asked for some advice on the best way to structure my code for a program I was writing. (see <a href="https://softwareengineering.stackexchange.com/questions/127841/how-to-structure-this-program">this question on Programmers.SE</a>). The solution I was given was quite elegant, however I am less happy with the code that I've written so that the UI remains responsive.</p>
<p>Here is my code, I will outline the reasons I am not happy with it below:</p>
<pre><code> private void buttonUpdateContacts_Click(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
(sender as BackgroundWorker).ReportProgress(0, "Parsing word document...");
WordDocumentParser wordDocumentParser;
try
{
wordDocumentParser = new WordDocumentParser(Settings.Default.OohSheetLocation);
}
catch (FileNotFoundException exception)
{
e.Result = new FileNotFoundException("Could not find the word document. File path is: " + exception.FileName, exception);
return;
}
List<TppContact> oohSheetContacts = wordDocumentParser.GetContacts();
try
{
_contactManager = GoogleContactsManager.CreateContactsManager();
}
catch (InvalidCredentialsException argumentException)
{
e.Result = argumentException;
return;
}
catch (ArgumentNullException nullArg)
{
e.Result = nullArg;
return;
}
(sender as BackgroundWorker).ReportProgress(0, "Comparing Google contacts to the word document...");
var comparer = new ContactComparer(oohSheetContacts, _contactManager);
_actions = comparer.Compare();
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
labelCurrentStatus.Text = e.UserState.ToString();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
MessageBox.Show((e.Result as Exception).Message);
}
else
{
if (_actions.Count == 0)
{
textBoxChanges.Text = "There are no changes to be made.";
buttonApplyChanges.Enabled = false;
}
else
{
textBoxChanges.Text = string.Empty;
_actions.ForEach(action => textBoxChanges.Text += action.ChangeDescription + Environment.NewLine);
buttonApplyChanges.Enabled = true;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
labelCurrentStatus.Text = "Updating Google...";
_contactManager.UpdateContacts(_actions);
labelCurrentStatus.Text = "Done.";
}
</code></pre>
<ol>
<li><p>I don't like how tied up my code is to the background worker. For example, to handle the exceptions that the various methods can throw, I have to set the result of the background worker to be the exception then handle it in the <code>worker_RunWorkerCompleted</code> method. This also means that I lose the ability to give the user proper error messages such as "invalid username and password supplied". Maybe the answer is to set that as the result rather than the exception?</p></li>
<li><p>It goes without saying that I probably shouldn't have all this logic being called from the button clicked method but I am unsure of a better way to do it. This is written in WinForms at the minute but there's very little reason not to write it in WPF.</p></li>
<li><p>Am I using the best structure here? I tried to use <code>Tasks</code> but didn't get very far and I've used background workers in the past so I know how they work.</p></li>
</ol>
<p>Can you offer any pointers how to make this code "better" or am I doing it the best I can?</p>
|
[] |
[
{
"body": "<p>1) I would use the <code>ProgressChanged</code> event with a custom object as my <code>e.UserState</code> which is updated within the code.</p>\n\n<pre><code>// sample worker state class definition\ninternal class WorkerState\n{\n public Exception ExceptionThrown { get; set; }\n public string ProgressMessage { get; set; }\n public int MaximumProgressValue { get; set; }\n public int ProgressValue { get; set; }\n public int Actions { get; set; }\n} \n</code></pre>\n\n<p><strong>Sample Usage</strong></p>\n\n<pre><code>// this would likely be initialized / reinitiatlized before the RunWorkerAsync is called\nprivate WorkerState m_WorkerState; \n\nprivate void buttonUpdateContacts_Click(object sender, EventArgs e)\n{\n // for question 2) this could be convered into some form of\n // factory where providing delegates for the ProgressChange and WorkCompleted\n BackgroundWorker worker = new BackgroundWorker(); \n\n worker.UserState = new WorkerState();\n\n worker.WorkerReportsProgress = true; \n worker.DoWork += new DoWorkEventHandler(worker_DoWork); \n worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); \n worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); \n worker.RunWorkerAsync(); \n} \n\nvoid worker_DoWork(object sender, DoWorkEventArgs e) \n{ \n Worker worker = (sender as BackgroundWorker);\n WorkerState state = worker.UserState;\n\n state.UserState.ProgressMessage = \"Parsing word document...\";\n state.UserState.MaximumProgressValue = 100;\n state.UserState.ProgressValue = 0;\n\n worker.ReportProgress(0, state); \n\n // ...\n\n try\n {\n // do something\n }\n catch (InvalidCredentialsException argumentException)\n {\n e.ExceptionThrown = argumentException;\n return;\n }\n catch (ArgumentNullException nullArg)\n {\n e.ExceptionThrown = nullArg;\n return;\n }\n\n // ..\n} \n</code></pre>\n\n<p>2) There is not too much wrong with putting the code in the button click event but you could make better use of OO concepts like factories for creating the <code>BackgroundWorker</code> component etc. I personally would split the bulk of the code in the <code>DoWork</code> method into seperate classes following SOLID principles (especially the Single Responsibility... this class is responsible for blah, blah blah).</p>\n\n<p>3) Tasks are likely to be unsuitable in this case as this is exactly what the <code>BackgroundWorker</code> component was designed for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T10:34:35.160",
"Id": "11609",
"Score": "0",
"body": "I like the idea of using a custom class for the `UserState` on the background worker, it's much more obvious what's happening and what I'm trying to report. I'm not so sure how to accomplish what you suggested for part 2 though. The work that I'm actually doing is already split into separate classes (eg: `GoogleContactManager`). Could you maybe elaborate on how you would write this code, possibly with an example? Also, I don't understand how a factory method for the background worker would help? Do you mean create a separate class for this specific piece of functionality?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T06:52:09.930",
"Id": "7408",
"ParentId": "7391",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-02T22:27:33.563",
"Id": "7391",
"Score": "3",
"Tags": [
"c#",
"multithreading",
"event-handling",
"user-interface"
],
"Title": "Keeping UI responsive while performing long running task"
}
|
7391
|
<p>Below is one of the first classes I've built. I started creating my functions like so:</p>
<pre><code>public function getCourseInfoByID($id) { }
</code></pre>
<p>Requiring the user to pass a course ID. I've recently modified it to assign the course ID (and <code>$course_info</code> - an array to reference each element from the DB) in the constructor, and I'd like to get some feedback if I'm doing it properly (I figured <code>$course->getCourseInfo();</code> was much better than <code>$course->getCourseInfoByID(1);</code>):</p>
<pre><code>class Course {
var $course_id;
var $course_info;
// The constructor just sets the database object
public function __construct($mysqli, $course_id = NULL) {
global $error;
$this->mysqli = $mysqli;
// If course_id is present (referencing a course instead of creating one, let's validate it and assign the course_id to the object)
if($course_id != NULL) {
if(! $course_info = $this->getCourseInfo($course_id)) {
$error[] = "Invalid Course ID";
setError();
return FALSE;
}
$this->course_id = $course_id;
$this->course_info = $course_info;
}
}
public function getCourseInfo($id = NULL) {
if($id == NULL) {
$id = $this->course_id;
}
$result = $this->mysqli->query("SELECT courses.*, students.first_name, students.last_name, course_types.name as course_type_name
FROM courses as courses
JOIN students as students on students.id=courses.instructor_id
JOIN course_types as course_types on course_types.id=courses.course_type_id
WHERE courses.id='$id'");
$course_info = $result->fetch_array(MYSQL_ASSOC);
// If found, return the student object
if($course_info) {
return $course_info;
}
return FALSE;
}
public function displayCourseInfo($id = NULL) {
global $error;
if($id == NULL) {
$id = $this->course_id;
}
// HTML to display each element of $this->course_info[]
// acccessible anytime by doing: $course->displayCourseInfo() in the script
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Going from top to bottom:</p>\n\n<p><strong>Constructor</strong> </p>\n\n<pre><code>public function __construct($mysqli, $course_id = NULL) {\n</code></pre>\n\n<p>What kind of object is '$mysqli'? You can probably <a href=\"http://php.net/manual/en/language.oop5.typehinting.php\" rel=\"nofollow noreferrer\">type-hint</a> it.</p>\n\n<pre><code> global $error;\n</code></pre>\n\n<p>Globals are bad. Forget about them (like you were <a href=\"https://codereview.stackexchange.com/questions/7331/first-oop-class\">told</a>).</p>\n\n<pre><code> $this->mysqli = $mysqli;\n\n // If course_id is present (referencing a course instead of creating one, let's validate it and assign the course_id to the object)\n if($course_id != NULL) {\n if(! $course_info = $this->getCourseInfo($course_id)) {\n $error[] = \"Invalid Course ID\";\n setError();\n</code></pre>\n\n<p>Setting errors is so c-style. Use exceptions.</p>\n\n<pre><code> return FALSE; \n</code></pre>\n\n<p>Not even sure this does work. If it does - don't do it. Throw an exception. See <a href=\"https://stackoverflow.com/questions/2214724/php-constructor-to-return-a-null\">this</a> discussion about return-values in constructors. </p>\n\n<pre><code> }\n\n $this->course_id = $course_id;\n $this->course_info = $course_info;\n</code></pre>\n\n<p>You might cast them to the corresponding data type. For example <code>intval($course_id)</code>.</p>\n\n<pre><code> }\n}\n</code></pre>\n\n<p>I would refactor this to (or something likish):</p>\n\n<pre><code>public function __construct(MyDBLayer $db, $courseId)\n{\n if($db == NULL)\n {\n throw new InvalidArgumentException('$db must not be null');\n }\n\n if($userId == NULL)\n {\n throw new InvalidArgumentException('$courseId must not be null');\n }\n\n $courseInfo = $this->getCourseInfo($courseID);\n if($courseInfo == NULL)\n {\n throw new MyCustomException(\"No Course found for id \" + $courseID);\n }\n\n $this->dbAdapter = $db;\n $this->courseId = intval($courseId);\n $this->courseInfo = $courseInfo;\n}\n</code></pre>\n\n<p>Or even make it a static method <code>load</code> or a <a href=\"http://en.wikipedia.org/wiki/Datamapper\" rel=\"nofollow noreferrer\">data mapper</a>:</p>\n\n<pre><code>public static function load(MyDBLayer $db, $courseId)\n{\n // do all the stuff as in the constructor\n return new Course($courseId, $courseInfo);\n}\n</code></pre>\n\n<p><strong>The other functions</strong></p>\n\n<p>Pretty much the same as for the constructor. Don't use global, use exceptions instead. Don't write the html code for displaying in this class. Every class should only have <strong>one</strong> responsibility. In this case: representing a course, not displaying it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T02:12:23.067",
"Id": "11580",
"Score": "2",
"body": "I agree with all of that except static. Static should almost never appear in object oriented code. It binds the code tightly making testing more difficult. It is the equivalent of referring to a global function (it is completely procedural code)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T02:15:16.340",
"Id": "11581",
"Score": "0",
"body": "@Paul: I totally aggree. However using static is the easy (but not that good) way to seperate the loading functionality from the actual data representation. The prefered way are data mappers of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T10:18:16.293",
"Id": "11729",
"Score": "0",
"body": "I'd agree that the only sensible way to tell the outside world that the constructor failed is to throw an exception. However, I'd contend that in general exceptions should be used sparingly. They introduce unpredictable program flow control (they've been described as fancy gotos, while I wouldn't go that far they can lead to confusion if overused), they also have a significant performance impact compared to other flow control structures. I'd reserve exceptions for exceptional events, such as input failing basic sanity checks. For sane but incorrect input I'd return false instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:03:52.590",
"Id": "11736",
"Score": "0",
"body": "Exceptions do **not** pose any signifanct performance issue (check stackoverflow for various posts about that). Exceptions should only be thrown if something goes wrong, having no db-result is probably no exception. Invalid parameters sure are (mostly because it's the programmer's fault). And if the program flow is unpredictable with exceptions you're probably using them in a wrong manner. Actually they make error handling a **lot** easier at the place of where they can be handled accordingly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T01:57:19.400",
"Id": "7400",
"ParentId": "7395",
"Score": "2"
}
},
{
"body": "<p>Good stuff: </p>\n\n<ul>\n<li>Passing the DB connection to your constructor, this is dependency injection and is encouraged as it makes objects less tightly coupled and it makes unit testing easier. </li>\n<li>The class appears to be only implementing code to deal with the area for which it's directly responsible. There's always a temptation in OOP to add more code to an object to easily facilitate additional features, but you should only add code that you need, and you certainly should not add code that's not directly related to the area of responsibility of the class. </li>\n</ul>\n\n<p>Bad stuff: </p>\n\n<ul>\n<li><code>global $error</code> Global state is BAD. It should be avoided at all costs</li>\n<li>public properties: $course_id and $course_info are public, meaning that any external entity can access them and change their values at any time. An object is responsible for its own state, it shouldn't allow outside entities access it except through controlled channels (getters and setters). Make your properties private or protected, and provide getters as needed. </li>\n<li>No type hinting: You can (and should) use PHP5's type hinting features to prevent inappropriate data being passed into your class methods. For example there's nothing stopping someone from passing a variable into your class that isn't a mysqli database connection. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T09:05:40.967",
"Id": "7481",
"ParentId": "7395",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T00:38:40.730",
"Id": "7395",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "PHP: Learning OOP"
}
|
7395
|
<p>I am writing a prototype for something at work. Not very many people here know much about Linux/Unix or Xlib, so I can't really ask here at work (most developers are expert Windows programmers). With this said, I have one class and a driver that I would like feedback on how well I have integrated threads, XLib and OpenGL.</p>
<p>The order of the files below is: </p>
<ol>
<li>glx_data.h</li>
<li>linux_main.cpp</li>
<li>map.h</li>
<li>map.cpp</li>
<li>Makefile</li>
</ol>
<p></p>
<pre><code>// 1. glx_data.h
#ifndef GLX_DATA_
#define GLX_DATA_
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glu.h>
typedef
struct glx_data
{
Display *dpy;
Window win;
XVisualInfo *vi;
Colormap cmap;
XSetWindowAttributes swa;
GLXContext cx;
XEvent event;
int dummy;
bool double_buffer;
} GLXDATA;
#endif//GLX_DATA
</code></pre>
<p><strong>linux_main.cpp</strong></p>
<pre><code>#include "glx_data.h"
#include "map.h"
static int snglBuf[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12, None };
static int dblBuf[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12,
GLX_DOUBLEBUFFER, None };
//Global Data
static Map *gsp_Map;
static GLXDATA glxdata;
bool init_instance() {
glxdata.dpy = XOpenDisplay(NULL);
if (glxdata.dpy == NULL) {
fprintf(stderr, "Failed to get XDisplay\n");
return false;
}
if (!glXQueryExtension( glxdata.dpy,
&glxdata.dummy,
&glxdata.dummy)) {
fprintf(stderr, "X server has no OpenGL GLX extension");
return false;
}
glxdata.vi = glXChooseVisual( glxdata.dpy,
DefaultScreen(glxdata.dpy),
dblBuf);
if (NULL == glxdata.vi) {
glxdata.vi = glXChooseVisual( glxdata.dpy,
DefaultScreen(glxdata.dpy),
snglBuf
);
if (NULL == glxdata.vi) {
fprintf(stderr, "No RGB visual with depth buffer");
return false;
}
glxdata.double_buffer = false;
} else {
glxdata.double_buffer = true;
}
glxdata.cmap = XCreateColormap( glxdata.dpy,
RootWindow(
glxdata.dpy,
(glxdata.vi)->screen
),
(glxdata.vi)->visual,
AllocNone);
glxdata.swa.colormap = glxdata.cmap;
glxdata.swa.border_pixel = 0;
glxdata.swa.event_mask = ExposureMask | ButtonPressMask |
StructureNotifyMask;
glxdata.win = XCreateWindow( glxdata.dpy,
RootWindow(
glxdata.dpy,
(glxdata.vi)->screen
),
0, 0,
300, 300,
0,
(glxdata.vi)->depth,
InputOutput,
(glxdata.vi)->visual,
CWBorderPixel | CWColormap |
CWEventMask,
&glxdata.swa
);
XSetStandardProperties(
glxdata.dpy,
glxdata.win,
"glxsimple",
"glxsimple",
None,
NULL,
0,
NULL
);
/*
* After window is set and glx context configured
* Note that we have not created the glx context yet
*/
gsp_Map = new Map(&glxdata, 300, 300);
/*
* Now we can show the window and go to main message loop
*/
XMapWindow(glxdata.dpy, glxdata.win);
return true;
}
void
message_loop()
{
while (1) {
do {
XNextEvent(glxdata.dpy, &glxdata.event);
switch (glxdata.event.type) {
case ButtonPress:
switch (glxdata.event.xbutton.button) {
case 1:
gsp_Map->inc_xrotate(10);
gsp_Map->set_update(true);
break;
case 2:
gsp_Map->inc_yrotate(10);
gsp_Map->set_update(true);
break;
case 3:
gsp_Map->inc_zrotate(10);
gsp_Map->set_update(true);
break;
}
break;
case ConfigureNotify:
gsp_Map->set_deminsions(
glxdata.event.xconfigure.width,
glxdata.event.xconfigure.height
);
case Expose:
gsp_Map->set_update(true);
break;
}
} while (XPending(glxdata.dpy));
}
pthread_join(gsp_Map->get_pthread(), NULL);
}
int
main(int argc, char *argv[]) {
if (!init_instance()) {
fprintf(stderr, "Failed to initialize application instance\n");
}
message_loop();
if(gsp_Map) {
delete gsp_Map;
}
}
</code></pre>
<p><strong>map.h</strong></p>
<pre><code>#ifndef MAP_H_
#define MAP_H_
#include "glx_data.h"
class Map
{
public:
Map();
Map(Map &copy);
Map(GLXDATA *glxdata, int width, int height);
~Map();
inline pthread_t &get_pthread() {return m_render_thread;}
inline void set_update(bool update) {m_update = update;}
inline void inc_xrotate(GLfloat deg)
{
if ((m_xAngle + deg) < 360) {
m_xAngle += deg;
} else {
m_xAngle = deg - (360 - m_xAngle);
}
}
inline void inc_yrotate(GLfloat deg)
{
if ((m_yAngle + deg) < 360) {
m_yAngle += deg;
} else {
m_yAngle = deg - (360 - m_yAngle);
}
}
inline void inc_zrotate(GLfloat deg)
{
if ((m_zAngle + deg) < 360) {
m_zAngle += deg;
} else {
m_zAngle = deg - (360 - m_zAngle);
}
}
inline void set_deminsions(int width, int height)
{
m_width = width;
m_height = height;
}
void render_data();
private:
GLXDATA *m_pglxdata;
pthread_t m_render_thread;
bool m_render;
bool m_update;
bool m_update_viewport;
int m_width;
int m_height;
GLfloat m_xAngle;
GLfloat m_yAngle;
GLfloat m_zAngle;
static void *create_pthread(void *data)
{
Map *thread_map = static_cast<Map *>(data);
thread_map->render_data();
return data;
}
};
#endif//MAP_H_
</code></pre>
<p><strong>map.cpp</strong></p>
<pre><code>#include "map.h"
Map::Map()
{
}
Map::Map(Map &copy)
{
}
Map::Map(GLXDATA *glxdata, int width, int height)
{
m_width = width;
m_height = height;
m_render = true;
m_update = true;
m_update_viewport = true;
m_xAngle = 42.0;
m_yAngle = 82.0;
m_zAngle = 112.0;
this->m_pglxdata = glxdata;
pthread_create(&m_render_thread, NULL, Map::create_pthread, this);
}
void Map::render_data()
{
m_pglxdata->cx = glXCreateContext(
m_pglxdata->dpy,
m_pglxdata->vi,
None,
True
);
if (NULL == m_pglxdata->cx) {
fprintf(stderr, "could not create rendering context");
return;
}
glXMakeCurrent(m_pglxdata->dpy, m_pglxdata->win, m_pglxdata->cx);
static Bool displayListInited = false;
glEnable(GL_DEPTH_TEST);
while(m_render) {
if(m_update_viewport) {
glViewport(0, 0, m_width, m_height);
m_update_viewport = false;
m_update = true;
}
if(m_update) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, 1, 1, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -3.0);
glRotatef(m_xAngle, 0.1, 0.0, 0.0);
glRotatef(m_yAngle, 0.0, 1.0, 0.0);
glRotatef(m_zAngle, 0.0, 0.0, 1.0);
if (displayListInited) {
glCallList(1);
} else {
glNewList(1, GL_COMPILE_AND_EXECUTE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
// Front face
glColor3f(0.0, 0.7, 0.1); // Green
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
// Back face
glColor3f(0.9, 1.0, 0.0); // Yellow
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
// Top face
glColor3f(0.2, 0.2, 1.0); // Blue
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
// Bottom face
glColor3f(0.7, 0.0, 0.1); // Red
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glEnd();
glEndList();
displayListInited = true;
}
if (m_pglxdata->double_buffer) {
glXSwapBuffers(m_pglxdata->dpy, m_pglxdata->win);
} else {
glFlush();
}
m_update = false;
}
}
}
Map::~Map()
{
}
</code></pre>
<p><strong>Makefile</strong></p>
<pre><code>all : linux_main
linux_main : map.o linux_main.o
g++ -pthread -Wall linux_main.o map.o -o linux_main -lGL -lXext -lX11 -lGLU
linux_main.o : linux_main.cpp
g++ -pthread -Wall -c -o linux_main.o linux_main.cpp
map.o : map.cpp
g++ -pthread -Wall -c -o map.o map.cpp
clean :
rm -f ./*.o linux_main
</code></pre>
|
[] |
[
{
"body": "<p>I would clean up the makefile<br>\nYou don't want to do it separately for each file as you then get cut/paste errors.<br>\nYou want to generalize this as much as possible (so that any change only needs to be done in one place (not in multiple locations). </p>\n\n<p>PS. Not tested.</p>\n\n<pre><code>CXX = g++\nCXXFLAGS += -Wall -pthread \n\nTARGET = linux_main\nSRC_FILES = $(wildcard *.cpp)\nOBJ_FILES = $(patsubst %.cpp,%.o,$(SRC_FILES))\n\nall: $(TARGET)\n\n$(TARGET): $(OBJ_FILES)\n $(CXX) -o $(TARGET) $* $(CXXFLAGS) -lGL -lXext -lX11 -lGLU\n\nclean:\n rm -f $(OBJ_FILES) $(TARGET)\n</code></pre>\n\n<p>The main():<br>\nIn C++ we try and use objects and RAII to make the code exception safe.<br>\nAny time you have init() followed by a dest() pair it is an indication that you should have wrapped in a class and done the init() in the constructor and the dest() in the destructor.</p>\n\n<p>Also note you never actually initialize <code>gsp_Map</code> so if it fails to initialize you end up deleting an invalid pointer.</p>\n\n<pre><code>int \nmain(int argc, char *argv[]) {\n if (!init_instance()) {\n fprintf(stderr, \"Failed to initialize application instance\\n\");\n }\n\n message_loop();\n\n if(gsp_Map) {\n delete gsp_Map;\n }\n}\n</code></pre>\n\n<p>This would have been much neater to implement as:</p>\n\n<pre><code>int main(int argc, char *argv[])\n{\n try\n {\n // Move the code for init_instance() into the Map constructor\n // Make sure the destructor tides up correctly.\n Map mapInstance;\n\n // Try to reduce the amount of global accessible state.\n // It makes testing really hard to do well. Instead pass objects as\n // parameters if the function needs to use it.\n message_loop(mapInstance);\n }\n catch(...)\n {\n fprintf(stderr, \"Failed to initialize application instance\\n\");\n }\n}\n</code></pre>\n\n<p>In C++ code there is no need for the typedef here:</p>\n\n<pre><code>typedef\nstruct glx_data\n{\n Display *dpy;\n Window win;\n XVisualInfo *vi;\n Colormap cmap;\n XSetWindowAttributes swa;\n GLXContext cx;\n XEvent event;\n int dummy;\n bool double_buffer;\n} GLXDATA;\n</code></pre>\n\n<p>Each of the pointers in this structure are initialied by a function call that obviously allocates so object and returns a pointer. I don't see any code that correctly tides this up. You should wrap each of these pointers in an class that will correctly tidy itself (otherwise at each failure point you need to write code to tidy up the object correctly).</p>\n\n<p>These constructors in Map are obviously not doing anything:</p>\n\n<pre><code>Map::Map()\n{\n}\n\nMap::Map(Map &copy)\n{\n}\n</code></pre>\n\n<p>Since you have a constructor that does real work:</p>\n\n<pre><code>Map::Map(GLXDATA *glxdata, int width, int height)\n</code></pre>\n\n<p>You should delete the useless ones above they are dangerous at best (you should probably make the copy constructor and assignment operator private until you work out what is happening with all the pointers flying around your code).</p>\n\n<p>The destructor is useless. Delete it and let the default compiler version do its job until you have some actual work to do here.</p>\n\n<pre><code>Map::~Map()\n{\n}\n</code></pre>\n\n<p>Yoda style testing was popular in the 80/90 but has since been discarded as untatural to read.</p>\n\n<pre><code>if (NULL == glxdata.vi)\n\n// Most people find it easier to read the other way around\n\nif (glxdata.vi == NULL)\n</code></pre>\n\n<p>There is no real advantage to the Yoda style (it is trying to protect you from accidental assignment) as all compilers will warn you if you accidentally do an assignment in a test and since you are compiling with warnings turned on and striving to have zero warning code it should not happen.</p>\n\n<pre><code>if (glxdata.vi = NULL)\n ^^^ Notice the single =\n</code></pre>\n\n<p>You are using fprint() rather than std::cerr (and your error messages and clean can be better handled by exceptions).</p>\n\n<p>Inside glxdate them members</p>\n\n<pre><code>GLXContext cx;\nXEvent event;\n</code></pre>\n\n<p>don't look like they should be part of this structrue. They are not used by it and only really manipulated by functions outside the structure.</p>\n\n<p>Member methods declared inside the class declaration are automatically inline. So there is no need to actually specify this:</p>\n\n<pre><code> inline pthread_t &get_pthread() {return m_render_thread;}\n inline void set_update(bool update) {m_update = update;}\n</code></pre>\n\n<p>Though I will sometimes put one liners in the header file I still usually prefer to put all methods into the source file (let the compiler worry about the inline optimization you have more important things to do).</p>\n\n<p>Technically this is not allowed:</p>\n\n<pre><code>pthread_create(&m_render_thread, NULL, Map::create_pthread, this);\n</code></pre>\n\n<p>The pthreads library is a C-Library and thus only understands the C ABI. It has no concept of the C++ ABI and thus can not call C++ functions and definitely can not call class methods. This just happens to work on some systems as you are getting lucky that that the ABI for static member methods is the same as the C-ABI.</p>\n\n<p>Best to just make a C-function so that you are guaranteed for it to work. This C function can call your static member in a valid fashion.</p>\n\n<pre><code>extern \"C\" void* create_pthread(void* data)\n{\n Map* mapObject = reinterpret_cast<Map*>(data);\n return Map::create_pthread(mapObject);\n}\n</code></pre>\n\n<p>In general there is still too much reaching into objects and interacting with their members. Your classes should define an interface that are verbs that allow you to interact with them but they should not expose the members.</p>\n\n<p>In particular the gxd_data and Map obejct are so interrelated that you should just make gxd_data a normal member of the Map (or pass it in by reference).</p>\n\n<h3>Edit</h3>\n\n<p>To try and find things I started wrapping things.<br>\nNote this is not a perfect design because I did not have a good test environment thus I was trying to wrap code without altering it too much:</p>\n\n<h3>glx_data.h</h3>\n\n<pre><code>#ifndef GLX_DATA_\n#define GLX_DATA_\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <pthread.h>\n\n#include <stdexcept>\n\n#include <X11/Xlib.h>\n#include <GL/glx.h>\n#include <GL/gl.h>\n#include <GL/glu.h>\n\n\nclass DisplayWrapper\n{\n Display* dpy;\n public:\n DisplayWrapper()\n {\n dpy = XOpenDisplay(NULL);\n if (dpy == NULL)\n { throw std::runtime_error(\"Failed to get XDisplay\");\n }\n int dummy;\n if (!glXQueryExtension( dpy, &dummy, &dummy))\n { throw std::runtime_error(\"X server has no OpenGL GLX extension\");\n }\n }\n ~DisplayWrapper()\n {\n // Add missing code to clean up Query extension\n // TODO\n\n // Add missing code to clean up display here:\n // TODO\n }\n // Not a perfect wrapper but an example\n // This is a conversion operator.\n // It is bad practice to use them;\n // I am just using it here to minimize changes to the original code.\n operator Display*() {return dpy;}\n};\nclass XVisualInfoWrapper\n{\n static int dblBuf[];\n static int snglBuf[];\n\n XVisualInfo* vi;\n bool double_buffer;\n\n public:\n XVisualInfoWrapper(DisplayWrapper& dpy)\n {\n double_buffer = true;\n vi = glXChooseVisual( dpy, DefaultScreen(static_cast<Display*>(dpy)), dblBuf);\n if (vi == NULL)\n {\n vi = glXChooseVisual( dpy, DefaultScreen(static_cast<Display*>(dpy)), snglBuf);\n if (vi == NULL)\n { throw std::runtime_error(\"No RGB visual with depth buffer\");\n }\n double_buffer = false;\n }\n }\n ~XVisualInfoWrapper()\n {\n // Add missing code to clean up VisualInfo\n // TODO\n }\n // Not a perfect wrapper but an example\n // This is a conversion operator.\n // It is bad practice to use them;\n // I am just using it here to minimize changes to the original code.\n operator XVisualInfo*() {return vi;}\n\n bool isDoubleBuffered() const {return double_buffer;}\n\n};\n\nstruct ColormapWrapper\n{\n Colormap cmap;\n ColormapWrapper(DisplayWrapper& dpy, XVisualInfoWrapper& vi)\n {\n cmap = XCreateColormap( dpy,\n RootWindow(static_cast<Display*>(dpy),static_cast<XVisualInfo*>(vi)->screen),\n static_cast<XVisualInfo*>(vi)->visual,\n AllocNone\n );\n }\n ~ColormapWrapper()\n {\n // TODO Destroy the colourmap\n }\n // Not a perfect wrapper but an example\n // This is a conversion operator.\n // It is bad practice to use them;\n // I am just using it here to minimize changes to the original code.\n operator Colormap&() {return cmap;}\n\n};\n\nstruct SetWindowAttributeWrapper: public XSetWindowAttributes\n{\n SetWindowAttributeWrapper(ColormapWrapper& cmap)\n {\n colormap = cmap;\n border_pixel = 0;\n event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask;\n }\n};\n\nclass WindowWrapper\n{\n Window win;\n public:\n WindowWrapper(DisplayWrapper& dpy, XVisualInfoWrapper& vi, ColormapWrapper& cmap, SetWindowAttributeWrapper& swa)\n {\n win = XCreateWindow( dpy,\n RootWindow(static_cast<Display*>(dpy), static_cast<XVisualInfo*>(vi)->screen),\n 0, 0,\n 300, 300,\n 0,\n static_cast<XVisualInfo*>(vi)->depth,\n InputOutput,\n static_cast<XVisualInfo*>(vi)->visual,\n CWBorderPixel | CWColormap |\n CWEventMask,\n &swa\n );\n\n XSetStandardProperties(dpy,win, \"glxsimple\", \"glxsimple\", None, NULL, 0, NULL);\n }\n ~WindowWrapper()\n {\n // TODO Correctly destroy the window\n }\n // Not a perfect wrapper but an example\n // This is a conversion operator.\n // It is bad practice to use them;\n // I am just using it here to minimize changes to the original code.\n operator Window() {return win;}\n};\n\nstruct glx_data\n{\n DisplayWrapper dpy;\n XVisualInfoWrapper vi;\n ColormapWrapper cmap;\n SetWindowAttributeWrapper swa;\n WindowWrapper win;\n GLXContext cx;\n\n glx_data()\n : dpy()\n , vi(dpy)\n , cmap(dpy, vi)\n , swa(cmap)\n , win(dpy, vi, cmap, swa)\n {}\n};\n\n#endif//GLX_DATA\n</code></pre>\n\n<h3>glx_data.cpp</h3>\n\n<pre><code>#include \"glx_data.h\"\n\nint XVisualInfoWrapper::dblBuf[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12, GLX_DOUBLEBUFFER, None };\nint XVisualInfoWrapper::snglBuf[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12, None };\n</code></pre>\n\n<h3>Map.h</h3>\n\n<pre><code>// 3. map.h\n#ifndef MAP_H_\n#define MAP_H_\n\n#include \"glx_data.h\"\n\nclass Map\n{\n glx_data glxdata;\n\n public:\n Map(int width, int height);\n void getEvent(XEvent& event)\n {\n XNextEvent(glxdata.dpy, &event);\n }\n bool pending()\n {\n return XPending(glxdata.dpy);\n }\n pthread_t &get_pthread() {return m_render_thread;}\n void set_update(bool update) {m_update = update;}\n void inc_xrotate(GLfloat deg) \n {\n if ((m_xAngle + deg) < 360) {\n m_xAngle += deg;\n } else {\n m_xAngle = deg - (360 - m_xAngle);\n }\n }\n void inc_yrotate(GLfloat deg) \n {\n if ((m_yAngle + deg) < 360) {\n m_yAngle += deg;\n } else {\n m_yAngle = deg - (360 - m_yAngle);\n }\n }\n void inc_zrotate(GLfloat deg) \n {\n if ((m_zAngle + deg) < 360) {\n m_zAngle += deg;\n } else {\n m_zAngle = deg - (360 - m_zAngle);\n }\n }\n void set_deminsions(int width, int height) \n {\n m_width = width;\n m_height = height;\n }\n void render_data();\n private:\n pthread_t m_render_thread;\n bool m_render;\n bool m_update;\n bool m_update_viewport;\n int m_width;\n int m_height;\n GLfloat m_xAngle;\n GLfloat m_yAngle;\n GLfloat m_zAngle;\n static void *create_pthread(void *data)\n {\n Map *thread_map = static_cast<Map *>(data);\n thread_map->render_data();\n return data;\n }\n};\n\n#endif//MAP_H_\n</code></pre>\n\n<h3>Map.cpp</h3>\n\n<pre><code>// 4. map.cpp\n#include \"map.h\"\n\nMap::Map(int width, int height)\n{\n m_width = width;\n m_height = height;\n m_render = true;\n m_update = true;\n m_update_viewport = true;\n m_xAngle = 42.0;\n m_yAngle = 82.0;\n m_zAngle = 112.0;\n pthread_create(&m_render_thread, NULL, Map::create_pthread, this);\n\n XMapWindow(glxdata.dpy, glxdata.win);\n}\n\nvoid Map::render_data()\n{\n glxdata.cx = glXCreateContext(\n glxdata.dpy,\n glxdata.vi,\n None,\n True\n );\n if (NULL == glxdata.cx) {\n fprintf(stderr, \"could not create rendering context\");\n return;\n }\n glXMakeCurrent(glxdata.dpy, glxdata.win, glxdata.cx);\n static Bool displayListInited = false;\n glEnable(GL_DEPTH_TEST);\n while(m_render) {\n if(m_update_viewport) {\n glViewport(0, 0, m_width, m_height);\n m_update_viewport = false;\n m_update = true;\n }\n if(m_update) {\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(60, 1, 1, 100);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glTranslatef(0.0, 0.0, -3.0);\n glRotatef(m_xAngle, 0.1, 0.0, 0.0);\n glRotatef(m_yAngle, 0.0, 1.0, 0.0);\n glRotatef(m_zAngle, 0.0, 0.0, 1.0);\n if (displayListInited) {\n glCallList(1);\n } else {\n glNewList(1, GL_COMPILE_AND_EXECUTE);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glBegin(GL_QUADS);\n // Front face\n glColor3f(0.0, 0.7, 0.1); // Green\n glVertex3f(-1.0, 1.0, 1.0);\n glVertex3f(1.0, 1.0, 1.0);\n glVertex3f(1.0, -1.0, 1.0);\n glVertex3f(-1.0, -1.0, 1.0);\n // Back face\n glColor3f(0.9, 1.0, 0.0); // Yellow\n glVertex3f(-1.0, 1.0, -1.0);\n glVertex3f(1.0, 1.0, -1.0);\n glVertex3f(1.0, -1.0, -1.0);\n glVertex3f(-1.0, -1.0, -1.0);\n // Top face\n glColor3f(0.2, 0.2, 1.0); // Blue\n glVertex3f(-1.0, 1.0, 1.0);\n glVertex3f(1.0, 1.0, 1.0);\n glVertex3f(1.0, 1.0, -1.0);\n glVertex3f(-1.0, 1.0, -1.0);\n // Bottom face\n glColor3f(0.7, 0.0, 0.1); // Red\n glVertex3f(-1.0, -1.0, 1.0);\n glVertex3f(1.0, -1.0, 1.0);\n glVertex3f(1.0, -1.0, -1.0);\n glVertex3f(-1.0, -1.0, -1.0);\n glEnd();\n glEndList();\n displayListInited = true;\n }\n if (glxdata.vi.isDoubleBuffered()) {\n glXSwapBuffers(glxdata.dpy, glxdata.win);\n } else {\n glFlush();\n }\n m_update = false;\n }\n }\n}\n</code></pre>\n\n<h3>linux_main.cpp</h3>\n\n<pre><code>// 2. linux_main.cpp \n\n\n#include <iostream>\n#include \"glx_data.h\"\n#include \"map.h\"\n\n\nvoid message_loop(Map& gsp_Map)\n{\n while (1) {\n do {\n XEvent event;\n gsp_Map.getEvent(event);\n switch (event.type) {\n case ButtonPress:\n switch (event.xbutton.button) {\n case 1:\n gsp_Map.inc_xrotate(10);\n gsp_Map.set_update(true);\n break;\n case 2:\n gsp_Map.inc_yrotate(10);\n gsp_Map.set_update(true);\n break;\n case 3:\n gsp_Map.inc_zrotate(10);\n gsp_Map.set_update(true);\n break;\n }\n break;\n case ConfigureNotify:\n gsp_Map.set_deminsions(\n event.xconfigure.width,\n event.xconfigure.height\n );\n case Expose:\n gsp_Map.set_update(true);\n break;\n }\n } while (gsp_Map.pending());\n }\n pthread_join(gsp_Map.get_pthread(), NULL);\n}\n\nint\nmain(int argc, char *argv[])\n{\n try\n {\n Map gsp_Map(300,300);\n message_loop(gsp_Map);\n }\n catch(std::exception const& e)\n {\n std::cerr << \"Exception: Failed to initialize application instance\\nBecause: \" << e.what() << \"\\n\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:43:25.027",
"Id": "11645",
"Score": "0",
"body": "Loki thanks again for your wonderful input, I have slightly altered the code. I did less wrapping than you suggest but I think it is getting better. What are your thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T00:40:34.580",
"Id": "11673",
"Score": "0",
"body": "Hate your main(). There is no need to call a create method. Just create an object. If it works then you just use it. If it fails it throws an exception and you print an error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T00:42:49.037",
"Id": "11674",
"Score": "0",
"body": "You may as well drop the use of inline it has no use. The compiler will inline the functions as its sees fit. You trying to tell the compiler what to inline will be ignored the compiler, as it is much better at it (and it knows it, and will silently ignores all your suggestions)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T00:45:00.797",
"Id": "11675",
"Score": "0",
"body": "If the call to `if (initialize_window(width, height))` I don't see any clean up code to remove the resources (Bad habbit to get into)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T00:45:40.263",
"Id": "11676",
"Score": "0",
"body": "This call can fail: `pthread_create(&m_render_thread, NULL, create_pthread, this);` You should check for failure and act appropriately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-28T20:25:45.430",
"Id": "371114",
"Score": "0",
"body": "I believe a static member function *is* exactly like a free function in terms of being able to make a pointer to a function handle them. The ABI difference (if any) would have to do with the calling convention — I assume you mean that the `extern \"C\"` function uses the proper convention by default if that differs from the one used by C++ functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-28T23:14:08.967",
"Id": "371126",
"Score": "0",
"body": "@JDługosz You can believe all you like it does not make anything true :-) There is no guarantees that the ABI of a C free standing function is the same as a C++ static member function."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T08:38:24.407",
"Id": "7409",
"ParentId": "7396",
"Score": "3"
}
},
{
"body": "<pre><code>static int snglBuf[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1,\n GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12, None };\n</code></pre>\n\n<p>Should that be <code>const</code>? I see it is used in one place, but I can’t tell if that modifies its value. If this is indeed constant, make it <code>constexpr</code> just to make sure it produces the table at compile time with no overhead.</p>\n\n<pre><code>static Map *gsp_Map;\n</code></pre>\n\n<p>The style in C++ is to put the <code>*</code> or <code>&</code> with the <em>type</em>, not the identifier. This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.</p>\n\n<pre><code>static GLXDATA glxdata;\n\nbool init_instance() {\n glxdata.dpy = XOpenDisplay(NULL);\n if (glxdata.dpy == NULL) {\n fprintf(stderr, \"Failed to get XDisplay\\n\");\n return false;\n }\n</code></pre>\n\n<p>You should put the initializer right on the variable, rather than having to call the <code>init_instance</code> function. It could be a <strong>constructor</strong> for <code>glxdata</code>.</p>\n\n<p>I take it that the stuff in the headers is C, not C++, and is used for C programs too. But you can derive a class from a C struct, adding member functions. This is a very handy technique.</p>\n\n<pre><code>class glxdata_t : public glx_data {\npublic:\n glxdata_t() { dpy = XopenDisplay(NULL); /* etc */ }\n ~glxdata() ⋯\n other handy stuff to encapsulate\n};\n</code></pre>\n\n<p>Be sure you use the <em>real</em> name of the struct, not the all-caps typedef, when you derive from it.</p>\n\n<p>I assume <code>XopenDisplay</code> is a C function, so I kept it as-is. In C++, you do not use the <code>NULL</code> macro.</p>\n\n<p>Given that the work is done automatically, you can then (just) report an error as part of your set-up.</p>\n\n<pre><code>if (NULL == glxdata.vi) {\n</code></pre>\n\n<p>Don’t use <code>NULL</code> macro in C++. Don’t compare pointers (or pointer-like objects) against <code>nullptr</code> explicitly; rather, use their truth value (an operator bool in smart pointer types)</p>\n\n<pre><code>if (glxdata.vi)\n</code></pre>\n\n<p>but as noted earlier, this should all be in the constructor, so it’s just <code>vi</code> not <code>glxdata.vi</code>.</p>\n\n<pre><code> fprintf(stderr, \"No RGB visual with depth buffer\");\n</code></pre>\n\n<p>You are using C library output? I suppose this whole function was just copied from example code that was for C. Even in C, <code>fprintf</code> with a string that does not contain any replacement sequences is just a pure waste of time.</p>\n\n<pre><code>std::cerr << \"No RGB vis⋯\";\n</code></pre>\n\n<p>(In <em>real</em> code, this would go to a logging module, or just use that string for the exception text)</p>\n\n<pre><code>gsp_Map = new Map(&glxdata, 300, 300);\n</code></pre>\n\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new\" rel=\"nofollow noreferrer\">Core Guideline C.149</a> — no naked <code>new</code> or <code>delete</code>.</p>\n\n<p>You should probably make this a <code>unique_ptr</code> as a drop-in replacement without otherwise changing the architecture.</p>\n\n<p>inline pthread_t &get_pthread() {return m_render_thread;}</p>\n\n<p>This is a pure accessor; it should be <code>const</code>. It’s already been noted that the <code>inline</code> keyword is not needed here. I won’t repeat the earlier observations on the overall class design.</p>\n\n<pre><code> inline void inc_xrotate(GLfloat deg) \n {\n if ((m_xAngle + deg) < 360) {\n m_xAngle += deg;\n } else {\n m_xAngle = deg - (360 - m_xAngle);\n }\n }\n</code></pre>\n\n<p>Did you notice that there are three functions with exactly the same contents except for the name of one variable?</p>\n\n<p>At the very least, use a helper function to condition the variable:</p>\n\n<pre><code> m_xAngle= keep_in_circle (m_xAngle, deg);\n</code></pre>\n\n<p>(though I don’t see why you don’t just modulo 360 after adding)<br>\nBut better for here and other uses in general would be to get rid of three separately named variables for x, y, and z and use an array of 3 values so they can be indexed by a loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-28T20:22:23.780",
"Id": "193163",
"ParentId": "7396",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7409",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T01:15:45.847",
"Id": "7396",
"Score": "3",
"Tags": [
"c++",
"opengl",
"pthreads"
],
"Title": "Separate rendering thread with XLib (GLX) and OpenGL"
}
|
7396
|
<p>I have this static class in an ASP.NET MVC project:</p>
<pre><code> public static class Setup
{
private static bool _intialized = false;
public static void Initialize(IWindsorContainer Container)
{
//Check if it has already run
if (_intialized)
{ return; }
var connectionString = config.ConnectionStrings["ccsMongo"].ConnectionString;
var dbName = config.AppSettings["ccsMongoDb"];
//Initialization code here.
Container.Register(
Component.For<IOrgRepos>().ImplementedBy<OrgRepos>()
.DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),
Component.For<IIndividualRepos>().ImplementedBy<IndividualRepos>()
.DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),
Component.For<IScoreboardRepos>().ImplementedBy<ScoreboardRepos>()
.DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName})
);
//Mark as run
_intialized = true;
}
}
</code></pre>
<p>I then include a call to it in my <code>Application_Start</code>. The intent is to be sure that it will never run more than once.</p>
<ol>
<li>Is there a better way to create a function that can't be run more than once in the the application lifetime?</li>
<li>Am I being paranoid? I could just put a call to the initialization code into my <code>Application_Start</code> and forget about the "run only once" guard code.</li>
</ol>
<p>I would be delighted to get any feedback.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-25T21:22:47.203",
"Id": "14835",
"Score": "0",
"body": "Is there any way that you can use a static constructor? Right now the parameter gets in your way. Where does the `IWindsorContainer come` from, and why can it be called multiple times, and yet should be \"initialized\" only once?"
}
] |
[
{
"body": "<p>This could execute more than once pretty easily if called on multiple threads at the same time. This should make it a bit more foolproof:</p>\n\n<pre><code> public static class Setup\n {\n private static readonly object _locker = new object();\n private static bool _intialized = false;\n\n public static void Initialize(IWindsorContainer Container)\n {\n lock (_locker)\n {\n //Check if it has already run\n if (_intialized)\n { return; }\n\n var connectionString = config.ConnectionStrings[\"ccsMongo\"].ConnectionString;\n var dbName = config.AppSettings[\"ccsMongoDb\"];\n\n //Initialization code here.\n Container.Register(\n Component.For<IOrgRepos>().ImplementedBy<OrgRepos>()\n .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),\n Component.For<IIndividualRepos>().ImplementedBy<IndividualRepos>()\n .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),\n Component.For<IScoreboardRepos>().ImplementedBy<ScoreboardRepos>()\n .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName})\n );\n\n //Mark as run\n _intialized = true;\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T01:50:40.367",
"Id": "7399",
"ParentId": "7397",
"Score": "3"
}
},
{
"body": "<p>Jesse's answer is good. My personal preference would be to put it inside <code>Application_Start</code>. I would do this because this code does not have any state, and since it has no state, it does not deserve to be a class. (The only state it has is trying to make sure it does not get invoked twice, so that does not count.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T01:35:25.247",
"Id": "46793",
"Score": "0",
"body": "That is interesting; you hold it that state is the only justification for a class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T21:17:34.697",
"Id": "46822",
"Score": "0",
"body": "In my book, it is by far the major justification. I usually take lack of state as an indication that whatever it is that I am looking at is probably suitable as part of something else. But there are no absolutes in this world. There certainly exist different considerations which might be taken into account in making the decision of whether something deserves to be a class or not. For example, you may turn something into a class despite the fact that it has no state, if you foresee that some of its functionality may, through inheritance, be reused and some of it altered by an inheritor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T09:15:50.497",
"Id": "7411",
"ParentId": "7397",
"Score": "1"
}
},
{
"body": "<p>I would not place logic to prevent the code from executing multiple times.</p>\n\n<p>The function itself does not operate on static data, but data passed as arguments. This makes it a very reusable function. It is simply a function that can configure a Windor container, but the function doesn't care about which container it is.</p>\n\n<p>The application does however care. The application desires to only have one container. Thus it is the application's responsibility to only create one container, and calling the function once for that container.</p>\n\n<p>Lets say you later want to create an automated test verifying that this function initializes the container correctly. That test would create a new container, call this function with that container as argument, and then operate on the container, verifying its state.</p>\n\n<p>If this function by itself prevents from being initialized more than once, you would be at a serious disadvantage in creating such tests.</p>\n\n<p>You could however do something else. If the function could examine the state of the passed container, it could determine if that container has already been configured. The function would then be able to make sure that a specific instance of a container is only configured once. But personally, I wouldn't bother in this particular case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T11:53:31.910",
"Id": "7413",
"ParentId": "7397",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7413",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T01:26:18.150",
"Id": "7397",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Having initialization code certain to run only once"
}
|
7397
|
<p>I've been working on a semi-awkward query in that it uses a very high number of functions given its relatively small size and scope. I was hoping to get some feedback on any ways I could format or re-factor this better?</p>
<pre><code>select Name ,
avg(TimeProcessing / 1000 + TimeRendering / 1000 + TimeDataRetrieval / 1000) as 'Current Month' ,
isnull(count(TimeProcessing), 0) as 'Sample' ,
min(l2.[Avg Exec Previous Month]) as 'Previous Month' ,
isnull(min(l2.[Sample Previous Month]), 0) as 'Sample' ,
min(l3.[Avg Exec Two Months Ago]) as 'Two Months ago' ,
isnull(min(l3.[Sample Two Months Ago]), 0) as 'Sample'
from marlin.report_execution_log l
inner join marlin.report_catalog c on l.ReportID = c.ItemID
left outer join ( select l2.ReportID ,
avg(TimeProcessing / 1000 + TimeRendering
/ 1000 + TimeDataRetrieval / 1000) as 'Avg Exec Previous Month' ,
count(TimeProcessing) as 'Sample Previous Month'
from marlin.report_execution_log l2
where TimeEnd between dateadd(MONTH, -2,
getdate())
and dateadd(MONTH, -1,
getdate())
group by l2.ReportID
) l2 on l.ReportID = l2.ReportID
left outer join ( select l3.ReportID ,
avg(TimeProcessing / 1000 + TimeRendering
/ 1000 + TimeDataRetrieval / 1000) as 'Avg Exec Two Months Ago' ,
count(TimeProcessing) as 'Sample Two Months Ago'
from marlin.report_execution_log l3
where TimeEnd between dateadd(MONTH, -3,
getdate())
and dateadd(MONTH, -2,
getdate())
group by l3.ReportID
) l3 on l.ReportID = l3.ReportID
group by l.ReportID, Name
order by Name
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T18:05:29.043",
"Id": "11638",
"Score": "0",
"body": "Because I _sincerely_ hope that you aren't actually getting a 'Month' value (say, `1` for 'January') by using the `AVG()` function, you should probably rename `Current Month` to whatever the actual measure is, including units - perhaps `Average Time Elapsed in Seconds` or something. And you might consider changing the operations to `(TimeProcessing + TimeRendering + TimeDataRetrieval) / 1000`, which will _guarantee_ that the same conversion is used for each field."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T22:17:51.800",
"Id": "11661",
"Score": "0",
"body": "Not at all, avg is receiving the average execution times of the references columns (see the where clause to understand how it's identifying what month)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:36:05.423",
"Id": "11696",
"Score": "1",
"body": "See, that's _exactly_ what I'm talking about - The result column name doesn't identify, **at all** what the data is. Some other interesting things I didn't really look at before: Are you sure your main `SELECT AVG()` is only getting the _current_ month? Without a `WHERE` clause, it won't restrict it - not if the previous two months are _also_ in the table. Also, be careful when using between - currently, anything equal to `dateadd(MONTH, -2, getdate())` will be counted _twice_ - once for `l2`, and once for `l3` - I reccomend exclusive upper bounds."
}
] |
[
{
"body": "<p>You might want to use Common Table Expression or Should use meaningful table alias in Join.</p>\n\n<p>You might also want to use indexes on your date column with <= and >= operator instead of between.</p>\n\n<p>Surround your column names in [] instead of single quotes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T05:42:34.963",
"Id": "11586",
"Score": "0",
"body": "Can you elaborate more on what makes a meaningful table alias? I would have thought ReportID (matching over each table and being key fields) would be a great match here and a cte seems unnecessary?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T08:37:54.657",
"Id": "11590",
"Score": "0",
"body": "l2 and l3 doesn't convey anything. Rather you should name it something like (e.g) AvgExecutionPreviousMonth."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T22:18:32.547",
"Id": "11662",
"Score": "0",
"body": "Right. But that doesn't address my question about why we would use a CTE here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T05:14:49.080",
"Id": "11679",
"Score": "0",
"body": "If it's easy to read and understand the whole thing, you should not get your subquery as CTE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:30:07.510",
"Id": "11695",
"Score": "0",
"body": "I second the CTE idea, as it will allow the exact same query to be used for the two subqueries (meaning that maintanence can't cause divergent results). Nil - maybe you could show an example of how you'd write the CTE?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T05:22:16.787",
"Id": "7405",
"ParentId": "7403",
"Score": "2"
}
},
{
"body": "<p>I agree with Nil; it seems like this might be a good situation to use a Common Table Expression.</p>\n\n<p>I haven't tested this out, but below is my attempt to rewrite this query using a CTE:</p>\n\n<pre><code>with ReportByMonth (ReportID, [Year], [Month], [Avg Exec], [Sample]) as\n(\n select ReportID ,\n avg(TimeProcessing / 1000 + TimeRendering / 1000 + TimeDataRetrieval / 1000) as [Avg Exec] ,\n datepart(YEAR, TimeEnd) as [Year] ,\n datepart(MONTH, TimeEnd) as [Month] ,\n count(TimeProcessing) as [Sample]\n from Marlin.report_execution_log\n group by\n ReportID,\n datepart(YEAR, TimeEnd),\n datepart(MONTH, TimeEnd)\n)\nselect Name ,\n CurrentMonthReport.[Avg Exec] as [Current Month Avg Exec] ,\n isnull(CurrentMonthReport.[Sample], 0) as [Current Month Sample] ,\n PreviousMonthReport.[Avg Exec] as [Previous Month Avg Exec] ,\n isnull(PreviousMonthReport.[Sample], 0) as [Previous Month Sample] ,\n TwoMonthAgoReport.[Avg Exec] as [Two Months Ago Avg Exec] ,\n isnull(TwoMonthAgoReport.[Sample], 0) as [Two Months Ago Sample]\nfrom marlin.report_catalog c\ninner join ReportByMonth CurrentMonthReport on\n CurrentMonthReport.ReportID = c.ItemID\n and CurrentMonthReport.Year = datepart(YEAR, getdate())\n and CurrentMonthReport.Month = datepart(MONTH, getdate())\nleft outer join ReportByMonth PreviousMonthReport on\n PreviousMonthReport.ReportID = c.ItemID\n and PreviousMonthReport.Year = datepart(YEAR, dateadd(MONTH, -1, getdate()))\n and PreviousMonthReport.Month = datepart(MONTH, dateadd(MONTH, -1, getdate()))\nleft outer join ReportByMonth TwoMonthAgoReport on\n TwoMonthAgoReport.ReportID = c.ItemID\n and TwoMonthAgoReport.Year = datepart(YEAR, dateadd(MONTH, -2, getdate()))\n and TwoMonthAgoReport.Month = datepart(MONTH, dateadd(MONTH, -2, getdate()))\norder by\n Name\n;\n</code></pre>\n\n<p>EDIT: I changed my query to try to match the behavior OP's original query. I changed the join for CurrentMonthReport from \"left outer join\" to \"inner join\". This means that if a particular report has not been run during this month, then it won't show up in the result.</p>\n\n<p>I also included use of the isnull function and added an order by clause.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T22:01:57.127",
"Id": "11716",
"Score": "0",
"body": "On initial testing this doesn't return any results. Just got in the door so I'll get some work done and will then take a look at this and update you further."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T17:54:54.750",
"Id": "7457",
"ParentId": "7403",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7405",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T04:25:40.457",
"Id": "7403",
"Score": "0",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Query to compare execution performance metrics for the three most recent months"
}
|
7403
|
<p>I am trying to create a very simple timer framework which allows you to setup event handling based on a timeout.</p>
<p>The basic primitives allow the programmer to:</p>
<ul>
<li>allocate or free timers</li>
<li>arm/disarm timers</li>
<li>set attributes and timeout for a timer</li>
</ul>
<p>Currently, the self contained example will create timers up to the maximum (currently defined as 10) with random timeout values from up to 20 seconds. Each timer will eventually expire and the associated call-back function executed.</p>
<pre><code> /* Very simplistic timer framework by amallory@qnx.com */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h> #include <sys/time.h>
#include <inttypes.h>
#include <sys/queue.h>
#define NUM_TIMERS 10
#define MAX_RANDOM_TIME_MS 20000
enum timer_callback_retval {
CB_RETURN_NORMAL = 0,
CB_RETURN_FREE_TIMER,
CB_RETURN_INVALID,
};
enum timer_type {
TT_RELATIVE = 0,
TT_ABSOLUTE,
TT_INVALID,
};
/* Define our timer list type */
TAILQ_HEAD(timer_list, timer_node);
/* Master tick clock/count */
uint64_t tick_cnt = 0;
/*
Timer data structure:
-the linked list
-the monotonic fire time (saved as an absolute time)
-the user callback handler to run on expiry of timer
-the registered data pointer to pass to the user callback
*/
struct timer_node {
TAILQ_ENTRY(timer_node) entries;
uint64_t fire;
int (*cb)(void* user_data);
void *user_data;
};
/* Our global timer lists */
struct timer_list active_timers;
struct timer_list free_timers;
struct timer_node *timer_memory;
#ifdef DEBUG
/* print out the contents of a given timer list */
void print_list(struct timer_list *list) {
struct timer_node *np;
TAILQ_FOREACH(np, list, entries) {
printf("timer fire %llu\n", np->fire);
}
}
#endif
/* put a timer onto the free list */
static void free_timer(struct timer_node *timer) {
TAILQ_INSERT_HEAD(&free_timers, timer, entries);
}
/* pull an available timer off the free list */
static struct timer_node* alloc_timer(void) {
struct timer_node *np;
if(TAILQ_EMPTY(&free_timers)) return NULL;
np=TAILQ_FIRST(&free_timers);
TAILQ_REMOVE(&free_timers, np, entries);
return np;
}
/* put a timer onto the actives timer queue */
static void arm_timer(struct timer_node* timer) {
struct timer_node *np;
if(TAILQ_EMPTY(&active_timers)) {
TAILQ_INSERT_HEAD(&active_timers, timer, entries);
} else {
for(np=TAILQ_FIRST(&active_timers) ; np ; np=TAILQ_NEXT(np, entries)) {
if(timer->fire < np->fire) {
TAILQ_INSERT_BEFORE(np, timer, entries);
return;
}
}
TAILQ_INSERT_TAIL(&active_timers, timer, entries);
}
}
/* remove a timer from the actives timer queue */
static void disarm_timer(struct timer_node* timer) {
TAILQ_REMOVE(&active_timers, timer, entries);
return;
}
/* set timer attributes such as relative/absolute fire timer,
fire timer, callback and user data passed to callback
*/
static int set_timer(struct timer_node* timer, enum timer_type tt, uint64_t fire, int (*cb)(void*), void* user_data) {
switch(tt) {
case TT_RELATIVE:
fire+=tick_cnt;
break;
case TT_ABSOLUTE:
break; /* do nothing */
case TT_INVALID:
default:
return -1;
}
timer->fire = fire;
timer->cb = cb;
timer->user_data = user_data;
return 0;
}
/* initialisation of the timer subsystem */
static void init_timers(void) {
unsigned i;
TAILQ_INIT(&active_timers);
TAILQ_INIT(&free_timers);
/* We're preallocating the memory and using a fixed timer pool size to keep
things simpler and avoid cluttering this exercise with lots of error checking
for bad memory conditions. This works or we're toast.
*/
if((timer_memory = malloc(sizeof(struct timer_node)*NUM_TIMERS)) == NULL) {
perror("Fatal! Can't allocate our block of timers!");
exit(EXIT_FAILURE);
}
/* seed our free timer list */
for(i=0 ; i < NUM_TIMERS; i++) {
free_timer(&timer_memory[i]);
}
}
/* Our clock handling routine that runs each clock tick */
static void clock_tick(int signo) {
struct timer_node *np;
tick_cnt++;
while(!TAILQ_EMPTY(&active_timers) && (np=TAILQ_FIRST(&active_timers)) && np->fire <= tick_cnt) {
disarm_timer(np);
if(np->cb(np->user_data) == CB_RETURN_FREE_TIMER) free_timer(np);
}
}
/* Setup a simulated clock tick that functions much like a real clock
interrupt might. We're using *NIX signals and a process timer as
it is a very common service available on almost any *NIX like system.
While not perfect, it's good enough to be illustrative.
*/
static int init_ticker(unsigned ms) {
struct itimerval it;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = ms*1000;
it.it_interval = it.it_value = tv;
signal(SIGALRM, clock_tick);
return setitimer(ITIMER_REAL, &it, NULL);
}
/* The user timer callback function */
int tcb(void *data) {
struct timer_node *np = data;
/* Normally you wouldn't only printf() as a result of a timer
but it is sufficient to be illustrative.
*/
printf("Timer Callback : %llu\n", np->fire);
return CB_RETURN_FREE_TIMER;
}
int main(int argc, char* argv[]) {
struct timer_node *np;
int i;
init_timers(); /* init the timer subsystem */
init_ticker(1); /* 1ms tick simulating a hw clock */
/* Create a bunch of timers from 1 to 5000ms in time and arm them */
for (i=0 ; i < NUM_TIMERS ; i++) {
if((np = alloc_timer()) == NULL) {
perror("Fatal! we ran out of timers?");
exit(EXIT_FAILURE);
}
if(set_timer(np, 0, (rand()+1) % MAX_RANDOM_TIME_MS , tcb, np) == -1) {
perror("Fatal! Bad timer set!");
exit(EXIT_FAILURE);
}
arm_timer(np);
}
/* Sit around letting the timers expire - not pretty but simple */
while(1) {
sleep(100);
}
/* never reached */
return 0;
}
</code></pre>
<p>I would like to identify as many weaknesses or bugs in the framework as I can find. You are welcome to identify any type of issue you feel is relevant. Anything from logic errors to algorithmic limitations as this is important for me to know all its weaknesses and make sure this piece of code runs efficient, bug free and that I am using best coding practices.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T05:34:23.107",
"Id": "11587",
"Score": "2",
"body": "Your signal handler should be async-safe see https://www.securecoding.cert.org/confluence/display/seccode/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers so your code is utterly wrong in its design"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T05:36:09.667",
"Id": "11588",
"Score": "0",
"body": "One specific issue is that you are running your user functions in a signal handler. This is very bad as there are very few safe functions that can be called in a signal handler. Move the receiving of the signals and calling of the functions onto another thread. You are also not reestablishing your signal handler, use sigaction instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T19:12:20.557",
"Id": "11640",
"Score": "0",
"body": "Thats Great guys, please keep your comments coming!"
}
] |
[
{
"body": "<p>Usability could be improved a bit. For example, <code>alloc_timer()</code> (note, name is deceptive as no actual allocation takes place) could be put inside of the <code>set_timer()</code> function. Let your framework worry about finding a free timer in the pool, or returning an error code. A separate function for allocating the timer would be more useful if you weren't using a pool and if it was important for a user to control when memory allocations occur.</p>\n\n<p>I don't like how the callback method controls whether the timer is freed. I could see lots of potential timer 'leaks'. I think if you added a repeating timer type, most of the cases where you wouldn't want to free your timer could then be taken care of by your framework. If you really need a handle to a timer that you could guarantee would be available when you need it, I think extending or overloading <code>alloc_timer()</code> (and/or <code>set_timer()</code>) would be a better place. That way, the decision to take it off and put it back on the <code>free_timers</code> list is in the same line of code.</p>\n\n<p>In <code>clock_tick()</code>, you're removing an element off the <code>active_timers</code> list while you iterate over it. In your case it looks like it'll work but that's usually an unsafe thing to do, I'd double check that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:17:12.163",
"Id": "7427",
"ParentId": "7406",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T05:26:17.403",
"Id": "7406",
"Score": "6",
"Tags": [
"c",
"timer"
],
"Title": "Timer framework in C"
}
|
7406
|
<p>Essentially, I am making an app that allows the user to type in chemistry formulas using a custom keyboard. </p>
<p>The keyboard will have several keys, for example, "Na", "H", and "O". Pressing them in different combinations will result in different formulas. For example, Na + O will result in NaO. Pressing any key consecutively will increase the subscript of that given element. For example, H + H + O will result in H<sub>2</sub>O.</p>
<p>The code below determines how the textfield combines the different elements to make the formulas. I'm wondering if it's too confusing. Also, I'm not sure if I'm correctly managing the memory.</p>
<pre><code>consecutiveElementCount = 0;
formula = [[NSMutableString stringWithString:@""] retain]; // released in dealloc
</code></pre>
<p>^^^ declared in the <code>init</code> method.</p>
<pre><code>- (void)addElement:(NSString *)currentElement {
if (![currentElement isEqualToString:lastElementPressed]) {
// when new element is pressed
[formula appendString:currentElement];
lastElementPressed = currentElement;
consecutiveElementCount = 1;
}
else if ([currentElement isEqualToString:lastElementPressed]) {
// when element is pressed consecutively
if (consecutiveElementCount == 1) {
// since there is no '1' subscript, nothing needs to be deleted
[formula appendString:@"₂"];
subscriptLength = 1;
}
if (consecutiveElementCount > 1) {
// deletes last subscript and replaces it with new subscript
NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil] autorelease];
NSRange range = NSMakeRange (([formula length] - subscriptLength), subscriptLength);
[formula deleteCharactersInRange:range];
NSString *tempSubscript = [[subscriptList objectAtIndex:consecutiveElementCount - 1] autorelease];
[formula appendString:tempSubscript];
subscriptLength = [tempSubscript length];
}
// don't increase subscript after 12
if (consecutiveElementCount < 11)
consecutiveElementCount ++;
}
NSLog(@"%@", formula);
}
</code></pre>
|
[] |
[
{
"body": "<p>You can use some <code>if else</code> statement, where u use several independent <code>if</code>s. This will lead to a slightly faster code, because in the case, where the previous if is try, no further testing is needed. Personally I also find it more readable for short and medium sized code block. </p>\n\n<pre><code>if (![currentElement isEqualToString:lastElementPressed]) {\n //…\n} else { \n if (consecutiveElementCount == 1) { \n //…\n } else if (consecutiveElementCount > 1) {\n //…\n } \n if (consecutiveElementCount < 11) {\n //…\n }\n}\n</code></pre>\n\n<p>But beside that, I don't think, that you are using to many if-statements. But you should use proper indention, as it will build visual block of your code and helps you, to understand the structure.</p>\n\n<p>There is a rule of thumb: If a method/function does not fit on your screen, it becomes to long, and you should use well-named helper functions to break it into several logical blocks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T16:22:14.833",
"Id": "11904",
"Score": "0",
"body": "`if (test) { ... } else if (!test) { /*...*/ }`\n\nis still too many ifs. The same goes for:\n\n`if (x == 1) { ... } else if ( x > 1) { /*...*/ }` when x is known to be >= 1 (which seems likely here)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T02:05:16.337",
"Id": "7434",
"ParentId": "7407",
"Score": "1"
}
},
{
"body": "<p>The following variation:</p>\n\n<ul>\n<li>initializes and uses subscriptLength more consistently.</li>\n<li>minimizes redundancy and special cases</li>\n<li>eliminates distracting whitespace.</li>\n</ul>\n\n<p>for</p>\n\n<pre><code>- (void)addElement:(NSString *)currentElement {\n if (![currentElement isEqualToString:lastElementPressed]) {\n // when new element is pressed \n [formula appendString:currentElement];\n lastElementPressed = currentElement;\n consecutiveElementCount = 1;\n subscriptLength = 0;\n }\n // TO DO: might want to replace 12 with a named constant like MAX_SUBSCRIPT\n // for greater readability and flexibility\n else if (consecutiveElementCount < 12)\n // when element is pressed consecutively, up to 12 times\n\n // since there is no '1' subscript, nothing needs to be deleted\n // for count == 1\n if (subscriptLength > 0) {\n // delete current subscript\n NSRange range = NSMakeRange (([formula length] - subscriptLength), subscriptLength);\n [formula deleteCharactersInRange:range];\n }\n // TO DO: might want to allocate subscriptList only once EVER\n // and keep it around for re-use, rather than reallocate it every time?\n NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@\"₂\", @\"₃\", @\"₄\", @\"₅\", @\"₆\", @\"₇\", @\"₈\", @\"₉\", @\"₁₀\", @\"₁₁\", @\"₁₂\", nil] autorelease]; \n // append subscript\n NSString *tempSubscript = [[subscriptList objectAtIndex:consecutiveElementCount-1] autorelease];\n [formula appendString:tempSubscript];\n subscriptLength = [tempSubscript length];\n consecutiveElementCount++;\n }\n // else { /* just ignore identical key-presses after 12 of them */ }\n NSLog(@\"%@\", formula);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T19:27:52.737",
"Id": "11913",
"Score": "0",
"body": "so should I alloc subscript list in the init method, or should I add a conditional in this method to allocate it if it's nil?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T22:10:15.903",
"Id": "11971",
"Score": "0",
"body": "It's not huge, so if you're very likely to need it over the lifetime of the object, init it in init and save the clutter of a conditional. If you need lots of instances of this class (as seems unlikely) create it (thread safely) and cache it (to share) outside any one instance. \n\nDon't know about Objective-C, but C++ has a subtle (but not thread-safe) way of initializing a local variable permanently once per process lifetime, sharing its value among calls, just by adding \"static\" to the local declaration. Barring that, I'd declare a member and init it in init."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T08:36:45.180",
"Id": "12061",
"Score": "0",
"body": "Thanks. I realized that I could simply the code slightly further by adding to array `subscriptList` an empty string `\"\"` to represent a subscript of 1. That way, I don't have to include `if (subscriptLenth > 0)` because when the subscript is 1, it essentially deletes \"\" from the text"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T18:08:15.190",
"Id": "7592",
"ParentId": "7407",
"Score": "1"
}
},
{
"body": "<p>A couple of observations:</p>\n\n<ol>\n<li><p>It looks to me that the if part of your code <code>else if ([currentElement isEqualToString:lastElementPressed])</code> is unnecessary; you already checked the negation of this condition in the top-level if statement.</p></li>\n<li><p>Although not necessary, you might want to put <code>else</code> in front of your if statement <code>if (consecutiveElementCount > 1)</code>. In fact, is there ever a chance that the <code>consecutiveElementCount</code> variable will be less than <code>1</code>? If not, then just turn it into an <code>else</code> without a condition.</p></li>\n</ol>\n\n<p>I kind of prefer to organize this code as shown in the code example below. Hopefully I haven't mangled it; I've combined some of your if statements into a switch statement.</p>\n\n<p>After reading your code, I decided that there are basically 3 steps that it performs:</p>\n\n<ol>\n<li><p>Detect whether the element pressed is a new element or is the same as the last element pressed.</p></li>\n<li><p>Perform work based on the number of times that the element has been pressed.</p></li>\n<li><p>Increment the counter to record the number of times the current element has been pressed</p></li>\n</ol>\n\n<p>Your original code kind of mixes #1 and #2 together. In the code below, I've separated them a bit and flattened things out with a switch statement. I think it's easier to read and understand what's happening. Similar-purpose code is grouped closer together.</p>\n\n<pre><code>- (void)addElement:(NSString *)currentElement {\n\n // determine if the element pressed is different than the last element pressed\n if (![currentElement isEqualToString:lastElementPressed]) {\n lastElementPressed = currentElement;\n // set count to zero to indicate that this element has not been pressed previously (consecutively)\n consecutiveElementCount = 0;\n }\n\n // perform logic based on the number of times the element has been pressed\n switch(consecutiveElementCount)\n {\n case 0: // first time the element is pressed\n // when new element is pressed \n\n [formula appendString:currentElement];\n break;\n case 1: // second time the element is pressed\n // since there is no '1' subscript, nothing needs to be deleted\n\n [formula appendString:@\"2\"]; \n subscriptLength = 1;\n break;\n default: // third or more times that the element is pressed\n // deletes last subscript and replaces it with new subscript\n\n\n NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@\"2\", @\"3\", @\"4\", @\"5\", @\"6\", @\"7\", @\"8\", @\"9\", @\"10\", @\"11\", @\"12\", nil] autorelease]; \n\n\n\n NSRange range = NSMakeRange (([formula length] - subscriptLength), subscriptLength);\n\n [formula deleteCharactersInRange:range];\n\n NSString *tempSubscript = [[subscriptList objectAtIndex:consecutiveElementCount - 1] autorelease];\n [formula appendString:tempSubscript];\n\n subscriptLength = [tempSubscript length];\n break;\n }\n\n // increment the counter to record the number of times this element has been pressed,\n // but don't increase subscript after 12\n if (consecutiveElementCount < 11)\n consecutiveElementCount ++;\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T18:27:13.440",
"Id": "7643",
"ParentId": "7407",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T06:40:46.910",
"Id": "7407",
"Score": "6",
"Tags": [
"objective-c",
"memory-management",
"ios"
],
"Title": "App for allowing the user to type in chemistry formulas using a custom keyboard"
}
|
7407
|
<p>I just wanted to know if I'm doing this right. Note that all the matrices are <code>int[16]</code>s.</p>
<pre><code>for (int i= 1; i <= 3; i++){
for (int j= 1; j <= 3; j++){
int sum = 0;
for (int h = 1; h <= 3; h++){
sum = sum + position[i*4+h]*projection[h*4+j];
}
modelview[i*4+j] = sum;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:03:45.387",
"Id": "11612",
"Score": "0",
"body": "It looks like you are indexing a vector (one dimension) rather than a matrix (at least 2 dimensions),"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:05:23.167",
"Id": "11613",
"Score": "0",
"body": "Are you representing a 4 x 4 as a 1 x 16? Are you getting the right answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:05:36.233",
"Id": "11614",
"Score": "2",
"body": "@JonnyBoats - no he is storing the 2d matrix in a 1d array, very common in c"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:06:27.757",
"Id": "11615",
"Score": "0",
"body": "Well, it's a one d array, yes, but it's a 16 size array, which is 4x4.\nYou don't need a 2d array to have 2 dimensions in an array, just got to write code like [width * height] or [(width * 2) + 3] instead of [2][3]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:11:42.950",
"Id": "11616",
"Score": "1",
"body": "Kinda nit picking here, but your title \"multiplying two matrices together\" would be better phrased \"one matrix by another\" or just \"multiplying matrices\" since order matters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:31:47.497",
"Id": "11617",
"Score": "0",
"body": "Note that there are libraries that will do that for you... and they can make use of parallelism such as MMX and SSE. I'd suggest you look into those (ipp comes to mind, apfloat may have int matrices support too...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:09:36.247",
"Id": "447612",
"Score": "0",
"body": "I am voting to close this question since the author isn't sure the code is working properly, which goes against CodeReview's format."
}
] |
[
{
"body": "<p>No. Let's first look at it as two dimensional arrays, so we know what we're talking about:</p>\n\n<pre><code>int i[4][4];\nint j[4][4];\nint k[4][4];\n\nfor (int x = 0; x < 4; x++) { // row number of output\n for (int y = 0; y < 4; y++) { // column number of output\n k[x][y] = 0;\n for (int z = 0; z < 4; z++) { // four elements are added for this output\n k[x][y] += i[x][z] * j[z][y];\n }\n }\n}\n</code></pre>\n\n<p>Important difference!!! We start at 0 for the indices!</p>\n\n<p>Now I'll convert it to <code>int[16]</code>s for you assuming that <code>i[1]</code> is the second element of the first row:</p>\n\n<pre><code>int i[16];\nint j[16];\nint k[16];\n\nfor (int x = 0; x < 4; x++) { // row number of output\n for (int y = 0; y < 4; y++) { // column number of output\n k[4*x+y] = 0;\n for (int z = 0; z < 4; z++) { // four elements are added for this output\n k[4*x+y] += i[4*x+z] * j[4*z+y];\n }\n }\n}\n</code></pre>\n\n<p>This is equivalent to your code except for the fact that you start at 1 instead of zero.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:07:01.163",
"Id": "7416",
"ParentId": "7415",
"Score": "12"
}
},
{
"body": "<p>@Dan \"equivalent ... except .. you start at 1 instead of zero\" solves the OP's first problem, but not the OP's second problem.</p>\n\n<p>The OP's second and larger problem is functioning 3x3 matrix multiplier code that reads enough like buggy 4X4 matrix multiplier code to trip up its reviewers. I suspect the problems STARTED with the common mistake of using 1-based counting instead of 0-based indexing. And that was followed by a superficial solution: just pad the indexed vectors so that the 1-based counts are still in range, never mind the unused gaps. </p>\n\n<p>The reviewer sees the idiomatic <code>i*4+j</code> and thinks \"AHA! 4 MUST be the matrix dimension.\" implicitly reasoning \"...because otherwise there would be unused gaps\".</p>\n\n<p>This miscue can be pinned on the use of \"magic numbers\", namely 3 and 4.\nWhich of these is the intended matrix dimension? \nIf the magic numbers had been referenced by name/purpose rather than by value, like via</p>\n\n<pre><code> const unsigned int DIMENSION = 3;\n const unsigned int ROW_LENGTH = DIMENSION + 1;\n</code></pre>\n\n<p>the intent would have been clear and the mis-step of padding the vectors much easier to spot.</p>\n\n<p>Or maybe I'm completely wrong and it always was just buggy 4x4 matrix multiplier code that coincidentally gave the right answer for 3x3 matrices.</p>\n\n<p>Regardless, the common wisdom goes: Unless there is a very good reason to do otherwise,</p>\n\n<ul>\n<li><p>use 0-based indexing, because it's simple, efficient, and idiomatic.</p></li>\n<li><p>likewise, use the <code>for</code> loop <code><</code> idiom for 0-based index iteration:</p>\n\n<pre><code>for (unsigned int i = 0; i < DIMENSION; i++) {\n</code></pre></li>\n<li><p>reference special numbers in the problem domain via named constants, for self-documentation (as well as for flexibility).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T15:26:58.613",
"Id": "7445",
"ParentId": "7415",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7416",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T05:00:56.560",
"Id": "7415",
"Score": "2",
"Tags": [
"c++",
"matrix"
],
"Title": "Am I multiplying two matrices together correctly?"
}
|
7415
|
<p>I want to make this code generic, so that I could remove <code>if</code>/<code>else</code> and recursive <code>for</code> loops. </p>
<p>I am open to accept all kind of suggestions regarding common interface implementation but kindly check that their property names FKID are different, and as these are POCO entities I can't change the proper names.</p>
<pre><code>var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();
int counter = -1;
for (int i = 0; i < newClientTripTypeContracts.Count; i++)
{
newClientTripTypeContracts[i].ClientTripTypeContractChargeValueListID = counter;
if (newClientTripTypeContracts[i].ChargeBITValues.Count > 0)
{
for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeBITValues.Count; j++)
{
newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeBITValues[j].ChargeBITValueFKID = counter;
}
}
else if (newClientTripTypeContracts[i].ChargeDECIMALValues.Count > 0)
{
for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeDECIMALValues.Count; j++)
{
newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeDECIMALValues[j].ChargeDECIMALValueFKID = counter;
}
}
else if (newClientTripTypeContracts[i].ChargeENUMValues.Count > 0)
{
for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeENUMValues.Count; j++)
{
newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeENUMValues[j].ChargeENUMValueFKID = counter;
}
}
else if (newClientTripTypeContracts[i].ChargeTierMONEYValues.Count > 0)
{
for (int j = 0; j < newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeTierMONEYValues.Count; j++)
{
newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i].ChargeTierMONEYValues[j].ChargeTierMONEYValueFKID = counter;
}
}
counter -= 1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T13:35:27.337",
"Id": "11619",
"Score": "0",
"body": "I would start by extracting newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i] and newClientTripTypeContracts[i] to make the loop easier to read."
}
] |
[
{
"body": "<p>Bug? In each of your 4 inner for loops, your code is referencing the following:</p>\n\n<pre><code>newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i]\n</code></pre>\n\n<p>Shouldn't it be this, instead?</p>\n\n<pre><code>newClientTripTypeContracts[i]\n</code></pre>\n\n<p>EDIT: I missed the OP's restriction in the question that indicated that property names couldn't be changed. I've added another section at the bottom to attempt to modify my original answer to accomodate this restriction.</p>\n\n<p>Making some assumptions about your data structures, I'd try consolidating the code with the following approach:</p>\n\n<ul>\n<li><p>Since it seems like your ChargeBITValues, ChargeDECIMALValues, ChargeENUMValues, and ChargeTierMONEYValues lists contain similar-but-different objects, I would first ensure that they are related by deriving from a common base class. I would define the heirarchy as follows:</p>\n\n<pre><code>abstract class ChargeValue\n{\n public abstract int ChargeValueFKID { get; set; }\n}\n\nclass ChargeBITValue : ChargeValue\n{\n // TODO: implement the ChargetValueFKID property\n}\n\nclass ChargeDECIMALValue : ChargeValue\n{\n // TODO: implement the ChargetValueFKID property\n}\n\nclass ChargeENUMValue : ChargeValue\n{\n // TODO: implement the ChargetValueFKID property\n}\n\nclass ChargeTierMONEYValue : ChargeValue\n{\n // TODO: implement the ChargetValueFKID property\n}\n</code></pre></li>\n</ul>\n\n<p>Notice that the base class has an abstract ChargeValueFKID property. This property can be overridden in each derived class, and is intended to replace or work with the ChargeBITValueFKID, ChargeDECIMALValueFKID, ChargeENUMValueFKID, and ChargeTierMONEYFKID properties that are in your original code.</p>\n\n<ul>\n<li><p>Next, I would create an \"ApplyCharges\" method to perform the same task as in each of your 4 inner for loops. You could define it as something like the following. Alternatively, you could make this a public instance method of the ClientTripTypeContract class:</p>\n\n<pre><code>static bool ApplyCharges(ClientTripTypeContract contract, IList<ChargeValue> charges, int fkid)\n{\n if (charges == null || charges.Count == 0)\n return false;\n\n foreach (var charge in charges)\n {\n charge.ChargeValueFKID = fkid;\n }\n\n return true;\n}\n</code></pre></li>\n<li><p>Finally, I'd update your original code to the following:</p>\n\n<pre><code> var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();\n\n int counter = -1;\n foreach(var contract in newClientTripTypeContracts)\n {\n contract.ClientTripTypeContractChargeValueListID = counter;\n\n bool chargesApplied = false;\n\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract, contract.ChargeBITValues, counter);\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract, contract.ChargeDECIMALValues, counter);\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract, contract.ChargeENUMValues, counter);\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract, contract.ChargeTierMONEYValues, counter);\n\n counter -= 1;\n }\n</code></pre></li>\n</ul>\n\n<p>Hopefully this will at least get you started and maybe give you a few ideas. You could probably come up with a cleaner or more specific approach that makes more sense, since you have the knowledge around what these data structures mean.</p>\n\n<p>EDIT:\nYou could, perhaps simplify your data structures with the following changes:</p>\n\n<ul>\n<li><p>Add a ChargeType property to the ChargeValue base class. Create a ChargeType enum with the following values: Bit, Decimal, Enum, and TierMoney.</p>\n\n<pre><code>enum ChargeType\n{\n Bit,\n Decimal,\n Enum,\n TierMoney,\n}\n\nabstract class ChargeValue\n{\n public abstract ChargeType ChargeType { get; }\n\n public abstract int ChargeValueFKID { get; set; }\n}\n</code></pre></li>\n<li><p>Then, Instead of having the 4 properties ChargeBITValues, ChargeDECIMALValues, ChargeENUMValues, and ChargeTierMONEYValues, you could simply have 1 property called ChargeValues, which contains all of the charge values from all of those properties. You could even keep those 4 original properties, but I would make them read-only and have them return an <code>IEnumerable<ChargeValue></code> object; adding/removing charge values should be done to the ChargeValues property. An example is shown below:</p>\n\n<pre><code>class ClientTripTypeContract\n{\n // ChargeValues replaces the original ChargeBITValues, ChargeDECIMALValues, ChargeENUMValues, and ChargeTierMONEYValues properties\n public IList<ChargeValue> ChargeValues { get; private set; }\n\n public IEnumerable<ChargeBITValue> ChargeBITValues\n {\n get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.Bit).Cast<ChargeBITValue>(); }\n }\n\n public IEnumerable<ChargeDECIMALValue> ChargeDECIMALValues\n {\n get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.Decimal).Cast<ChargeDECIMALValue>(); }\n }\n\n public IEnumerable<ChargeENUMValue> ChargeENUMValues\n {\n get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.Enum).Cast<ChargeENUMValue>(); }\n }\n\n public IEnumerable<ChargeTierMONEYValue> ChargeTierMONEYValues\n {\n get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.TierMoney).Cast<ChargeTierMONEYValue>(); }\n }\n}\n</code></pre></li>\n</ul>\n\n<p><hr>\nAccording to the OP's question, the properties of the data structure classes can't be changed/renamed, so below is my attempt to take the suggestions mentioned above and still work with that restriction:</p>\n\n<p>Below, I've removed the ChargeValue base class and replaced it with an IChargeValue interface. You can have each Charge*Value class implement this interface. In the example code below, I've implemented that interface explicitly so that the properties of that interface do not show up as public properties; I don't know if that matters...perhaps an OR mapper tool that you are using looks at the public properties. Alternatively, there ought to be some mechanism that your OR mapper uses that allows you to ignore these properties.</p>\n\n<pre><code> enum ChargeType\n {\n Bit,\n Decimal,\n Enum,\n TierMoney,\n }\n\n interface IChargeValue\n {\n ChargeType ChargeType { get; }\n\n int ChargeValueFKID { get; set; }\n }\n\n class ChargeBITValue : IChargeValue\n {\n int ChargeBITValueFKID { get; set; }\n\n ChargeType IChargeValue.ChargeType\n {\n get { return ChargeType.Bit; }\n }\n\n int IChargeValue.ChargeValueFKID\n {\n get { return this.ChargeBITValueFKID; }\n set { this.ChargeBITValueFKID = value; }\n }\n }\n\n class ChargeDECIMALValue : IChargeValue\n {\n int ChargeDECIMALValueFKID { get; set; }\n\n ChargeType IChargeValue.ChargeType\n {\n get { return ChargeType.Decimal; }\n }\n\n int IChargeValue.ChargeValueFKID\n {\n get { return this.ChargeDECIMALValueFKID; }\n set { this.ChargeDECIMALValueFKID = value; }\n }\n }\n\n class ChargeENUMValue : IChargeValue\n {\n int ChargeENUMValueFKID { get; set; }\n\n ChargeType IChargeValue.ChargeType\n {\n get { return ChargeType.Enum; }\n }\n\n int IChargeValue.ChargeValueFKID\n {\n get { return this.ChargeENUMValueFKID; }\n set { this.ChargeENUMValueFKID = value; }\n }\n }\n\n class ChargeTierMONEYValue : IChargeValue\n {\n int ChargeTierMONEYValueFKID { get; set; }\n\n ChargeType IChargeValue.ChargeType\n {\n get { return ChargeType.TierMoney; }\n }\n\n int IChargeValue.ChargeValueFKID\n {\n get { return this.ChargeTierMONEYValueFKID; }\n set { this.ChargeTierMONEYValueFKID = value; }\n }\n }\n</code></pre>\n\n<p>Using this approach, you could modify the \"ApplyCharges\" method mentioned above to the following:</p>\n\n<pre><code> static bool ApplyCharges(IEnumerable<IChargeValue> charges, int fkid)\n {\n if (charges != null && charges.Any())\n {\n foreach (var charge in charges)\n {\n charge.ChargeValueFKID = fkid;\n }\n\n return true;\n }\n else\n {\n return false;\n }\n }\n</code></pre>\n\n<p>And you can call this method using the following:</p>\n\n<pre><code> // NOTE: the .ToList() call on this line is not required, because the code below uses a foreach loop instead of a for loop.\n var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();\n\n int counter = -1;\n foreach (var contract in newClientTripTypeContracts)\n {\n contract.ClientTripTypeContractChargeValueListID = counter;\n\n bool chargesApplied = false;\n\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract.ChargeBITValues.Cast<IChargeValue>(), counter);\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract.ChargeDECIMALValues.Cast<IChargeValue>(), counter);\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract.ChargeENUMValues.Cast<IChargeValue>(), counter);\n if (!chargesApplied)\n chargesApplied = ApplyCharges(contract.ChargeTierMONEYValues.Cast<IChargeValue>(), counter);\n\n counter -= 1;\n }\n</code></pre>\n\n<p>Although not used in the example above, you could also add a ChargeValues property to the ClientTripTypeContract class, as shown below:</p>\n\n<pre><code> class ClientTripTypeContract\n {\n public IList<ChargeBITValue> ChargeBITValues { get; private set; }\n public IList<ChargeDECIMALValue> ChargeDECIMALValues { get; private set; }\n public IList<ChargeENUMValue> ChargeENUMValues { get; private set; }\n public IList<ChargeTierMONEYValue> ChargeTierMONEYValues { get; private set; }\n\n public IEnumerable<IChargeValue> ChargeValues\n {\n get { return this.ChargeBITValues.Cast<IChargeValue>().Concat(this.ChargeDECIMALValues).Concat(this.ChargeENUMValues).Concat(this.ChargeTierMONEYValues); }\n }\n }\n</code></pre>\n\n<p>The ChargeValues property just consolidates all of the charges contained in the other properties into a single <code>IEnumerable<IChargeValue></code> object, so that you can more easily iterate over all of the charges without duplicating code.</p>\n\n<p>The bottom line is that if you want to simplify your code and reduce redundancy, then you will need to somehow add some semantics to your data structures to indicate that the different types of charges are in some ways the same. In my examples, I tried to add those semantics by either inheriting from a common base class or implementing a common interface. If you simply cannot change the code for those classes at all, then another option that would require more work and more refactoring would be to create a layer of abstraction by defining your own wrapper classes. These wrapper classes would encapsulate your existing classes and would expose public properties and methods to allow your application code to manipulate the underlying data.</p>\n\n<hr>\n\n<p>Update: below is a more simple approach to condensing the original code.</p>\n\n<p>This approach doesn't rely on any data structure changes. This is a bare-bones approach to simplifying the original code.</p>\n\n<ul>\n<li><p>First, define a ForEach extension method. This is just a utility method, so it is not at all specific to this problem:</p>\n\n<pre><code>public static class EnumerableExtensions\n{\n public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)\n {\n foreach (var item in source)\n {\n action(item);\n }\n }\n}\n</code></pre></li>\n<li><p>Next, update the original code to the following:</p>\n\n<pre><code> var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();\n\n int counter = -1;\n foreach (var contract in newClientTripTypeContracts)\n {\n contract.ClientTripTypeContractChargeValueListID = counter;\n\n if (contract.ChargeBITValues.Any())\n contract.ChargeBITValues.ForEach(charge => charge.ChargeBITValueFKID = counter);\n else if (contract.ChargeDECIMALValues.Any())\n contract.ChargeDECIMALValues.ForEach(charge => charge.ChargeDECIMALValueFKID = counter);\n else if (contract.ChargeENUMValues.Any())\n contract.ChargeENUMValues.ForEach(charge => charge.ChargeENUMValueFKID = counter);\n else if (contract.ChargeTierMONEYValues.Any())\n contract.ChargeTierMONEYValues.ForEach(charge => charge.ChargeTierMONEYValueFKID = counter);\n\n counter -= 1;\n }\n</code></pre></li>\n</ul>\n\n<p>I don't think this code can be condensed much/any further without modifying the data structures.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:49:46.473",
"Id": "11628",
"Score": "0",
"body": "Thanks for such a great effort, This can't be done as i mentioned these are poco entities and i can't change the property names and use them as you suggested"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T16:15:38.520",
"Id": "11630",
"Score": "0",
"body": "@Manvinder - Erm...sorry, I missed that in your question. \\*grumble grumble\\* Ok, I understand that you can't change property names; I'm guessing that they map to your database schema. Can you at least add new properties to the classes and leave the existing properties alone? I'll update my answer to try to accomodate this additional restriction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T10:45:47.367",
"Id": "11731",
"Score": "0",
"body": "Great effort, however at your 5th bullet point, you forgot to change ChargeType.Bit for each respective case to ChargeType.Money, ChargeType.Enum etc"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:06:22.503",
"Id": "7418",
"ParentId": "7417",
"Score": "5"
}
},
{
"body": "<p>I've hoisted a couple of expressions into locals and converted to <code>foreach</code> syntax to better describe intent. It was still not all that readable, so I also extracted each <code>foreach</code> into its own method. I also then replaced <code>.Count > 0</code> with the LINQ extension method <code>.Any()</code> to also express intent.</p>\n\n<pre><code> var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0);\n\n var counter = -1;\n var i = 0;\n foreach (var clientTripTypeContractChargeValueList in newClientTripTypeContracts)\n {\n var tripTypeContractChargeValueList = newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i++];\n\n clientTripTypeContractChargeValueList.ClientTripTypeContractChargeValueListID = counter;\n if (clientTripTypeContractChargeValueList.ChargeBITValues.Any())\n {\n ProcessBITValues(tripTypeContractChargeValueList, counter);\n }\n else if (clientTripTypeContractChargeValueList.ChargeDECIMALValues.Any())\n {\n ProcessDECIMALValues(tripTypeContractChargeValueList, counter);\n }\n else if (clientTripTypeContractChargeValueList.ChargeENUMValues.Any())\n {\n ProcessENUMValues(tripTypeContractChargeValueList, counter);\n }\n else if (clientTripTypeContractChargeValueList.ChargeTierMONEYValues.Any())\n {\n ProcessTierMONEYValues(tripTypeContractChargeValueList, counter);\n }\n\n counter -= 1;\n }\n\n private static void ProcessTierMONEYValues(ClientTripTypeContractChargeValueList tripTypeContractChargeValueList, int counter)\n {\n foreach (var chargeTierMONEYValue in tripTypeContractChargeValueList.ChargeTierMONEYValues)\n {\n chargeTierMONEYValue.ChargeTierMONEYValueFKID = counter;\n }\n }\n\n private static void ProcessENUMValues(ClientTripTypeContractChargeValueList tripTypeContractChargeValueList, int counter)\n {\n foreach (var chargeENUMValue in tripTypeContractChargeValueList.ChargeENUMValues)\n {\n chargeENUMValue.ChargeENUMValueFKID = counter;\n }\n }\n\n private static void ProcessDECIMALValues(ClientTripTypeContractChargeValueList tripTypeContractChargeValueList, int counter)\n {\n foreach (var chargeDECIMALValue in tripTypeContractChargeValueList.ChargeDECIMALValues)\n {\n chargeDECIMALValue.ChargeDECIMALValueFKID = counter;\n }\n }\n\n private static void ProcessBITValues(ClientTripTypeContractChargeValueList tripTypeContractChargeValueList, int counter)\n {\n foreach (var chargeBITValue in tripTypeContractChargeValueList.ChargeBITValues)\n {\n chargeBITValue.ChargeBITValueFKID = counter;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:47:01.247",
"Id": "11627",
"Score": "0",
"body": "Thanks a lot, this is a very good attempt, but i don't find it generic or it don't help me remove some redundant code from my app"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:17:37.757",
"Id": "7419",
"ParentId": "7417",
"Score": "0"
}
},
{
"body": "<p>Tried something using Observables and Reactive extensions.</p>\n\n<p>\"using System.Reactive.Linq;\" (For the operator)</p>\n\n<p>\"using System.Reactive.Concurrency\" (For the scheduler, to speed up observing process)</p>\n\n<p>Two options..</p>\n\n<p>Code Snippet # 1 (Managing only loops, any one of the condition will be performed)</p>\n\n<pre><code>int counter = -1;\n\nnewClientTripTypeContracts.ToObservable<ClientTripTypeContractChargeValue>().Subscribe<ClientTripTypeContractChargeValue>(clientTripTypeContractItem =>\n {\n clientTripTypeContractItem.ClientTripTypeContractChargeValueListID = counter;\n\n if (clientTripTypeContractItem.ChargeBITValues.Count > 0)\n clientTripTypeContractItem.ChargeBITValues.ToObservable<ChargeBIT>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeBITValueFKID = counter);\n else if (clientTripTypeContractItem.ChargeDECIMALValues.Count > 0)\n clientTripTypeContractItem.ChargeDECIMALValues.ToObservable<ChargeDECIMAL>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeDECIMALValueFKID = counter);\n else if (clientTripTypeContractItem.ChargeENUMValues.Count > 0)\n clientTripTypeContractItem.ChargeENUMValues.ToObservable<ChargeENUM>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeENUMValueFKID = counter);\n else if (clientTripTypeContractItem.ChargeTierMONEYValues.Count > 0)\n clientTripTypeContractItem.ChargeTierMONEYValues.ToObservable<ChargeTierMONEY>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeTierMONEYValueFKID = counter);\n\n counter -= 1;\n});\n</code></pre>\n\n<p>Code Snippet # 2 (Managing loops and each list is called if any items found, FKID is assigned value of counter)</p>\n\n<pre><code> int counter = -1;\nnewClientTripTypeContracts.ToObservable<ClientTripTypeContractChargeValue>()\n .Subscribe<ClientTripTypeContractChargeValue>(clientTripTypeContractItem =>\n {\n clientTripTypeContractItem.ClientTripTypeContractChargeValueListID = counter;\n clientTripTypeContractItem.ChargeBITValues.ToObservable<ChargeBIT>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeBITValueFKID = counter);\n clientTripTypeContractItem.ChargeDECIMALValues.ToObservable<ChargeDECIMAL>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeDECIMALValueFKID = counter);\n clientTripTypeContractItem.ChargeENUMValues.ToObservable<ChargeENUM>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeENUMValueFKID = counter);\n clientTripTypeContractItem.ChargeTierMONEYValues.ToObservable<ChargeTierMONEY>().SubscribeOn(Scheduler.Immediate).ObserveOn(Scheduler.TaskPool).Subscribe(innerItem => innerItem.ChargeTierMONEYValueFKID = counter);\n counter -= 1;\n });\n</code></pre>\n\n<p>Hope it would help. Not tested fully but simple enough to manage.\nP.S: Use LinqPad to dump values and debug the composition</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:54:57.383",
"Id": "7429",
"ParentId": "7417",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T13:10:14.850",
"Id": "7417",
"Score": "3",
"Tags": [
"c#",
"generics"
],
"Title": "Client trip type contracts"
}
|
7417
|
<p>I've got this function which returns an SQLObject instance as a dict (taking into account inherited classes, properties, etc). It doesn't work right now on SQLObject classes which inherit from another class but add new attributes, so that's a work in progress, but I feel like this could be done smarter/better in Python.</p>
<p>What do you think?</p>
<p>PS the purpose of this is to allow a generic presentation of an object as a JSON document. It returns a dict which can be then given to json.dumps. If you've got a different way to convert an SQLObject to a JSON doc, that would be cool as well</p>
<pre><code>def sqlobject_to_dict(obj):
obj_dict = {}
cls_name = type(obj)
has_props = False
for attr in vars(cls_name):
attr_parent = type(getattr(obj, attr)).__bases__[0]
if isinstance(getattr(cls_name, attr), property):
has_props = True
if isinstance(getattr(obj, attr), Decimal):
obj_dict[attr] = float(getattr(obj, attr))
elif isinstance(getattr(obj, attr), list):
dict_list = []
for list_item in getattr(obj, attr):
dict_list.append(sqlobject_to_dict(list_item))
obj_dict[attr] = dict_list
elif isinstance(getattr(obj, attr), dict):
dict_dict = {}
for key, val in getattr(obj, attr):
dict_dict[key] = sqlobject_to_dict(val)
obj_dict[attr] = dict_dict
elif attr_parent == SQLObject:
obj_dict[attr] = sqlobject_to_dict(getattr(obj, attr))
else:
obj_dict[attr] = getattr(obj, attr)
elif not has_props and attr_parent != SQLObject:
if "_get_" in attr:
attr_name = '_'.join(attr.split('_', 3)[3:])
if hasattr(obj, attr_name):
obj_dict[attr_name] = getattr(obj, attr_name)
return obj_dict
</code></pre>
|
[] |
[
{
"body": "<pre><code>def sqlobject_to_dict(obj):\n obj_dict = {}\n cls_name = type(obj)\n</code></pre>\n\n<p>That's not a name, its a class object</p>\n\n<pre><code> has_props = False\n for attr in vars(cls_name):\n attr_parent = type(getattr(obj, attr)).__bases__[0]\n</code></pre>\n\n<p>You have <code>getattr(obj, attr)</code> over and over and over. Do it once, and store it in a local variable</p>\n\n<pre><code> if isinstance(getattr(cls_name, attr), property):\n has_props = True\n if isinstance(getattr(obj, attr), Decimal):\n obj_dict[attr] = float(getattr(obj, attr))\n elif isinstance(getattr(obj, attr), list):\n dict_list = []\n for list_item in getattr(obj, attr):\n dict_list.append(sqlobject_to_dict(list_item))\n obj_dict[attr] = dict_list\n</code></pre>\n\n<p>I recommend doing <code>obj_dict[attr] = map(sql_object_dict, getattr(obj, attr))</code></p>\n\n<pre><code> elif isinstance(getattr(obj, attr), dict):\n dict_dict = {}\n for key, val in getattr(obj, attr):\n</code></pre>\n\n<p>Don't you need <code>.items()</code>?\n dict_dict[key] = sqlobject_to_dict(val)\n obj_dict[attr] = dict_dict</p>\n\n<p>I'd do <code>obj_dict[attr] = dict( (key, sql_object_to_dict(value)) for key, value in getattr(obj, attr) )</code>\n elif attr_parent == SQLObject:</p>\n\n<p>Why did you fetch <code>attr_parent</code> instead of using isinstance?</p>\n\n<pre><code> obj_dict[attr] = sqlobject_to_dict(getattr(obj, attr))\n else:\n obj_dict[attr] = getattr(obj, attr)\n</code></pre>\n\n<p>Is a default really a good idea? There may some sort of attribute with isn't valid JSON that makes it through.</p>\n\n<pre><code> elif not has_props and attr_parent != SQLObject:\n\n\n if \"_get_\" in attr:\n attr_name = '_'.join(attr.split('_', 3)[3:])\n</code></pre>\n\n<p>Thats a confusing way to do that. I'm sure what exactly the form you are trying to match here is, but I think this is a use case for regular expressions.</p>\n\n<pre><code> if hasattr(obj, attr_name):\n obj_dict[attr_name] = getattr(obj, attr_name)\n</code></pre>\n\n<p>So I'm guessing you've got various <code>_get_foo()</code> functions which are invoked by some sort of <code>__getattr__</code> magic. You stop checking for this once you find a property. (Probably newer objects use properties instead.) I would consider not doing the <code>has_props</code> thing. It makes your code less clear, and probably doesn't make much difference performance wise.</p>\n\n<pre><code> return obj_dict\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:06:52.783",
"Id": "11642",
"Score": "1",
"body": "Excellent advice. Let me factor this all in. I'm using attr_parent because I'm working on getting the properties of the inherited class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T18:24:48.233",
"Id": "7421",
"ParentId": "7420",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T15:46:21.603",
"Id": "7420",
"Score": "4",
"Tags": [
"python",
"json"
],
"Title": "A better way to convert an SQLObject instance into a dict"
}
|
7420
|
<p>I have a method which compares two lists of strings. If the strings, and only the strings, from <code>listA</code> appear in <code>listB</code>, return <code>true</code>. Else return <code>false</code>.</p>
<pre><code>internal bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds)
{
bool result = true;
if (Ids.Count == XmlIds.Count)
{
foreach (var hwId in Ids)
{
if(!XmlIds.Contains(hwId))
{
result = false;
break;
}
}
}
else
{
result = false;
}
return result;
}
</code></pre>
<p>My initial unit test is passing (no edge cases etc. yet), but I was wondering if there is a more compact, but still readable, way to do it.</p>
|
[] |
[
{
"body": "<p>If you can use LINQ, I think you can do</p>\n\n<pre><code>internal bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds)\n{\n return \n Ids.Count == XmlIds.Count &&\n Ids.All(XmlIds.Contains) &&\n XmlIds.All(Ids.Contains);\n}\n</code></pre>\n\n<p>to achieve the same result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:02:03.867",
"Id": "11648",
"Score": "3",
"body": "Perhaps `Ids.All(XmlIds.Contains)` might sound a bit Yoda-like, but I think it's still readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:18:31.127",
"Id": "11653",
"Score": "3",
"body": ":-) Yoda like it does indeed sound"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:19:03.843",
"Id": "7424",
"ParentId": "7422",
"Score": "6"
}
},
{
"body": "<p>So let me get this straight, you are trying to determine if list A is a <em>subset</em> of list B?</p>\n\n<pre><code>internal bool DoIdsMatchThoseFromXml(List<string> ids, List<string> xmlIds)\n{\n return !ids.Except(xmlIds).Any(); // A - B = {}\n}\n</code></pre>\n\n<p>Or are you trying to see if list A is <em>set equal</em> to list B?</p>\n\n<pre><code>internal bool DoIdsMatchThoseFromXml(List<string> ids, List<string> xmlIds)\n{\n return ids.Count == xmlIds.Count // assumes unique values in each list\n && new HashSet<string>(ids).SetEquals(xmlIds);\n}\n</code></pre>\n\n<p>I would avoid performing linear searches through this as you'd be looking at O(n*m) performance when you could be doing O(n+m). Use set operations if you can. Use <code>HashSet<string></code> if possible too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:14:27.320",
"Id": "11651",
"Score": "0",
"body": "Thanks Jeff. These (LINQ?) methods are new to me! Care to explain the `xmlIds.Count > 0` in the second example? I'm not sure what this adds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:25:26.160",
"Id": "11655",
"Score": "0",
"body": "In the second case, you need to make sure set B is non-empty otherwise it will always be true which would be incorrect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:28:03.033",
"Id": "11656",
"Score": "0",
"body": "Hmm... with the non-empty check it is just the same as the first code example, except the lists swap places. So wouldn't the second example return whether B was a subset of A, just as the first example returns whether A is a subset of B?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:34:24.553",
"Id": "11657",
"Score": "0",
"body": "The way I see it, if you're checking if a set A is a subset of set B, just remove all common elements from set A that's also in set B (`A - B`) and it should yield the empty set. The empty set (as set A) is a subset of all sets so we need to allow for it. If you're checking if set A is equal to set B, then provided that set B is not empty, removing all from set B all in common from set A should yield the empty set. It's unlikely that both your lists will be empty so I've omitted that check (you can certainly add it if you wish)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T22:31:02.397",
"Id": "11664",
"Score": "0",
"body": "But in example 2, set B could just be a subset of set A. What if A = {1,2,3,4} and B = {1,2}? Apologies if I'm missing the obvious here!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T22:45:27.217",
"Id": "11666",
"Score": "0",
"body": "Ah, yeah you're right, in that case, it would require some modifications."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:27:09.703",
"Id": "7426",
"ParentId": "7422",
"Score": "16"
}
},
{
"body": "<p>The solutions proposed by Jeff and w0lf are very fine, but have you considered simply rearranging your code a little bit? Because even though the following does O(M*N), your question was about readability, not performance, and I think that people unfamiliar with linq will find this more graspable:</p>\n\n<pre><code>internal bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds)\n{\n if (Ids.Count != XmlIds.Count)\n return false;\n foreach (var hwId in Ids)\n if(!XmlIds.Contains(hwId))\n return false;\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T02:02:11.810",
"Id": "11678",
"Score": "2",
"body": "I'm no LINQ expert, but I found them eminently readable. LINQ is about describing intent (what) over implementation (how). Gory internals is why we've invented higher-level languages and libraries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T07:38:09.700",
"Id": "11681",
"Score": "0",
"body": "I have to admit you are right. So, I will reword my answer a little bit. I am changing \"people not awfully familiar with linq will find this more readable\" to \"people unfamiliar with linq will find this more graspable\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T23:27:51.403",
"Id": "7431",
"ParentId": "7422",
"Score": "2"
}
},
{
"body": "<p>This is more compact, but also performs better:</p>\n\n<pre><code>internal bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds) {\n if (Ids.Count != XmlIds.Count) return false;\n HashSet<string> xmlIds = new HashSet<string>(XmlIds);\n return Ids.All(id => xmlIds.Contains(id));\n}\n</code></pre>\n\n<p>This is close to O(n), compared to the original O(n*n).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T08:07:59.833",
"Id": "7440",
"ParentId": "7422",
"Score": "2"
}
},
{
"body": "<p>This uses no LINQ, just methods defined on <code>List<T></code>:</p>\n\n<pre><code> internal static bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds)\n {\n return Ids.TrueForAll(XmlIds.Contains) && XmlIds.TrueForAll(Ids.Contains);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-09T21:54:49.397",
"Id": "99753",
"Score": "0",
"body": "I like how clean this one is."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T20:01:37.587",
"Id": "7463",
"ParentId": "7422",
"Score": "4"
}
},
{
"body": "<p>If you sort the two lists and then return the SequenceEqual method you can do it all in three lines of code. SequenceEqual returns whether or not two Lists have the same items in the same order (hence the sorting before the comparing).</p>\n\n<pre><code> internal bool DoIdsMatchThoseFromXml(List<string> Ids, List<string> XmlIds)\n {\n Ids.Sort();\n XmlIds.Sort();\n\n return Ids.SequenceEqual(XmlIds);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-26T20:17:40.223",
"Id": "78674",
"ParentId": "7422",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T19:59:29.090",
"Id": "7422",
"Score": "13",
"Tags": [
"c#",
"algorithm",
"strings"
],
"Title": "Compare items in two lists"
}
|
7422
|
<p>I created a simple Python script to log track listens in iTunes and it seems that it's pretty inefficient. I'm primarily a front-end developer, so this is clearly not my area of expertise. I know loops can cause problems in any language, so I assume that's the issue here.</p>
<p>If I run this script for a while (say, a couple of hours or more) the fan on my computer starts working overtime and won't stop until I kill the script.</p>
<p>Any idea what might be making this happen? Suggestions on how to optimize? Appreciate any help I can get.</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx, sqlite3, datetime, threading
from appscript import *
it = app('iTunes')
from AppKit import *
# Create the DB
Tapedeck = sqlite3.connect('Tapedeck.db', check_same_thread = False)
TapedeckQuery = Tapedeck.cursor()
Tapedeck.execute('''CREATE TABLE IF NOT EXISTS plays (id INTEGER PRIMARY KEY, track_id TEXT, track TEXT, artist TEXT, album TEXT, genres TEXT, play_count INTEGER, rating INTEGER, skip_count INTEGER, year_released INTEGER, date_played DATE)''')
Tapedeck.commit()
def getSec(s):
l = s.split(':')
return int(l[0]) * 60 + int(l[1])
def addTrack(track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating):
#print ' --\n Position: {}\n Length: {}'.format(it.player_position(),getSec(it.current_track.time()))
TapedeckQuery.execute('''INSERT INTO plays (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating) VALUES (?,?,?,?,?,?,?,?,?,?)''',
(track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating))
Tapedeck.commit()
loop_int = 1.0
last_track = '0'
def listen():
global loop_int, last_track
threading.Timer(loop_int, listen).start()
if it.player_state() == k.playing:
# check to see if track was restarted
if it.player_position() < getSec(it.current_track.time())/2 and last_track == it.current_track.persistent_ID():
self.last_track = '0'
# has the track played beyond the halfway mark?
if it.player_position() >= getSec(it.current_track.time())/2 and last_track != it.current_track.persistent_ID():
today = datetime.datetime.today()
now = '{}-{}-{} {}:{}:{}'.format(today.year, '%02d' % today.month, '%02d' % today.day, '%02d' % today.hour, '%02d' % today.minute, '%02d' % today.second)
print '\nArtist: {}\nTrack: {}\nAlbum: {}\nGenres: {}\nDatetime: {}'.format(it.current_track.artist().encode('ascii','ignore'), it.current_track.name().encode('ascii','ignore'), it.current_track.album().encode('ascii','ignore'), it.current_track.genre().encode('ascii','ignore'), now)
last_track = it.current_track.persistent_ID()
addTrack(it.current_track.persistent_ID(), it.current_track.name(), it.current_track.artist(), it.current_track.album(), it.current_track.genre(), it.current_track.played_count(), it.current_track.skipped_count(), it.current_track.year(), now, it.current_track.rating())
listen()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:02:00.200",
"Id": "11643",
"Score": "0",
"body": "Try running it through `python -m cProfile -o prof.dat <prog> <args>` for a while, and you'll get file that gives you calls and how long each call took in CPU seconds. To view it interactively, you would want `python -m pstats prof.dat`. Take a look at that, then see if you can isolate the parts in which performance is acting up. A sorted (by cumulative time) .dat file would be helpful to isolate any issues as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T20:56:09.777",
"Id": "11646",
"Score": "0",
"body": "Firstly, have you actually determined whether it runs out of memory? Does it have a large memory usage when you come back two hours later?"
}
] |
[
{
"body": "<pre><code>#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport wx, sqlite3, datetime, threading\nfrom appscript import *\n</code></pre>\n\n<p><code>import *</code> is frowned upon as it makes it difficult to trace where names came from.</p>\n\n<pre><code>it = app('iTunes')\n</code></pre>\n\n<p>I recommend avoiding abbreviated names like <code>it</code> its hard to figure out what it means later.</p>\n\n<pre><code>from AppKit import *\n\n\n\n# Create the DB\nTapedeck = sqlite3.connect('Tapedeck.db', check_same_thread = False)\nTapedeckQuery = Tapedeck.cursor()\nTapedeck.execute('''CREATE TABLE IF NOT EXISTS plays (id INTEGER PRIMARY KEY, track_id TEXT, track TEXT, artist TEXT, album TEXT, genres TEXT, play_count INTEGER, rating INTEGER, skip_count INTEGER, year_released INTEGER, date_played DATE)''')\nTapedeck.commit()\n</code></pre>\n\n<p>Generally, performing actions at the module level is frowned upon. You should do it in a main function.</p>\n\n<pre><code>def getSec(s):\n</code></pre>\n\n<p>Python style guide recommends lowercase_with_underscores for function names. Also, don't needlessly abbreviate.</p>\n\n<pre><code> l = s.split(':')\n return int(l[0]) * 60 + int(l[1])\n</code></pre>\n\n<p>I'd have done:</p>\n\n<pre><code>minutes, seconds = s.split(':')\nreturn int(minutes)*60 + int(seconds)\n</code></pre>\n\n<p>I think its easier to see what's going on </p>\n\n<pre><code>def addTrack(track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating):\n #print ' --\\n Position: {}\\n Length: {}'.format(it.player_position(),getSec(it.current_track.time()))\n TapedeckQuery.execute('''INSERT INTO plays (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating) VALUES (?,?,?,?,?,?,?,?,?,?)''',\n (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating))\n Tapedeck.commit()\n\n\nloop_int = 1.0\nlast_track = '0'\n\ndef listen():\n\n global loop_int, last_track\n</code></pre>\n\n<p>Avoid global variables. You should generally only be using globals as constants. </p>\n\n<pre><code> threading.Timer(loop_int, listen).start()\n</code></pre>\n\n<p>Python isn't Javascript. Instead of playing with threads, use time.Sleep(1) to sleep for a second between each attempt. Put everything in a loop. It'll be easier to follow.</p>\n\n<pre><code> if it.player_state() == k.playing:\n # check to see if track was restarted\n if it.player_position() < getSec(it.current_track.time())/2 and last_track == it.current_track.persistent_ID():\n self.last_track = '0'\n</code></pre>\n\n<p>self?</p>\n\n<pre><code> # has the track played beyond the halfway mark?\n if it.player_position() >= getSec(it.current_track.time())/2 and last_track != it.current_track.persistent_ID():\n today = datetime.datetime.today()\n now = '{}-{}-{} {}:{}:{}'.format(today.year, '%02d' % today.month, '%02d' % today.day, '%02d' % today.hour, '%02d' % today.minute, '%02d' % today.second)\n</code></pre>\n\n<p>The datetime has a formatting function which may be better suited to that</p>\n\n<pre><code> print '\\nArtist: {}\\nTrack: {}\\nAlbum: {}\\nGenres: {}\\nDatetime: {}'.format(it.current_track.artist().encode('ascii','ignore'), it.current_track.name().encode('ascii','ignore'), it.current_track.album().encode('ascii','ignore'), it.current_track.genre().encode('ascii','ignore'), now)\n last_track = it.current_track.persistent_ID()\n addTrack(it.current_track.persistent_ID(), it.current_track.name(), it.current_track.artist(), it.current_track.album(), it.current_track.genre(), it.current_track.played_count(), it.current_track.skipped_count(), it.current_track.year(), now, it.current_track.rating())\n\nlisten()\n</code></pre>\n\n<p>As for your actual problem. I don't know this appscript/AppKit you are using. But I'll speculate that under some circumstances iTunes stops responding. Maybe a dialog gets popped or something. As a result, each thread gets stuck waiting for iTunes. But because you set the timer as your first action, a new thread keeps getting started which also gets stuck. Eventually, your poor scripts piles many many threads and that explains the hang. </p>\n\n<p>If you use the sleep method I suggested above, that should prevent the script from running many threads. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:29:36.153",
"Id": "7428",
"ParentId": "7423",
"Score": "3"
}
},
{
"body": "<p>You could run <code>ps</code> or <code>top</code> to find out how much memory, CPU your script consumes (<a href=\"https://code.google.com/p/psutil/\" rel=\"nofollow\"><code>psutil</code></a> allows to do it from Python).</p>\n\n<p>If <code>app('iTunes')</code> supports it you could replace your polling interface with a callback on event e.g., a track change.</p>\n\n<p>If not then you could remove <code>threading.Timer()</code> call and replace it with this code:</p>\n\n<pre><code>import time\n\nwhile True:\n next_time = time.time() + loop_int\n listen()\n delay = next_time - time.time()\n if delay > 0:\n assert delay <= loop_int # break loudly on clock adjustments\n time.sleep(delay)\n</code></pre>\n\n<p>This code runs <code>listen()</code> function every <code>loop_int</code> seconds (approximately) or if <code>listen()</code> function takes us longer than <code>loop_int</code> seconds then it runs the next <code>listen()</code> call immediately after the previous one. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T23:51:12.810",
"Id": "7432",
"ParentId": "7423",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7428",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T19:57:30.340",
"Id": "7423",
"Score": "2",
"Tags": [
"python"
],
"Title": "Inefficient Python script eating up memory (I believe)"
}
|
7423
|
<p>It seems that lxml/etree are generally imported as <code>from lxml import etree</code> -- why is that? It keeps the code tidier, and while the potential namespace ambiguity might not be a concern, I don't have any incentive of doing this as it's generally frowned upon.</p>
<p>I know for a script of this size it doesn't matter much, but I'm going to be using these modules for a lot more. I'm also curious about what others have to say.</p>
<pre><code>#!/usr/bin/python
# Stuart Powers http://sente.cc/
import sys
import urllib
import lxml.html
from cStringIO import StringIO
""" This script parses HTML and extracts the div with an id of 'search-results':
ex: <div id='search-results'>...</div>
$ python script.py "http://www.youtube.com/result?search_query=python+stackoverflow&page=1"
The output, if piped to a file would look like: http://c.sente.cc/E4xR/lxml_results.html
"""
parser = lxml.html.HTMLParser()
filecontents = urllib.urlopen(sys.argv[1]).read()
tree = lxml.etree.parse(StringIO(filecontents), parser)
node = tree.xpath("//div[@id='search-results']")[0]
print lxml.etree.tostring(tree, pretty_print=True)
</code></pre>
|
[] |
[
{
"body": "<p>You might be confusing <code>from lxml import etree</code> that is a legitimate (even preferred) form of an absolute import with relative imports for intra-package imports that are discouraged: <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">http://www.python.org/dev/peps/pep-0008/</a> (see \"Imports\" section)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:54:34.363",
"Id": "7454",
"ParentId": "7430",
"Score": "3"
}
},
{
"body": "<p>In your and most of the cases I had while working with <code>lxml.etree</code> or <code>lxml.html</code>, there was only need for parsing and dumping, which in case of string input and output can be achieved with <code>fromstring()</code> and <code>tostring()</code> functions:</p>\n\n<pre><code>from lxml.html import fromstring, tostring\n</code></pre>\n\n<p>Which would transform your code to:</p>\n\n<pre><code>import sys\nimport urllib\n\nfrom lxml.html import fromstring, tostring\n\n\ndata = urllib.urlopen(sys.argv[1]).read()\n\ntree = fromstring(data)\nnode = tree.xpath(\"//div[@id='search-results']\")[0]\n\nprint(tostring(tree, pretty_print=True))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-05T04:47:13.850",
"Id": "156951",
"ParentId": "7430",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T22:15:32.377",
"Id": "7430",
"Score": "6",
"Tags": [
"python",
"parsing",
"lxml"
],
"Title": "Extracting a div from parsed HTML"
}
|
7430
|
<p>Is there a better way to express the dispatch (switch) code without using a lambda? I think I need the lambda to act as an intermediary because the functions have varying numbers of parameters.</p>
<pre><code>def printf(arg):
print arg
def printf2(arg1, arg2):
print arg1
print arg2
def printn(arg):
print arg
action = 'op2'
functions = {
'op1': lambda: printf('op1 called'),
'op2': lambda: printf2('op2 called', 'param 2'),
}
functions.get(action, lambda: printn('default op'))()
</code></pre>
|
[] |
[
{
"body": "<p>You could change it to just store the functions <em>and</em> the arguments. Then use the argument unpacking to fill in the correct arguments to the function call.</p>\n\n<pre><code>action = 'op2'\nfunctions = {\n 'op1': (printf, ('op1 called',)),\n 'op2': (printf2, ('op2 called', 'param 2')),\n}\n\nfn, args = functions.get(action, (printn, ('default op',)))\nfn(*args) # call the function unpacking the provided arguments\n</code></pre>\n\n<hr>\n\n<p>A better solution in this particular case IMHO, rather than defining multiple functions with varying number of arguments, you could just define one function accepting variable arguments to achieve the same thing.</p>\n\n<pre><code>def printf(*args):\n if args:\n for arg in args:\n print arg\n else:\n print 'default op'\n</code></pre>\n\n<p>Then it's just a matter of storing only the arguments to the call rather than the functions themselves:</p>\n\n<pre><code>action = 'op2'\narguments = {\n 'op1': ('op1 called',),\n 'op2': ('op2 called', 'param 2'),\n}\n\nprintf(*arguments.get(action, ()))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T02:26:17.980",
"Id": "7435",
"ParentId": "7433",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T01:58:23.687",
"Id": "7433",
"Score": "4",
"Tags": [
"python"
],
"Title": "Dictionary-based dispatch in Python with multiple parameters"
}
|
7433
|
<p>I read that if an object is made using the <code>init</code> it must be released, but if it's something like this <code>elementFormula = [[NSMutableString stringWithString:@""]</code> it is autoreleased. However, there are some other aspects of memory management that confuse me.</p>
<p>For example, something like <code>[[NSMutableString stringWithString:@""] retain]</code> If I retain an autoreleased object, do I have to release it myself, or is it still autoreleased? Also, if I declare a pointer to an object in the .h and assign it a value in the .m like so <code>completeFormula = [self synthesizeFormula];</code> without going through the init process, do I have to release <code>completeFormula</code>?</p>
<p>Those are my main concerns, but I have posted the entire code below if needed.</p>
<pre><code>@interface EquationTextField : UIView <KeyInput> {
FormulaKeyboard *keyboard;
int consecutiveElementCount;
int subscriptLength;
int chargeIndex;
NSMutableString *elementFormula;
NSString *lastElementPressed;
NSString *charge;
NSString *state;
NSString *completeFormula;
}
init {
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:@"FormulaKeyboard" owner:self options:nil];
for (id object in bundle) {
if ([object isKindOfClass:[FormulaKeyboard class]])
keyboard = (FormulaKeyboard *)object;
}
self.inputView = keyboard;
keyboard.delegate = self;
elementFormula = [[NSMutableString stringWithString:@""] retain];
charge = [[NSString alloc] initWithString:@""];
state = [[NSString alloc] initWithString:@""];
}
- (void)addElement:(NSString *)currentElement {
if (![currentElement isEqualToString:lastElementPressed]) {
// when new element is pressed
[elementFormula appendString:currentElement];
lastElementPressed = currentElement;
consecutiveElementCount = 1;
}
else if ([currentElement isEqualToString:lastElementPressed]) {
// when element is pressed consecutively
if (consecutiveElementCount == 1) {
// since there is no '1' subscript, nothing needs to be deleted
[elementFormula appendString:@"₂"];
subscriptLength = 1;
}
if (consecutiveElementCount > 1) {
// deletes last subscript and replaces it with new subscript
NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil] autorelease];
NSRange range = NSMakeRange (([elementFormula length] - subscriptLength), subscriptLength);
[elementFormula deleteCharactersInRange:range];
NSString *tempSubscript = [subscriptList objectAtIndex:consecutiveElementCount - 1];
[elementFormula appendString:tempSubscript];
subscriptLength = [tempSubscript length];
}
if (consecutiveElementCount < 11)
consecutiveElementCount ++;
}
completeFormula = [self synthesizeFormula];
}
- (void)changeCharge:(NSString *)chargeIncrease {
NSArray *chargeList = [[[NSArray alloc] initWithObjects:@"⁴⁻", @"³⁻", @"²⁻", @"⁻", @"", @"⁺", @"²⁺", @"³⁺", @"⁴⁺", nil] autorelease];
if ([chargeIncrease isEqualToString:@"+"]) {
chargeIndex += 1;
charge = [chargeList objectAtIndex:chargeIndex];
}
else if ([chargeIncrease isEqualToString:@"-"]) {
chargeIndex -= 1;
charge = [chargeList objectAtIndex:chargeIndex];
}
completeFormula = [self synthesizeFormula];
}
- (void) changeState:(NSString *)stateName {
state = stateName;
completeFormula = [self synthesizeFormula];
}
- (NSString *)synthesizeFormula {
NSMutableString *synthesizedFormula = [[[NSMutableString alloc] initWithString:elementFormula] autorelease];
[synthesizedFormula appendString:charge];
[synthesizedFormula appendString:state];
return synthesizedFormula;
}
- (void)dealloc
{
[charge release];
[state release];
self.inputView = nil;
keyboard.delegate = nil;
[keyboard release];
[super dealloc];
}
</code></pre>
|
[] |
[
{
"body": "<p>It's not init that causes you to have to be responsible for releasing the memory its alloc. If you call alloc, retain or new (this is rarely used these days) then you are responsible for releasing the memory yourself.</p>\n\n<p>So in the case where you had an autoreleased object and you retained it. Then yes you would then be responsible for subsequently releasing it.</p>\n\n<p>The most common side affect where you can be responsible for releasing an object you didn't explicitly call alloc or retain on is with a property that has the retain attribute.</p>\n\n<p>@property (retain) NSString *string;</p>\n\n<p>if you then have the following code somewhere</p>\n\n<pre><code>self.string = [NSString stringWithString:@\"This is an autoreleased string typically\"];\n</code></pre>\n\n<p>calling the self.string piece will cause it to retain the value you are setting it with. So you would want to make sure and have the following to clean it up, probably in your dealloc.</p>\n\n<pre><code>self.string = nil;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:04:43.980",
"Id": "7448",
"ParentId": "7437",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7448",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T04:26:18.977",
"Id": "7437",
"Score": "3",
"Tags": [
"objective-c",
"memory-management"
],
"Title": "Am I managing my memory correctly?"
}
|
7437
|
<p>I've made a mock version of Silverlight in D2. It is meant to output HTML, but since I don't know HTML yet, its current output is in. HTML is not the reason I'm here, though. The goal of my project was to create a framework that uses XAML and MVVM to create a site bound to a viewmodel. It doesn't do too much and isn't dynamic as of yet, but right now I'm just at the first milestone. </p>
<p>Before I go any further with the project I'd like some feedback on what I have so far. Specifically, my use of template mixins to achieve polymorphism and override base class methods, even if they contain the exact same code (this problem is explained in code-comments). But at the same time this is my first forray into D and I'm sure there are other things I could use help with, so I'm open to any suggestions.</p>
<p>The code is on <a href="https://github.com/jeanbern/darklight/blob/master/source/darklight/control.d" rel="nofollow">GitHub</a> for anyone interested. I know it's not very useful but I'm having fun with it.</p>
<p>In my opinion, the code explains itself with comments, but I can add more if it's unclear.</p>
<pre><code>module darklight;
import std.stdio: writeln;
enum string __module = "darklight";
//A sample view model class
//Can compound classes other than OddVM as well, this is just a demo
class OddVM {
string text;
OddVM inner;
OddVM list[];
string amethod(string name) {
return "my name is: "~name;
}
this(string te) {
this.text = te;
}
}
//showing off the different controls, as well as binding features and some of the xml capacity
enum string _xml = "
<StackPanel name=viewModel.text
binding=viewModel.inner>
<TextBox name=\"itext1\"
text=binding.text>
</TextBox>
<TextBox name=\"itext2\"
binding=viewModel.inner
text=binding.text
/>
<TextBox name=\"itext3\"
binding=viewModel.inner
text=binding.amethod(\"robot\") />
<TextBox name=\"itext4\"
binding=viewModel.inner.inner
text=\"too deep, would error if I tried binding\"/>
<ListPanel name=\"somename\"
binding=viewModel.list>
<TextBox name=\"itextinside\"
text=binding.text/>
</ListPanel>
<DoubleText name=\"double\"
binding=viewModel.inner/>
</StackPanel>";
//viewModel when accessed provides the passed in vm
//binding is the new one if set, or the same as viewModel if not
int main(string[] args) {
//create a sample viewModel
OddVM vm = new OddVM ("bound");
vm.inner = new OddVM ("bound inner");
vm.inner.inner = new OddVM ("bound inner inner");
OddVM vm1 = new OddVM("first");
OddVM vm2 = new OddVM("second");
OddVM vm3 = new OddVM("third");
vm.inner.list = [vm1, vm2, vm3];
//The vm could be any type of object
//It just needs the proper variables as defined in the xml
auto res = Control.BuildControl!(_xml)(vm);
writeln(res.content());
//change some values in the viewmodel
vm.text = "new text";
vm.inner.text = "new inner text";
//can add things to a list and the templates won't be disturbed
vm.inner.list ~= vm1;
//need to rebuild controls to bind new values
res = Control.BuildControl!(_xml)(vm);
writeln(res.content());
return 0;
}
abstract class Control {
string name;
mixin template codegen(string _xml) {
//provides access to some parsed sections of the xml
static const string extr[] = parsexml!(_xml);
static const string _tag = extr == [] ? "" : extr[0];
static const string _attr = extr == [] ? "" : extr[1];
static const string _inner = extr == [] ? "" : extr[2];
static const string _rem = extr == [] ? "" : extr[3];
static const string _elem = extr == [] ? "" : extr[4];
}
mixin template setvarsgen() {
private auto setvars(string _xml, T)(T viewModel) {
//for access to attr
mixin codegen!(_xml);
//add the string of assignments for binding to the viewModel
mixin(assignstring(_attr));
return binding;
}
}
//This is in a mixin template because when I want it to be called by a subclass
//the subclass needs to have it's own implementation of it or the method bindings will crash.
//ex: if this was called from TextBox without beind re-mixed-in, it would fail on assigning this.text
//This might be a failure of polymorphism with templated methods, or just me
mixin template extractgen(string _newxml = null) {
static if (_newxml == null) {
//a base extraction method, sets variables to the bindings outlined in xml
private auto extract(string _xml, T)(T viewModel) {
this.setvars!(_xml)(viewModel);
return this;
}
} else {
// This one is for controls with custom xaml, usually you shouldn't need to override this
// But you'll probably have to do Control.extractgen!(_newxaml) to bypass any overrides
private auto extract(string _xml, T)(T viewModel) {
// The var setting from this gets overwritten, but we need the binding
auto binding = setvars!(_xml)(viewModel);
// Distinction here is that _newxml replaces xml
auto ret = super.extract!(_newxml)(binding);
// This lets xml bindings (ex: name) from the outside override anything on the inside
setvars!(_xml)(viewModel);
return ret;
}
}
}
mixin setvarsgen!();
mixin extractgen!();
//Outputs the html/other things representing the control
abstract pure string content();
static auto BuildControl(string _xml, T)(T viewModel) {
mixin codegen!(_xml);
mixin(_tag~" control = cast("~_tag~") Object.factory(\""~__module~"."~_tag~"\");");
return control.extract!(_xml)(viewModel);
}
}
class TextBox : Control {
string text;
//the new class variable text means these two have to be re-added
mixin setvarsgen!();
mixin extractgen!();
pure string content() {
return "<p "~this.name~">" ~ this.text ~ "<p>\n";
}
}
class StackPanel : Control {
Control controls[];
mixin template extractgen() {
//overrides the extract method, adds inner controls
private auto extract(string _xml, T)(T viewModel) {
mixin codegen!(_xml);
auto binding = setvars!(_xml)(viewModel);
this.controls = this.chain!(_inner)(binding);
return this;
}
}
mixin setvarsgen!();
mixin extractgen!();
pure string content() {
string ret;
foreach(contr; controls) {
ret ~= contr.content();
}
return "<div "~this.name~">\n"~ret~"<div>\n";
}
private Control[] chain(string _xml, T)(T viewModel) {
mixin codegen!(_xml);
//this 5 is completely arbitrary, limits you w.r.t. the xml
static if (_rem.length > 5) {
return [cast(Control)BuildControl!(_elem)(viewModel)] ~ chain!(_rem)(viewModel);
} else {
return [cast(Control)BuildControl!(_xml)(viewModel)];
}
}
}
//example specialization of existing control
class ListPanel : StackPanel {
//this is necessary because templates don't override well...
//without this, the this.chain! call doesn't call ListPanel.chain! it calls StackPanel.chain!
//I described this earlier
mixin extractgen!();
//setvarsgen! doesn't need to be here since there are no new class variables
private Control[] chain(string _xml, T)(T viewModel) {
Control ret[];
foreach(vm; viewModel) {
ret ~= BuildControl!(_xml)(vm);
}
return ret;
}
}
//example of user defined xml for a new control
class DoubleText : StackPanel {
enum _xmlstring = "
<StackPanel name=\"doubletext type\">
<TextBox name=\"itext1\"
text=binding.text>
</TextBox>
<TextBox name=\"itext2\"
text=\"danger zone!\">
</TextBox>
</StackPanel>";
//this will call super.extract, while using the new xml
//"Control." is necessary for this control and sometimes others because their parents overwrite extractgen! without defining a string constructor
//in other cases you might need to rewrite extract!
mixin Control.extractgen!(_xmlstring);
}
/*
* THE CODE BEYOND THIS POINT IS EMBARRASSING AND SHAKY, BUT SERVES IT'S PURPOSE
* It's for slightly picky xml parsing
* It's not as bad as it once was...
*/
//returns a string of code to be mixin'd, that will do the binding
//text=\"hi\" -> this.text="hi";
//text=method() -> this.text=method();
//binding=something -> auto binding = something; //if not defined, auto binding = viewModel; is added.
//binding is always set on the first line
//could additionally be modified to allow for method calls without assignment, but not sure if needed
pure string assignstring(string content) {
string ret;
int start, mid, i;
bool tracking, pastmid, strtracker, bound;
void falsify() {
tracking = false;
pastmid = false;
strtracker = false;
}
pure bool isformatchar(char a) {
return (a == ' ' || a == '\n' || a=='\t' || a=='<' || a=='>' || a=='/' || a=='\\');
}
string bindingconcat(string ret, string content, int start, int mid, int i) {
string first = content[start..mid];
string second = content[mid+1..i];
assert(first~"="~second == content[start..i]);
if (first == "binding") {
bound = true;
return "auto binding = "~second~";\n"~ret;
} else {
return ret~"this."~content[start..i]~";\n";
}
}
for(; i < content.length; i++) {
if (!tracking && !isformatchar(content[i])) {
start = i;
tracking = true;
}
if (tracking && content[i]=='=') {
pastmid = true;
mid = i;
if (i+1 < content.length && content[i+1] == '"') {
strtracker = true;
i++;
}
}
else if (tracking && !pastmid && isformatchar(content[i])) {
falsify();
}
else if (tracking && pastmid && strtracker && content[i] == '"') {
falsify();
ret ~= "this."~content[start..i+1]~";\n";
}
else if (tracking && pastmid && !strtracker && isformatchar(content[i])) {
falsify();
ret = bindingconcat(ret,content,start,mid,i);
}
}
if (tracking && pastmid) {
ret = bindingconcat(ret,content,start,mid,i);
}
if (!bound) {
ret = "auto binding = viewModel;\n" ~ ret;
}
return ret;
}
template parsexml(string xml) {
enum parsexml = xmlparse(xml);
}
pure string[] xmlparse(string xml) {
//tag, attr, inner, remainder, elem
int b[5]; //"|<jkh| |> |</jkh|>";
int open;
int i = -1;
while(++i < xml.length) {
if (xml[i] == '<') {
b[0] = i;
open = 1;
break;
}
}
while(++i < xml.length) {
if ((xml[i] == ' ' || xml[i] == '\n') && b[1] == 0) {
b[1] = i;
}
if (xml[i] == '>') {
break;
};
if (open == 1 && xml[i] == '/' && xml[i+1] == '>') {
--open;
b[3] = i;
b[4] = i+1;
break;
}
}
b[1] = b[1] == 0 ? i : b[1];
b[2] = i;
while(open > 0 && ++i < xml.length-1) {
if (xml[i] == '<') {
open += xml[i+1]=='/' ? -1 : 1;
}
if (xml[i] == '/' && xml[i+1] == '>') {
--open;
}
}
b[3] = b[3] == 0 ? i : b[3];
while (b[4] == 0 && ++i < xml.length) {
if (xml[i] == '>') {
break;
}
}
b[4] = b[4] == 0 ? i : b[4];
//"|<jkh| |> |</jkh|>";
string ret[]; //tag, attr, inner, remainder, elem
ret ~= xml[b[0]+1..b[1]];
ret ~= xml[b[1]..b[2]];
ret = ret ~ ((b[2]==b[3]) ? "" : xml[b[2]+1..b[3]]);
ret ~= xml[b[4]+1..$];
ret ~= xml[b[0]..b[4]+1];
if (b[2] != b[3]) {
assert(ret[0] == xml[b[3]+2..b[3]+(b[1]-b[0])+1]);
}
return ret;
}
</code></pre>
<p>The output when this is run is the following, which contains two runs of the control builder, to demonstrate viewModel changes. I know it's not real HTML; that's something I have yet to learn.</p>
<pre><code><div bound>
<p itext1>bound inner<p>
<p itext2>bound inner inner<p>
<p itext3>my name is: robot<p>
<p itext4>too deep, would error if I tried binding<p>
<div somename>
<p itextinside>first<p>
<p itextinside>second<p>
<p itextinside>third<p>
<div>
<div double>
<p itext1>bound inner inner<p>
<p itext2>danger zone!<p>
<div>
<div>
<div new text>
<p itext1>new inner text<p>
<p itext2>bound inner inner<p>
<p itext3>my name is: robot<p>
<p itext4>too deep, would error if I tried binding<p>
<div somename>
<p itextinside>first<p>
<p itextinside>second<p>
<p itextinside>third<p>
<p itextinside>first<p>
<div>
<div double>
<p itext1>bound inner inner<p>
<p itext2>danger zone!<p>
<div>
<div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T10:39:09.153",
"Id": "16303",
"Score": "1",
"body": "You will be happy to learn that in HTML you can use either `\"` or `'` around the properties... so you can use `name='item1'` instead of `name=\\\"item1\\\"`. :) You will also find this useful: http://developers.whatwg.org/"
}
] |
[
{
"body": "<p>Here's what I've settled with in case anyone is interested:</p>\n\n<p>Using the factory pattern I was able to build an <strong>injectable factory</strong>. Then using dependency injection I forward the factory through all the control extraction steps. <strong>This has the advantage of allowing a control class to instantiate a sub-control inside itself without worrying about importing the proper modules</strong> (and avoiding circular references).</p>\n\n<p>The <code>extract</code> method is now able to access all the member variables because it is passed the type (as ForwardRefT), instead of using the class's own, <strong>bypassing the lack of polymorphism for templated methods</strong>. Thankfully, this also removes the need to add template mixins everywhere, which was ugly.</p>\n\n<p>Now that you've read it and are fully prepared for the wackyness to come, here is the code:</p>\n\n<pre><code>//This factory is mixed in once, at the highest level of your web app.\n//This way it can reference every module with controls in it and inject itself into them, giving them that ability as well.\nmixin template FactoryGen() {\n import darklight.parse : parse_tag;\n struct ControlFactory\n {\n static auto Extract(string _xml, T)(T viewModel)\n {\n //parse_tag takes \"<StackPanel ...> ... </StackPanel> and returns \"StackPanel\"\n enum Ty = parse_tag!(_xml);\n mixin(\"return \"~Ty~\".extract!(ControlFactory, _xml, \"~Ty~\", T)(viewModel);\");\n }\n }\n}\n\nabstract class Control\n{\n override abstract string toString();\n\n static auto extract(alias F, string _xml, ForwardRefT, T)(T viewModel)\n {\n ForwardRefT self = new ForwardRefT();\n //parse_attr takes \"<StackPanel {0}> ... </StackPanel>\" and returns {0}\n mixin(assignstring(parse_attr!(_xml))); \n return self;\n }\n}\n\nabstract class ContainerControl(int I=0) : Control\n{\n static if (I == 0)\n {\n Control[] controls;\n }\n else\n {\n Control[I] controls;\n }\n\n override string toString()\n {\n string content;\n static if (I == 0)\n {\n content = reduce!(\"a~b.toString()\")(\"\",this.controls);\n }\n else\n {\n foreach(control; this.controls)\n {\n content ~= control.toString();\n }\n }\n\n return format(`\n<div>%s\n</div>`, content);\n }\n}\n\nabstract class StackControl(int I=0) : ContainerControl!(I)\n{\n static auto extract(alias F, string _xml, ForwardRefT, T)(T viewModel)\n {\n ForwardRefT self = new ForwardRefT();\n mixin(assignstring(parse_attr!(_xml)));\n //parse_inner takes \"<StackPanel ...> {0} </StackPanel>\" and returns {0}\n //subparse takes \"<1></1><2></2>\" and returns [\"<1></1>\",\"<2></2>\"]\n enum contents = subparse(parse_inner!(_xml));\n static assert(I == 0 || contents.length == I);\n Chain!(F, contents)(self, vm);\n return self;\n }\n\n static void Chain(alias F, alias inners, ForwardRefT, T)(ForwardRefT self, T viewModel)\n {\n static if (inners.length > 0)\n {\n Control next = F.Extract!(inners[0])(viewModel);\n static if (I == 0)\n {\n self.controls ~= next;\n }\n else\n {\n self.controls[I-inners.length] = next;\n }\n\n Chain!(F, inners[1..$])(self, viewModel);\n }\n }\n}\n\nclass StackPanel : StackControl!() { }\n\nclass ListPanel : ContainerControl!(0)\n{ \n static auto extract(alias F, string _xml, ForwardRefT, T)(T viewModel)\n {\n ForwardRefT self = new ForwardRefT();\n //assignstringPlus is likeassignstring but makes sure there is a variable named \"list\", defaulting it to null if it isn't in the xml\n mixin(assignstringPlus(parse_attr!(_xml),\"list\",\"null\"));\n enum contents = subparse(parse_inner!(_xml));\n static assert(contents.length == 1);\n foreach(item; list)\n {\n self.controls ~= F.Extract!(contents[0])(item);\n }\n\n return self;\n }\n}\n</code></pre>\n\n<p>I'm very pleased with the results as it makes user code much more manageable and cleaner without the mixins. The extract method may look nasty, but the only really scary part is the method signature. Users shouldn't ever have to write another extract method, but if they do it should be much easier than it was in the past.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T23:17:11.577",
"Id": "34779",
"Score": "0",
"body": "I felt this was appropriate as an answer instead of an edit because I have come up with a way to avoid the bad mixins and improve on the use of [**Best practices and design pattern usage**](http://codereview.stackexchange.com/faq#questions)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T23:07:55.583",
"Id": "21645",
"ParentId": "7438",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "21645",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T05:52:41.720",
"Id": "7438",
"Score": "10",
"Tags": [
"template-meta-programming",
"mixins",
"d",
"silverlight"
],
"Title": "Mixin and template-heavy code for a Silverlight clone"
}
|
7438
|
<p>I'm worried about my code performance. The code I've written is an implementation of SHA-256 using pseudocode from Wikipedia. It works fine, but I want to speed it up. With a buffer of 4096 bytes, I only get 40 Mb/s, whereas commercial software gets 120Mb/s. I've degugged the code, and it seems that the problem is in the loop: it computes the SHA-256 slowly.</p>
<p>Can anybody help me or offer advice?</p>
<pre><code>void sha256_file(HWND hDlg, TCHAR *filename, unsigned int *sha256)
{
unsigned long long lenBits, lenBytes, lenPadding, ctBuffer, index, j, i, nBlocks, chunk, pr, temp;
unsigned int w[64], h0, h1, h2, h3, h4, h5, h6, h7, ch, z, ct , memR;
unsigned int s0, s1, a, b, c, d, e, f, g, h, maj, t1, t2;
unsigned char *padding;
TCHAR szPr[20];
HWND hPb;
HANDLE hf, hp;
LARGE_INTEGER fSize;
DWORD bytesRead;
//Create the file
hf = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if(hf == NULL)
{
MessageBox(hDlg, TEXT("Can't create file!"), TEXT("SHA - 256 Calc"), MB_OK);
exit(1);
}
if(GetLastError() == ERROR_FILE_NOT_FOUND)
{
MessageBox(hDlg, TEXT("File not found!"), TEXT("SHA - 256 Calc"), MB_OK | MB_ICONEXCLAMATION);
exit(1);
}
hp = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 0, 0);
if(hp == NULL)
{
MessageBox(hDlg, TEXT("Can't create heap!"), TEXT("SHA - 256 Calc"), MB_OK);
exit(1);
}
//Get Process bar handle
hPb = GetDlgItem(hDlg, IDC_PROGRESS1);
//Set range 0-100
SendMessage(hPb, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
SendMessage(hPb, PBM_SETSTEP, (WPARAM) 1, 0);
SendMessage(hPb, PBM_SETPOS, (WPARAM) 0, 0);
//Get the size of file
GetFileSizeEx(hf, &fSize);
//Get 64 bit size
lenBytes = (unsigned long long)fSize.QuadPart;
//len message in bits
lenBits = lenBytes << 3;
//Blocks of message
nBlocks = ((lenBytes + 8) >> 6) + 1;
lenPadding = lenBytes + 1;
//Calculate padding len msg MOD 512 == 448
while((lenPadding & 0x3f) != 56) lenPadding++;
lenPadding -= lenBytes;
memR = (unsigned int) lenPadding;
memR += 8;
//Allocate memory for padding
padding = (unsigned char *) HeapAlloc(hp, HEAP_ZERO_MEMORY, memR);
if(padding == NULL)
{
MessageBox(hDlg, TEXT("Can't create heap!"), TEXT("SHA - 256 Calc"), MB_OK);
exit(1);
}
//Append 1 bit to message
padding[0] = 0x80;
//Append 64 bit len of message big endian
for(i = (memR - 1); i >= (memR - 8); i--)
{
padding[i] = (unsigned char) lenBits;
lenBits >>= 8;
}
//Hash vars
h0 = H0;
h1 = H1;
h2 = H2;
h3 = H3;
h4 = H4;
h5 = H5;
h6 = H6;
h7 = H7;
index = 0;
ctBuffer = 0;
temp = 0;
pr = 0;
ct = 0;
//Read the first chunk before enter in main loop
ReadFile(hf, buffer, BUFFER_SIZE, &bytesRead, NULL);
for(chunk = 0; chunk < nBlocks ; chunk++)
{
//Handle messages
DoEvents();
//Pregress bar stuff
temp = pr;
pr = ((chunk + 1) * 100 / nBlocks);
if(pr != temp)
{
StringCbPrintf(szPr, sizeof(szPr), TEXT("%d %%"), pr);
SetDlgItemText(hDlg, IDC_STATIC_PR, szPr);
SendMessage(hPb, PBM_STEPIT, 0, 0);
}
//Break message in 32 bit chunks
j = 0;
z = 0;
for(i = index; i < (index + 64); i++, j++, ctBuffer++)
{
if(ctBuffer < lenBytes)
{
w[j >> 2] = (unsigned int)(w[j >> 2] << 8) | buffer[i];
}
else
{
w[j >> 2] = (unsigned int)(w[j >> 2] << 8) | padding[ctBuffer - lenBytes];
z++;
}
}
index += 64;
//Extend the sixteen 32-bit words into sixty-four 32-bit words:
for (i = 16 ; i < 64; i++)
{
s0 = (RROT(w[i-15], 7)) ^ (RROT(w[i-15],18)) ^ (w[i-15] >> 3);
s1 = (RROT(w[i-2], 17)) ^ (RROT(w[i-2],19)) ^ (w[i-2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
f = h5;
g = h6;
h = h7;
//SHA 256 calculations
for(i = 0 ; i < 64 ; i++)
{
s0 = (RROT(a,2)) ^ (RROT(a,13)) ^ (RROT(a, 22));
maj = (a & b) ^ (a & c) ^ (b & c);
t2 = s0 + maj;
s1 = (RROT(e,6)) ^ (RROT(e, 11)) ^ (RROT(e,25));
ch = (e & f) ^ ((~e) & g);
t1 = h + s1 + ch + k[i] + w[i];
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
//Add results to current hash values
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
h5 += f;
h6 += g;
h7 += h;
//Update buffer for read next chunk of file
if(index == BUFFER_SIZE)
{
ReadFile(hf, buffer, BUFFER_SIZE, &bytesRead, NULL);
index = 0;
}
}
sha256[0] = h0;
sha256[1] = h1;
sha256[2] = h2;
sha256[3] = h3;
sha256[4] = h4;
sha256[5] = h5;
sha256[6] = h6;
sha256[7] = h7;
CloseHandle(hf);
if(!HeapFree(hp, 0, padding))MessageBox(hDlg, TEXT("Can't free memory!"), TEXT("SHA - 256 Calc"), MB_OK);
}
void ParseDigest(TCHAR *szMsg, unsigned int len ,unsigned int *digest)
{
StringCbPrintf(szMsg, len, TEXT("%02x%02x%02x%02x%02x%02x%02x%02x"), digest[0],
digest[1],
digest[2],
digest[3],
digest[4],
digest[5],
digest[6],
digest[7]);
}
</code></pre>
<p>I'm going to change my code by computing SHA-256 using OpenSSL style with three functions because it's cleaner:</p>
<pre><code>SHA_CTX ctx; // <-- Struct wih Hash vars for this context
unsigned char disgest[len_of_sha_disgest]
SHA_Init(&ctx); // Init Hash Vars
//This function computes "The SHA Main loop" and it will be inside file read loop
while( not EOF)SHA_Update(ctx,buffer, len);
//This function calculates the padding and creates the digest
SHA_Final(ctx, digest)
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>As a really quick comment, you can do : </p>\n\n<pre><code>for(i = index, index+=64; i < index; i++, j++, ctBuffer++) { (...) }\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>for(i = index; i < (index + 64); i++, j++, ctBuffer++) { (...) } index += 64;\n</code></pre>\n\n<p>to make the code very slightly shorter and faster.</p></li>\n<li><p>Also, to improve readability, please define your variables in the smallest possible scope and as you initialise them (if possible as a <code>const</code> object), such as :</p>\n\n<pre><code>for (unsigned long long chunk = 0; chunk < nBlocks ; chunk++)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>const HANDLE hf = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T15:56:17.900",
"Id": "7446",
"ParentId": "7443",
"Score": "5"
}
},
{
"body": "<p>Suggestions off the top of my head:</p>\n\n<ul>\n<li>Disable debugging switches and enable full optimization (assuming you haven't already).</li>\n<li>Enable profiling to find bottleneck.</li>\n<li>Make sure BUFFER_SIZE is sufficiently large for desired throughput, say at least 1 MiB.\nPersonally, I would go with 16 MiB.</li>\n</ul>\n\n<p>For helping detect bitrot, I once wrote a file-checksumming utility in Perl which runs at disk speed (80 MB/sec external FireWire in my case) using Perl's SHA library, and I found that the block size I used for file read operations made a huge huge huge difference to overall throughput.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T23:59:05.883",
"Id": "7475",
"ParentId": "7443",
"Score": "5"
}
},
{
"body": "<p>I think your problem may be <code>SendMessage</code>. It doesn't return until the message gets processed. So may be waiting on something UI related at that point. I'd try commenting out all of the UI stuff and seeing if the speed improves.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T00:25:59.910",
"Id": "7477",
"ParentId": "7443",
"Score": "4"
}
},
{
"body": "<p>Your edit makes your code look like C not C++.</p>\n\n<p>Any style where you have init() doStuff() fin() is a case for where a RAII could be good:</p>\n\n<pre><code> MartinSha ctx(stdandard_stream);\n std::cout << ctx.c_str() << \"\\n\";\n\n // Alternative constructor for internal buffers.\n std::stringstream streambuffer;\n streambuffer.rdbuf()->pubsetbuf(buffer,bufferSize);\n\n MartinSha ctx(streambuffer);\n std::cout << ctx.c_str() << \"\\n\";\n</code></pre>\n\n<p>Your first attempt did everything in one function.<br>\nYou should have split that up. There is UI code/file reading code/sh256 code all intermixed into the same function. A better technique is to separate these out into different things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T18:58:47.613",
"Id": "7496",
"ParentId": "7443",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7446",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T13:56:59.540",
"Id": "7443",
"Score": "11",
"Tags": [
"c++",
"performance",
"reinventing-the-wheel",
"cryptography"
],
"Title": "My own SHA-256 code implementation"
}
|
7443
|
<p>A method that I'm working on in a C# project includes the following:</p>
<pre><code>if (isDailyRateRequired)
{
CalculatedDailyRate = dailyRate;
}
if (isWeeklyRateRequired)
{
CalculatedDailyRate = weeklyRate / 7;
}
if (isMonthlyRateRequired)
{
CalculatedDailyRate = monthlyRate / 30;
}
</code></pre>
<p>There has to be a cleaner implementation than this. I could compress it to one line with a set of nested ternary operators, but that would be pretty much unreadable. </p>
<p>Other suggestions? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T11:37:58.987",
"Id": "11732",
"Score": "0",
"body": "Show the code please where the boolean variables is set I mean isDailyRateRequired etc. Show more code or explain what you want to do at all. I think it is need to redesign not only this method with if statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:23:33.343",
"Id": "99255",
"Score": "0",
"body": "*I could compress it to one line with a set of nested ternary operators, but that would be pretty much unreadable.* - Not necessarily. Please see my answer for a [similar question](http://codereview.stackexchange.com/questions/6544/ternary-operation-java-isnt-this-abuse/6562#6562)."
}
] |
[
{
"body": "<p>Since those seem to be mutually exclusive conditions, you may not want to execute all 3 <code>if</code>s every time by putting an <code>else</code> in between:</p>\n\n<pre><code>if (isDailyRateRequired) \n{\n CalculatedDailyRate = dailyRate;\n}\nelse if (isWeeklyRateRequired) \n{\n CalculatedDailyRate = weeklyRate / 7;\n}\nelse if (isMonthlyRateRequired) \n{\n CalculatedDailyRate = monthlyRate / 30;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:34:55.570",
"Id": "7451",
"ParentId": "7447",
"Score": "8"
}
},
{
"body": "<p>By looking at your code it appears to me that your basic problem is that <code>isDailyRateRequired</code>, <code>isWeeklyRateRequired</code> and <code>isMonthlyRateRequired</code> are distinct boolean variables instead of an <code>enum</code>. If you just turned them all into an enum things would be a lot more simple, there would be no possibility of inconsistencies between their values, and you would not even have this multiple-choice issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:45:01.530",
"Id": "11697",
"Score": "0",
"body": "Good thought. However, these values are coming out of a `DataSet` and are stored as three columns in a database. Did I mention I'm working on a legacy app? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:26:44.853",
"Id": "11699",
"Score": "1",
"body": "@JoshEarl - yikes! Perhaps you could [add a calculated column to your DataTable](http://msdn.microsoft.com/en-us/library/ms810291.aspx). You could use [the IFF function in the expression](http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.71).aspx) in order to convert those 3 boolean values into a single Enum value, or you could define the expression to derive the correct rate directly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:37:13.480",
"Id": "7453",
"ParentId": "7447",
"Score": "12"
}
},
{
"body": "<p>How about adding a <a href=\"http://msdn.microsoft.com/en-us/library/ms810291.aspx\" rel=\"nofollow\">calculated column to your DataTable</a>?</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression%28v=vs.71%29.aspx\" rel=\"nofollow\">expression</a> is not exactly simpler, but doing it this way might provide it's own advantages:</p>\n\n<pre><code>new System.Data.DataColumn(\"CalculatedDailyRate\", typeof(decimal), \"IIF(isDailyRateRequired, dailyRate, IIF(isWeeklyRateRequired, weeklyRate / 7, IIF(isMonthlyRateRequired, monthlyRate / 30, null)))\")\n</code></pre>\n\n<p>Multi-line version that might be easier to read:</p>\n\n<pre><code> new System.Data.DataColumn(\"CalculatedDailyRate\", typeof(decimal), @\"\n IIF(isDailyRateRequired, dailyRate,\n IIF(isWeeklyRateRequired, weeklyRate / 7,\n IIF(isMonthlyRateRequired, monthlyRate / 30,\n null)))\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:17:21.810",
"Id": "11701",
"Score": "1",
"body": "This hides the messiness inside the thing that's causing the messiness. :) Kinda liking this option. The only downside is that it seems like it might be hard to find later. We have a ~1 million line codebase, so discoverability is a consideration."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:41:29.307",
"Id": "7458",
"ParentId": "7447",
"Score": "3"
}
},
{
"body": "<p>If these conditions are exclusive conditions you should not use booleans. \nUse an enumeration with three named constants (or states): <code>DailyRate</code>, <code>WeeklyRate</code> and <code>MonthlyRate</code>.\n It prevents invalid states where more than one (or zero) boolean are <code>true</code>. (As @MikeNakis already suggested.)</p>\n\n<p>If these three <code>if</code> statements repeating in the code replace the conditional with polymorphism. (See <em>Replacing the Conditional Logic on Price Code with Polymorphism</em> in <em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>).</p>\n\n<p>Since these booleans comes from a legacy database maybe you want to throw an exception or at least log an error message when more than one (or zero) flags are <code>true</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T21:50:20.873",
"Id": "7470",
"ParentId": "7447",
"Score": "6"
}
},
{
"body": "<p>You could create a class <code>Interval</code> with subclasses <code>DailyInterval</code>, <code>WeeklyInterval</code>, and <code>MonthlyInterval</code> and then do:</p>\n\n<pre><code>interval = isDailyRateRequired? new DailyInterval(dailyRate):\n isWeeklyRateRequired? new WeeklyInterval(weeklyRate):\n isMonthlyRateRequired? new MonthlyInterval(monthlyRate):\n /* throw exception */;\n\ncalculatedDailyRate = interval.DailyRate();\n</code></pre>\n\n<p>...where the method <code>DailyRate()</code> automatically returns the appropriate rate based on the internally-known interval duration.</p>\n\n<p>Of course, this only makes sense if you'll be using intervals in lots of places.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T23:40:13.350",
"Id": "7473",
"ParentId": "7447",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:02:47.417",
"Id": "7447",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Cleaning up a three-factor if statement"
}
|
7447
|
<p>I have written a class and spec for testing my class. Can anyone determine whether or not this is a correct and good spec?</p>
<p><strong>Class:</strong></p>
<pre><code>module Sitemap
=begin
Class Name: Cities
Function: This class is responsible for getting the data to create the sitemap
for each country according to cities.
=end
class City
attr_accessor :country_version, :directory, :country_host, :locale
def initialize(country_version, directory, country_host,locale)
@country_version = country_version
@directory = directory
@country_host = country_host
@locale = locale
end
def get_data
::City.find_each(:conditions => {:country_version_id => @country_version.id}) do |city|
I18n.locale=(@locale)
yield entry(city)
end
end
private
def entry(city)
{
:loc => ActionController::Integration::Session.new.url_for(:controller => 'cities', :action => 'show', :city_name => city.name, :host => @country_host.value),
:changefreq => 0.8,
:priority => 'monthly',
:lastmod => city.updated_at
}
end
end
end
</code></pre>
<p><strong>Spec:</strong></p>
<pre><code>require File.join(File.dirname(__FILE__), "/../spec_helper" )
module Sitemap
describe City do
before :all do
@city = City.new :country_version, :directory, :country_host, :locale
end
describe "#new" do
it "takes four parameters and returns a City object" do
@city.should be_an_instance_of City
end
end
describe "#country_version" do
it "returns the correct country version" do
@city.country_version.should eql :country_version
end
end
describe "#directory" do
it "returns the correct filepath" do
@city.directory.should eql :directory
end
end
describe "#country_host" do
it "returns the correct country host" do
@city.country_host.should eql :country_host
end
end
describe "#locale" do
it "returns the correct locale for translation" do
@city.locale.should eql :locale
end
end
describe "#get_data" do
it "returns collections for xml entries" do
@city.get_data.should eql ::City
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Here are a few things I thought of:</p>\n\n<ol>\n<li><p>Use let when you can, it is a pretty versatile function for testing.</p>\n\n<pre><code>before :all\n @city = City.new :country_version, :directory, :country_host, :locale\nend\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<pre><code>let(:city) { @city = City.new :country_version, :directory, :country_host, :locale }\n</code></pre>\n\n<p>This will only call city when you use it.</p></li>\n<li><p>I don't typically test accessors/intatiation but if I did, I would probably test it with a specify block, it is also good for most tests where the description is \"it should do something correctly\":</p>\n\n<p>This is nice for simple tests that explain themselves</p>\n\n<p>specify { city.should be_an_instance_of City }</p></li>\n<li><p>When testing, I try to think in terms of cases:\nEx:</p>\n\n<pre><code>it \"should act in manner x when no cities are found\"\nit \"should act in manner y when 1 city is found\"\nit \"should act in manner z when n cities are found\"\n</code></pre>\n\n<p>I find testing 0, 1, n catches a lot of potential errors</p></li>\n<li><p>The testing gods expect you to test first, then write code. If you don't :D, then make sure that your test fails in the way you expect it to.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T14:01:58.540",
"Id": "14187",
"Score": "1",
"body": "Small correction: `let(:city) { City.new :country_version, :directory, :country_host, :locale }` without `@city =`. And then use `city` instead of `@city` in your code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T15:18:19.920",
"Id": "8655",
"ParentId": "7452",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T16:36:58.313",
"Id": "7452",
"Score": "3",
"Tags": [
"ruby",
"unit-testing",
"rspec"
],
"Title": "City class and spec for testing it"
}
|
7452
|
<p>I am new to Android programming and I'm working on an Activity in an app that will plot the location of contacts from a specific email account on to a map. The following is what I in a class that the Activity will use to get the Contact info I want to use when plotting the location. I have tested this and it works. But as I researched the possible ways to pull this off (and how to program with Android in general). I have found that best practice is to optimize your code. I have two questions I want to ask.</p>
<p>First, is there a more optimized way of getting the name, full address, and geopoints of a contact from a specific email account (like an exchange email)? </p>
<p><strong>my class file:</strong></p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.provider.ContactsContract;
import android.content.ContentResolver;
import android.content.Context;
public class Contacts {
ArrayList<String> nameList = new ArrayList<String>();
ArrayList<String> locList = new ArrayList<String>();
ArrayList<GeoPoint> geoList = new ArrayList<GeoPoint>();
Context context = null;
Geocoder gc;
private String getContactName(String id){
String name = null;
ContentResolver nmCr = context.getContentResolver();
String selection = ContactsContract.Contacts._ID + " = ?";
String[] selectionArgs = new String[]{id};
String[] projection = new String[]{
ContactsContract.Contacts.DISPLAY_NAME
};
Cursor nmCur = nmCr.query(ContactsContract.Contacts.CONTENT_URI,
projection, selection, selectionArgs, null);
if (nmCur.getCount() > 0)
{
while (nmCur.moveToNext())
{
//if the account is under com.android.exchange and not com.google
// Pick out the ID, and the Display name of the
// contact from the current row of the cursor
name = nmCur.getString(nmCur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
}
}
nmCur.close();
return name;
}
public String getContactLocations(String id){
String addr = null;
ContentResolver addrCr = context.getContentResolver();
String selection = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?";
String[] selectionArgs = new String[]{id};
String[] projection = new String[]{
ContactsContract.CommonDataKinds.StructuredPostal.STREET,
ContactsContract.CommonDataKinds.StructuredPostal.CITY,
ContactsContract.CommonDataKinds.StructuredPostal.REGION,
ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE
};
Cursor addrCur = addrCr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
projection, selection, selectionArgs, null);
if (addrCur.getCount() > 0)
{
while(addrCur.moveToNext()) {
addr = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
addr += " " + addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
addr += " " + addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
addr += " " + addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
}
}
addrCur.close();
return addr;
}
public GeoPoint getContactGeo(String addr){
GeoPoint p = null;
gc = new Geocoder(context); //create new geocoder instance
try {
List<Address> foundAdresses = gc.getFromLocationName(addr, 5); //Search addresses
for (int i = 0; i < foundAdresses.size(); ++i) {
//Save results as Longitude and Latitude
Address x = foundAdresses.get(i);
p = new GeoPoint((int)(x.getLatitude() * 1E6),(int)(x.getLongitude() * 1E6));
}
}
catch (Exception e) {
e.printStackTrace();
}
return p;
}
public void getContactNames( Context context, String email){
this.context = context;
ContentResolver cr = context.getContentResolver();
String[] projection = new String[]{
ContactsContract.RawContacts.CONTACT_ID
};
String selection = ContactsContract.RawContacts.ACCOUNT_NAME + " = ? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?";
String[] selectionArgs = new String[]{
email,
"com.android.exchange"
};
Cursor cur = cr.query(ContactsContract.RawContacts.CONTENT_URI,
projection, selection, selectionArgs, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));
nameList.add(
getContactName(id)
);
String addr = getContactLocations(id);
locList.add(addr);
geoList.add(getContactGeo(addr));
}
}
cur.close();
}
}
</code></pre>
<p>Second, right now, to use the data coming back from this file, I am calling this class's <code>ArrayList</code>s after executing <code>c.getContactNames(this, email);</code> in my Activity.</p>
<p><strong>Looks like this:</strong></p>
<pre><code>c.getContactNames(this, sale.smtpEmail);
MapArray = MapView.getOverlays();
for (int i = 0; i < c.nameList.size(); i++) {
OverlayItem overlayitem = null;
drawable = new BitmapDrawable(mar.marker(i, this));
itemizedOverlay = new MapsItemizedOverlay(drawable, this);
if(c.locList.get(i) != null){
overlayitem = new OverlayItem(c.geoList.get(i), c.nameList.get(i), c.locList.get(i));
itemizedOverlay.addOverlay(overlayitem);
MapArray.add(itemizedOverlay);
}
}
</code></pre>
<p>Which I am doing so I <a href="http://developer.android.com/guide/practices/design/performance.html#object_creation" rel="nofollow">create unnecessary objects</a>. Is this best practice? </p>
|
[] |
[
{
"body": "<p>Just some generic Java notes since I'm not too familiar with Android.</p>\n\n<ol>\n<li><p>The reference type of your list should be only <code>List</code>. Instead of:</p>\n\n<pre><code>ArrayList<String> nameList = new ArrayList<String>();\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>List<String> nameList = new ArrayList<String>();\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java\">Type List vs type ArrayList in Java</a></p></li>\n<li><p>Setting <code>context</code> to <code>null</code> looks unnecessary, since <code>null</code> is the default value.</p>\n\n<pre><code>Context context = null;\n</code></pre></li>\n<li><p>You should close the <code>Cursor</code> in a <code>finally</code> block:</p>\n\n<pre><code>Cursor nmCur = nmCr.query(...);\ntry {\n ...\n} finally {\n nmCur.close();\n}\n</code></pre>\n\n<p>It will help to avoid resource leaks. (When the code throws an exception <code>close</code> won't be called.)</p></li>\n<li><p>I'd use guard clauses to check the return value of the query. It makes the code flatten and easier to read.</p>\n\n<pre><code>if (nmCur.getCount() <= 0) {\n return null;\n}\n</code></pre>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Flattening Arrow Code</a></p></li>\n<li><p>If I'm right, you use just the last result of the query in the <code>getContactName</code> method. It looks unnecessary to read all results in the <code>while</code> loop:</p>\n\n<pre><code>while (nmCur.moveToNext()) {\n name = nmCur.getString(nmCur.getColumnIndex(\n ContactsContract.Contacts.DISPLAY_NAME));\n}\n</code></pre>\n\n<p>Anyway, you could move the <code>getColumnIndex</code> calls out of the loop which should be faster:</p>\n\n<pre><code>final int displayNameIndex = nmCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)\nwhile (nmCur.moveToNext()) {\n name = nmCur.getString(displayNameIndex);\n}\n</code></pre>\n\n<p>(The latter is true for the <code>getContactLocations</code> method too.)</p></li>\n<li><p>In the <code>getContactLocations</code> method <code>addr</code> should be a <code>StringBuilder</code> instead of <code>String</code>. You concatenate Strings in a loop.</p>\n\n<p>(I don't know, maybe the compiler change/optimize it for you.)</p></li>\n<li><p>This:</p>\n\n<pre><code>Geocoder gc;\n</code></pre>\n\n<p>should be a local variable in the <code>getContactGeo</code> method, since other methods don't use this reference.</p></li>\n<li><p>Instead of magic number <code>5</code> use a named constants or variable:</p>\n\n<pre><code>final int maxResults = 5;\nList<Address> foundAdresses = gc.getFromLocationName(addr, maxResults);\n</code></pre>\n\n<p>It helps readers a lot to figure out what the code should do without checking the javadoc.</p></li>\n<li><p>If there is an error you should handle it, or maybe show an error message to the user instead of the <code>printStackTrace</code>:</p>\n\n<pre><code>} catch (Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3855187/843804\">It isn't the best idea to use <code>printStackTrace()</code> in Android exceptions</a></li>\n<li><a href=\"https://stackoverflow.com/q/10477607/843804\">Avoid printStackTrace(); use a logger call instead</a></li>\n<li><a href=\"https://stackoverflow.com/q/7469316/843804\">Why is exception.printStackTrace() considered bad practice?</a></li>\n</ul></li>\n<li><p>Maybe you should create a constructor with a <code>Context</code> parameter since other methods are unusable without a reference to a <code>Context</code> instance.</p>\n\n<pre><code>private final Context context;\n\npublic Contacts(final Context context) {\n if (context == null) {\n throw new NullPointerException(\"context cannot be null\");\n }\n this.context = context;\n}\n</code></pre>\n\n<p>Anyway, the methods currently temporally coupled (need to be called in a specific order) which could be confusing to the clients and lead to <code>NullPointerException</code>s.</p></li>\n<li><p>Fields should be <code>private</code>:</p>\n\n<pre><code>private List<String> nameList = new ArrayList<String>();\nprivate List<String> locList = new ArrayList<String>();\nprivate List<GeoPoint> geoList = new ArrayList<GeoPoint>();\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/5484845/should-i-always-use-the-private-access-modifier-for-class-fields\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.</p></li>\n<li><p>This line doesn't <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smell</a> good:</p>\n\n<pre><code>overlayitem = new OverlayItem(c.geoList.get(i),c.nameList.get(i) ,c.locList.get(i));\n</code></pre>\n\n<p>Maybe the <code>getContactNames</code> should create the list of <code>OverlayItem</code> objects instead of the three lists whose are accessed with the same index.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:01:03.793",
"Id": "11735",
"Score": "0",
"body": "Thank you for your feedback. However if I set my lists to private ( in no. 11), how do I access the data in them from my Activity class? They are in to different java files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:22:04.890",
"Id": "11737",
"Score": "1",
"body": "Just create a getter method. (Also check *Item 39: Make defensive copies when needed* in *Effective Java Second Edition*.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:32:00.680",
"Id": "11738",
"Score": "0",
"body": "Will do. Again thank you for your input it is much appreciated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T13:39:28.457",
"Id": "7487",
"ParentId": "7465",
"Score": "6"
}
},
{
"body": "<p>One other suggestion is that you combine the separate queries of the contact database into a single query to get the name and location. I believe that this would improve performance as there is overhead involved in calling out to the content provider so many times. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-08T18:21:21.460",
"Id": "9825",
"ParentId": "7465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7487",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T20:03:29.350",
"Id": "7465",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Extracting Android contact Info"
}
|
7465
|
<p>I have a navigation, with a sprite that changes based on the class. In my jQuery, I'm clearing out the classes so it will just have <code>.nav</code> and then <code>addClass</code> the right class based on the click. It works but feels very redundant. Does anyone have suggestions on optimizing this?</p>
<p>HTML: </p>
<pre><code><div class="grid_12 nav home">
<ul class="tabs">
<li class="home"><a href="javascript:;">HOME</a></li>
<li class="game-stats"><a href="javascript:;">GAME STATS</a></li>
<li class="game-talk"><a href="javascript:;">GAME TALK</a></li>
<li class="game-info"><a href="javascript:;">GAME INFO</a></li>
</ul>
</div>
</code></pre>
<p>JS:</p>
<pre><code>$('DIV.content DIV.nav ul li.home').click(function(){
$('DIV.content DIV.nav').attr('class', 'nav');
$('DIV.content DIV.nav').addClass('home');
});
$('DIV.content DIV.nav ul li.game-stats').click(function(){
$('DIV.content DIV.nav').attr('class', 'nav');
$('DIV.content DIV.nav').addClass('gamestats');
});
$('DIV.content DIV.nav ul li.game-talk').click(function(){
$('DIV.content DIV.nav').attr('class', 'nav');
$('DIV.content DIV.nav').addClass('gametalk');
});
$('DIV.content DIV.nav ul li.game-info').click(function(){
$('DIV.content DIV.nav').attr('class', 'nav');
$('DIV.content DIV.nav').addClass('gameinfo');
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:16:17.727",
"Id": "11700",
"Score": "0",
"body": "is the `grid_12` class supposed to go away when you click a link?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:43:38.730",
"Id": "11706",
"Score": "0",
"body": "what happens to the `grid_12` class when you click on something?"
}
] |
[
{
"body": "<p>How about this? (Untested!)</p>\n\n<pre><code>$('DIV.content DIV.nav ul li').click(function(){\n $(this).closest('DIV.nav').attr('class', 'nav').addClass($(this).attr('class'));\n});\n</code></pre>\n\n<p>The idea is that when an li element is clicked, you take whatever classes are on that li element and apply those classes to the nav element.</p>\n\n<p>The other aspect of this is that I replaced your duplicate references to <code>$('DIV.content DIV.nav')</code> with <code>$(this).closest('DIV.nav')</code>. I prefer this approach because it might be faster (jQuery doesn't have to search through the DOM again), and it also avoids issues in case you have multiple DIV.content and DIV.nav elements on the page.</p>\n\n<hr>\n\n<p>EDIT: In order to address the issue that the CSS classes that you are applying to the DIV.nav element are slightly different than the CSS classes that are applied to the li elements, you could define the HTML as below:</p>\n\n<pre><code><div class=\"grid_12 nav home\">\n <ul class=\"tabs\">\n <li class=\"home\"><a href=\"javascript:;\">HOME</a></li>\n <li class=\"game-stats gamestats\"><a href=\"javascript:;\">GAME STATS</a></li>\n <li class=\"game-talk gametalk\"><a href=\"javascript:;\">GAME TALK</a></li>\n <li class=\"game-info gameinfo\"><a href=\"javascript:;\">GAME INFO</a></li>\n </ul>\n </div>\n</code></pre>\n\n<p>It's a bit of a hack, but not too bad in my opinion.</p>\n\n<hr>\n\n<p>EDIT: Below is an updated javascript function. This one attempts to preserve any of the existing classes on the DIV.nav element, such as grid_12.</p>\n\n<pre><code>$('DIV.content DIV.nav ul li').click(function(){\n\n var navDiv = $(this).closest('DIV.nav');\n\n // first, remove any classes from the li elements that are currently applied to the DIV.nav element\n navDiv.find('ul li').each(function() {\n navDiv.removeClass($(this).attr('class'));\n });\n\n // next, apply the classes from the clicked li element to the DIV.nav element\n navDiv.addClass($(this).attr('class'));\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:18:06.553",
"Id": "11702",
"Score": "0",
"body": "I like this approach, its more along the lines of the way I would have done it, my only reservation is that `$(this).attr('class') == 'game-info'` but the handlers add the class of `gameinfo` (no hyphen). a simple `.replace('-','')` would resolve it be it feels fragile to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:41:10.503",
"Id": "11703",
"Score": "0",
"body": "@32bitkid - ah, yes. I did notice that your CSS class names for your li elements are different than the classes that you are applying to the nav div. Is there a reason for that? I would try to make them the same for the sake of consistency. If you're making them different because of how you've defined your CSS, then perhaps your CSS definitions could be tweaked to make it work. Also, see my updated answer for a simple way to address this issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T20:00:07.603",
"Id": "11705",
"Score": "0",
"body": "@32bitkid - woops! sorry, I got you confused with the OP."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T19:04:50.160",
"Id": "7460",
"ParentId": "7466",
"Score": "1"
}
},
{
"body": "<p>You can add both classes at once with <code>attr</code>, since all you need to do is pass a string with the classes you want separated by spaces:</p>\n\n<pre><code>$('DIV.content DIV.nav ul li.home').click(function(){\n $('DIV.content DIV.nav').attr('class', 'nav home');\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:40:22.480",
"Id": "7467",
"ParentId": "7466",
"Score": "2"
}
},
{
"body": "<p>When an li is clicked, it sets the closest <code>.nav</code> classes to \"nav\" and the class on the clicked li:</p>\n\n<pre><code>$('.content .nav li').on('click', function(){\n $(this).closest('.nav').attr('class', 'nav ' + $(this).attr('class'));\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:43:27.847",
"Id": "11707",
"Score": "0",
"body": "That's not quite right.. the class he is replacing for 'game-info' is 'gameinfo'. So the current class and the class he is replacing is not the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:45:45.517",
"Id": "11708",
"Score": "0",
"body": "Yes I know but those classes could be easily changed to match for the sake of not having redundant code. `div.gameinfo` can be unique from `li.gameinfo`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:46:56.330",
"Id": "11709",
"Score": "0",
"body": "Or simply just remove the dash `.replace('-', '')`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:47:40.200",
"Id": "11710",
"Score": "0",
"body": "I changed the classes, this was just what I wanted. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:42:08.127",
"Id": "7468",
"ParentId": "7466",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7468",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T18:34:27.240",
"Id": "7466",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Changing a sprite based on the class"
}
|
7466
|
<p><strong>Preview:</strong> <a href="http://sparksonrails.pennfolio.com/" rel="nofollow">http://sparksonrails.pennfolio.com/</a></p>
<p><strong>Jquery:</strong></p>
<pre><code>function introIconFirst()
{
$('h2.ribbon').css(
{
'marginTop': '+30px',
'opacity': '0'
}).animate(
{
marginTop: '0',
opacity: '1'
}, 1500, 'easeOutElastic', introIconSecond());
}
function introIconSecond()
{
$('#ico_website').rotate('0deg').css(
{
'top': '+900px',
'opacity': '0'
}).animate(
{
top: '50px',
opacity: '1'
}, {
queue: false,
duration: 1100,
easing: 'easeOutElastic'
}).animate(
{
rotate: '-30deg'
}, 1000, 'easeOutElastic', introIconThird());
}
function introIconThird()
{
$('#ico_rails').css(
{
'top': '+900px',
'opacity': '0'
}).delay(300).animate(
{
top: '145px',
opacity: '1'
}, 1400, 'easeOutElastic', introIconFourth());
}
function introIconFourth()
{
$('#ico_plane').css(
{
'left': '255px',
'top': '90px',
'opacity': '0'
}).delay(800).animate(
{
top: '18px',
left: '299px',
opacity: '1'
}, 600, 'linear');
}
// Rotate/Animate Stuff - Page2 Options
function rotPlane()
{
$('li#blk-specialize span.elem2').animate(
{
rotate: '-=30deg'
}, 300, 'linear');
}
function rotGear1()
{
$('li#blk-happen span.elem1').animate(
{
rotate: '+=30deg'
}, 700, 'linear');
}
function rotGear2()
{
$('li#blk-happen span.elem2').animate(
{
rotate: '-=30deg'
}, 400, 'linear');
}
//Globe plane
setInterval( rotPlane, 1 );
//Gear 1 - Large
setInterval( rotGear1, 1 );
//Gear 2 - Small
setInterval( rotGear2, 1 );
$(function() {
introIconFirst();
$(".options li").hover(
function () {
$(this).append('<span class="elem1"></span><span class="elem2"></span>');
},
function () {
$(".options li span").detach();
}
);
// Cache the Window object
$window = $(window);
// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function()
{
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
}); // For each element that has a data-type attribute
$('section[data-type="background"]').each(function()
{ // Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top; // When the window is scrolled...
$(window).scroll(function()
{ // If this section is in view
if (($window.scrollTop() + $window.height()) > (topOffset) && ((topOffset + $self.height()) > $window.scrollTop()))
{ // Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed')); // If this element has a Y offset then add it on
if ($self.data('offsetY'))
{
yPos += $self.data('offsetY');
} // Put together our final background position
var coords = '50% ' + yPos + 'px'; // Move the background
$self.css(
{
backgroundPosition: coords
}); // Check for other sprites in this section
$('[data-type="sprite"]', $self).each(function()
{ // Cache the sprite
var $sprite = $(this); // Use the same calculation to work out how far to scroll the sprite
var yPos = -($window.scrollTop() / $sprite.data('speed'));
var coords = $sprite.data('Xposition') + ' ' + (yPos + $sprite.data('offsetY')) + 'px';
$sprite.css(
{
backgroundPosition: coords
});
}); // sprites
// Check for any Videos that need scrolling
$('[data-type="video"]', $self).each(function()
{ // Cache the video
var $video = $(this); // There's some repetition going on here, so
// feel free to tidy this section up.
var yPos = -($window.scrollTop() / $video.data('speed'));
var coords = (yPos + $video.data('offsetY')) + 'px';
$video.css(
{
top: coords
});
}); // video
} // in view
}); // window scroll
}); // each data-type
}); // document ready
</code></pre>
<p><strong>Concerns:</strong></p>
<ol>
<li><p>jQuery might be to bloated for what I intended to do. Can this still be simplified and optimized? </p></li>
<li><p>Improper use of HTML tags</p></li>
<li><p>Code (animation) are running without the other elements fully loaded yet.</p></li>
</ol>
<p>This is still being develop, I'd appreciate to hear your thoughts.</p>
|
[] |
[
{
"body": "<p>First off, if you're trying to do these animations sequentially, the code isn't written to do that. You need to pass a function reference, not the result of a function call so this:</p>\n\n<pre><code>function introIconFirst()\n{\n $('h2.ribbon').css(\n {\n 'marginTop': '+30px',\n 'opacity': '0'\n }).animate(\n {\n marginTop: '0',\n opacity: '1'\n }, 1500, 'easeOutElastic', introIconSecond());\n}\n</code></pre>\n\n<p>should be this:</p>\n\n<pre><code>function introIconFirst()\n{\n $('h2.ribbon').css(\n {\n 'marginTop': '+30px',\n 'opacity': '0'\n }).animate(\n {\n marginTop: '0',\n opacity: '1'\n }, 1500, 'easeOutElastic', introIconSecond); // <== change made to pass only function reference here\n}\n</code></pre>\n\n<p>and likewise, fix the other ones that have the same issue.</p>\n\n<p>Other issues I see:</p>\n\n<ol>\n<li>You're doing a 200ms interval on a 400ms animation or a 200ms interval on a 700ms animation. That sounds like you're asking for trouble and won't visually get what you want with two/three animations competing at the same time.</li>\n<li>You probably don't want to be recalculating the selectors every time your setInterval gets called as that's a lot of wasted CPU multiple times per second. Calculate them once before you start the setInterval and use that result.</li>\n<li><code>.detach()</code> should be changed to <code>.remove()</code> in this code as <code>.detach()</code> should only be used if you're saving a reference to the removed items and reusing them later. Otherwise, <code>.remove()</code> does a better job cleaning up jQuery stuff and I assume you probably want to only clean up the item you are no longer hovering over:</li>\n</ol>\n\n<p>Change to <code>.remove()</code> here:</p>\n\n<pre><code>$(\".options li\").hover(\n function () {\n $(this).append('<span class=\"elem1\"></span><span class=\"elem2\"></span>');\n },\n function () {\n $(this).find(\"span\").remove();\n }\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T05:06:14.400",
"Id": "11724",
"Score": "0",
"body": "Thanks for your review. \n\nHonestly, I'm still confused how to use setInterval properly. Im confused because I animated it by interval and I also animate it using animate(). \n\nI tried making the interval the same as the animation's (animation()) milliseconds and it caused delayed every time I hover.\n\nThank You!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T05:09:40.380",
"Id": "11725",
"Score": "0",
"body": "@Pennf0lio - If you want it to start right away, you call the animation directly the first time and then you call it the subsequent times with `setInterval()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T22:41:22.743",
"Id": "7472",
"ParentId": "7471",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7472",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-04T22:01:10.760",
"Id": "7471",
"Score": "2",
"Tags": [
"jquery",
"optimization",
"css",
"html5"
],
"Title": "Can my code be optimized more?"
}
|
7471
|
<p>Basically I'm trying to generalise and extend the notion of mapping one string into another.
There are two methods I often find myself using for this: Functions, and Dictionairies.</p>
<p>So here are my 3 classes. (I intend to create some explict classes as well, like ToCamelCase - as my current project requires)</p>
<pre><code>public abstract class StringMapping
{
public string this[string from]
{
get
{
return this.Get(from);
}
}
public abstract string Get(string from);
public static implicit operator Func<string, string>(StringMapping mapping)
{
return mapping.Get;
}
public ComposableStringMapping AndThen (StringMapping second)
{
return new ComposableStringMapping(this, second);
}
//An alias for AndThen
public static ComposableStringMapping operator + (StringMapping first, StringMapping next)
{
return first.AndThen(next);
}
}
public class ComposableStringMapping : StringMapping
{
private StringMapping _first;
private StringMapping _andThen;
public ComposableStringMapping(StringMapping first, StringMapping andThen)
{
_first = first;
_andThen = andThen;
}
public override string Get(string from)
{
var res = _first[from];
return _andThen[res];
}
}
public class FuncStringMapping : StringMapping
{
private Func<string, string> _underlyingMapping;
public FuncStringMapping(Func<string, string> underlyingMapping)
{
_underlyingMapping = underlyingMapping;
}
public FuncStringMapping(StringMapping underlyingMapping)
{
_underlyingMapping = underlyingMapping.Get;
}
public static implicit operator FuncStringMapping(Func<string, string> underlyingMapping)
{
return new FuncStringMapping(underlyingMapping);
}
public override string Get(string from)
{
return _underlyingMapping(from);
}
}
public class ExplictStringMapping : StringMapping, IEnumerable<KeyValuePair<string, string>>
{
IDictionary<string, string> _mappings = new Dictionary<string, string>();
public void Add(string from,string to)
{
_mappings.Add(from,to);
}
public override string Get(string from)
{
return _mappings.ContainsKey(from) ? _mappings[from] : from;
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _mappings.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _mappings.GetEnumerator();
}
}
</code></pre>
<p>and here is the nUnit tests / examples of use.</p>
<pre><code>[TestFixture]
public class FuncStringMappingTests
{
[Test]
public void ShouldRemoveAllSpaces()
{
FuncStringMapping mapping = new FuncStringMapping((string str) => str.Replace(" ", ""));
Assert.AreEqual(expected: "HelloWorld", actual: mapping["Hello World"]);
}
[Test]
public void ShouldWorkWithSelect()
{
const string dest = "crush";
FuncStringMapping mapping = (FuncStringMapping)(str => dest);
var src = new List<string> { "alpha", "gamma", "beta" };
CollectionAssert.AreEqual(
expected: Enumerable.Repeat(dest, src.Count()),
actual: src.Select<string,string>(mapping)
);
}
}
[TestFixture]
public class ExplictStringMappingTests
{
[Test]
public void ShouldMapThingsGivenInIntitilser()
{
ExplictStringMapping mapping = new ExplictStringMapping()
{
{"1", "one"},
{"2", "two"},
{"3", "three"},
};
Assert.AreEqual(expected: "two", actual: mapping["2"]);
}
[Test]
public void ShouldMapThingsNotGivenInIntitilserToSelf()
{
ExplictStringMapping mapping = new ExplictStringMapping()
{
{"1", "one"},
{"2", "two"},
{"3", "three"},
};
const string unchanged = "alpha";
Assert.AreEqual(expected: unchanged, actual: mapping[unchanged]);
}
[Test]
public void ShouldWorkWithSelect()
{
ExplictStringMapping mapping = new ExplictStringMapping()
{
{"1", "one"},
{"2", "two"},
{"3", "three"},
};
const string unchanged = "alpha";
var src = new List<string> { "1", "2", "3",unchanged };
CollectionAssert.AreEqual(
expected: new string []{"one","two","three",unchanged},
actual: src.Select<string,string>(mapping)
);
}
}
[TestFixture]
public class ComposableStringMappingTests
{
[Test]
public void ShouldComposeMappings()
{
StringMapping mapping = ((FuncStringMapping)(from => "hello " + from)).AndThen( ((FuncStringMapping)(from => from.ToUpper())));
Assert.AreEqual(expected: "HELLO JIM", actual: mapping["jim"]);
}
}
</code></pre>
<p>Basically I would like for the user not to have to think about whether they are using a function <code>string foo (string param)</code> or a StringMapping object. I would like them to be interchangable.</p>
<p>I'm pretty certain there must be a better way, as (can be seen in examples) I keep having to use explicit type cases between the two (incuding giving full type arguments to the LINQ select method).</p>
<p>EDIT:
Another problem is my lack ofa nice inline operator to do the AndThen / compose methood.
Like |> would have been ideal, or >> would work ok.
The problem with using + is that this is not commititive (then again nor is string concatination. But string concat is obviosly not commutive where as this is a bit more subtle)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:47:44.863",
"Id": "11739",
"Score": "0",
"body": "Hmm, try adding an implicit operator to convert `Expression<Func<string, string>>` to `FuncStringMapping`. I think that your issue might be that the compiler does not consider the code `(from => \"hello\" + from)` to be an actual `Func<string, string>` object; rather, it's a lamba expression that is implicitly convertible to `Func<string, string>`. However, you would still need an explicit cast in order to make your first `.AndThen` call, or you would need to move that call to the next statement after assigning the lambda expression to the mapping variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:10:12.973",
"Id": "11741",
"Score": "0",
"body": "No, I gave my suggestion a try, and that doesn't seem to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-01T02:38:16.077",
"Id": "226288",
"Score": "0",
"body": "Wow, this was a terrible idea,. Why did I want to do this?"
}
] |
[
{
"body": "<p>This is a fairly hackish idea. You can decide whether you want to pollute your codebase with this. This idea is similar to jQuery, which heavily overloads the $ character to provide a multitude of functionality.</p>\n\n<p>First, define a utility class named \"s\":</p>\n\n<pre><code>public static class s\n{\n public static FuncStringMapping Map(Func<string, string> mapping)\n {\n return new FuncStringMapping(mapping);\n }\n}\n</code></pre>\n\n<p>Below I've rewritten one of your examples to take advantage of this:</p>\n\n<pre><code> StringMapping mapping = s.Map(from => \"hello \" + from).AndThen(s.Map(from => from.ToUpper()));\n</code></pre>\n\n<p>Secondly, you could add another Map function that takes any number of <code>Func<string, string></code> arguments, as shown below:</p>\n\n<pre><code>public static StringMapping Map(params Func<string, string>[] underlyingMappings)\n{\n if (underlyingMappings == null || underlyingMappings.Length == 0)\n throw new ArgumentNullException(\"underlyingMappings\");\n\n StringMapping mapping = new FuncStringMapping(underlyingMappings[0]);\n\n for (int i = 1; i < underlyingMappings.Length; i++)\n {\n mapping = mapping.AndThen(new FuncStringMapping(underlyingMappings[i]));\n }\n\n return mapping;\n}\n</code></pre>\n\n<p>This allows you to rewrite the above example as follows:</p>\n\n<pre><code>StringMapping mapping = s.Map(from => \"hello \" + from, from => from.ToUpper());\n</code></pre>\n\n<p>I'm not a fan of this approach, because it's hard to read.</p>\n\n<p>Thirdly, you could add extension methods to simplify calls to <code>.AndThen</code> when passing in a <code>Func<string, string></code> delegate:</p>\n\n<pre><code>public static class FuncStringMappingExtensions\n{\n public static StringMapping AndThen(this StringMapping mapping, Func<string, string> andThen)\n {\n return mapping.AndThen(new FuncStringMapping(andThen));\n }\n}\n</code></pre>\n\n<p>Building off of the first suggestion, this allows you to rewrite the example as follows:</p>\n\n<pre><code>StringMapping mapping = s.Map(from => \"hello \" + from).AndThen(from => from.ToUpper());\n</code></pre>\n\n<hr>\n\n<p>Addressing your concerns about the need to specify the generic arguments for the Select method, below is the only approach that I can suggest:</p>\n\n<p>First, add an AsDelegate method to your StringMapping class:</p>\n\n<pre><code> public Func<string, string> AsDelegate()\n {\n return this.Get;\n }\n</code></pre>\n\n<p>Next, add an AsDelegate extension method for <code>Func<string, string></code>. The purpose of this is to hide from the developer whether or not their object is a StringMapping object or a <code>Func<string, string></code> object.</p>\n\n<pre><code>public static class DelegateExtensions\n{\n public static Func<string, string> AsDelegate(this Func<string, string> mapping)\n {\n return mapping;\n }\n}\n</code></pre>\n\n<p>This ensures that the developer will always be able to call <code>.AsDelegate()</code> on their object, regardless of whether the object is a StringMapping or a <code>Func<string, string></code>.</p>\n\n<p>Naturally, this would require you to call the Select method as follows:</p>\n\n<pre><code> src.Select(mapping.AsDelegate());\n</code></pre>\n\n<p>This may not be the ideal solution, but I don't think that you'll have much luck with tricking the compiler into deriving the generic arguments another way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:25:31.693",
"Id": "11743",
"Score": "0",
"body": "that's no better than the typecasts I'm currently doing. (execpt that it's shorter)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:25:45.733",
"Id": "11744",
"Score": "0",
"body": "I think I could also define a extention method:\n`public static AsStringMapping(this Func<string,string> mapping)`\n`{return new FuncStringMapping(mapping)}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:42:13.980",
"Id": "11747",
"Score": "0",
"body": "@Oxinabox - I agree, it's not much better than explicit casts, but it does at least not require the developer to think \"What was the name of that class again? Oh, that's right, it's FuncStringMapping.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:43:38.903",
"Id": "11749",
"Score": "0",
"body": "Hmm I guess I could have (in the StringMapping Class):\n'public static implicit operator StringMapping (Func<string, string>mapping)'\n' { return (FuncStringMapping) mapping; }'\nWhich would also save the need to s.Map converts a Func to a StringMapping"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T22:34:03.590",
"Id": "11769",
"Score": "0",
"body": "I considered the other suggestions also.\nAn extention to andThen only helps with that one method - it's not scalable.\nand an mapping.AsDelegate() is questionably more clear than mapping.Get"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T14:22:32.543",
"Id": "11817",
"Score": "0",
"body": "@Oxinabox - Yes, but you can't write `.Get` if the mapping variable is a `Func<string, string>` object. There is no such \"Get\" method on a delegate object. You wanted to a way to keep the developer unconcerned with whether the mapping variable is a `StringMapping` object or a `Func<string, string>` object. I suppose another idea is that you could create your own `Select` extension method overload that accepts a `StringMapping` object as a parameter. Perhaps not a great solution, but it would allow you to write `.Select(mapping)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T14:57:28.750",
"Id": "11819",
"Score": "0",
"body": "Writing an extention to select has the same problem as writing an extention to AndThen.\nIt is not solving the problem, just \"plugging the leak\" (as i'm sure your realise)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T14:59:00.153",
"Id": "11820",
"Score": "0",
"body": "the developer \"Knows\" that there is no `.AsDelegate()` method on a `Func<string,string>` (This is my big grip with extentsion methods)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T15:02:45.613",
"Id": "11821",
"Score": "0",
"body": "@Oxinabox - I would hope that they do know that. The issue, though, is that you said that you don't want the developer to \"know\" whether the mapping variable is of type `StringMapping` or `Func<string, string>`. If you create the AsDelegate extension method for `Func<string, string>`, then the developer can always call `.AsDelegate()` on the mapping variable, regardless of which type it is. Not a great solution; I don't think I would go that way, but I'm just trying to explain the merit (what little there is) behind the approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T15:12:24.983",
"Id": "11822",
"Score": "0",
"body": "I knew what your were getting at.\nI think the best (and impossible solution) would be to Inherit from Func<string,string>"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:15:19.033",
"Id": "7490",
"ParentId": "7480",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T08:48:29.810",
"Id": "7480",
"Score": "1",
"Tags": [
"c#",
"strings",
"functional-programming",
"operator-overloading"
],
"Title": "Extending string mapping"
}
|
7480
|
<p>I started an open source Markdown editor using C#. I'm a huge fan of the MVC pattern, however I am having trouble refactoring my back-end form code. It's getting pretty long and I was wondering if anyone had tips on which pieces I can move to separate classes.</p>
<p>Here is my main form C# code: </p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Marker.UI
{
public partial class MainWindow : Form
{
private String appName;
private MarkdownConverter converter;
private FileHandler fileHandler;
private String lastSavedFilename, lastSavedFilePath;
private bool markdownTextChanged;
protected Font markdownFont, htmlFont;
#region Constructors
public MainWindow(String filePath)
{
InitializeWindow();
OpenFile(filePath);
}
public MainWindow()
{
InitializeWindow();
}
#endregion
private void InitializeWindow()
{
InitializeComponent();
this.Size = UserSettings.LoadWindowSize();
this.Icon = Properties.Resources.Marker;
appName = Application.ProductName;
markdownFont = Properties.Settings.Default.MarkdownFont;
htmlFont = Properties.Settings.Default.HtmlFont;
converter = new MarkdownConverter();
converter.Font = htmlFont;
fileHandler = new FileHandler();
lastSavedFilename = "";
lastSavedFilePath = "";
markdownTextChanged = false;
}
#region Form Events
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
UserSettings.SaveWindowSize(this.Size);
if (!PromptForUnsavedChanges())
e.Cancel = true;
}
private void markdownTextBox_TextChanged(object sender, EventArgs e)
{
markdownTextChanged = true;
markdownPreview.DocumentText = converter.ToHtml(markdownTextBox.Text);
}
#endregion
#region Menu Events
private void newMenuItem_Click(object sender, EventArgs e)
{
NewMarkdownDocument();
}
private void openMenuItem_Click(object sender, EventArgs e)
{
OpenMarkdownDocument();
}
private void saveMenuItem_Click(object sender, EventArgs e)
{
SaveMarkdownDocument();
}
private void saveAsMenuItem_Click(object sender, EventArgs e)
{
String filePath = SaveMarkdownDialog();
SaveFile(filePath);
markdownTextChanged = false;
}
private void exportToHTMLToolMenuItem_Click(object sender, EventArgs e)
{
String filePath = SaveHtmlDialog();
ExportHtml(filePath);
}
private void exitMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutMenuItem_Click(object sender, EventArgs e)
{
ShowAboutWindow();
}
private void preferencesMenuItem_Click(object sender, EventArgs e)
{
ShowPreferenceWindow();
}
#endregion
#region Dialogs
/// <summary>
/// Shows SaveFileDialog with Markdown filter
/// </summary>
/// <returns>filePath - Path to which user selected </returns>
private String SaveMarkdownDialog()
{
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Markdown (*.md)|*.md";
saveDialog.ShowDialog();
return saveDialog.FileName;
}
/// <summary>
/// Shows SaveFileDialog with HTML filter
/// </summary>
/// <returns>filePath - Path to file which user selected</returns>
private String SaveHtmlDialog()
{
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "HTML (*.html)|*html";
saveDialog.DefaultExt = "html";
saveDialog.FileName = "Untitled.html";
saveDialog.ShowDialog();
return saveDialog.FileName;
}
/// <summary>
/// Shows OpenFileDialog with Markdown filter
/// </summary>
/// <returns>filePath - Path to which user selected</returns>
private String OpenMarkdownDialog()
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Markdown (*.md)|*md";
fileDialog.Title = "Open Markdown file";
fileDialog.RestoreDirectory = true;
fileDialog.ShowDialog();
return fileDialog.FileName;
}
/// <summary>
/// Shows About Box
/// </summary>
private void ShowAboutWindow()
{
using (AboutBox aboutWindow = new AboutBox())
{
aboutWindow.ShowDialog(this);
}
}
private void ShowPreferenceWindow()
{
using (PreferenceWindow preferenceWindow = new PreferenceWindow())
{
preferenceWindow.ShowDialog(this);
markdownFont = preferenceWindow.markdownFont;
htmlFont = preferenceWindow.htmlFont;
}
}
#endregion
/// <summary>
/// Appends last saved filename to Main window's title
/// </summary>
private void RefreshTitle()
{
if (lastSavedFilename.Trim().Length > 0)
this.Text = String.Format("{0} - {1}", lastSavedFilename, appName);
else
this.Text = appName;
}
/// <summary>
/// Setter for the lastSavedFilePath and lastSavedFilename
/// </summary>
private void SetLastSavedFile(String filePath)
{
lastSavedFilePath = filePath;
int startOfFileName = lastSavedFilePath.LastIndexOf("\\") + 1;
int length = lastSavedFilePath.Length - startOfFileName;
lastSavedFilename = lastSavedFilePath.Substring(startOfFileName, length);
}
/// <summary>
/// Opens file from filePath and puts it into markdown TextBox
/// </summary>
/// <param name="filePath">File path to Markdown file</param
private void OpenFile(String filePath)
{
markdownTextBox.Text = fileHandler.OpenFile(filePath);
SetLastSavedFile(filePath);
RefreshTitle();
}
/// <summary>
/// Takes Markdown text and sends it to the fileHandler for saving.
/// </summary>
/// <param name="filePath">File path to save the Markdown file</param>
private void SaveFile(String filePath)
{
if (filePath.Trim() == "") return;
fileHandler.MarkdownText = markdownTextBox.Text;
fileHandler.SaveMarkdown(filePath);
SetLastSavedFile(filePath);
RefreshTitle();
}
/// <summary>
/// Takes the HTML from the preview and sends it to the
/// fileHandler for saving.
/// </summary>
/// <param name="filePath">File path to save the HTML file</param>
private void ExportHtml(String filePath)
{
if (filePath.Trim() == "") return;
fileHandler.HtmlText = markdownPreview.DocumentText;
fileHandler.SaveHtml(filePath);
}
private DialogResult PromptUserToSave()
{
String promptMessage =
String.Format("Do you want to save changes to {0}", lastSavedFilePath);
return MessageBox.Show(
promptMessage, "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
}
private void NewMarkdownDocument()
{
if (PromptForUnsavedChanges())
{
SetLastSavedFile("");
markdownTextChanged = false;
RefreshTitle();
Clear();
}
}
private void SaveMarkdownDocument()
{
String filePath = lastSavedFilePath != "" ? lastSavedFilePath : SaveMarkdownDialog();
SaveFile(filePath);
markdownTextChanged = false;
}
private void OpenMarkdownDocument()
{
if (PromptForUnsavedChanges())
{
String openPath = OpenMarkdownDialog();
OpenFile(openPath);
}
}
/// <summary>
/// Checks if there are any unsaved changes and prompts
/// the user accordingly.
/// </summary>
/// <returns>Returns false if the user presses cancel</returns>
private bool PromptForUnsavedChanges()
{
if (!markdownTextChanged) return true;
DialogResult result = PromptUserToSave();
if (result == DialogResult.Cancel) return false;
if (result == DialogResult.Yes) SaveMarkdownDocument();
return true;
}
/// <summary>
/// Clears the MarkdownTextBox and MarkdownPreview
/// </summary>
private void Clear()
{
markdownTextBox.Text = "";
markdownPreview.DocumentText = "";
}
}
}
</code></pre>
<p>The rest of the repository can be found here: <a href="https://github.com/chrisledet/Marker" rel="nofollow">https://github.com/chrisledet/Marker</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T15:00:46.540",
"Id": "63131",
"Score": "1",
"body": "My experience is that the MVP pattern works better with Windows Forms. It is more or less the same principle.\nIt also makes it easier to create a WebForms application with the same logic.\nHave a look at the following articles: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter http://msdn.microsoft.com/en-us/magazine/cc188690.aspx"
}
] |
[
{
"body": "<p>There is a port to C# of PureMVC out there that I have been using, and made modifications to it to do the following:</p>\n\n<ol>\n<li>In PureMVC the views are called Mediators, so the technique is to group concerns into a mediator -- so your MainForm will have numerous Mediators (basically, ideally, one for every control -- with the exception of menus, which are generally broken down into one mediator for every submenu)</li>\n<li>The painful part is hooking up the windows/controls event mechanism to the MVC, you dont want to write a bunch of stubs that call into the Mediator stubs. So you use reflection to do the work at the point where the mediator is instantiated.</li>\n<li>What you end up with is a MainForm.cs that has nothing in it, it is completely managed by its mediators in a code-behind fashion.</li>\n<li>If you've done everything correctly, you should be able to take mediators out of your system and nothing evil will happen (ie, you can still compile, and run, but certain things simply won't work [no crashes]).</li>\n</ol>\n\n<p>If you decide to try out this library, here is a couple tips for changing things up. </p>\n\n<p>In the mediator, there is a callback called ListNotificationInterests, which is called when the mediator is registered. I found this to be an awkward way of showing the notifications so the modification is to use reflection again to make the registerer look for certain dummy members in the mediator, named in a particular fashion -- </p>\n\n<pre><code>public const string ___P_APPEARANCECHANGED=\"MainFmMed_APPEARANCECHANGED\"\n</code></pre>\n\n<p>That shows a published notification, so you would reference that from another file when listing an interest -- like so --</p>\n\n<pre><code>private const string ___I_MainFmMed_APPEARANCECHANGED=MainFmMed.___P_APPEARANCECHANGED;\n</code></pre>\n\n<p>The registerer will pick up on that signature and register you to receive those events. Doing things this way exposes the publish/interest system to your coding tools since it is not buried in a function. That way it is easier to figure out what is going on. (one of the problems with MVC is that you cannot follow what happens simply by following functions around). So, if you have a decent editor, you can even make some macros that will do the proper kind of search when you are on one of these notification identifiers -- revealing all who listen and the locations where it is dispatched.</p>\n\n<p>You will notice that doing it the above way with the interest creates a dependency, if the XXX of XXX.__P_MMM is not present, you cant compile (sometimes this is useful) -- but to get rid of it you just use the literal:</p>\n\n<pre><code>private const string ___I_MainFmMed_APPEARANCECHANGED=\"MainFmMed_APPEARANCECHANGED\";\n</code></pre>\n\n<p>The mediators get hooked up like so:</p>\n\n<pre><code>protected override void hookEvents() {\n assignFormEvent(\"Shown\");\n}\n</code></pre>\n\n<p>Which hooks the event to:</p>\n\n<pre><code>private void EvtShown(object sender_, EventArgs e_){}\n</code></pre>\n\n<p>Additionally:</p>\n\n<pre><code>/// // If I am a -Form- mediator - options are...\n/// assignFormEvent(\"Shown\",\"evtShown\");\n/// assignFormEvent(\"Shown\"[,\"EvtShown\"]);\n/// assignEvent(object c_, string event_name_, string handler_);\n/// assignControlEvent(\"Button1\",\"Click\",\"evtClick\");\n/// assignControlEvent(\"Button1\",\"Click\"[,\"EvtClick\"]);\n/// assignFormLookAndFeelEvent(\"evtFormLookAndFeel\"); //look change evt\n///\n/// // If I am a control Mediator - options are...\n/// assignEvent(\"Click\",\"evtClick\"); //assign to view component (control I am mediating)\n/// assignEvent(button1,\"Click\",\"evtClick\"); // button1 must be made a property of mediator using reflection\n/// assignAllControlEvents();\n</code></pre>\n\n<p>Controls you are mediating are implemented as properties:</p>\n\n<pre><code>private TextBox buggTB{\n get{return GetControl(\"buggTB\") as TextBox;}\n}\n</code></pre>\n\n<p>If mediating a single control, I use this (it) to genericize things:</p>\n\n<pre><code>private PanelControl it {\n get{\n return ViewComponent as PanelControl;\n }\n}\n</code></pre>\n\n<p>I hope that gives you some ideas. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T13:25:41.877",
"Id": "7763",
"ParentId": "7485",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7763",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T12:49:31.620",
"Id": "7485",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"mvc"
],
"Title": "Refactor Windows Form code to follow MVC"
}
|
7485
|
<p>How can I re-factor the code to remove duplication and create a common method ?</p>
<pre><code>(function(){
$("#a", "#main").bind("mouseover", function(){
var id1 = $("#one").text(),
args = ["DCSext.common1","common1","DCSext.common2","DCSext.title","one", "DCSext.ti", id1];
dcsMultitrack.apply(this, args);
});
$("#b", "#cool").bind("click", function(){
var id2 = $("#two").text(),
args = ["DCSext.common1","common1","DCSext.common2","DCSext.title", "two", "DCSext.some", id2];
dcsMultitrack.apply(this, args);
});
$("body").delegate("a", "click", function(){
var id3 = $("#three").text(),
args = ["DCSext.common1","common1","DCSext.common2","DCSext.new", "what", "DCSext.where", "us"];
dcsMultitrack.apply(this, args);
});
}());
</code></pre>
<p>I have some common logs which are almost repeated in all callbacks. I can use a variable like </p>
<pre><code>var commonlogs = ["DCSext.common1","common1","DCSext.common2","common2", "DCSext.common3", "common3" ];
</code></pre>
<p>i can use <code>commonlogs.push("DCSext.title","one","DCSext.ti", "two").</code> But not finding a proper way to re-factoring repeating the DCSext stuff again and again since its very granular level . </p>
<p>Thanks for any advice or suggestions. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T02:05:34.890",
"Id": "12471",
"Score": "0",
"body": "@paul Can you clarify your problem? I don't understand what you mean by \"common logs\". Are you referring to the `args` array you're passing into `dcsMultitrack()`? The `commonlogs` array you posted includes some strings that aren't in any of the above `args` arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T06:43:36.100",
"Id": "13658",
"Score": "0",
"body": "@seand purpose of including commonlogs variable is to move out repeated strings from the existing arrays in callback function .If you see my top code mostly [\"DCSext.common1\",\"common1\",\"DCSext.common2\"] been repeated almost in all callback function .So I can extract into an variable and can just do commonlogs.push(extra strings) but i do not think it i san elegent solution .So looking for some other advice. Thanks"
}
] |
[
{
"body": "<p>There is not much you can do,\nthe only thing I would suggest is to use <code>concat</code> instead of <code>push</code>, this way you can keep re-using <code>commonLogs</code>, and maybe have 1 <code>commonLogs</code> per group.</p>\n\n<p>So</p>\n\n<pre><code> var commonLogs = [ [] ];\n commonLogs[1] = [\"DCSext.common1\",\"common1\"];\n commonLogs[2] = commonLogs[1].concat( [\"DCSext.common2\",\"common2\"] );\n commonLogs[3] = commonLogs[2].concat( [\"DCSext.common3\",\"common3\"] );\n</code></pre>\n\n<p>Then you can</p>\n\n<pre><code>(function(){\n\n $(\"#a\", \"#main\").bind(\"mouseover\", function(){\n var id1 = $(\"#one\").text(),\n args = commonLogs[2].concat( [\"DCSext.title\",\"one\", \"DCSext.ti\", id1] );\n dcsMultitrack.apply(this, args);\n });\n\n $(\"#b\", \"#cool\").bind(\"click\", function(){\n var id2 = $(\"#two\").text(),\n args = commonLogs[2].concat( [\"DCSext.title\", \"two\", \"DCSext.some\", id2] );\n dcsMultitrack.apply(this, args);\n });\n\n $(\"body\").delegate(\"a\", \"click\", function(){\n var args = commonLogs[2].concat( [\"DCSext.new\", \"what\", \"DCSext.where\", \"us\"] );\n dcsMultitrack.apply(this, args);\n });\n\n}());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T03:01:22.270",
"Id": "40235",
"ParentId": "7486",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T12:57:18.110",
"Id": "7486",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Creating a webtrend function to remove duplication using js apply and call"
}
|
7486
|
<p>These two methods do very similar things. Is it possible to condense these somehow? This is using the Entity Framework. </p>
<pre><code>public void ExportSiteData (FLEX_INV_EXP_SITE siteData)
{
var uniqueSite = from e in _context.FLEX_INV_EXP_SITE
where e.SITE_ID == siteData.SITE_ID
select e;
var count = uniqueSite.Count();
if (count != 0) return;
_context.FLEX_INV_EXP_SITE.AddObject(siteData);
_context.SaveChanges();
}
public void ExportAddressData (FLEX_INV_EXP_ADDRESS addressData)
{
var uniqueSite = from e in _context.FLEX_INV_EXP_ADDRESS
where e.SITE_ID == addressData.SITE_ID
select e;
var count = uniqueSite.Count();
if (count != 0) return;
_context.FLEX_INV_EXP_ADDRESS.AddObject(addressData);
_context.SaveChanges();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T15:48:09.097",
"Id": "11752",
"Score": "0",
"body": "Can you make them both share an interface? - that would be the easiest way (and wouldn't use generics at all).\nThere is also a duck typing library for C# (never looked at it myself though)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T16:46:12.783",
"Id": "11761",
"Score": "0",
"body": "I probably could get them to share an interface - I'm not sure how that'd help though, can you provide an explanation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T17:53:43.203",
"Id": "11763",
"Score": "0",
"body": "what type is `_context.FLEX_INV_EXP_ADDRESS`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T23:39:51.797",
"Id": "11770",
"Score": "4",
"body": "+1 because it is interesting how complex the proposed solutions are: Makeing the solution a little more [dry](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) by violating the [kiss](http://en.wikipedia.org/wiki/KISS_principle) principle :-("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T08:55:11.247",
"Id": "11792",
"Score": "0",
"body": "@k3b - Can't agree more, the idea was to make things simpler"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-30T14:28:53.973",
"Id": "53700",
"Score": "0",
"body": "I think that your original code is fairly simple and straight to the point. the only thing to think about here is speed, or performance, try it with their code try it with your code and see what is better, **on paper**"
}
] |
[
{
"body": "<p>Here is a wildly simplified example, but you could try something like this:</p>\n\n<pre><code>public class EXP_SITE\n{\n public int SITE_ID { get; private set; } \n}\n\npublic class EXP_ADDRESS\n{\n public int SITE_ID { get; private set; } \n}\n\npublic class SomeList<T> : List<T>\n{\n public void AddObject(object o) { }\n}\n\npublic class UnknownClass\n{\n private SomeList<EXP_ADDRESS> Addresses;\n private SomeList<EXP_SITE> Sites;\n\n private void ExportGeneric<T>(T item, SomeList<T> list, Func<T, bool> matcher)\n {\n var uniqueSite = from e in list\n where matcher.Invoke(e) \n select e;\n\n var count = uniqueSite.Count();\n\n if (count != 0) return;\n list.AddObject(item);\n //save();\n }\n\n public void ExportSiteData(EXP_SITE site)\n {\n ExportGeneric(site, Sites, s => s.SITE_ID == site.SITE_ID);\n }\n\n public void ExportAddressData(EXP_ADDRESS addr)\n {\n ExportGeneric(addr, Addresses, a=> a.SITE_ID == addr.SITE_ID);\n }\n}\n</code></pre>\n\n<p>But really, I would probably change <code>ExportGeneric</code> to say:</p>\n\n<pre><code> private void ExportGeneric<T>(T item, SomeList<T> list, Func<T, bool> matcher)\n {\n if(list.Any(matcher)) return;\n list.AddObject(item);\n //save();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T18:06:30.390",
"Id": "7494",
"ParentId": "7488",
"Score": "0"
}
},
{
"body": "<p>It seems the only two unique things about the blocks of code are the Tables that you are searching/adding to and how the <code>SITE_ID</code>s are obtained (from different types). You could just make your method accept two additional parameters, the table that is being searched and a lambda which selects the <code>SITE_ID</code>. You'll just have to rewrite some expressions.</p>\n\n<pre><code>public static void ExportData<TEntity, TSite>(\n ObjectSet<TEntity> table,\n Expression<Func<TEntity, TSite>> siteIdSelector,\n TEntity data)\n where TEntity : class\n{\n var condition = GetCondition(siteIdSelector, data);\n var isInTable = table.Where(condition).Any();\n if (!isInTable)\n {\n table.AddObject(data);\n table.Context.SaveChanges();\n }\n}\n\nprivate static Expression<Func<TEntity, bool>> GetCondition<TEntity, TKey>(\n Expression<Func<TEntity, TKey>> keySelector,\n TEntity data)\n where TEntity : class\n{\n var entity = Expression.Parameter(typeof(TEntity), \"entity\");\n var entityKey = BindParameter(keySelector, entity);\n var dataKey = BindParameter(keySelector, Expression.Constant(data));\n var body = Expression.Equal(entityKey , dataKey);\n return Expression.Lambda<Func<TEntity, bool>>(body, entity);\n}\n\nprivate static Expression BindParameter<TEntity, TKey>(\n Expression<Func<TEntity, TKey>> keySelector,\n Expression entity)\n where TEntity : class\n{\n return new SubstitutionVisitor\n {\n OldExpr = keySelector.Parameters.Single(),\n NewExpr = entity,\n }.Visit(keySelector.Body);\n}\n\npublic class SubstitutionVisitor : ExpressionVisitor\n{\n public Expression OldExpr { get; set; }\n public Expression NewExpr { get; set; }\n\n public override Expression Visit(Expression node)\n {\n return (node == OldExpr) ? NewExpr : base.Visit(node);\n }\n}\n</code></pre>\n\n<p>Then to use it, you could do something like this:</p>\n\n<pre><code>ExportData(_context.FLEX_INV_EXP_SITE, entity => entity.SITE_ID, siteData);\nExportData(_context.FLEX_INV_EXP_ADDRESS, entity => entity.SITE_ID, addressData);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T19:00:42.707",
"Id": "7497",
"ParentId": "7488",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T14:42:08.820",
"Id": "7488",
"Score": "5",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Exporting site and address data"
}
|
7488
|
<p>I'm hoping someone is willing and can take a minute to look over this function and tell me what they think of it, if it can be improved or what not. I tried commenting out what the purpose of everything is. I would like to note that something isn't quite right with the time_remaining and what not because what's supposed to happen when its been passed the 10 minutes the users account clears out the failed logins and redirects to the index function but doesn't.</p>
<p>EDIT: I have redone my code and was hoping someone could tell me what they thought of it now?</p>
<pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Usermanagement extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
if(!$this->session->userdata('logged_in'))
{
$bodyContent = "login";//which view file
}
else
{
redirect('cpanel/index');
}
$bodyType = "full";//type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view('usermanagement/index', $this->data);
}
function login()
{
// Set validation rules for login form fields
$this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[50]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|max_length[12]|xss_clean');
// Verify login form was submitted
if ($this->form_validation->run() == FALSE)
{
// Form was not submitted
redirect('usermanagement/index');
}
else
{
// Create variables from login form submission
$username = $this->input->post('username');
$password = $this->input->post('password');
// Run function to check if username exists in database
$user_data = $this->loggedin->get_user_data($username);
// No username match in database
if($user_data == false)
{
echo json_encode(array('error' => 'yes', 'msg' => 'Username not found, check your username and try again.', 'flags' => 3));
}
else
{
// User was found in database
// Check account status of username
if ($user_data->users_statuses_id == 1)
{
echo json_encode(array('error' => 'yes', 'msg' => 'Account has not been authenticated. Check your email for verification instructions!', 'flags' => 3));
}
elseif ($user_data->users_statuses_id == 3)
{
echo json_encode(array('error' => 'yes', 'msg' => 'Account has been suspended!', 'flags' => 3));
}
elseif ($user_data->users_statuses_id == 4)
{
echo json_encode(array('error' => 'yes', 'msg' => 'Account has been banned!', 'flags' => 3));
}
elseif ($user_data->users_statuses_id == 5)
{
echo json_encode(array('error' => 'yes', 'msg' => 'Account has been deleted!', 'flags' => 3));
}
else
{
// Create a user_id variable from returned data
$user_id = $user_data->user_id;
$lock_date = $user_data->lock_date;
$current_time = time();
$failed_logins = $user_data->failed_logins;
// Check to see if account is currently locked
if ($lock_date !== "0000-00-00 00:00:00")
{
if((strtotime($lock_date) < $current_time && $failed_logins > 0))
{
$lock_date = strtotime($lock_date);
// See how much time is remaining efore user can login again
$time_difference = $this->genfunc->time_since($lock_date);
// Time must be
if ($time_difference <= 10)
{
// Has not been 10 minutes yet
$time_remaining = 10 - $time_difference;
echo json_encode(array('error' => 'yes', 'msg' => 'Your account is currently locked, we appologize for the inconvienence. You must wait ' .$time_remaining.' minutes before you can log in again!', 'flags' => 3));
}
else
{
// Clear the lock
$this->loggedin->clear_login_attempts($user_id);
echo json_encode(array('error' => 'no', 'msg' => 'Your account is now unlocked, you may now log in again!', 'flags' => 3));
}
}
}
else
{
// Assign variables to returned data
$passwordDB = $user_data->password;
$passwordDB2 = $user_data->password2;
$first_name = $user_data->first_name;
$last_name = $user_data->last_name;
$email = $user_data->email;
$users_roles_id = $user_data->users_roles_id;
$generated_password = $this->genfunc->reGenPassHash($password, $passwordDB2);
$date_time = $this->genfunc->unixToMySQL($current_time);
// Passwords match username in database
if ($passwordDB == $generated_password)
{
// Run functions for user to update logins and clearing of failed attempts
$this->loggedin->update_logins($user_id);
$this->loggedin->clear_login_attempts($user_id);
// Create variables about user and assign them to session for database entry
$op_system = $this->genfunc->getUserOS();
$user_ip = $this->genfunc->getRealIpAddr();
$user_browser = $this->session->userdata('user_agent');
$session_id = $this->session->userdata('session_id');
$this->loggedin->insert_session($user_id, $session_id, $user_ip, $user_browser, $date_time);
$this->session->set_userdata(array(
'session_id' => $session_id,
'logged_in' => TRUE,
'user_id' => $user_id,
'username' => $username,
'users_roles_id' => $users_roles_id
));
redirect('cpanel/index');
}
else
{
// Passwords didn't match in database
// Take failed logins and compare it
if ($failed_logins == 5)
{
// Retrieve IP Address of user trying to hack into account
$hacker_ip_address = $this->genfunc->getRealIpAddr();
$this->loggedin->update_hacked_account($user_id, $hacker_ip_address, $date_time);
$my_domain_name = $this->genfunc->myDomainName();
// Email user new registration account
$sender_email = "noreply@kansasoutlawwrestling.com";
$reply_to = "noreply@kansasoutlawwrestling.com";
$recipient_email = $email;
$email_subject = "KOW Manager Account Locked";
$email_body = 'Hello '.$first_name.' '.$last_name.' You, or someone using your account at '.$my_domain_name.', has attempted to hack into your account. If this is an error, ignore this email and you will be removed from our mailing list.<br /><br />Regards, '.$my_domain_name.' Team';
$this->genfunc->mailSomeone($email, $sender_email, $email_subject, $email_body);
echo json_encode(array('error' => 'yes', 'msg' => '"Your account is currently locked, we appologize for the inconvienence. This is a security messure implimented by to many failed login\'s! You must wait 10 minutes before you can login again!', 'flags' => 3));
}
else
{
// Upate amount of failed logins
$this->loggedin->update_failed_logins($user_id);
$chances_left = 5 - $failed_logins;
echo json_encode(array('error' => 'yes', 'msg' => 'Invalid Username and Password combination! You have ' .$chances_left. ' chances left to login succesfully or the account will be locked!', 'flags' => 3));
}
}
}
}
}
}
}
function logout()
{
$this->session->sess_destroy();
redirect('usermanagement/index');
}
}
/* End of file usermanagement.php */
/* Location: ./application/controllers/usermanagement.php */
</code></pre>
<p><strong>MODEL :</strong> </p>
<pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Loggedin extends CI_Model
{
/**
* Loggedin::__construct()
*
* @return
*/
function __construct()
{
parent::__construct();
}
/**
* Loggedin::get_user_data()
*
* @param string $username Username that was posted via login script
* @return $query->row OR false depending on if a user was found in the database
*/
public function get_user_data($username)
{
$this->db->select('*');
$this->db->from('users');
$this->db->join('users_logins', 'users.user_id = users_logins.user_id');
$this->db->where('users.username', $username);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->row();
}
else
{
return false;
}
}
/**
* Loggedin::clear_login_attempts()
*
* @param int $user_id $user_id of the account trying to be accessed
*/
public function clear_login_attempts($user_id)
{
$this->db->set('lock_date', 'NULL');
$this->db->set('hacker_ip_address', 'NULL');
$this->db->set('failed_logins', '0');
$this->db->where('user_id', $user_id);
$this->db->update('users_logins');
}
/**
* Loggedin::update_logins()
*
*
*/
public function update_logins($user_id)
{
$this->db->query('UPDATE users_logins SET number_of_logins = number_of_logins+1 WHERE user_id ='.$user_id);
}
/**
* Loggedin::insert_session()
*
* @param int $user_id $user_id of the account trying to be accessed
*/
public function insert_session($user_id, $session_id, $user_ip, $user_browser, $current_time)
{
$data = array(
'user_id' => $user_id ,
'session_id' => $session_id,
'ip_address' => $user_ip,
'user_agent' => $user_browser,
'session_started' => $current_time
);
$this->db->insert('users_logins_sessions', $data);
}
/**
* Loggedin::update_failed_logins()
*
* @param int $user_id $user_id of the account trying to be accessed
*/
public function update_failed_logins($user_id)
{
$this->db->query('UPDATE users_logins SET failed_logins = failed_logins+1 WHERE user_id ='.$user_id);
}
/**
* Loggedin::update_hacked_account()
*
*
*/
public function update_hacked_account($user_id, $hacker_ip_address, $current_time)
{
$this->db->set('lock_date', $current_time);
$this->db->set('hacker_ip_address', $hacker_ip_address);
$this->db->where('user_id', $user_id);
$this->db->update('users_logins');
}
}
/* End of file loggedin.php */
/* Location: ./app/models/loggedin.php */
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>I have rewritten it all just to try and start over that way it'd be possible to accomplish all tasks in the correct logical order as well as with the smallest bit of code. I tend to fail at both of those things.</p>
<p>Revised code:</p>
<p>Controller: </p>
<pre><code>function login_submit()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
$user_id = $this->users->get_user_id_by_username($this->input->post('username'));
if ($user_id !== 0)
{
if ($this->kow_auth->is_max_login_attempts_exceeded($user_id))
{
echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently locked, we appologize for the inconvienence. You must wait 10 minutes before you can login again!'));
}
else
{
$user_status = $this->users->get_user_status($user_id);
if ($user_status == 1)
{
echo json_encode(array('error' => 'yes', 'message' => 'Sorry you must verify your account before logging in!'));
}
elseif ($user_status == 3)
{
echo json_encode(array('error' => 'yes', 'message' => 'Your account has been suspended!'));
}
elseif ($user_status == 4)
{
echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently banned!'));
}
elseif ($user_status == 5)
{
echo json_encode(array('error' => 'yes', 'message' => 'Your account has been deleted!'));
}
else
{
}
}
}
else
{
echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!'));
}
}
</code></pre>
<p>Models: </p>
<p>Users Model</p>
<pre><code><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Users
*
* This model represents user authentication data. It operates the following tables:
* - user account data,
* - user profiles
*
* @package Kow_auth
* @author Jeffrey Davidson
*/
class Users extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_user_id_by_username($username)
{
$this->db->select('user_id');
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->user_id;
}
else
{
return 0;
}
}
function get_user_status($user_id)
{
$this->db->select('users_statuses_id ');
$this->db->where('user_id', $user_id);
$query = $this->db->get('users');
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->users_statuses_id;
}
else
{
return 0;
}
}
}
</code></pre>
<p>Login Attempts Model</p>
<pre><code><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Login_attempts
*
* This model serves to watch on all attempts to login on the site
* (to protect the site from brute-force attack to user database)
*
* @package Kow_auth
* @author Jeffrey Davidson
*/
class Login_attempts extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_attempts_num($user_id)
{
$this->db->select('failed_logins');
$this->db->from('users_logins');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->failed_logins;
}
else
{
return 0;
}
}
}
</code></pre>
<p>Library:</p>
<pre><code><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* KOW Auth Library
* Authentication Library for Code Igniter
* @author Jeffrey Davidson
* @version 1.0.0
* @copyright 2012
*/
class Kow_auth
{
function __construct()
{
//assign the CI superglobal to $CI
$this->ci =& get_instance();
}
function is_max_login_attempts_exceeded($user_id)
{
$this->ci->load->model('kow_auth/login_attempts');
$login_attempts = $this->ci->login_attempts->get_attempts_num($user_id);
if ($login_attempts >= 5)
{
return true;
}
else
{
return false;
}
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p><strong>Okey, first of all; I had a hard time determining if this was a login script or a registration script even if you explicitly said it was a script containing login validation. If I was you I would review the code and try to clear up any vagueness, because I got a headache trying to sort your code out. Here we go anyway:</strong></p>\n\n<p>At <em>line 6</em>: Why do you use <code>xss_clean()</code> if you're not inserting the data into the database for later display to the user? Use <code>remove_invisible_characters()</code> instead.</p>\n\n<p>By the looks of it, you never do any credential checks against the database before starting the log-in routine. This is prone to brute force attacks if you let your attackers check if the username already exists <strong>before</strong> giving an error message such as 'Wrong username/password'. I tried to figure out exactly where you did the login function, but I couldn't find it.</p>\n\n<p>What exactly is <code>$user_login_data</code>? Shouldn't this information already exist in <code>$user_data</code>? I would recommend using an independent method such as <code>getUserData()</code> instead of returning a data object by a function that is supposed to <strong>check if a username exists</strong>.</p>\n\n<p>Why do you load first name, last name, e-mail address and <strong>two</strong> passwords? At this point I was so confused I could barely keep track of the script's purpose. It would remind more of a registration form.</p>\n\n<p>You should use cleaner variable names such as <code>$user_data</code> instead of <code>$user_data[0]</code> everywhere, it can quickly get messy if you decide to change things.</p>\n\n<p>What is <code>$users_statuses_id</code>? I would call this <code>$status_code</code> or something similar. Since variables bound to an object reside within it, there is no point in calling them <code>$user_some_info</code> since the object should already state the purpose well enough by it's name: <code>$user->some_info</code>.</p>\n\n<p>It's hard to know what functions such as <code>genfunc->time_since()</code> does without knowing the code. Though you seem to be checking <strong>seconds</strong> instead of <strong>minutes</strong>. <code>if ($time_difference >= 10)</code> should be <code>if ($time_difference >= (10*60))</code>.</p>\n\n<p>Why do you use <code>genfunc->getRealIpAddr();</code> at one place and <code>$_SERVER['REMOTE_ADDR'];</code> another?</p>\n\n<p>Vague function names: <code>loggedin->update_hacked_account(), genfunc->mailSomeone()?</code> etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T18:58:33.270",
"Id": "11828",
"Score": "0",
"body": "Excellent comments. Thank you for the response. I'll do some updating in my code and post back and try and explain things a little more clearer with my code. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:01:17.577",
"Id": "11914",
"Score": "0",
"body": "What do you think of it now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:26:02.837",
"Id": "11921",
"Score": "0",
"body": "I'd like to add something to this answer. Try to use short functions (no more than 20 lines), that will help you (and others) to understand what the code really does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T19:45:05.140",
"Id": "12511",
"Score": "0",
"body": "I've updated my post check out EDIT 2!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:46:51.227",
"Id": "7511",
"ParentId": "7501",
"Score": "6"
}
},
{
"body": "<p>Some notes: </p>\n\n<p>1, </p>\n\n<pre><code>elseif ($user_data->users_statuses_id == 4) \n</code></pre>\n\n<p>Instead of magic numbers you should use named constants. Consider creating an <code>$user_data->isUserBanned()</code> function also. The same is true for <code>'flags' => 3</code> and <code>($lock_date !== \"0000-00-00 00:00:00\")</code> (the latter should be <code>$user_data->isLocked()</code>). It helps readers a lot and improves encapsulation. </p>\n\n<p>2, Sender's e-mail address should be in a configuration file as well as the e-mail template. </p>\n\n<p>3, Extract out smaller function. For example, code below </p>\n\n<pre><code>// Create variables about user and assign them to session for database entry \n</code></pre>\n\n<p>should be in a function called <code>storeUserDataInSession()</code>. </p>\n\n<p>4, The code really needs <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">flattening</a>. Extracting out some functions would help. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T16:54:23.017",
"Id": "11966",
"Score": "0",
"body": "So your saying:\n\n1. I should do a function for isUserBanned, isUserSuspended, isUserActived, all of the rest of those? Also why would I need to make a function for the lock_date and flags if its only going to be like 2-3 lines.\n\n2. Thank you I'll do that. But with CI what file would I put that in?\n\n3. I'll do that as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T17:00:31.620",
"Id": "11967",
"Score": "0",
"body": "3. I already have a function for storing session data in the database"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T21:37:16.297",
"Id": "12461",
"Score": "0",
"body": "1, It would improve code readability and help maintainability a lot. The key words are *encapsulation* and\n[*high cohesion*](http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29#High_cohesion). It makes possible to change the implementation without changing the code of the clients. If you haven't read yet read *Clean Code* by Robert C. Martin.\n2, Sorry, I don't know CI. It maybe worth a question on SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T19:45:39.260",
"Id": "12513",
"Score": "0",
"body": "I've updated my post check out EDIT 2!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T12:37:28.460",
"Id": "7625",
"ParentId": "7501",
"Score": "3"
}
},
{
"body": "<p>Another recommendation apart from all of the good ones you have already received.</p>\n\n<p>Don't create variables that are not variables.</p>\n\n<pre><code> // Assign variables to returned data \n $passwordDB = $user_data->password;\n $passwordDB2 = $user_data->password2;\n $first_name = $user_data->first_name;\n $last_name = $user_data->last_name;\n $email = $user_data->email;\n $users_roles_id = $user_data->users_roles_id;\n</code></pre>\n\n<p>These variables are assigned once and used once (or possibly twice), however they are never modified. They only abstract away the details of what is being done later in the function. Accessing the object properties is more descriptive than referring to local variables. When you have a local variable you have to track back to where it was last set to see its value. Also, there is less clutter without these lines that do very little.</p>\n\n<p>Personally I like to handle data in larger chunks rather than lots of fields spread everywhere. I would be using arrays to hold the data and avoid line by line first name, last name, email access. Here is how I would do it for the if block that follows the variables i referred to above.</p>\n\n<pre><code> // No need to Assign variable to returned data.\n\n if ($user_data->valid_password())\n {\n // loggedin doesn't feel like a real object, it looks like\n // something you are using to call functions with. I would\n // call it login_manager if it was managing the logins.\n $this->loggedin->update_logins($user_id);\n $this->loggedin->clear_login_attempts($user_id); \n\n // Again, I wouldn't Create variables about user and assign them to session for database entry\n\n // This call makes loggedin do something to the session.\n // loggedin should be called with things about logins, not\n // with direct calls to modify the session.\n // $this->loggedin->insert_session($user_id, $session_id, $user_ip, $user_browser, $date_time);\n\n // The logic for this belongs in the session.\n $this->session->set_userdata($user_data);\n redirect('cpanel/index'); \n }\n</code></pre>\n\n<p><strong>EDIT 2:</strong> This code looks a lot better. It is less cluttered by lots of field settings. Actually, I think it looks like its finished now. I can't see too much to critique.</p>\n\n<p>One thing of interest is you specify the from in your SQL query in the Login_Attempts model, but in the Users model it seems to be part of the get?</p>\n\n<p>Premature optimization is the root of all evil. So I'm not going to suggest that you combine all of your database queries into 1 query. What I would have done was have 1 model that combined the data from the two tables. The SQL would look something like:</p>\n\n<pre><code>SELECT * FROM users LEFT JOIN users_logins on users.user_id=users_logins.user_id WHERE users.username=?\n</code></pre>\n\n<p><code>*</code> should possibly be replaced with the exact fields you wanted.</p>\n\n<p>I suggest you keep it as you have it, but have only included this for you to remember if you find this to be a bottleneck. I would go straight to this sort of solution on heavily used parts of the system or anything within a highly nested loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T18:59:45.290",
"Id": "12001",
"Score": "0",
"body": "Thank you for the comments. What are you talking about in the second part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T03:11:40.450",
"Id": "12036",
"Score": "0",
"body": "I have edited in some further details for the second part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T19:45:22.957",
"Id": "12512",
"Score": "0",
"body": "I've updated my post check out EDIT 2!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T05:53:16.387",
"Id": "7633",
"ParentId": "7501",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T22:05:33.043",
"Id": "7501",
"Score": "3",
"Tags": [
"php",
"codeigniter"
],
"Title": "Login Validation"
}
|
7501
|
<p>I am working on bettering my C# skills, and recently wrote this program to solve a projecteuler.net problem:</p>
<blockquote>
<p>A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 * 99. Find
the largest palindrome made from the product of two 3-digit numbers.</p>
</blockquote>
<p>The code works and produced the correct answer, but I'm looking to avoid bad code and use best practices. Any critique of changes to make this more efficient would be appreciated! (Also, if there are any WTF's in there, please point them out!)</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
namespace NumericPalindrome {
class Program
{
static void Main(string[] args)
{
long result = 0;
for (int i = 100; i < 1000; i++)
{
for (int k = 100; k < 1000; k++)
{
if (IsPalindrome(i * k))
if ((i * k) > result)
result = i * k;
}
}
Console.WriteLine(result);
}
static bool IsPalindrome(long testNumber)
{
List<int> list = new List<int>();
//Break testNumber into an integer list of its digits
while (testNumber >= 1)
{
list.Add((int)(testNumber % 10));
testNumber /= 10;
}
List<int> reverseList = new List<int>(list);
reverseList.Reverse();
bool palindrome = true;
for (int i = 0; i < list.Count; i++)
{
if (list[i] != reverseList[i])
palindrome = false;
}
return palindrome;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>First of all, add benchmarking to your program: before anything else, record the current time. Right before the program terminates, subtract the recorded time from the current time and display the difference. Run it and record the time it takes. Then, implement the following optimizations, and see how much time you save.</p></li>\n<li><p>In your first nested two for-loops you are not taking advantage of the fact that A<em>B = B</em>A. So, you are doing about twice the work that is necessary. Cut it in half! (I presume that once you realize the idea, you can figure out how; if not, ask me.)</p></li>\n<li><p>The three repeated calculations of i * k are kind of ugly. Why don't you compute the product once, and use it 3 times? This is not a performance issue, just an aesthetic one.</p></li>\n<li><p>To check if the list is a palindrome, you do not need to make a copy of it and reverse. You can do something which far more efficient, and even easier to implement: loop from the start of the list until the middle, and compare the digit at that position with the corresponding digit counting from the end of the list. If the list contains an odd number of digits, ignore the one in the middle. (Again, I presume you can figure it out; if not, ask me.)</p></li>\n<li><p>You can <code>return false</code> from within the loop immediately upon finding that the number is not a palindrome; it is totally unnecessary to keep looping until you have checked all the digits.</p></li>\n<li><p>If you <em>really-really</em> care about performance, you can start doing hacks, like making the list a static member variable of your program, allocating once, and clearing it each time before using it, instead of reallocating a new list each time. You can also find an algorithm which can determine whether a number is a palindrome without constructing a list. It is ugly, but it works; look here: <a href=\"https://stackoverflow.com/questions/199184/how-do-i-check-if-a-number-is-a-palindrome\">https://stackoverflow.com/questions/199184/how-do-i-check-if-a-number-is-a-palindrome</a></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T20:07:06.833",
"Id": "12023",
"Score": "0",
"body": "Great answer with a lot of improvements. Thanks, Mike!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T20:11:06.943",
"Id": "12024",
"Score": "0",
"body": "Glad to be of help, Jim! Another happy customer!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T02:09:37.293",
"Id": "7512",
"ParentId": "7502",
"Score": "11"
}
},
{
"body": "<p>In addition to Mike Nakis's great suggestions, I think the <code>IsPalindrome</code> function can be made more simple and readable like this:</p>\n\n<pre><code>static bool IsPalindrome(long testNumber)\n{\n var stringRepresentation = testNumber.ToString(\"d\");\n\n return stringRepresentation == Reverse(stringRepresentation);\n}\n\nprivate static string Reverse(string stringRepresentation)\n{\n var charArray = stringRepresentation.ToCharArray();\n Array.Reverse(charArray);\n\n return new string(charArray);\n}\n</code></pre>\n\n<p>This also reduced the total execution time on my machine from 416ms to 246ms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T08:15:41.603",
"Id": "7523",
"ParentId": "7502",
"Score": "4"
}
},
{
"body": "<p>I second @MikeNakis.<br>\nAdditionally:</p>\n\n<p>If you only want the largest, why not check from the top down? Just mind the pitfall that the first found might not be the largest.<br>\n(583 x 995 = 580085; 517 x 995 = 514415; 913 x 993 = 906609; 121 x 991 = 119911)</p>\n\n<pre><code>private int? GetLargestNumericPalindrome(int minBound, int maxBound) {\n int largestFound = minBound - 1;\n for (int i = maxBound; i >= minBound; i--) {\n // \"taking advantage of the fact that A*B = B*A\"\n // So we don't need to check N*maxBound since we already checked maxBound*N...\n // So only checking from N*N downwards.\n for (int k = i; k >= minBound; k--) {\n int num = i*k;\n if (num <= largestFound) {\n break; // Any other values of k for this i will also be lower.\n }\n if (IsPalindrome(num)) {\n largestFound = num;\n if(k > minBound) {\n // Black magic. Prove with logic and THEN uncomment this next line.\n //minBound = k;\n }\n break;\n }\n }\n }\n if(largestFound < minBound) {\n return null;\n }\n return largestFound;\n}\n\nprivate bool IsPalindrome(int num) {\n // Use OP's implementation.\n // Consider @MikeNakis's comments.\n throw new NotImplementedException();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T10:07:24.473",
"Id": "11797",
"Score": "0",
"body": "+1 LOL ! should have thought of that! 8-) (But you are still not taking advantage of the fact that A*B = B*A. You can improve it even further!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T10:09:55.503",
"Id": "11798",
"Score": "0",
"body": "do this actually works, or is this just a coincidence? What about numbers with any N digits, and not N = 3 ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T10:46:47.133",
"Id": "11801",
"Score": "0",
"body": "Is that a trick question? [First question.] Logic dictates it works the same: but instead of working our way up and replacing our found value for \"max\", we work our way down and look for the first find; that value will automatically be the max, since if we continue we will only find smaller values. Does this explain your question? If it does not, you will have to make a more concrete question. [Second question.] As for numbers with digits!=3, that is not part of the original question/issue/problem; but it could be addressed by calculating the 999 and the 100, instead of using static values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T12:01:26.963",
"Id": "11802",
"Score": "0",
"body": "@ANeves when you are replying to someone, use '@' + their nickname, so that they receive notification. Also, a separate answer to each person is better, so as to avoid confusion. Because I am now confused by your above comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T12:11:14.253",
"Id": "11804",
"Score": "0",
"body": "@SteveB My previous comment was addressed at you, and the two questions in your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T12:51:59.453",
"Id": "11805",
"Score": "0",
"body": "@Aneves: I was actually wondering if the logic you are suggesting (starting by the upper bound) is true, whatever value has N. This was a unique question, semantically split into two to show why I'm questioning. In fact, I think your logic fill find, in this order, the following palindromes : `583 x 995 = 580085 /\n517 x 995 = 514415 /\n913 x 993 = 906609 /\n121 x 991 = 119911`. You can see the palindromes order is not the order of one of its component. Am I wrong ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T12:56:58.690",
"Id": "11806",
"Score": "0",
"body": "@SteveB Not wrong at all! Very well thought. I will edit the answer accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T13:03:47.283",
"Id": "11807",
"Score": "0",
"body": "@ANeves: as it does not fit a comment, I've pushed an edit suggestion. In fact, I can reduce the inner loop by not testing numbers below actually max found / first component."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T13:28:03.053",
"Id": "11808",
"Score": "0",
"body": "@SteveB How about a compromise. Working with larger k and i first, I can't \"return\" when I find the first palindrome, but I CAN break from the k loop. There won't be a larger palindrome until I get a new value of i."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T13:33:09.653",
"Id": "11809",
"Score": "0",
"body": "@ANeves: same conclusion, check the edit of my answer for the full implementation, including MikeNakis suggestion to use another algorithm for testing the palindrome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T13:35:34.743",
"Id": "11811",
"Score": "0",
"body": "@SteveB I was editing and by saving on top yours was rejected - apologies, and thanks. (I have my quite convoluted proposed code, now. I really dislike how it sacrifices simplicity for supposed efficiency.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T14:07:17.530",
"Id": "11816",
"Score": "0",
"body": "I don't understand how\n\n int largestFound = minBound - 1;\n\nis an improvement on\n\n int largestFound = 0;\n\nIt seems arbitrary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T18:49:43.467",
"Id": "11827",
"Score": "0",
"body": "In your case it is arbitrary. It guarantees that the method never returns false negatives for \"any\" value of minBound, including 0. (Underflow on subtraction being irrelevant because of faster underflow on multiplication.)"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T10:01:37.053",
"Id": "7525",
"ParentId": "7502",
"Score": "3"
}
},
{
"body": "<p>Building on @Neves, but filtering with multiples of 10 and leveraging the inner for loop to reduce multiplications:</p>\n\n<pre><code>private int? GetLargestNumericPalindrome(int minBound, int maxBound) {\n int largestFound = 0;\n for (int i = maxBound; i >= minBound; i--) {\n // Normally, numbers don't have leading zeros, \n // so palindromes don't have trailing zeros.\n // Testing this up front seems worthwhile (almost a 10% improvement?).\n if (i % 10 == 0) {\n continue;\n }\n int smallestWorthChecking = i * minBound;\n if (smallestWorthChecking <= largestFound) {\n smallestWorthChecking = largestFound + 1;\n }\n // \"taking advantage of the fact that A*B = B*A\"\n // So we don't need to check N*maxBound since we already checked maxBound*N...\n // So only checking from N*N downwards.\n for (int num = i*i; num >= smallestWorthChecking; num -= i) {\n // ... palindromes don't have trailing zeros.\n if (num % 10 != 0 && IsPalindrome(num)) {\n largestFound = num;\n break;\n }\n }\n }\n if(largestFound == 0) {\n return null;\n }\n return largestFound;\n}\n</code></pre>\n\n<p>synthesizing ideas from @MikeNakis -- no need to reverse/match the whole, and @SteveB -- keeping it numeric</p>\n\n<pre><code>static bool IsPalindrome(long testNumber)\n{\n var reversed = 0L;\n var forward = testNumber\n while (reversed < forward)\n {\n var digit = forward % 10;\n reversed = reversed * 10 + digit;\n forward = forward / 10;\n }\n // Here, reversed can have at most 1 more digit than forward\n // Test for even palindromes, forward and reversed identical,\n // or odd palindromes, reversed adds 1 extra digit\n return forward == reversed || forward == reversed / 10;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T15:22:45.770",
"Id": "7534",
"ParentId": "7502",
"Score": "3"
}
},
{
"body": "<p>I do not do C# but I can offer another way of approaching the problem:</p>\n\n<p>As our range of numbers is \\$[100\\cdot100, 999\\cdot999] = [10000, 998001]\\$, assume a palindromic number on the form \\$abccba\\$. </p>\n\n<p>The largest \\$abccba < 998001\\$ is \\$k = abccba = 997799\\$. We need to determine if \\$k\\$ can be written as the product of two 3-digit numbers. Using a prime table (or generate one with a sieve at program start) see if any prime number \\$p\\$ where \\$\\min\\left(\\frac{k}{100}, 999\\right) \\lt p\\le k\\$ evenly divides \\$k\\$. </p>\n\n<p>If you can find such a prime then we know that \\$\\frac{k}{p} \\lt 100 \\$ and any remaining factors are too small or that \\$p \\gt 999\\$ and we have a factor that is too large. So we can discard \\$k\\$ and decrement \\$c\\$ by one to form the next smaller palindrome, eg. \\$k=996699\\$, and keep trying smaller palindromes.</p>\n\n<p>If you reach \\$p\\lt \\min\\left(\\frac{k}{100}, 999\\right) \\$ without finding any prime that evenly divides \\$k\\$ we need to convince ourselves that the remaining factors can be multiplied into two factors so that both factors are three digits.</p>\n\n<p>There are a few ways to convince ourselves of the above. One way is trial division by simply trying all divisors \\$d\\$ such that \\$100\\le d \\le \\max\\left(\\frac{k}{100}, 999\\right)\\$ and checking what the other factor is. </p>\n\n<p>Another more elegant way is to use the fact that we know that there is no prime factor larger than \\$p\\le\\min\\left(\\frac{k}{100}, 999\\right)\\$ and find the largest prime factor \\$p_{max}\\le\\min\\left(\\frac{k}{100}, 999\\right)\\$ and let \\$r_i = \\frac{k}{p_{max}}\\$.</p>\n\n<p>Let the prime factors of \\$r_i\\$ be \\$p_i\\$ and let \\$Q=\\prod_{\\forall i:p_i>\\frac{999}{p_{max}}}p_i\\$. At this point you have the largest prime factor of \\$k\\$ as \\$p_{max}\\$ and all prime factors of \\$r_i=\\frac{k}{p_{max}}\\$ that are too big to be together with \\$p_{max}\\$ multiplied together as \\$Q\\$. </p>\n\n<p>Now, factor \\$\\frac{r_i}{Q}\\$ into primes \\$P_k\\$. Each of the \\$P_k\\$ primes has to be multiplied into either \\$Q\\$ or \\$p_{max}\\$. Iteratively try all combinations (and exit early for impossible branches) until you find one that is satisfactory or retry next smallest palindrome if no combination was found.</p>\n\n<p><em>Note: This may well be slower than trial multiplication but it's another way to approach the problem and it may give birth to other ideas.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-16T13:42:09.420",
"Id": "151509",
"Score": "1",
"body": "Wow. I lost you before the middle, but this is worth up-voting just for the formatting!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T17:08:49.340",
"Id": "55353",
"ParentId": "7502",
"Score": "12"
}
},
{
"body": "<p>I am kind of thinking like SteveB</p>\n\n<p>I think that you should shorten up your code a little bit and make it straight to the point</p>\n\n<pre><code> static void Main(string[] args)\n {\n long result = 0;\n\n for (int i = 100; i < 1000; i++)\n {\n for (int k = 100; k < 1000; k++)\n {\n if (IsPalindrome(i * k))\n if ((i * k) > result)\n result = i * k;\n }\n }\n\n Console.WriteLine(result);\n }\n</code></pre>\n\n<p>could become this</p>\n\n<pre><code>static void Main(string[] args)\n{\n long result = 0;\n\n for (int i = 100; i < 1000; i++)\n {\n for (int k = 100; k < 1000; k++)\n {\n int product = i * k;\n if (IsPalindrome(product) && product > result)\n { \n result = product;\n }\n }\n }\n Console.WriteLine(result);\n}\n</code></pre>\n\n<p>And then I would turn that into a function so that you are not doing all this work in the Main Method</p>\n\n<pre><code>public int largestPalindrome(int smallNumber, int largeNumber)\n{\n int result = 0;\n\n for (int i = smallNumber; i < largeNumber; i++)\n {\n for (int k = smallNumber; k < largeNumber; k++)\n {\n int product = i * k;\n if (IsPalindrome(product) && product > result)\n {\n result = product;\n }\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Then you just call this in your Main Method</p>\n\n<pre><code>static void Main(string[] args)\n{\n int bigPalindrome = largestPalindrome(100,1000);\n Console.WriteLine(bigPalindrome.ToString());\n}\n</code></pre>\n\n<p>I changed everything to <code>int</code> type because with a max of <code>1000*1000</code> you won't break <code>2,147,483,647</code> and because you aren't going negative then you could actually use an unsigned integer and double the result size. </p>\n\n<p>for this simple exercise you only need an integer.</p>\n\n<hr>\n\n<p>you can use the functions without adding scope classifiers as long as they are in the same class</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-07T15:07:15.857",
"Id": "56350",
"ParentId": "7502",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7512",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T22:06:28.743",
"Id": "7502",
"Score": "9",
"Tags": [
"c#",
"programming-challenge",
"palindrome"
],
"Title": "Determining numeric palindromes"
}
|
7502
|
<p>I've tried making a payment system for an <a href="http://api.payson.se/" rel="nofollow">API called Payson</a>, which is a European company similar to PayPal.</p>
<p>I get the right response when I press the button so it seems to work, and I wonder if you can look at my code to see if it looks OK. I didn't test the part receive but the part send i.e. the first part I've testet and it appears to work:</p>
<pre><code>class PaysonHandler(webapp2.RequestHandler):
def get(self):
"""
............Returns a simple HTML form for Payson
........"""
logging.info('in payson')
SellerEmail = 'niklas...@gmail.com'
Cost = 250
ExtraCost=0
GuaranteeOffered=2
OkUrl = self.request.host+"/payson_okurl" # TO DO
Key = '319033-6152-402-b95a-37430de6b6'
text = SellerEmail + ':' + str(Cost) + ':' + str(ExtraCost) + ':' + OkUrl + ':' + str(GuaranteeOffered) + Key
logging.info('mdtext5: '+text)
m = hashlib.md5()
Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest()
BuyerEmail = 'niklas@.....se'
AgentID = 11366
path = os.path.join(os.path.dirname(__file__), 'templates',
'payson.html')
self.response.out.write(template.render(path, {
'SellerEmail':SellerEmail, 'Cost':Cost, 'Cost':Cost, 'AgentID':AgentID,
'ExtraCost':ExtraCost, 'GuaranteeOffered':GuaranteeOffered, 'OkUrl':OkUrl, 'Key':Key, 'Generated_MD5_Hash_Value':Generated_MD5_Hash_Value, 'BuyerEmail':BuyerEmail, }))
class PaysonReceiveHandler(webapp2.RequestHandler):
def get(self):
"""
............Receives Payson messages. Not tested
........"""
logging.info('in payson')
SellerEmail = 'niklas....@gmail.com'
Cost = 10
ExtraCost=0
GuaranteeOffered=2
OkUrl = self.request.host+'/payson_okurl' # TO DO
text = SellerEmail + ':' + str(Cost) + ':' + str(ExtraCost) + ':' + OkUrl + ':' + str(GuaranteeOffered) + Key
logging.info('mdtext5: '+text)
m = hashlib.md5()
Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest()
AgentID = 11366
strYourSecretKey = "3190fb33-6152-4052-b95a-379b430de6b6";
strOkURL = self.request.GET.get('OkURL')
strRefNr = self.request.GET.get('RefNr')
strPaysonRef = self.request.GET.get('Paysonref')
strTestMD5String = strOkURL + strPaysonRef + strYourSecretKey
strMD5Hash = hashlib.md5(strTestMD5String).hexdigest()
logging.info('testing MD5 value')
if strMD5Hash == self.request.GET.get('MD5'):
logging.info('Korrekt anrop från Payson')
logging.info('Rätt!')
logging.info('OkUrl: ') + strOkURL
logging.info('RefNr: ') + strRefNr
logging.info('PaysonRef: ') + strPaysonRef
else:
#Felaktigt anrop från någon annan.
logging.info("Felaktig MD5-summa!")
</code></pre>
|
[] |
[
{
"body": "<p>First of all, please make sure that your indentation is correct, especially when posting Python code. Also, take a look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>. You are violating it in at least the following places:</p>\n\n<ul>\n<li>You have tabs, not spaces</li>\n<li>Comments should be in English</li>\n<li>It is apparently not directly against PEP 8, but giving locals CapsWords names makes the code harder to understand, in my opinion (especially seeing as SE highlights them a different colour).</li>\n</ul>\n\n<p>You also seem to have an awful lot of duplicate code. Try to factor common operations (such as setting up all those members) into separate functions.</p>\n\n<p>Speaking of which, your functions aren't particularly clear. Why does a method called <code>get</code> not return anything? What is it supposed to get?</p>\n\n<p>You've got plenty of hard-coded values in there. I hope that <code>strYourSecretKey</code> is a placeholder value; the other ones should be passed in as parameters. Could you make it determine the agent ID based on the email? As things are, it seems like this is prone to incorrect combinations of input if anything is changed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:09:20.870",
"Id": "12106",
"Score": "1",
"body": "Where does PEP 8 suggest commenting in English?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T21:08:21.203",
"Id": "12131",
"Score": "1",
"body": "@WinstonEwert: Section Comments, \"Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don't speak your language.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T23:22:47.633",
"Id": "12744",
"Score": "0",
"body": "Many thanks for the contructive criticism. I'm updating the question with a more developed part of the code if you feel like continuing reviewing the same use case (use case is paying to my web shop.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T23:36:40.773",
"Id": "12766",
"Score": "2",
"body": "@NickRosencrantz: Feel free to start a new question for the update. Maybe more people will answer an unanswered new question than an answered (and updated) one."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T18:32:19.633",
"Id": "7681",
"ParentId": "7503",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7681",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T23:55:59.920",
"Id": "7503",
"Score": "3",
"Tags": [
"python",
"finance"
],
"Title": "Payment system for a web shop"
}
|
7503
|
<p>I am relearning C so if you could point obvious faults in this solution to <a href="http://news.ycombinator.com/item?id=3429466" rel="noreferrer">this problem</a> I'd greatly appreciate such comments. Please note that I'm using GCC extensions to use larger than 32 bit numbers. Most importantly I want to be aware of the quality of memory management in particular.</p>
<p><a href="http://news.ycombinator.com/item?id=3429466" rel="noreferrer">http://news.ycombinator.com/item?id=3429466</a></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int64_t* next_pascal_row(int64_t* previous_row, int64_t previous_size)
{
int64_t i;
int64_t* retval;
retval = (int64_t*)malloc(sizeof(int64_t)*(previous_size+1));
for (i=0;i<previous_size+1;i++) {
if (i==0 || i == previous_size) {
retval[i] = 1;
} else {
retval[i] = previous_row[i-1] + previous_row[i];
}
}
return retval;
}
void print_row(int64_t* row, int64_t size)
{
int64_t i;
for(i = 0; i < size; i++) {
printf("%lld ",row[i]);
}
printf("\n");
}
int main()
{
int64_t* first_row;
int64_t* previous_row;
int64_t* next_row;
int64_t i,size;
first_row = (int64_t*)malloc(sizeof(int64_t));
first_row[0] = 1;
size = 1;
print_row(first_row,size);
previous_row = first_row;
for(i = 0; i<31;i++) {
next_row = next_pascal_row(previous_row,size);
size++;
print_row(next_row,size);
free(previous_row);
previous_row = next_row;
}
free(next_row);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks pretty good to me. If I were doing this for an interview question, I would take on the challenge of implementing it recursively. Here are some minor changes I would make:</p>\n\n<ol>\n<li><p>You are hard-coding your for loop to 31 iterations. That ought to be a <code>const uint32_t num_iterations = 31;</code> at the top of your code. That makes it more clear to future users what to change if they want a different number of iterations.</p></li>\n<li><p>You are using <code>int64_t</code>. These are all going to be positive numbers, so <code>uint64_t</code> is more appropriate.</p></li>\n<li><p>Your variables <code>i</code> and <code>size</code> are <code>int64_t</code>. But your values are going to overflow 64-bits well before the line they are on gets that big. I'm guessing that <code>uint32_t</code> is enough.</p></li>\n<li><p>In regards to the memory management, all of the allocing and freeing is expensive and slow. If you wanted to minimize that, you should alloc 2 rows of max length up front and then ping-pong them as previous/next rows.</p></li>\n<li><p>In your <code>next_pascal_row</code> routine, you're using an array pointer called <code>retval</code>. I see that name way overused. It would be better called <code>this_row</code> or <code>next_row</code>.</p></li>\n<li><p>There is no need for a <code>first_row</code> pointer. Just use the <code>previous_row</code> pointer in initialization.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T16:25:28.957",
"Id": "11824",
"Score": "0",
"body": "And on top of that, I should probably check the return value of `malloc()` for NULLness. As insightful as Paul's suggestions on reducing the algorithmic complexity are, I'm still choosing this answer for pointing out my failures to adhere to good C coding standards."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T03:37:35.577",
"Id": "7516",
"ParentId": "7504",
"Score": "6"
}
},
{
"body": "<p>Rows of Pascal's triangle are palindromes, so if you add a count-down loop to print_row, you can get by with about half the calculations and half the memory.</p>\n\n<p>Allocating 2 max length buffers and swapping re: @Luke is a good idea.\nBut taking it one step further, you might get better memory cache performance if you interleaved the elements of the two current rows within a single allocated buffer. So, incrementing by 2 everywhere, you'd calculate something like</p>\n\n<pre><code> row[i] = row[i-1] + row[i+1];\n</code></pre>\n\n<p>except to use that exact formula, you'd have to keep your \"center\" values rather than your edge values aligned at the same index -- like you would if you were drawing the triangle on paper. That's easier to do if you adopt the half-row optimization -- your \"center\" values can always be placed at the end or at the start of the vector, depending on whether you want to calculate the left half of the triangle growing backward/left or the right half of the triangle, growing forward/right.</p>\n\n<p>OR I suppose you could get the same kind of interleaving and locality of reference with code that is much closer to your current code just by solely addressing even-indexed elements, incrementing by 2 and using </p>\n\n<pre><code> this_row[i] = prev_row[i-2] + prev_row[i];\n</code></pre>\n\n<p>where this_row and prev_row swap values between row pointers that were initially set to be out of phase with each other:</p>\n\n<pre><code> even_row = malloc(...); /* enough for two rows */\n odd_row = even_row+1; /* even-indexed entries are now interleaved */\n</code></pre>\n\n<p>At some scales, you might even get better memory performance by calculating every other row in reverse order so you are initially operating on the same cached memory pages where you left off for the prior row.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T05:57:41.880",
"Id": "7518",
"ParentId": "7504",
"Score": "4"
}
},
{
"body": "<p>I don't know if your solution used memory allocation intentionally to practice that but if not, there is a much simpler solution to this problem. \nYou can print the Pascal triangle with a simple 2 for loops over a 2D array.\nSure, it takes 2 times the memory it actually needs but it will run faster and be less error prone, which is considered 'better' programming. (no risk for memory leakage or dangling pointers).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-31T08:36:34.360",
"Id": "231781",
"Score": "0",
"body": "Hi, welcome to Code Review. Your answer came through the First Post review queue, but your answer does not review the code, it just provides a different solution. This is not a review, but, if you show how your code is different, and why your code is better, it will improve this answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-31T08:59:50.427",
"Id": "231795",
"Score": "0",
"body": "@Tunaki I don't think this isn't a review. It passes all the points in [this meta](http://meta.codereview.stackexchange.com/a/5409/64958) and actually explains why the proposed approach is better (although the reasons are controversial)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-31T09:05:49.363",
"Id": "231798",
"Score": "0",
"body": "Thank you @Tunaki for your comment. I will take it to accunt the next time I post an answer. Code snippet is a little difficult (or time consuming) through the android app but I will try to edit this when I get home."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-31T07:58:57.530",
"Id": "124334",
"ParentId": "7504",
"Score": "1"
}
},
{
"body": "<p><code>int64_t</code> is not a GCC extension; it comes from <code><stdint.h></code> (which you should <code>#include</code> to use).</p>\n\n<p>All the values in a Pascal triangle are positive by definition, so you can fit in one extra bit, and calculate one further row before overflow, by using <code>uint64_t</code> instead of the signed <code>int64_t</code>.</p>\n\n<p>There's no need to typecast the result of <code>malloc()</code> in C. It's an old and quirky tradition from 90s' language called \"C/C++\", but it doesn't fit in either proper C (because in C, <code>void *</code> is compatible with other pointer types) nor proper C++ (because in C++, you'd use <code>new int[...]</code> instead of <code>malloc(...)</code>.)</p>\n\n<p>I would suggest using <code>for (...; i <= previous_size; ...)</code> instead of <code>i < previous_size + 1</code>. One less operation makes the intent slightly easier for the human to read, and a loop to <code>previous_size</code> with <code>previous_size</code> included makes sense in the context.</p>\n\n<p>I would take assigning the border values out of the loop, like this:</p>\n\n<pre><code>retval[0] = 1;\nfor (i = 1; i < previous_size; i++)\n retval[i] = previous_row[i - 1] + previous_row[i];\nretval[previous_size] = 1;\n</code></pre>\n\n<p>Again, it reduces the number of moving parts, and makes the intent easier for human reader to track.</p>\n\n<p>When iterating over each row, it's a bit of an overkill to use <code>int64_t</code> as the index. It doesn't exactly hurt (unless profiler tells you otherwise), but the middle numbers of the Pascal triangle grow very fast, and your signed 64-bit cells oveflow on the row with 68 cells on it, long before an ordinary <code>int</code> would run out of bits to index it. You can get to 69 if you use unsigned 64-bit cells.</p>\n\n<p>Your main loop is a bit clumsy. You only need two pointers to rows rather than three, I would roll the loop a bit so that there's only one call to <code>print_row()</code>, and <code>i</code>th row is necessarily <code>i</code> cells long, so I would write it roughly like this instead:</p>\n\n<pre><code>int64_t *current_row;\nint i; /* row counter and length of current_row */\n\ncurrent_row = malloc(sizeof(int64_t));\ncurrent_row[0] = 1;\n\nfor (i = 1; i <= 32; i++) {\n int64_t *next_row;\n print_row(current_row, i);\n next_row = next_pascal_row(current_row);\n free(current_row);\n current_row = next_row;\n}\n</code></pre>\n\n<p>(You may, of course, disagree about combining <code>i</code> and <code>size</code>. It doesn't necessarily make sense in other potential similar contexts; it's just a property of the Pascal triangle.)</p>\n\n<p>Because of the way C handles pointer variable declarations, I believe it makes more sense to place the star next to the variable's name, as in <code>char *foo;</code>, rather than next to the type, as in <code>char* foo;</code>. Even if you never declare more than one variable in a single declaration, it feels to me that this fits the spirit of C better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-03T14:19:48.457",
"Id": "366939",
"Score": "0",
"body": "Given that an exactly-64-bits type isn't required, you ought to recommend `uint_fast64_t`, or perhaps `uint_least64_t` (both of which `<stdint.h>` must provide, unlike `uint64_t`). `uintmax_t` would be another good choice, if the number of iterations can be made to match (e.g. using `sizeof (uintmax_t) * CHAR_BIT`)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-02T00:51:23.867",
"Id": "191037",
"ParentId": "7504",
"Score": "5"
}
},
{
"body": "<h2>Fix the compiler warnings</h2>\n<p>I get the following two warnings (after adding the necessary include of <code><stdint.h></code>):</p>\n<pre class=\"lang-none prettyprint-override\"><code>7504.c: In function ‘next_pascal_row’:\n7504.c:9:44: warning: conversion to ‘long unsigned int’ from ‘int64_t’ {aka ‘long int’} may change the sign of the result [-Wsign-conversion]\n retval = (int64_t*)malloc(sizeof(int64_t)*(previous_size+1));\n ^\n7504.c: In function ‘print_row’:\n7504.c:24:16: warning: format ‘%lld’ expects argument of type ‘long long int’, but argument 2 has type ‘int64_t’ {aka ‘long int’} [-Wformat=]\n printf("%lld ",row[i]);\n ~~~^ ~~~~~~\n %ld\n</code></pre>\n<p>The first is best fixed by using an unsigned type such as <code>size_t</code> for <code>previous_size</code>.</p>\n<p>To fix the second, we can use one of the format macros in <code><inttypes.h></code>:</p>\n<pre><code> printf("%"PRId64" ",row[i]);\n</code></pre>\n<h2>Choose your element type</h2>\n<p>Entries will never be negative, so we can use an unsigned type, such as <code>uint_least64_t</code>. Even better, we can use a typedef so that it's clear where we're using this for the values in our triangle.</p>\n<h2>Always check your allocations succeed</h2>\n<p>When you use <code>malloc()</code> and family, you <em>must</em> check whether the returned pointer is null before using it. Also, there's no need to cast the return value (and doing so can sometimes mask errors you'll want to know about).</p>\n<h2>Don't allocate on every iteration</h2>\n<p>If you know in advance how many iterations you'll perform (as you do here), you can allocate two buffers big enough to hold all the values (i.e. one more than the iteration count), and swap between them at each iteration.</p>\n<p>This change reduces allocations noticeably, from</p>\n<pre class=\"lang-none prettyprint-override\"><code>total heap usage: 33 allocs, 33 frees, 5,248 bytes allocated\n</code></pre>\n<p>to</p>\n<pre class=\"lang-none prettyprint-override\"><code>total heap usage: 3 allocs, 3 frees, 1,536 bytes allocated\n</code></pre>\n<h2>Use <code>const</code> when reading</h2>\n<p>In <code>next_pascal_row</code>, we only read from <code>previous_row</code>, so we can pass it as a pointer to <code>const</code> numbers. Similarly, we can pass pointer-to-const into <code>print_row()</code>.</p>\n<h2>Avoid testing for first and last in the loop</h2>\n<p>We're in control of the loop, so if we go from the second to the penultimate element, we can fill in the first and last values outwith the loop.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <inttypes.h>\n#include <limits.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n\ntypedef uintmax_t number;\n\nvoid next_pascal_row(number *current,\n const number *previous, size_t previous_size)\n{\n current[0] = 1;\n for (size_t i = 1; i < previous_size; ++i) {\n current[i] = previous[i-1] + previous[i];\n }\n current[previous_size] = 1;\n}\n\nvoid print_row(const number *row, size_t size)\n{\n for (size_t i = 0; i < size; ++i) {\n printf("%"PRId64" ", row[i]);\n }\n puts("");\n}\n\nint main()\n{\n /* Estimate how many iterations we can have - conservatively\n assume that we double the middle value each round. */\n static const size_t iterations = sizeof (number) * CHAR_BIT;\n\n number *current_row = malloc(sizeof *current_row * iterations);\n number *previous_row = malloc(sizeof *previous_row * iterations);\n if (!current_row || !previous_row) {\n /* malloc failed */\n return 1;\n }\n\n for (size_t i = 0; i < iterations; ++i) {\n next_pascal_row(current_row, previous_row, i);\n print_row(current_row, i+1);\n /* now swap rows */\n number *next_row = previous_row;\n previous_row = current_row;\n current_row = next_row;\n }\n\n free(current_row);\n free(previous_row);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-03T15:13:24.220",
"Id": "191173",
"ParentId": "7504",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:30:07.027",
"Id": "7504",
"Score": "6",
"Tags": [
"c"
],
"Title": "Pascal's triangle in C"
}
|
7504
|
<p>I'm attempting some Project Euler problems in an attempt to learn Python. While I can get the correct answer quite easily, my programs are quite slow. Project Euler, if doing it correctly, specifies that each program should run in <1 minute. Some of mine take 5-10 mins.</p>
<p><a href="http://projecteuler.net/problem=14" rel="nofollow">Here</a> is one example.</p>
<pre><code>x=1;
terms=0;
maxTerms=0;
maxTermsNum=0;
for x in range(1,1000000):
i=x;
while (i!=1):
terms+=1;
if (i%2==0):
i/=2
else:
i=3*i+1
if (terms>maxTerms):
maxTerms=terms;
maxTermsNum=x;
print(x);
terms=0;
print("Biggest one: is %s." %maxTermsNum)
</code></pre>
<p>It produces the correct answer, but it takes a long long time. How can I speed this up? This is also in 32-bit Windows.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:00:29.793",
"Id": "11773",
"Score": "4",
"body": "Yuck, it looks like you are trying to write C in python"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:02:12.117",
"Id": "11774",
"Score": "1",
"body": "use xrange instead of range"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:04:06.847",
"Id": "11775",
"Score": "0",
"body": "The easiest way would be to remove one zero in your range size :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:06:37.287",
"Id": "11776",
"Score": "2",
"body": "@TJD Since the OP is using the print function, they probably are using python 3 where range is fine. Regardless, the range is not the problem, it's the algorithm implementation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:08:07.373",
"Id": "11777",
"Score": "11",
"body": "When a project euler problem runs slowly, it is usually a matter of changing the approach to the problem, and the underlying algorithm, rather than optimizing a few lines of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:14:37.540",
"Id": "11778",
"Score": "0",
"body": "@wim Haha, I'm coming from a Java background so I'm used to writing in a certain way. What about this in particular is 'yuck'?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:15:04.077",
"Id": "11779",
"Score": "0",
"body": "@JarrodRoberson, sorry, I didn't know and I'll do that next time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:16:49.387",
"Id": "11780",
"Score": "0",
"body": "just looks unpythonic.. semicolons at the end of lines, no spacing between operators, too many assignments and increments. you can usually handle loops in a much cleaner way in python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:20:44.413",
"Id": "11781",
"Score": "1",
"body": "@user1092865 - Python does not require semi-colons (unless writing multiple statements on the same line, which is rarely necessary). Also, there is no need to put parentheses around conditionals in your `if` statements. More spacing would also make this look cleaner (`i = x` instead of `i=x`), although that is more opinion. Check out [Python's style guide](http://www.python.org/dev/peps/pep-0008/) for reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:23:41.497",
"Id": "11782",
"Score": "0",
"body": "@wim and F.J. thanks, the semicolons are a force of habit, the whole code is an inconsistent mess now that I look at it again. Thanks."
}
] |
[
{
"body": "<p>While many of the Project Euler problems <em>can</em> be solved by brute force, this often isn't the fastest way to do them. Usually there is some kind of algorithmic insight that you can apply that will make your solution faster. This kind of insight is independent of programming language - simply running your code through a hypothetical \"go-fast compiler\" still won't match the speed of the correct algorithm.</p>\n\n<p>In your case, here's a hint. Many of the sequences you calculate look the same as ones you've previously done. How could you use that information to speed up your algorithm?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:14:42.723",
"Id": "11785",
"Score": "0",
"body": "You win, take all the upvotes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:16:14.450",
"Id": "11786",
"Score": "0",
"body": "Hmm, looks like I'll have to come back and redo some of my programs. A few of them took longer to run than they did to write... thanks for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T16:52:03.853",
"Id": "11826",
"Score": "1",
"body": "Another thing worth noting is that most problems can be solved using mathematical concepts/theorems/tricks, which is the main point of the project."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:03:57.923",
"Id": "7507",
"ParentId": "7505",
"Score": "25"
}
},
{
"body": "<p>If you are under Python 2.x use xrange instead of range for loops.<a href=\"http://docs.python.org/library/functions.html#xrange\" rel=\"nofollow noreferrer\">[XRange Doc]</a><a href=\"https://stackoverflow.com/questions/135041/should-you-always-favor-xrange-over-range\">[Xrange vs range]</a></p>\n\n<p>A good optimization for big cases of this problem is to start mapping them to avoid recalculating every step. So only if it hits an unknown number it will either multiply or divide and continue. Have a look at the Collatz conjecture and its properties: <a href=\"http://en.wikipedia.org/wiki/Collatz_conjecture\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Collatz_conjecture</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:07:29.433",
"Id": "7508",
"ParentId": "7505",
"Score": "2"
}
},
{
"body": "<p>Maybe instead of a modulus use a binary shift and a subtraction to determine if i is even or odd. Also doing a binary shift once and assigning the value to i if it is even would be better than calculating the division twice.</p>\n\n<p>Also use a lookup table for previously traversed solutions to x:</p>\n\n<pre><code>x=1;\nterms=0;\nmaxTerms=0;\nmaxTermsNum=0;\nprevTerms = dict()\nfor x in range(1,1000000):\n i=int(x)\n while (i!=1):\n if i in prevTerms:\n terms += prevTerms[i]\n break\n terms+=1\n a = i >> 1\n b = i - (a << 1)\n if (b==0):\n i = a\n else:\n i=3*i+1\n if x not in prevTerms:\n prevTerms[x] = terms\n if (terms>maxTerms):\n maxTerms=terms\n maxTermsNum=x\n print(x)\n terms=0;\nprint(\"Biggest one: is %s.\" %maxTermsNum)\n</code></pre>\n\n<p>This runs in under 10 seconds.\nTested in 2.7 on a 2.8 Ghz Windows 7 with 6 cores (not that cores matter here) machine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:11:59.297",
"Id": "12342",
"Score": "0",
"body": "Just for the heck of it I ran this program in PyPy and it ran in 1-2 seconds rather than 4-5 seconds. So PyPy is another avenue to speed up Python programs that only run pure Python code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:12:57.557",
"Id": "7509",
"ParentId": "7505",
"Score": "1"
}
},
{
"body": "<p>There are many ways to speed up a program. I've found it really helps to profile it (see: <a href=\"http://docs.python.org/library/profile.html\" rel=\"nofollow\">http://docs.python.org/library/profile.html</a> for more information) so you can see which functions are using up the most time. From there, you can work on optimizing the steps that take up the most time. Another awesome resource is the MIT open courseware course on algorithms, which starts you off with a simple text-file comparison exercise which you modify in steps to increase its speed (see: <a href=\"http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/\" rel=\"nofollow\">http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/</a>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T00:18:47.520",
"Id": "7510",
"ParentId": "7505",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7507",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-05T23:58:22.827",
"Id": "7505",
"Score": "7",
"Tags": [
"python",
"performance",
"project-euler"
],
"Title": "Project Euler #14 - Longest Collatz sequence"
}
|
7505
|
<p>I just created a script on jQuery which loads my articles dynamically with an AJAX call if the user changes the page.</p>
<p>I added some cool effects like the articles move on the left, then the new ones appear in fade while a loading black screen cover the articles.</p>
<p>The thing is, I'm afraid my code is too heavy and not really well optimized. Could you give me your feedback about it? By the way, do you have any idea if Google is going to be able to read all my articles with that system?</p>
<pre><code>$(".pages li a").click(function(e){ // IF PAGE NUMBER IS CLICKED
e.preventDefault();
$(".pages li a").removeClass("active");
$(this).addClass("active");
//VARIABLES
var currentPage=currentPage;
var nextPage=$(this).attr("data-page");
var currentCategory="1";
//SHOW DYNAMIC LOADING WINDOW
$(".layerarticles").before("<div class='layerloading'><img src='images/ajax-loader.gif'></div>");
$(".layerloading").height($(".layerarticles").height());
$(".layerloading img").css("margin-top",$(".layerarticles").height()/2-16);
$(".layerloading").fadeIn("slow",function(){
//DATA LOAD
$.post("ajax/articles-request.php", { currentPage: currentPage, nextPage: nextPage },function(data){ //AJAX CALL
//WE KICK ALL OLD ARTICLES
$(".layerarticles").animate({"margin-left":"-=630px"},'slow','easeOutQuint',function(){
$(".layerarticles").css("height",$(".layerarticles").height());
$(".layerarticles article").remove();
$(".layerarticles").css("margin-left","0px");
//WE MAKE APPEAR THE OTHERS IN THE HTML
$.each(data, function(){
$(".layerarticles").append("<article style='display:none' id='"+this.iden+"'><header><h2>"+this.title+"</h2></header><img src='images/"+this.image+"'><p>"+this.chapeau+"</p></article>");
});
//WE SHOW THEM WITH FADE EFFECT
$('.layerarticles article:hidden:first').delay(100).fadeIn("fast",function(){
if($('.layerarticles article:hidden').length!=0){
$(this).next().delay(100).fadeIn("fast",arguments.callee);
}else{
//ONCE ALL ARTICLES APPEARED WE REMOVE THE LOADING
$(".layerloading").fadeOut("slow",function(){
$(".layerloading").remove();
});
}
});
});
}, "json");
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T02:43:33.997",
"Id": "11789",
"Score": "1",
"body": "I think you could improve by perhaps utilising chaining, and also wrapping it up as your own plugin so you can just go `$('div').myplugin()` but if it works and looks good then that's always a positive start, happy coding."
}
] |
[
{
"body": "<p>One big step to opimize your code is to cache your jQuery objects.</p>\n\n<pre><code>var $layer = $('#layer');\n</code></pre>\n\n<p>You can also chain your method calls</p>\n\n<pre><code>$layer.css({ height: '30px' }).fadeIn(300).append('<span>hi</span>');\n</code></pre>\n\n<p>Also, make use of context</p>\n\n<pre><code>var $layerLoading = $('.layerLoading');\n$layerLoading.fadeOut(\"slow\",function(){\n //$(\".layerloading\").remove();\n // instead do - this refers to the context which is '.layerloading' in this case\n $(this).remove(); \n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T02:58:35.427",
"Id": "11790",
"Score": "0",
"body": "Is using $(this) in this case a performance improvement over reusing the cached $layerLoading or is it more of a style preference? I tend to always repeat the cached jQuery element but shouldn't if it's a performance hit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T02:51:45.433",
"Id": "7514",
"ParentId": "7513",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T02:34:21.073",
"Id": "7513",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery"
],
"Title": "Loading articles dynamically on page change"
}
|
7513
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.