body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I am trying to implement an expression parser via the shunting yard algorithm about which I learnt here.</p>
<p>I am able to get the correct results for the cases I'm testing, but I think it would be better if someone experienced could go through it and verify it. Also, I plan to add more operators, such as '!' (factorial), sine, cosine, etc. Is there anything I should keep in mind before going forth with them?</p>
<pre><code>#include<cmath>
#include<string>
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
map <char,int> priority;
struct numstack
{
double n;
numstack *next;
}*numtop=0;
struct opstack
{
char ch;
opstack *next;
}*optop=0;
void pushNum(double n)
{
struct numstack *newnode=new numstack[sizeof(numstack)];
newnode->n=n;
newnode->next=0;
newnode->next=numtop;
numtop=newnode;
}
void pushOp(char ch)
{
struct opstack *newnode=new opstack[sizeof(opstack)];
newnode->ch=ch;
newnode->next=0;
newnode->next=optop;
optop=newnode;
}
double popNum()
{
struct numstack *node=numtop;
double n=numtop->n;
numtop=numtop->next;
delete node;
return n;
}
char popOp()
{
struct opstack *node=optop;
char ch=optop->ch;
optop=optop->next;
delete node;
return ch;
}
void display(numstack *head1,opstack *head2)
{
if(head1!=0)
{
while(head1!=0)
{
cout<<head1->n<<" ";
head1=head1->next;
}
cout<<endl;
}
if(head2!=0)
{
while(head2!=0)
{
cout<<head2->ch<<" ";
head2=head2->next;
}
cout<<endl;
}
}
bool Operator(char ch)
{
string operators="+-*/(^";
if(operators.find(ch)!=string::npos)
return true;
return false;
}
bool evaluate(char ch)
{
if(optop==0)
return false;
if(priority[ch]==-1)
return false;
cout<<"ch : "<<ch<<" optop : "<<optop->ch<<endl;
if(priority[ch]>priority[optop->ch])
return false;
return true;
}
void initialize()
{
priority['+']=2;
priority['-']=2;
priority['*']=3;
priority['/']=3;
priority['^']=4;
priority['(']=-1;
}
int main()
{
initialize();
double a,b;
char expr[1000];
cout<<"Enter expression to evaluate : \n\n"; //1+2-3*4+8-1
cin>>expr;
cout<<endl;
int len=strlen(expr);
for(int i=0;i<len;i++)
{
cout<<"character : "<<expr[i]<<endl;
if(expr[i]==')')
{
char ch=popOp();
while(ch!='(')
{
a=popNum();
b=popNum();
cout<<"a:"<<a<<" b:"<<b<<" op:"<<ch<<endl;
if(ch=='+')
pushNum(a+b);
else if(ch=='-')
pushNum(b-a);
else if(ch=='*')
pushNum(a*b);
else if(ch=='/')
pushNum(b/a);
ch=popOp();
}
}
else if(Operator(expr[i]))
{
if(evaluate(expr[i]))
{
a=popNum();
b=popNum();
char ch=popOp();
cout<<"a:"<<a<<" b:"<<b<<" op:"<<ch<<endl;
if(ch=='+')
pushNum(a+b);
else if(ch=='-')
pushNum(b-a);
else if(ch=='*')
pushNum(a*b);
else if(ch=='/')
pushNum(b/a);
else if(ch=='^')
pushNum( pow((double)b,(double)a));
pushOp(expr[i]);
}
else
pushOp(expr[i]);
}
else
{
string num;
for(int j=i;expr[j]>='0' && expr[j]<='9';j++)
num+=expr[j];
pushNum(atoi(num.c_str()));
}
display(numtop,0);
display(0,optop);
}
while(optop!=0)
{
char ch=popOp();
a=popNum();
b=popNum();
cout<<"a:"<<a<<" b:"<<b<<" op:"<<ch<<endl;
if(ch=='+')
pushNum(a+b);
else if(ch=='-')
pushNum(b-a);
else if(ch=='*')
pushNum(a*b);
else if(ch=='/')
pushNum(b/a);
else if(ch=='^')
pushNum(pow((double)b,(double)a));
display(numtop,0);
display(0,optop);
}
cout<<"result = "<<popNum()<<endl;
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Dont do this:</p>\n\n<pre><code>struct numstack\n{\n double n;\n numstack *next;\n}*numtop=0; // <---- WHAT\n // Type and variable declaration all crammed together..\n</code></pre>\n\n<p>Its not as if you need to save space so be clear.</p>\n\n<pre><code>struct Numstack\n{\n double n;\n numstack *next;\n};\nNumstack* numtop=nullptr; // USE nullptr over 0.\n</code></pre>\n\n<p>You though it was worth implementing your type specific singly linked list?</p>\n\n<pre><code>void pushNum(double n)\nvoid pushOp(char ch)\ndouble popNum()\nchar popOp()\n</code></pre>\n\n<p>It is not only a waste of time, but probably much less efficient than std::list (it uses pool allocations to prevent repeated requests to the runtime memory management system).</p>\n\n<p>Also did you really want a review on that?</p>\n\n<pre><code>void display(numstack *head1,opstack *head2)\n</code></pre>\n\n<p>Would be much clearer to write output operators for the two different types!</p>\n\n<pre><code>// As it is std::list can easily be printed:\nstd::copy(head1.begin(), head1.end(), std::ostream_iterator<double>(std::cout, \" \"));\nstd::cout << \"\\n\";\n</code></pre>\n\n<p>This object never changes and is only used for lookup.</p>\n\n<pre><code>string operators=\"+-*/(^\";\n\n// so make it const.\n// Also make it static so we only construct it once\n// the identifier `operators` is a bit close to the keyword for me.\nstatic string const operator = \"+-*/(^\";\n</code></pre>\n\n<p>Don't write <code>if statements</code> that return <code>true</code> or <code>false</code></p>\n\n<pre><code>if(operators.find(ch)!=string::npos)\n return true;\nreturn false;\n\n// easier to write and read\n\nreturn operators.find(ch)!=string::npos);\n</code></pre>\n\n<p>Don't use global variables.</p>\n\n<pre><code>map <char,int> priority;\nbool evaluate(char ch) { /* uses priority */}\n</code></pre>\n\n<p>It is also immutable so you should not have used <code>Initialize()</code> to set it up. Should have used the maps constructor. But it would have been even better if you wrapped this functionality into an class.</p>\n\n<p>What happens if I type a 200 character expression?</p>\n\n<pre><code>char expr[1000];\ncout<<\"Enter expression to evaluate : \\n\\n\"; //1+2-3*4+8-1\ncin>>expr;\n</code></pre>\n\n<p>Prefer to use a ccontainer that automatically expands:</p>\n\n<pre><code>std::string expr;\nstd::cout<<\"Enter expression to evaluate : \\n\\n\"; //1+2-3*4+8-1\nstd::getline(std::cin, expr);\n</code></pre>\n\n<p>Also <code>operator>></code> is probably not the best to use for user intput. User input is line based while <code>operator>></code> is space based. It reads upto the first space and then stops. Users normally type a line at a time before expecting feedback.</p>\n\n<p>The main algorithm is too complicated to follow without more detailed comments. There should be a description of what is happening in there.</p>\n\n<p>This seems very hard way to read a number.</p>\n\n<pre><code> string num;\n for(int j=i;expr[j]>='0' && expr[j]<='9';j++)\n num+=expr[j];\n pushNum(atoi(num.c_str()));\n\n // Why not use the built in stream operators.\n\n double number;\n std::stringstream exprStr(expr);\n\n expr >> number;\n</code></pre>\n\n<p>Don't use C style casts.</p>\n\n<pre><code>pushNum(pow((double)b,(double)a));\n</code></pre>\n\n<p>C++ has four explicit cast operators use those:</p>\n\n<pre><code>static_cast // Most often used.\ndynamic_cast // If used means you have not correctly implemented the appropriate virtual method.\nreinterpret_cast // If used you should be casting to void* or char* for use with C library.\nconst_cast // If used means you are doing something wrong probably.\n</code></pre>\n\n<p>But you need none of those.<br>\nSince <code>a</code> and <code>b</code> are already double.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T16:28:12.320",
"Id": "73413",
"Score": "0",
"body": "You can solve must of your issues easily. 1) Don't use globals and start wrapping things inside a class. 2) Write stream operator `operator<<` to do the printing. 3) Use standard types that have already been built."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T16:50:28.277",
"Id": "73414",
"Score": "0",
"body": "Is there a particular reason for wrapping up things in a class? Regarding the rest i shall do so thank you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:05:34.837",
"Id": "73419",
"Score": "0",
"body": "Yes. Wrapping things in classes makes the code more readable and maintainable. You are putting all the code the interacts with the data in the same place and protecting the data from mutation from an unexpected source. Thus making it wasier to maintain your invariants. You should avoid global mutable state as function with side affects are hard to test debug and validate."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:57:33.517",
"Id": "42549",
"ParentId": "42448",
"Score": "5"
}
},
{
"body": "<p>Step 1: </p>\n\n<p>Wrap your global state into classes.</p>\n\n<pre><code>class Stack\n{\n std::list<double> numtop;\n std::list<char> optop;\n public:\n\n friend std::ostream& operator<<(std::ostream& s, Stack const& data)\n {\n std::copy(data.numtop.begin(), data.numtop.end(), std::ostream_iterator<double>(s, \" \"));\n s << \"\\n\";\n std::copy(data.optop.begin(), data.optop.end(), std::ostream_iterator<char>(s, \" \"));\n s << \"\\n\";\n return s;\n }\n void push(double v) {numtop.push_front(v);}\n void push(char v) {optop.push_front(v);}\n\n double popNum() {double result = numtop.front();numtop.pop_front();return result;}\n char popOp() {char result = optop.front();optop.pop_front();return result;}\n\n char peekOp() {return optop.front();}\n\n bool empty() const{return optop.empty();}\n};\n\nclass Priority\n{\n std::map <char,int> priority;\n Stack& stack;\n public:\n Priority(Stack& s)\n : stack(s)\n {\n priority['+']=2;\n priority['-']=2;\n priority['*']=3;\n priority['/']=3;\n priority['^']=4;\n priority['(']=-1;\n }\n bool evaluate(char ch)\n {\n if(stack.empty())\n return false;\n if(priority[ch]==-1)\n return false;\n std::cout<<\"ch : \"<<ch<<\" optop : \"<<stack.peekOp()<<std::endl;\n if(priority[ch]>priority[stack.peekOp()])\n return false;\n return true;\n }\n bool Operator(char ch)\n {\n static std::string const operators=\"+-*/(^\";\n return (operators.find(ch)!=std::string::npos);\n }\n};\n</code></pre>\n\n<p>Now use like this:</p>\n\n<pre><code>int main()\n{\n Stack stack;\n Priority priority(stack);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:06:52.920",
"Id": "42611",
"ParentId": "42448",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42549",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:19:49.187",
"Id": "42448",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"math-expression-eval"
],
"Title": "Expression parser using the shunting yard algorithm"
} | 42448 |
<p>I have written this simple program that is a basically a maths test. I would like to know is there any areas I can improve on and if I have any bad habits that would be useful to break now. I realise I could have written this in the main class, but I was trying to practice implementing other classes, so I tried to use a few classes.</p>
<p>Also, are there good practices that I am using that I should try to keep?</p>
<p>P.S. I don't usually use the comments I just added them to tell you what my intention is for a particular piece of code.</p>
<pre><code>import java.util.Scanner;
import java.util.Random;
class Machine {
int num1, num2, ans, att;
int score = 0;
Random rand = new Random();
Scanner in = new Scanner(System.in);
public void sumGenerator(){
num1 = rand.nextInt(10);
num2 = rand.nextInt(10);
ans = num1 + num2;
System.out.println(num1 + " + " + num2 );
}//sumGenerator Method
public void answerGetter_score(){
att = in.nextInt();
if(att == ans){
score = score + 1;
System.out.println("Correct");
System.out.println("Score is currently: " + score + "/5");
}else{
score = score - 1;
System.out.println("Incorrect");
System.out.println("Score is currently: " + score + "/5");
}//else
}//answer Getter method
}//machine class
public class calcu {
public static void main(String[] args) {
Machine machine1 = new Machine();
System.out.println("***Welcome to addition Math test***");
for(int i=5; i>0; i--){
machine1.sumGenerator();
machine1.answerGetter_score();
}
System.out.println("Thanks for taking the test.");
}//main method
</code></pre>
| [] | [
{
"body": "<p><strong>Member Names</strong> - don't use too short names, <code>answer</code> is better than <code>ans</code>; what exactly is <code>att</code>?</p>\n\n<p><strong>Method Names</strong> - method names should be verbs describing <em>what</em> the method does - <code>generateNewSum()</code> is better than <code>sumGenerator()</code>. Also use Java method conventions - CamelCase (no underscore in method names - <code>answerGetterScore()</code>, see below for more about this method)</p>\n\n<p><strong>Class Names</strong> - follow Java Class naming conventions - they should start with a capital letter, and don't be lazy - write the whole word - <code>Calculator</code>. The name of the class should denote its part in the program - <code>Machine</code> tells you nothing about the class, perhaps something more in the lines of <code>SumExercise</code>?</p>\n\n<p><strong>Responsibilities</strong> - object oriented programming is all about division of responsibility - one object is responsible for interacting with the user, another represents an item in a list, etc.</p>\n\n<p>This means that a single class should be responsible for interacting with the user - getting input, printing out results. A single class should be responsible for managing the exercise - how many iterations there are, how you calculate score...</p>\n\n<p>In your code, for example, the number of iterations (<code>5</code>) appears both in the main class and the <code>Machine</code> class - tomorrow you'll want to make it <code>10</code> iterations - you are bound to forget to change it inside the <code>Machine</code> class.</p>\n\n<p>Same goes for method names - remember <code>answerGetterScore()</code>? The name that came out is awkward, because it tries to convey that the method does at least two things which are apparently unrelated - see if the answer is correct, and calculate the score (actually it does three - it also requests the answer from the user). You should split the method to its parts - (1) get the answer from the user; (2) check if it is correct; (3) calculate the new score; (4) notify the user. I'll leave it to you to decide which of those methods should go to which class.</p>\n\n<p><strong>Comments</strong> - you said you added comments for our behalf, to show your intention, and sometimes comments are really needed (not too often though!), but these comments do not convey any information, they simply say where a block ends (<code>//else</code>). Indentation should do that. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:44:54.123",
"Id": "73086",
"Score": "1",
"body": "Thank you so much. This is exactly what I was looking for. I will look to improve on these areas as the videos I am learning from don't really specify these conventions. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:33:10.273",
"Id": "73102",
"Score": "0",
"body": "I've rolled back the edit you suggested. Whitespace is a matter to be reviewed, not silently changed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:53:03.753",
"Id": "42453",
"ParentId": "42449",
"Score": "9"
}
},
{
"body": "<p><strong>Scope</strong> - Objects and variables should be defined with the most restrictive scope possible, considering their use. Properties and methods that are only going to be used in the class they're defined in should be marked <code>private</code>. For instance, all of the properties you define for the class <code>Machine</code> should be <code>private</code>. Properties that are only used in a single method should be declared in that method. For instance, <code>num1</code>, <code>num2</code> and <code>att</code> can all have their declarations moved into the methods that use them. </p>\n\n<p>And a style point about scope. Although some people don't like it, <a href=\"https://stackoverflow.com/questions/725770/should-the-java-this-keyword-be-used-when-it-is-optional\">consider using the this keyword for all object properties</a>. For instance, you would write <code>this.ans</code> instead of just <code>ans</code>. Whoever reads your code will immediately see that <code>ans</code> is not a local variable. Although most IDEs will color your object properties differently from local variables, some places (like CodeReview) won't. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:48:39.340",
"Id": "73087",
"Score": "0",
"body": "Thank you I will take this advice on board. I only hope I don't develop more bad habits. Kind of makes me think about waiting until college to learn but I enjoy it so much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:20:18.383",
"Id": "73094",
"Score": "0",
"body": "@user3117051: http://codereview.stackexchange.com/q/31/7076"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:23:47.267",
"Id": "73098",
"Score": "1",
"body": "I agree with the first paragraph and disagree with the second. Use a modern IDE, Eclipse does it fairly well: \"Since modern IDEs colour code member fields, the unnecessary use of this is background noise to the intent you're trying to convey in the code.\" (Source: http://stackoverflow.com/a/725852/843804)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:29:24.070",
"Id": "73269",
"Score": "0",
"body": "Modern IDEs do it, but your code isn't always viewed in an IDE. The code user3117051 posted doesn't have such highlighting because Code Review doesn't understand code deeply enough to do that. It helps to add a `this` if you view your code anywhere else, and it doesn't feel like excessive noise, at least to me. It's a matter of personal preference, or better, whatever your organizations style guide says."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:19:08.570",
"Id": "42454",
"ParentId": "42449",
"Score": "5"
}
},
{
"body": "<p>Some notes which was not mentioned earlier:</p>\n\n<ol>\n<li>\n\n<pre><code>Machine machine1 = new Machine();\n</code></pre>\n\n<p>The variable name could be simply <code>machine</code>. I don't see any reason for the <code>1</code> postfix.</p></li>\n<li><p>I think the usual style for a for loop is the following and the most developer is more familiar with it than a countdown loop:</p>\n\n<pre><code>for (int i = 0; i < 5; i++) { ... }\n</code></pre>\n\n<p>Using a well-known pattern makes maintenance easier.</p></li>\n<li><p>I've found good practice to have a separate class for the <code>main</code> method as you did.</p></li>\n<li><p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>Having one <code>Random</code> instance and using it multiple times is good. (Initializing it every time could be slow and unnecessary.)</p></li>\n<li><p>Using <code>System.out.format</code> instead of <code>System.out.println</code> with long string concatenations is easier to read:</p>\n\n<pre><code>System.out.format(\"%d + %d\\n\", num1, num2);\n</code></pre></li>\n<li><p>I guess using ++ and -- is a little bit easier to read than</p>\n\n<pre><code>score = score + 1;\n</code></pre></li>\n<li><p>I agree with <em>@Uri Agassi</em>, you should separate the responsibilities. Aside from that you could move the last <code>System.out</code> after the if-else condition:</p>\n\n<pre><code>if (att == ans) {\n score = score + 1;\n System.out.println(\"Correct\");\n System.out.println(\"Score is currently: \" + score + \"/5\");\n} else {\n score = score - 1;\n System.out.println(\"Incorrect\");\n System.out.println(\"Score is currently: \" + score + \"/5\");\n}\n</code></pre>\n\n<p>It would remove some duplication:</p>\n\n<pre><code>if (att == ans) {\n score++;\n System.out.println(\"Correct\");\n} else {\n score--;\n System.out.println(\"Incorrect\");\n}\nSystem.out.println(\"Score is currently: \" + score + \"/5\");\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:17:54.583",
"Id": "42458",
"ParentId": "42449",
"Score": "5"
}
},
{
"body": "<h3>Naming and Problem Decomposition</h3>\n\n<ul>\n<li><strong>Class names should be nouns; method names should be verbs.</strong> If you have a method named as a noun like <code>sumGenerator()</code>, that's a red flag.</li>\n<li><strong>Each method should do one thing only; its name should reflect its purpose.</strong> If you have a method named <code>answerGetter_score()</code>, that's a red flag. Is it getting an answer <em>and</em> keeping score? It also breaks the standard <code>interCapsNaming()</code> convention.</li>\n<li><strong>Each class should do one thing only; its name should reflect its purpose.</strong> I have no idea what a <code>Machine</code> or a <code>calcu</code> is. The latter also breaks the standard capitalization convention.</li>\n<li><strong>Separate your input/output routines from the calculation routines.</strong> Forcing yourself to separate the two helps you come up with clean designs.</li>\n<li><strong>Keep your <code>main()</code> function minimal.</strong> The temptation to stuff a lot of functionality into <code>main()</code> leads to sloppy design.</li>\n<li><strong>Avoid hard-coding assumptions in more than one place.</strong> What if you want to change the length of the quiz? Currently, 5 is hard-coded in several places. It's easy to introduce a bug if someone fails to make the same change everywhere.</li>\n</ul>\n\n<p>For this problem, I think that there should be two classes: <code>SumGenerator</code> and <code>ArithmeticQuiz</code>. <code>SumGenerator</code> is responsible for making random addition questions. <code>ArithmeticQuiz</code> \"drives\" it.</p>\n\n<p>What if you want to change the quiz to do multiplication? Just swap out the <code>SumGenerator</code> for a <code>ProductGenerator</code>. To ease that transition, it would be helpful to define a <code>QuestionGenerator</code> interface.</p>\n\n<h3>Code Formatting (only because you asked about good habits)</h3>\n\n<p>Consistent indentation is very important for readability. Do that, and discard the noisy <code>//end</code> comments.</p>\n\n<p>Also, add some horizontal spacing around punctuation, such as comparison operators.</p>\n\n<p>The one-point penalty for an incorrect answer deserves a comment, since not everyone expects that behaviour.</p>\n\n<h3>Proposed Solution</h3>\n\n<p><strong>QuestionGenerator.java:</strong></p>\n\n<pre><code>interface QuestionGenerator {\n void next();\n String getQuestion();\n int getAnswer();\n}\n</code></pre>\n\n<p><strong>SumGenerator.java:</strong></p>\n\n<pre><code>import java.util.Random;\n\nclass SumGenerator implements QuestionGenerator {\n private int maxAddend, num1, num2, ans;\n private Random rand = new Random();\n\n public SumGenerator(int maxAddend) {\n this.maxAddend = maxAddend;\n this.next();\n }\n\n @Override\n public void next() {\n num1 = rand.nextInt(this.maxAddend + 1);\n num2 = rand.nextInt(this.maxAddend + 1);\n ans = num1 + num2;\n }\n\n @Override\n public String getQuestion() {\n return num1 + \" + \" + num2;\n }\n\n @Override\n public int getAnswer() {\n return ans;\n }\n}\n</code></pre>\n\n<p><strong>ArithmeticQuiz.java:</strong></p>\n\n<pre><code>import java.util.Scanner;\n\npublic class ArithmeticQuiz {\n private int length;\n private QuestionGenerator questions;\n\n public ArithmeticQuiz(int length, QuestionGenerator q) {\n this.length = length;\n this.questions = new SumGenerator();\n }\n\n public void run() {\n // Closing the Scanner after use is a good habit.\n // Automatically closing the Scanner using the\n // try-with-resources feature of Java 7 is even better.\n try (Scanner in = new Scanner(System.in)) {\n int score = 0; \n for (int i = this.length; i > 0; i--) {\n System.out.println(this.questions.getQuestion());\n int answer = in.nextInt();\n if (this.questions.getAnswer() == answer) {\n score++;\n System.out.println(\"Correct\");\n }else{\n score--; // Penalty for incorrect answer\n System.out.println(\"Incorrect\");\n }\n System.out.printf(\"Score is currently: %d/%d\\n\", score, this.length);\n this.questions.next();\n }\n }\n }\n\n public static void main(String[] args) {\n System.out.println(\"***Welcome to addition Math test***\");\n ArithmeticQuiz quiz = new ArithmeticQuiz(5, new SumGenerator(9));\n quiz.run();\n System.out.println(\"Thanks for taking the test.\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:22:00.377",
"Id": "42459",
"ParentId": "42449",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:21:31.753",
"Id": "42449",
"Score": "11",
"Tags": [
"java",
"quiz"
],
"Title": "Maths test program"
} | 42449 |
<p>This is a calculator I wrote for a student's project.</p>
<p>It still has a problem (one that I know of), where it can't handle inputs of the form <code>2*2*2</code>... (more than one <code>*</code> or <code>/</code> sign). The case <code>2*2</code> was solved in hackish ways.</p>
<p>I'd appreciate any remarks or advice on the code and possibly how to solve that problem.</p>
<p>Relevant inputs are using <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>(</code>, <code>)</code>, etc.</p>
<p>EDIT: I fixed the problems listed above.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void getInput(char * in) {
printf("> ");
fgets(in, 256, stdin);
}
int isLeftParantheses(char p) {
if (p == '(') return 1;
else return 0;
}
int isRightParantheses(char p) {
if (p == ')') return 1;
else return 0;
}
int isOperator(char p) {
if (p == '+' || p == '-' || p == '*' || p == '/') return p;
else return 0;
}
int performOperator(int a, int b, char p) {
switch(p) {
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/':
if (b == 0) { printf("Can't divide by 0, aborting...\n"); exit(1); }
return a/b;
}
return 0;
}
char isDigit(char p) {
if (p >= '0' && p <= '9') return 1;
else return 0;
}
int charToDigit(char p) {
if (p >= '0' && p <= '9') return p - '0';
else return 0;
}
int isNumber(char * p) {
while(*p) {
if (!isDigit(*p)) return 0;
p++;
}
return 1;
}
int len(char * p) {
return int(strlen(p));
}
int numOfOperands(char * p) {
int total = 0;
while(*p) {
if (isOperator(*p)) total++;
p++;
}
return total+1;
}
int isMDGRoup(char * p) {
while(*p) {
if (!isDigit(*p) && *p != '/' && *p != '*')
return 0;
p++;
}
return 1;
}
int getLeftOperand(char * p, char * l) {
// Grab the left operand in p, put it in l,
//and return the index where it ends.
int i = 0;
// Operand is part of multi-*/ group
if (isMDGRoup(p)) {
while(1) {
if (*p == '*' || *p == '/') break;
l[i++] = *p++;
}
return i;
}
// Operand is in parantheses
if(isLeftParantheses(*p)) {
int LeftParantheses = 1;
int RightParantheses= 0;
p++;
while(1) {
if (isLeftParantheses(*p)) LeftParantheses++;
if (isRightParantheses(*p)) RightParantheses++;
if (isRightParantheses(*p) && LeftParantheses == RightParantheses)
break;
l[i++] = *p++;
}
// while (!isRightParantheses(*p)) {
// l[i++] = *p++;
// }
l[i] = '\0';
return i+2;
}
// Operand is a number
while (1) {
if (!isDigit(*p)) break;
l[i++] = *p++;
}
l[i] = '\0';
return i;
}
int getOperator(char * p, int index, char * op) {
*op = p[index];
return index + 1;
}
int getRightOperand(char * p, char * l) {
// Grab the left operand in p, put it in l,
//and return the index where it ends.
while(*p && (isDigit(*p) || isOperator(*p) ||
isLeftParantheses(*p) || isRightParantheses(*p))) {
*l++ = *p++;
}
*l = '\0';
return 0;
}
int isEmpty(char * p) {
// Check if string/char is empty
if (len(p) == 0) return 1;
else return 0;
}
int calcExpression(char * p) {
// if p = #: return atoi(p)
//
// else:
// L = P.LeftSide
// O = P.Op
// R = P.RightSide
// return PerformOp(calcExpression(L), calcExpression(R), O)
// ACTUAL FUNCTION
// if p is a number, return it
if (isNumber(p)) return atoi(p);
// Get Left, Right and Op from p.
char leftOperand[256] = ""; char rightOperand[256]= "";
char op;
int leftOpIndex = getLeftOperand(p, leftOperand);
int operatorIndex = getOperator(p, leftOpIndex, &op);
int rightOpIndex = getRightOperand(p+operatorIndex, rightOperand);
printf("%s, %c, %s", leftOperand, op, rightOperand);
getchar();
if (isEmpty(rightOperand)) return calcExpression(leftOperand);
return performOperator(
calcExpression(leftOperand),
calcExpression(rightOperand),
op
);
}
int main()
{
char in[256];
while(1) {
// Read input from user
getInput(in);
if (strncmp(in, "quit", 4) == 0) break;
// Perform calculations
int result = calcExpression(in);
printf("%d\n", result);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T19:14:34.723",
"Id": "73075",
"Score": "0",
"body": "This codes doesn't compile for multiple reasons, so I am led to believe this code doesn't work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:03:02.773",
"Id": "73089",
"Score": "0",
"body": "What language is this? If true is defined do you have booleans? If so bool isEmpty(char * p){return len(p)== 0);}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:04:30.397",
"Id": "73090",
"Score": "3",
"body": "@syb0rg: `gcc` can't compile it, but it compiles with `g++`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:40:38.677",
"Id": "73103",
"Score": "0",
"body": "@palacsint: This is barely C++ code, but there must be some if it cannot compile with `gcc`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:03:18.077",
"Id": "73110",
"Score": "1",
"body": "Not sure I understand, works fine for me, along with the limitations specified above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:18:05.763",
"Id": "73115",
"Score": "2",
"body": "It's not clear if this is supposed to be C or C++. Could you make the language absolutely clear, and tell us your compiler setup (e.g. which compiler and what options you are using)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:24:50.667",
"Id": "73117",
"Score": "1",
"body": "Honestly, I don't know. Sorry. I intended for this to be C only, could you tell me what part is C++? Also, palacsint says he successfully compiled it using g++, so I assume that is what I'm using (Sublime Text 2). I'm sorry you can't run it for some reason, my question was mostly about the logic really. Thanks regardless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:44:33.267",
"Id": "73127",
"Score": "0",
"body": "@user2327670 Take a look [here](http://stackoverflow.com/q/861517/1937270) for issues compiling C code as C++ code. Also, if you do compile it with GCC (*not* G++) and compiler warnings, you should be able to fix it with a bit of effort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-26T15:51:15.880",
"Id": "213660",
"Score": "0",
"body": "Any idea on how this program could be modified to detect false input like --2 and calculate things like -2+2(returns 4 instead of 0), 2-2-2 (returns 0 instead of -2) ???"
}
] | [
{
"body": "<h1>Things you did well on:</h1>\n\n<ul>\n<li><p>Organization</p></li>\n<li><p>Use of comments</p></li>\n<li><p>Using <code>switch</code> statements instead of multiple <code>if-else</code>s.</p></li>\n</ul>\n\n<h1>Things that could be improved:</h1>\n\n<h3>Compilation</h3>\n\n<ul>\n<li><p>I couldn't compile this program with this method written the way it is.</p>\n\n<blockquote>\n<pre><code>int len(char * p) {\n return int(strlen(p));\n}\n</code></pre>\n</blockquote>\n\n<p>I'm going to assume that is due to the issues of you compiling it with <code>g++</code>, and me having a strict compiler. My compiler thinks that this code is trying to make some sort of function call instead of parsing the string length to an <code>int</code>. Put the parentheses around the <code>int</code> instead, and it will work just fine.</p>\n\n<pre><code>int len(char * p)\n{\n return (int) strlen(p);\n}\n</code></pre></li>\n</ul>\n\n<h3>Refactoring</h3>\n\n<ul>\n<li><p>You could simplify down some of your loops.</p>\n\n<blockquote>\n<pre><code>int isMDGRoup(char * p) {\n\n while(*p) {\n if (!isDigit(*p) && *p != '/' && *p != '*')\n return 0;\n p++;\n }\n return 1;\n}\n</code></pre>\n</blockquote>\n\n<p>Use a <code>for</code> loop here instead.</p>\n\n<pre><code>int isMDGRoup(char *p)\n{\n\n for(; *p; p++)\n {\n if (!isDigit(*p) && *p != '/' && *p != '*') return 0;\n }\n return 1;\n}\n</code></pre></li>\n</ul>\n\n<h3>Syntax</h3>\n\n<ul>\n<li><p>When you <code>return</code> variables that are performing operations on the same line as the <code>return</code>, surround them with parenthesis.</p>\n\n<pre><code>return (i+2);\n</code></pre></li>\n<li><p>You use some magic numbers.</p>\n\n<blockquote>\n<pre><code>char in[256];\n</code></pre>\n</blockquote>\n\n<p>I see you use the number 256 in some other places as well. Pull out that value into a <code>#define</code>d variable.</p>\n\n<pre><code>#define BUFLEN 256\n</code></pre></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\"><code>puts()</code></a> instead of <code>printf()</code> when you aren't formatting strings.</p></li>\n<li><p>Use a <code>default</code> in your <code>switch</code>.</p>\n\n<pre><code>default:\nputs(\"Error message.\");\nbreak;\n</code></pre></li>\n</ul>\n\n<h3>Error handling:</h3>\n\n<ul>\n<li><p>It is more common to <code>return 0</code> (or some error indicator) rather than to <code>exit(0)</code>. Both will call the registered <code>atexit</code> handlers and will cause program termination though. You have both spread throughout your code. Choose one to be consistent. Also, you should return different values for different errors, so you can pinpoint where something goes wrong in the future.</p></li>\n<li><p>Your program can't handle the input of non-whole numbers.</p>\n\n<pre><code>> 7.7*6\n7, ., 7*6\n7, *, 6\n0\n>\n</code></pre></li>\n<li><p>Your program can't handle malformed input.</p>\n\n<pre><code>> 7a*6\n7, a, *6\n, *, 6\n0\n>\n</code></pre></li>\n<li><p>Your program can't handle negative numbers properly</p>\n\n<pre><code>> -5+6\n, -, 5+6\n5, +, 6\n-11\n>\n</code></pre></li>\n<li><p>Your program can't handle whitespace.</p>\n\n<pre><code>> 5 * 6\n5, , *\n, *, \n0\n> \n</code></pre></li>\n<li><p>Your program doesn't handle no input very well.</p>\n\n<pre><code>> \n, \n, \n0\n> \n</code></pre></li>\n<li><p>Your program can't handle numbers larger than the max size of an <code>int</code>.</p>\n\n<pre><code>> 99999999999999*99999999999999\n9999999999999999999, *, 99999999999999\n-276447231\n> \n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:08:21.457",
"Id": "42491",
"ParentId": "42450",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "42491",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T18:23:45.707",
"Id": "42450",
"Score": "11",
"Tags": [
"c",
"recursion",
"math-expression-eval"
],
"Title": "Recursive calculator in C"
} | 42450 |
<p>I have been doing some programming 'exercises'. I'm trying to come up with the most efficient algorithm for tree traversal.</p>
<p>Consider the following function signature: </p>
<pre><code>CNode * CNode::find(int number) const
</code></pre>
<p>where <code>CNode</code> structure is not organized as a binary search tree (otherwise obviously a faster algorithm would have been used - not involving the entire tree traversal), so all the nodes have to be inspected.</p>
<p>I have implemented 3 algorithms so far:</p>
<p><strong>Stack-based search</strong></p>
<pre><code>CNode * CNode::findStackBased(int number)
{
Node *tmp = this;
stack<CNode*> onStack;
while (tmp != NULL || !onStack.empty())
{
if (tmp == NULL)
{
tmp = onStack.top();
onStack.pop();
}
if (tmp->number == number)
{
return tmp;
}
if (tmp->right)
{
onStack.push(tmp->right);
}
tmp = tmp->left;
}
return NULL;
}
</code></pre>
<p><strong>Recursive search</strong></p>
<pre><code>CNode * CNode::findRecursion(int number)
{
if (this->number == number)
{
return this;
}
Node * result = NULL;
if (this->left != NULL && (result = left->findRecursion(data)))
{
return result;
}
if (this->right != NULL)
{
return this->right->findRecursion(data);
}
return NULL;
}
</code></pre>
<p><strong>Walking along the edge</strong></p>
<pre><code>CNode * CNode::findWalkAlongTheEdge(int number)
{
Node *tmp = this;
while (tmp != NULL)
{
if (tmp->number == number)
{
return tmp;
}
if (tmp->left != NULL)
{
tmp = tmp->left;
continue;
}
else if (tmp->right != NULL)
{
tmp = tmp->right;
continue;
}
else
{
while (1)
{
if (tmp->parent->left == tmp)
{
if (tmp->parent->right != NULL)
{
tmp = tmp->parent->right;
break;
}
}
else
{
if (tmp->parent == this)
{
return NULL;
}
tmp = tmp->parent;
}
}
}
}
return NULL;
}
</code></pre>
<p>Each of the above have have some advantages/drawbacks, but performance wise 'walking along the edge is the winner so far(out of the 3 given above). </p>
<p>My question is: </p>
<p>Do you see any way to optimize it further (recursive implementation already benefits from the tail recursion optimization, at least <code>gcc</code> seems to optimize it this way)?</p>
| [] | [
{
"body": "<blockquote>\n <p>Do you see any way to optimize it further</p>\n</blockquote>\n\n<p>I don't see why you have (i.e. don't think you should have) <code>while (tmp != NULL)</code> at the top:</p>\n\n<ul>\n<li>On entry you know that this != NULL</li>\n<li>You verify that the result won't be NULL before you execute the statement before each continue or break</li>\n</ul>\n\n<p>Removing that would make it slightly faster.</p>\n\n<hr>\n\n<p>Also I don't understand ...</p>\n\n<pre><code> if (tmp->parent->left == tmp)\n {\n if (tmp->parent->right != NULL)\n {\n tmp = tmp->parent->right;\n break;\n }\n }\n</code></pre>\n\n<p>... because if <code>(tmp->parent->left == tmp)</code> and <code>(tmp->parent->right == NULL)</code> then you do nothing and therefore stay inside <code>while(1)</code> forever. So perhaps either your code is wrong, or one of those <code>if</code> conditions is unecessary.</p>\n\n<hr>\n\n<p>Apart from the two items above, the existing code looks simple? Multi-threading, using a more-optimizing compiler, or trying to write in assembly are possibilities but not clever. Good optimizations sometimes come from changing the data layout.</p>\n\n<p>For example, one faster algorithm might be to change the way in which the tree is contained in memory: use a custom allocator or similar, to ensure that nodes are physically contained in a contiguous array or vector.</p>\n\n<p>Walking the whole tree would then mean, simply, iterating through the contiguous array: which is pretty quick.</p>\n\n<p>If you do that, it would be easier to change your left, right, and parent pointers to indexes (into the array): because then you wouldn't need to change them if you reallocate (move) the array.</p>\n\n<p>Alternatively keep the nodes in random heap-allocated memory but store the numbers themselves in a contiguous array. Instead of a <code>number</code> member, nodes would have an <code>index</code> member which says which slot in the array contains their number. Making the numbers contiguous (without extraneous tree-node pointers) might be the fastest way to iterate them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T21:07:10.437",
"Id": "42465",
"ParentId": "42463",
"Score": "2"
}
},
{
"body": "<p>You can simplify all those algorithms a lot by just moving the test for NULL to a single location near the top. Then treating left and write identically (even when NULL).</p>\n<pre><code>CNode * CNode::findStackBased(int number)\n{\n stack<CNode*> onStack;\n onStack.push(this);\n\n while(!onStack.empty())\n {\n CNode tmp = onStack.top();\n onStack.pop();\n\n if (!tmp) {\n continue;\n }\n\n if (tmp->number == number) {\n return tmp;\n }\n\n onStack.push(tmp->right);\n onStack.push(tmp->left);\n }\n\n return NULL;\n}\n</code></pre>\n<p>Recursion</p>\n<pre><code>CNode* CNode::findRecursion(int number) {\n return findRecusion(this, number);\n}\nCNode* CNode::findRecursion(CNode node, int number) {\n\n if ((node == NULL) || (node->number == number) {\n return node;\n }\n\n return findRecursion(node->left); // Only do the right side if left\n || findRecursion(node->right); // returns NULL\n}\n</code></pre>\n<p>Walking along the edge just seems to be doing depth first left to right traversal. Its just messy and convoluted. It also requires the concept of a parent pointer.</p>\n<blockquote>\n<p>Each of the above have have some advantages/drawbacks, but performance wise 'walking along the edge is the winner so far(out of the 3 given above).</p>\n</blockquote>\n<p>Really. Please name them.<br />\nHow are you measuring that? Not convinced that it is actually significantly faster because of all the extra comparisons you are doing. But for certain types of trees it could be faster as you don't need to maintain a stack object.</p>\n<p>What you are doing is trading space for time (a common optimization). You are adding a parent pointer into each node to help you do the traversal more quickly. The other two techniques require you to build and maintain a stack (the state of the search (one explicitly and one implicitly in the call stack)) while the walk the edge has the information you need built into the graph.</p>\n<blockquote>\n<p>My question is:</p>\n<p>Do you see any way to optimize it further (recursive implementation already benefits from the tail recursion optimization, at least gcc seems to optimize it this way)?</p>\n</blockquote>\n<p>I would be surprised if most compilers don't turn the recursion into a loop. Its an easy optimization. I would worry less about optimization and more about readability. Its usually much more important. The compilers are darn good at making the code fast.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:24:54.240",
"Id": "42521",
"ParentId": "42463",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:50:50.163",
"Id": "42463",
"Score": "2",
"Tags": [
"c++",
"optimization",
"algorithm",
"recursion",
"tree"
],
"Title": "Algorithms for traversing unordered tree"
} | 42463 |
<p>I have implemented an user defined colors enumerator, and if is possible I appreciate if I will get a code review.
I want to know if my implementation is correctly or must improve it.
If there exist a better alternative (color enumerator) to my code which is?</p>
<p><strong>Usage example:</strong></p>
<pre><code> HANDLE hConsole;
setTextColor(hConsole,YELLOW_TEXT|PINK_BACKGROUND);
std::cout << "YELLOW_TEXT|PINK_BACKGROUND";
resetTextColor(hConsole);
</code></pre>
<p><strong>Colors enumerator:</strong></p>
<pre><code> enum COLOR
{
// Text foreground colors
// Standard text colors
GRAY_TEXT=8, BLUE_TEXT, GREEN_TEXT,
TEAL_TEXT, RED_TEXT, PINK_TEXT,
YELLOW_TEXT, WHITE_TEXT,
// Faded text colors
BLACK_TEXT=0, BLUE_FADE_TEXT, GREEN_FADE_TEXT,
TEAL_FADE_TEXT, RED_FADE_TEXT, PINK_FADE_TEXT,
YELLOW_FADE_TEXT, WHITE_FADE_TEXT,
// Standard text background color
GRAY_BACKGROUND=GRAY_TEXT<<4, BLUE_BACKGROUND=BLUE_TEXT<<4,
GREEN_BACKGROUND=GREEN_TEXT<<4, TEAL_BACKGROUND=TEAL_TEXT<<4,
RED_BACKGROUND=RED_TEXT<<4, PINK_BACKGROUND=PINK_TEXT<<4,
YELLOW_BACKGROUND=YELLOW_TEXT<<4, WHITE_BACKGROUND=WHITE_TEXT<<4,
// Faded text background color
BLACK_BACKGROUND=BLACK_TEXT<<4, BLUE_FADE_BACKGROUND=BLUE_FADE_TEXT<<4,
GREEN_FADE_BACKGROUND=GREEN_FADE_TEXT<<4, TEAL_FADE_BACKGROUND=TEAL_FADE_TEXT<<4,
RED_FADE_BACKGROUND=RED_FADE_TEXT<<4, PINK_FADE_BACKGROUND=PINK_FADE_TEXT<<4,
YELLOW_FADE_BACKGROUND=YELLOW_FADE_TEXT<<4, WHITE_FADE_BACKGROUND=WHITE_FADE_TEXT<<4
};
</code></pre>
<p><strong>Set and reset functions:</strong></p>
<pre><code> BOOL resetTextColor(HANDLE h)
{
return SetConsoleTextAttribute(h,WHITE_FADE_TEXT);
}
BOOL setTextColor(HANDLE h, WORD c)
{
return SetConsoleTextAttribute(h,c);
}
</code></pre>
<p><strong>Capture:</strong>
<img src="https://i.stack.imgur.com/4s0Zx.jpg" alt="Program output"></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-19T21:40:09.043",
"Id": "369792",
"Score": "0",
"body": "Here is full list of **Background** and **ForeGround** colors.\n[Complete list of WinAPI colors](https://stackoverflow.com/a/49929936/6219626)"
}
] | [
{
"body": "<blockquote>\n <p>If there exist a better alternative (color enumerator) to my code which is?</p>\n</blockquote>\n\n<p>You should use the constants defined in a Windows header file named <code>Wincon.h</code>, which are as follows:</p>\n\n<pre><code>#define FOREGROUND_BLUE 0x0001 // text color contains blue.\n#define FOREGROUND_GREEN 0x0002 // text color contains green.\n#define FOREGROUND_RED 0x0004 // text color contains red.\n#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.\n#define BACKGROUND_BLUE 0x0010 // background color contains blue.\n#define BACKGROUND_GREEN 0x0020 // background color contains green.\n#define BACKGROUND_RED 0x0040 // background color contains red.\n#define BACKGROUND_INTENSITY 0x0080 // background color is intensified.\n</code></pre>\n\n<p>For example, you could write:</p>\n\n<pre><code>enum COLOR\n{\n // Text foreground colors\n // Standard text colors\n GRAY_TEXT=FOREGROUND_INTENSITY,\n BLUE_TEXT=FOREGROUND_BLUE,\n</code></pre>\n\n<p>The answers to <a href=\"https://stackoverflow.com/q/17125440/49942\">C++ Win32 Console Color</a> should be useful to you.</p>\n\n<p>Alternatively here's a copy-and-paste of the equivalent .NET enum for C#, which I believe uses the same bit-values and assigns conventional color-names:</p>\n\n<pre><code>#region Assembly mscorlib.dll, v4.0.30319\n// C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\Profile\\Client\\mscorlib.dll\n#endregion\n\nnamespace System\n{\n // Summary:\n // Specifies constants that define foreground and background colors for the\n // console.\n [Serializable]\n public enum ConsoleColor\n {\n // Summary:\n // The color black.\n Black = 0,\n //\n // Summary:\n // The color dark blue.\n DarkBlue = 1,\n //\n // Summary:\n // The color dark green.\n DarkGreen = 2,\n //\n // Summary:\n // The color dark cyan (dark blue-green).\n DarkCyan = 3,\n //\n // Summary:\n // The color dark red.\n DarkRed = 4,\n //\n // Summary:\n // The color dark magenta (dark purplish-red).\n DarkMagenta = 5,\n //\n // Summary:\n // The color dark yellow (ochre).\n DarkYellow = 6,\n //\n // Summary:\n // The color gray.\n Gray = 7,\n //\n // Summary:\n // The color dark gray.\n DarkGray = 8,\n //\n // Summary:\n // The color blue.\n Blue = 9,\n //\n // Summary:\n // The color green.\n Green = 10,\n //\n // Summary:\n // The color cyan (blue-green).\n Cyan = 11,\n //\n // Summary:\n // The color red.\n Red = 12,\n //\n // Summary:\n // The color magenta (purplish-red).\n Magenta = 13,\n //\n // Summary:\n // The color yellow.\n Yellow = 14,\n //\n // Summary:\n // The color white.\n White = 15,\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If you're going to define your own enum then use it in your function declaration, i.e.:</p>\n\n<pre><code>BOOL setTextColor(HANDLE h, COLOR c)\n</code></pre>\n\n<p>... not ...</p>\n\n<pre><code>BOOL setTextColor(HANDLE h, WORD c)\n</code></pre>\n\n<p>I'd usually use mixed-case e.g. <code>Color</code> instead of <code>COLOR</code> for an enum; and I'd worry that it's already been defined in a header file.</p>\n\n<p>Also I'd split it into two parameters instead of doubling the number of enum values, for example:</p>\n\n<pre><code>BOOL setTextColor(HANDLE h, ConsoleColor foregound, ConsoleColor background)\n{\n WORD color = foregound | (background << 4);\n return SetConsoleTextAttribute(h, color);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:27:41.087",
"Id": "42469",
"ParentId": "42467",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42469",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:03:52.877",
"Id": "42467",
"Score": "3",
"Tags": [
"c++",
"console",
"windows",
"enum"
],
"Title": "User-defined color implementation in windows console"
} | 42467 |
<p>I'm working on my own little library on top of jQuery to make working with tabular data easier.</p>
<p>Currently my script takes user clicks in a table's thead element and creates an array of all of the table cells in that column, and gives the user an animation of changing the background color of the td elements in the column that was clicked on the table. When a user clicks on a thead element, all of the td's in that column are added to a variable <code>clickedHeader</code>. By holding down the shift key, the user can add multiple table columns to this array.</p>
<p>I'm looking for a cleaner way to package this, specifically the section marked in the comments. <a href="http://jsfiddle.net/nx3mG/1/" rel="nofollow">fiddle</a></p>
<p><strong>EDIT:</strong> For some reason the animations don't work in the fiddle, but do locally. The rest of the script works fine in the fiddle</p>
<p><strong>JS</strong></p>
<pre><code>(function () {
//all tables in this example have a thead element
var headers = $('table').find('thead > tr th'),
clickedHeaders = [];
//to test what's currently in clickedHeaders
$(document).dblclick(function () {
console.log(clickedHeaders);
});
headers.click(function (e) {
//allow only one table column to have background color at a time
//this looks a little hooky to me
var tds = $('td');
var columnData = getColumnData.call(this);
if (!e.shiftKey) {
//if no shift, empty the array
clickedHeaders.length = 0;
tds.each(function () {
$(this).css('background-color', 'white');
});
//adds animation to notify user
notifyClick(columnData.cells);
clickedHeaders.push(columnData.returnData);
}
else {
notifyClick(columnData.cells);
clickedHeaders.push(columnData.returnData);
}
});
//passed a tbody's td elements as array
function notifyClick(data) {
data.each(function (i) {
$(this).delay(30 * i).animate({ backgroundColor: $(this)
.css('background-color'), backgroundColor: '#ccc'
}, 25, 'swing');
});
};
//find the column that was clicked
function getColumnData() {
//table's selector is column headers
var clickedIndex = $(this).index() + 1,
tableId = $(this).closest('table').attr('id');
//selector to get the index of a column
var columnSelector = function (index) {
return '#' + tableId + ' tbody tr td:nth-child(' + index + ')';
};
//processing will be done on the text of the td elements
//but I still wanted to be able to keep the array of elements as well
var columnData = $(columnSelector(clickedIndex));
var returnData = columnData.map(function () {
return parseInt($(this).text(), 10);
}).get();
return {
returnData: returnData,
cells: columnData
}
}
})();
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><table id="testTable2">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>11</td>
<td>22</td>
</tr>
<tr>
<td>33</td>
<td>44</td>
</tr>
</tbody>
</table>
<table id="testTable">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>57</td>
<td>100</td>
</tr>
<tr>
<td>56</td>
<td>80</td>
</tr>
<tr>
<td>56</td>
<td>45</td>
</tr>
<tr>
<td>56</td>
<td>30</td>
</tr>
<tr>
<td>56</td>
<td>10</td>
</tr>
</tbody>
</table>
</code></pre>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>I would call <code>tds</code> -> <code>$td</code>, it shows the reader that its the result of a td query</li>\n<li><p>There is some duplication in your dealing with <code>shiftKey</code>, you could try this:<br></p>\n\n<pre><code>if (!e.shiftKey) {\n //if no shift, empty the array\n clickedHeaders.length = 0;\n $td.css('background-color', 'white');\n}\nnotifyClick(columnData.cells);\nclickedHeaders.push(columnData.returnData);\n</code></pre></li>\n<li>I am not sure how your animation can work, jQuery docs state : <em>width, height, or left can be animated but background-color cannot be</em></li>\n<li><p>I am not a big fan of <code>closest</code>, you might as well use <code>parents</code> : <br></p>\n\n<pre><code>tableId = $(this).parents('table').attr('id');\n</code></pre>\n\n<p>This should give you less potential surprises</p></li>\n<li>Finally, I find that your code does not work well, if I keep shift-clicking the same header, I will get a duplication of the data in <code>console.log(clickedHeaders);</code>. You should keep a unique list of values so that the collected columns are useful/usable.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:37:39.207",
"Id": "73539",
"Score": "0",
"body": "@konjin it worked because I forgot I had included jQueryUI (which does animate colors). I just remembered why :). +1 for keeping a unique list as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:36:25.373",
"Id": "42677",
"ParentId": "42468",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:08:13.503",
"Id": "42468",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Table manipulation/data extraction"
} | 42468 |
<p>I hope this isn't getting annoying, but I've asked a lot of questions about improving my game lately:</p>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/31124/how-can-i-improve-my-game-project-design">How can I improve my game project design?</a></li>
<li><a href="https://codereview.stackexchange.com/questions/37085/using-the-observer-pattern-with-collision-detection">Using the observer pattern with collision detection</a></li>
<li><a href="https://codereview.stackexchange.com/questions/37069/is-this-a-good-way-to-cascade-a-property">Is this a good way to cascade a property?</a></li>
<li><a href="https://codereview.stackexchange.com/questions/41750/how-should-i-implement-my-domain-model">How should I implement my domain model?</a></li>
<li><a href="https://codereview.stackexchange.com/questions/42232/setting-up-keyboard-bindings-using-json-and-reflection">Setting up keyboard bindings using JSON and reflection</a></li>
<li><a href="https://codereview.stackexchange.com/questions/42345/setting-up-keyboard-bindings-using-json-no-reflection">Setting up keyboard bindings using JSON (no reflection!)</a></li>
<li><a href="https://codereview.stackexchange.com/questions/42395/get-array-of-pressed-buttons-using-extension-method">Get array of pressed buttons using extension method</a></li>
</ul>
<p>No, you don't have to read all of those. I'm starting to think all my questions stem from problems I have with XNA's default project template. After creating a new Windows game project in Visual Studio, this is what it gives you:</p>
<pre><code>static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
</code></pre>
<hr>
<pre><code>/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
</code></pre>
<p>I feel like I've been fighting the framework all along because I don't like how it is structured. There are several tutorials around the net, and most (if not all) of them show you how to add your code to the <code>Game</code> class directly - loading sprites, animating sprites, drawing sprites, adding sound effects, responding to input, etc. I've tried several times to abstract this as much as possible, but my results haven't been great because I'm not the best designer. This is my latest iteration:</p>
<pre><code>public static class Program
{
private static void Main( string[] args )
{
IFileHandler fileHandler = new JsonHandler();
var settings = fileHandler.Read<Settings>( "settings.json" );
var level = fileHandler.Read<Level>( "level.json" );
var player = fileHandler.Read<Entity>( "player.json" );
using ( var game = new MyGame( new Graphics( settings.DisplaySettings, level, player ),
new Input( settings.GamePadSettings, settings.KeyboardSettings, level, player ) ) )
{
game.Run();
fileHandler.Write( "player.json", player );
fileHandler.Write( "level.json", level );
}
}
}
</code></pre>
<hr>
<pre><code>public class MyGame : Game
{
private readonly IGraphics graphics;
private readonly IInput input;
public MyGame( IGraphics graphics, IInput input )
{
if ( graphics == null || input == null )
{
throw new ArgumentNullException();
}
this.graphics = graphics;
this.input = input;
graphics.Setup( this );
input.Setup( this );
}
protected override void LoadContent()
{
Content.RootDirectory = "Content";
graphics.Load( GraphicsDevice, Content );
}
protected override void Update( GameTime gameTime )
{
input.Process();
base.Update( gameTime );
}
protected override void Draw( GameTime gameTime )
{
graphics.Draw();
base.Draw( gameTime );
}
}
</code></pre>
<p>Not only are there <a href="https://codereview.stackexchange.com/a/42404/29587">several problems</a> with my code, but in a way I feel like it doesn't make sense for me to try and do this. One of the biggest problems I have is <code>GraphicsDeviceManager</code> is, by its very definition, tightly coupled to the <code>Game</code> class - you can't instantiate it without giving it an instance of <code>Game</code>. Furthermore, <code>Game</code> already has a <code>GraphicsDevice</code> property (separate from <code>GraphicsDeviceManager</code>) that's needed to load sprites into the content pipeline. I really wanted to get this stuff - loading, drawing, input - out of my base class, but I can't figure out how to create a class that does this without tightly coupling it to <code>Game</code>. See:</p>
<pre><code>public class Graphics : IGraphics
{
private readonly DisplaySettings displaySettings;
private readonly Level level;
private readonly Entity player;
private GraphicsDeviceManager graphicsDeviceManager;
private SpriteBatch spriteBatch;
public Graphics( DisplaySettings displaySettings, Level level, Entity player )
{
if ( displaySettings == null || level == null || player == null )
{
throw new ArgumentNullException();
}
this.displaySettings = displaySettings;
this.level = level;
this.player = player;
}
public void Setup( Game game )
{
if ( game == null )
{
throw new ArgumentNullException();
}
graphicsDeviceManager = new GraphicsDeviceManager( game )
{
IsFullScreen = displaySettings.IsFullScreen,
PreferredBackBufferWidth = displaySettings.PreferredBackBufferWidth,
PreferredBackBufferHeight = displaySettings.PreferredBackBufferHeight
};
}
public void Load( GraphicsDevice graphicsDevice, ContentManager contentManager )
{
if ( graphicsDevice == null || contentManager == null )
{
throw new ArgumentNullException();
}
spriteBatch = new SpriteBatch( graphicsDevice );
level.Load( contentManager );
player.Load( contentManager );
}
public void Draw()
{
level.Clear( graphicsDeviceManager.GraphicsDevice );
spriteBatch.Begin( SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.Default,
RasterizerState.CullNone );
level.Draw( spriteBatch );
player.Draw( spriteBatch );
spriteBatch.End();
}
}
</code></pre>
<p>Like I said, I feel like I'm fighting the framework. I'm not convinced that what I've come up with is any better, and it might even be worse than if I simply stuck everything in the <code>Game</code> class. At least that seems to be the way the XNA team intended for us to work with it.</p>
<p>TLDR: How can I use XNA without shooting myself in the foot? How would you work with the template to make it more SOLID?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:51:36.060",
"Id": "73541",
"Score": "0",
"body": "My strategy so far has been to go ahead and use the main game loop, rather than avoiding it. This doesn't mean I put all my code there, however. I'm really doing a lot of it iteratively. As I get farther along, where I put things is becoming more and more obvious. Input ended up being inside my character, for instance, but when first designing it, it was in the main Game class. Soon, my character class will be removed from Game. It would take a serious architect to plan something like this ahead of time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:13:32.940",
"Id": "73840",
"Score": "0",
"body": "I don't know XNA, so I want to ask a few questions first. `SpriteBatch` constructor gets a `GraphicsDevice` argument, later in draw you get a `GraphicsDevice` from `GraphicsDeviceManager`. How does that work, are these two required to be same, how does `spritebatch` know current device?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T16:33:35.610",
"Id": "73911",
"Score": "2",
"body": "\"`SpriteBatch` constructor gets a `GraphicsDevice` argument, later in draw you get a `GraphicsDevice` from `GraphicsDeviceManager`... are these two required to be same\" I assume so - in my \"improved\" version I tried to get the `GraphicsDeviceManager` and `GraphicsDevice` stuff out of the `Game` class but in reality they are in both now. \"how does spritebatch know current device?\" I don't know - I assume it holds a reference to the device but it's all very magical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T02:18:33.223",
"Id": "77733",
"Score": "0",
"body": "Seen [this answer](http://stackoverflow.com/a/5459955/1188513)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T23:13:27.340",
"Id": "78417",
"Score": "0",
"body": "@Mat'sMug he has some cool ideas but I get lost with the whole component thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T23:34:16.987",
"Id": "78418",
"Score": "1",
"body": "I wish there was an easy way to ask that dude directly. He seems to have a lot of good advice on XNA."
}
] | [
{
"body": "<p>I haven't done enough XNA to really get to the core of this question, I hope to see this reviewed from an XNA perspective.</p>\n<p>I'll only make a few observations about the <code>Program</code> class.</p>\n<h1>Main()</h1>\n<p>Looking at the <code>Main</code> method and the <code>Program</code> class, I see mixed abstraction levels and some temporal coupling, I'm tempted to move stuff around a bit:</p>\n<pre><code>public static class Program\n{\n private static void Main(string[] args)\n {\n var data = GetGameFileData(); // temporal coupling removed!\n \n // extracted variables improve readability...\n var graphics = new Graphics(data.Settings.DisplaySettings, \n data.Level, \n data.Player);\n\n var input = new Input(data.Settings.GamePadSettings, \n data.Settings.KeyboardSettings, \n data.Level, \n data.Player);\n\n // ...and makes the intent clearer:\n using (var game = new MyGame(graphics, input))\n {\n game.Run();\n data.Save();\n }\n }\n\n private static GameFileData GetGameFileData()\n {\n var result = new GameFileData();\n result.Load();\n\n return result;\n }\n}\n</code></pre>\n\n<pre><code>private class GameFileData\n{\n private readonly IFileHandler _fileHandler;\n\n public GameFileData() \n : this(new FileHandler()) \n {\n }\n\n // probably YAGNI\n public GameFileData(IFileHandler fileHandler)\n {\n _fileHandler = fileHandler;\n }\n\n public Settings Settings { get; private set; }\n public Level Level { get; private set; }\n public Entity Player { get; private set; }\n\n public void Load()\n {\n Settings = _fileHandler.Read<Settings>("settings.json"),\n Level = _fileHandler.Read<Level>("level.json"),\n Player = _fileHandler.Read<Entity>("player.json")\n }\n\n public void Save()\n {\n _fileHandler.Write("level.json", Level);\n _fileHandler.Write("player.json", Player);\n }\n}\n</code></pre>\n<hr />\n<h3>Nitpick</h3>\n<blockquote>\n<pre><code>new Graphics( settings.DisplaySettings, level, player )\nfileHandler.Write( "player.json", player );\n</code></pre>\n</blockquote>\n<p>If this is really how much whitespace your actual code has, ...you're <em>fighting the IDE</em> to achieve it - Visual Studio automatically removes these spaces then you hit <code>;</code> or when you close a scope with <code>}</code>.</p>\n<pre><code>new Graphics(settings.DisplaySettings, level, player)\nfileHandler.Write("player.json", player);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T21:01:11.623",
"Id": "79801",
"Score": "0",
"body": "Thanks for your advice. I'm a bit skeptical on moving the file names inside of GameFileData though - isn't it a good idea to have implementation details like that as close to the composition root as possible? Now they're buried. As for the spacing, the conventions I use are enforced by ReSharper, and I use them because of work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T02:33:41.160",
"Id": "45053",
"ParentId": "42472",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:40:18.727",
"Id": "42472",
"Score": "4",
"Tags": [
"c#",
"dependency-injection",
"inheritance",
"xna"
],
"Title": "Improving XNA's default project template"
} | 42472 |
<p>I'm looking for general advice on my code on the following problem:</p>
<blockquote>
<p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p>
<p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p>
</blockquote>
<pre><code>public class Problem2 extends Problem<Integer> {
@Override
public void run() {
result = FibonacciGenerator.finiteStream(i -> (i <= 4_000_000))
.filter(i -> (i % 2 == 0))
.mapToInt(i -> i)
.sum();
}
@Override
public String getName() {
return "Problem 2";
}
}
</code></pre>
<hr />
<pre><code>public class FibonacciGenerator extends RestrictedGenerator<Integer> {
private int beforePrevious = 0;
private int previous = 1;
protected FibonacciGenerator(final Predicate<Integer> predicate) {
super(predicate);
}
@Override
public boolean hasNext() {
return predicate.test(previous);
}
@Override
public Integer next() {
int result = beforePrevious + previous;
beforePrevious = previous;
previous = result;
return result;
}
public static Stream<Integer> finiteStream(final Predicate<Integer> predicate) {
return RestrictedGenerator.toStream(new FibonacciGenerator(predicate), Spliterator.ORDERED);
}
public static Stream<Integer> infiniteStream() {
return RestrictedGenerator.toStream(new FibonacciGenerator(i -> true), Spliterator.ORDERED);
}
public static Stream<Integer> finiteParallelStream(final Predicate<Integer> predicate) {
return RestrictedGenerator.toParallelStream(new FibonacciGenerator(predicate), Spliterator.ORDERED);
}
public static Stream<Integer> infiniteParallelStream() {
return RestrictedGenerator.toParallelStream(new FibonacciGenerator(i -> true), Spliterator.ORDERED);
}
}
</code></pre>
<hr />
<pre><code>public abstract class RestrictedGenerator<T> implements Iterator<T> {
protected final Predicate<T> predicate;
protected RestrictedGenerator(final Predicate<T> predicate) {
this.predicate = predicate;
}
@Override
public abstract boolean hasNext();
@Override
public abstract T next();
protected static <T> Stream<T> toStream(final RestrictedGenerator<T> generator, final int charasterics) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(generator, charasterics), false
);
}
protected static <T> Stream<T> toParallelStream(final RestrictedGenerator<T> generator, final int charasterics) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(generator, charasterics), true
);
}
}
</code></pre>
<hr />
<pre><code>public abstract class Problem<T> implements Runnable {
protected T result;
public String getResult() {
return String.valueOf(result);
}
abstract public String getName();
}
</code></pre>
<hr />
<pre><code>public class ProjectEuler {
private final List<Problem<?>> problems = new ArrayList<>();
private void init() {
problems.add(new Problem1());
problems.add(new Problem2());
process();
}
private void process() {
problems.stream().forEachOrdered(new ProblemConsumer());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new ProjectEuler().init();
}
private class ProblemConsumer implements Consumer<Problem<?>> {
@Override
public void accept(Problem<?> problem) {
long start = System.nanoTime();
problem.run();
String result = problem.getResult();
long end = System.nanoTime();
long elapsed = end - start;
System.out.println(problem.getName() + ": " + result + " (" + String.format("%,d", (elapsed / 1_000_000)) + " ms" + ")");
}
}
}
</code></pre>
<p>Maybe I've gotten a bit over excited with the new options in Java 8, my main concern is readability, and for the rest just general advice.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:01:49.217",
"Id": "73130",
"Score": "1",
"body": "Could you give some background on the `Problem<T>` class? Where is it from, what does it do? Is there a `main()` method somewhere? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T12:56:53.543",
"Id": "73184",
"Score": "0",
"body": "@rolfl Added all code on request."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:16:26.417",
"Id": "73225",
"Score": "0",
"body": "Just saying ... I have your code loaded up, and I really appreciate the Problem model you have set up. I think I will 'borrow' it, if you don't mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:19:20.830",
"Id": "73227",
"Score": "0",
"body": "@rolfl That's no problem at all, I'd be honered by that. I do have some other question though, I've changed by code a bit yet again, should I update this post or make a new one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:20:30.493",
"Id": "73228",
"Score": "0",
"body": "There are no answers (yet), so you can change your code. I am goin through your problem now, so don't take too long ;-) (I will do other things till you're done)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:23:24.540",
"Id": "73231",
"Score": "0",
"body": "@rolfl The update has been done already :) Added proper `Iterator<T>` to `Stream<T>` support."
}
] | [
{
"body": "<p>So a fair amount of Java8 is new to me, including the Stream API, which is, in essence, why this review is useful to me too. Bear with me...</p>\n\n<h2>Readability</h2>\n\n<p>You say <em>\"my main concern is readability\"</em>. Now that I have spent some time looking in to what you are doing, what you are using, and reading up on some documentation, the answer is: <strong>yes!</strong></p>\n\n<p>The code does look strange, but that is only because the language structures are new. You are using them right, conforming to what few 'standards' there are... and it is fine.</p>\n\n<h2>General</h2>\n\n<p><strong>RestrictedGenerator</strong></p>\n\n<blockquote>\n<pre><code>public abstract class RestrictedGenerator<T> implements Iterator<T> {\n</code></pre>\n</blockquote>\n\n<p>This class is essentially useless. It is a container for a Predicate, which is accessed through it's protected nature anyway. Also, what about it is 'restricted'? Why does it have that name?</p>\n\n<p>The static methods on it could be anywhere too. They have no business being on this class specifically.</p>\n\n<p>Basically the class is irrelevant, and makes the class structure more complicated than it needs to be. Moving the functionality to <code>FibonacciGenerator</code> is trivial.</p>\n\n<h2><code>Problem<T></code></h2>\n\n<p>I really like how you have set up a system for running your tests. This is a worthwhile investment. I have taken your system, and extended it quite a lot. I have made the performance tests a bit more structured. Also, I have rearranged the <code>Problem<T></code> class. This is a <strong><em>compliment</em></strong> for your code... not a criticism... it's good. I just want to use it differently from you. On the other hand, you may like what I have done, so have a look.</p>\n\n<p>I did find some problems... you are doing long-division on the time values:</p>\n\n<blockquote>\n<pre><code>String.format(\"%,d\", (elapsed / 1_000_000))\n</code></pre>\n</blockquote>\n\n<p>As your code gets faster (warmed up), you will want to convert that to a floating-point:</p>\n\n<pre><code>String.format(\"%.5f\", (elapsed / 1_000_000.0))\n</code></pre>\n\n<h2>Functionality</h2>\n\n<p>I cannot find anything wrong with the algorithm. It works as advertized, but there are some places where the code is excessive, redundant, or 'artificial'. The <code>RestrictedGenerator</code> was the worst offender.</p>\n\n<h2>Performance</h2>\n\n<p>Right, Performance is where I really get interested in problems... I have modified your code and run it through some benchmarks, then I have made alternate systems, and benchmarked them too.</p>\n\n<p>The first thing I noticed is that you are reporting the performance time of the first run. It is common knowledge that Java only starts getting 'fast' when it is 'warmed up'. You want to know what sort of difference it makes? Well, you say your code runs in <code>56ms</code> (your benchmark code), but, I say it runs in <code>0.00100ms</code>. Yeah, the numbers are really small. The problem is not particularly challenging.</p>\n\n<p>But, I thought, <em>\"I always complain about people using autoboxing instead of primitives... surely the Streams API has primitive processing options?\"</em>, and, when I looked, it does! So, I converted your code to use <code>IntStream</code> and other <code>Int*</code> constructs, instead of <code>Stream<Integer></code>. This has helped with performance. There is an example of that code.</p>\n\n<p>I also thought, what If I write it as I 'learn' Java8, and compare it to what I would have done in Java7.</p>\n\n<p>So, I now have 4 implementations of the problem:</p>\n\n<ol>\n<li>your version</li>\n<li>your version converted to IntStream</li>\n<li>my version in Java8</li>\n<li>my version in Java7</li>\n</ol>\n\n<hr>\n\n<p><strong>Your Version</strong></p>\n\n<p>No reason to do anything here....</p>\n\n<hr>\n\n<p><strong>Your Version as IntStream</strong></p>\n\n<p>I have removed the code that's not relevant (including the <code>RestrictedGenerator</code>)</p>\n\n<p>Problem2IntStream.java</p>\n\n<pre><code>public final class Problem2IntStream extends Problem<Integer> {\n\n public Problem2IntStream() {\n super(\"Problem 2 - IntStream\", 1000, 100);\n }\n\n @Override\n public Integer execute() {\n return FibonacciIntGenerator.finiteStream(i -> (i <= 4_000_000))\n .filter(i -> (i % 2 == 0))\n .sum();\n }\n\n}\n</code></pre>\n\n<p>FibonacciIntGenerator.java</p>\n\n<pre><code>public class FibonacciIntGenerator implements PrimitiveIterator.OfInt {\n private int beforePrevious = 0;\n private int previous = 1;\n private final IntPredicate predicate;\n\n protected FibonacciIntGenerator(final IntPredicate predicate) {\n this.predicate = predicate;\n }\n\n @Override\n public boolean hasNext() {\n return predicate.test(previous);\n }\n\n @Override\n public int nextInt() {\n int result = beforePrevious + previous;\n beforePrevious = previous;\n previous = result;\n return result;\n }\n\n public static IntStream finiteStream(final IntPredicate predicate) {\n return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(new FibonacciIntGenerator(predicate), Spliterator.ORDERED), false);\n }\n\n public static IntStream infiniteStream() {\n return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(new FibonacciIntGenerator(i -> true), Spliterator.ORDERED), false);\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p><strong>My first Streams code ever</strong></p>\n\n<p>Note, this code works off a Spliterator instead of an Iterator... which, I think, removes a level of abstraction....</p>\n\n<pre><code>public final class Problem2Java8 extends Problem<Integer> {\n\n public Problem2Java8() {\n super(\"Problem 2 - rolfl java8\", 1000, 100);\n }\n\n @Override\n public Integer execute() {\n\n return StreamSupport\n .intStream(new FibGenerator(i -> i <= 4000000), false)\n .filter(i -> (i & 1) == 0).sum();\n\n }\n\n private static class FibGenerator implements Spliterator.OfInt {\n\n private static final int CHARACTERISTICS = IMMUTABLE | ORDERED;\n\n int fib = 1;\n int prev = 1;\n private final IntPredicate predicate;\n\n public FibGenerator(IntPredicate pred) {\n predicate = pred;\n }\n\n @Override\n public boolean tryAdvance(IntConsumer action) {\n if (!predicate.test(fib)) {\n return false;\n }\n action.accept(fib);\n int tmp = fib;\n fib += prev;\n prev = tmp;\n return true;\n }\n\n @Override\n public long estimateSize() {\n return Long.MAX_VALUE;\n }\n\n @Override\n public int characteristics() {\n return CHARACTERISTICS;\n }\n\n @Override\n public java.util.Spliterator.OfInt trySplit() {\n return null;\n }\n\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Standard Java7 version</strong></p>\n\n<p>What if the code was implemented as a simple Java problem?</p>\n\n<pre><code>public final class Problem2Java7 extends Problem<Integer> {\n\n public Problem2Java7() {\n super(\"Problem 2 Java7\", 1000, 100);\n }\n\n @Override\n public Integer execute() {\n int sum = 0;\n int fib = 1;\n int prev = 1;\n int tmp = 0;\n while (fib <= 4000000) {\n tmp = fib;\n fib += prev;\n prev = tmp;\n if ((fib & 1) == 0) {\n sum += fib;\n }\n }\n return sum;\n }\n\n}\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>The performance results are somewhat revealing....</p>\n\n<blockquote>\n<pre><code>Problem 2 => 4613732 (hot 0.00095ms - cold 0.035ms (total 9.018ms))\nProblem 2 - IntStream => 4613732 (hot 0.00071ms - cold 0.036ms (total 10.038ms))\nProblem 2 - rolfl java8 => 4613732 (hot 0.00061ms - cold 0.023ms (total 14.494ms))\nProblem 2 Java7 => 4613732 (hot 0.00018ms - cold 0.018ms (total 7.779ms))\n</code></pre>\n</blockquote>\n\n<p>To me, this means that, for this type of CPU-intensive work, the overhead of the streams is still significant. It is essentially 5 times faster than your code, and 3 times faster than the fastest Streams alternative.</p>\n\n<p>This problem is a tiny problem though... the computations are really small, and the method overhead of the streams will be the bulk of the runtime. I don't know where the performance/usability curve will cross from being 'wasteful' to 'useful', but, it is not useful for <em>this</em> problem.</p>\n\n<p>Also, because I am new to this, the standard Java is more readable ;-)</p>\n\n<h2>The Framework</h2>\n\n<p>I took the liberty of playing with your framework. This is what it looks like now in my environment:</p>\n\n<p><strong>Problem.java</strong></p>\n\n<pre><code>public abstract class Problem<T> {\n private final String name;\n private final int warmup;\n private final int avgcnt;\n\n public Problem(String name, int warmups, int realruns) {\n this.name = name;\n this.warmup = warmups;\n this.avgcnt = realruns;\n }\n\n public String getResult() {\n return String.valueOf(execute());\n }\n\n public final int getWarmups() {\n return warmup;\n }\n\n public final int getRealRuns() {\n return avgcnt;\n }\n\n public final String getName() {\n return name;\n }\n\n public abstract T execute();\n\n}\n</code></pre>\n\n<p><strong>ProjectEuler.java</strong></p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Consumer;\n\npublic class ProjectEuler {\n private static final double MILLION = 1_000_000.0;\n\n private final List<Problem<?>> problems = new ArrayList<>();\n private final int longestname;\n\n public ProjectEuler() {\n // problems.add(new Problem1());\n problems.add(new Problem2IntStream());\n problems.add(new Problem2());\n problems.add(new Problem2Java7());\n problems.add(new Problem2Java8());\n\n int namelen = 0;\n for (Problem<?> p : problems) {\n namelen = Math.max(namelen, p.getName().length());\n }\n longestname = namelen;\n }\n\n private void process() {\n problems.stream().forEachOrdered(new ProblemConsumer());\n }\n\n /**\n * @param args\n * the command line arguments\n */\n public static void main(String[] args) {\n ProjectEuler pe = new ProjectEuler();\n pe.process();\n System.out.println(\"\\n\\nRound 1 Complete\\n\\n\");\n pe.process();\n }\n\n private class ProblemConsumer implements Consumer<Problem<?>> {\n @Override\n public void accept(final Problem<?> problem) {\n\n final long basetime = System.nanoTime();\n final int wreps = problem.getWarmups();\n final int rreps = problem.getRealRuns();\n\n long btime = System.nanoTime();\n final String result = problem.getResult();\n btime = System.nanoTime() - btime;\n for (int i = wreps; i > 0; i--) {\n\n String actual = problem.getResult();\n if (!result.equals(actual)) {\n throw new IllegalStateException(\"Unexpected result \"\n + actual);\n }\n ;\n }\n\n System.gc();\n\n final long start = System.nanoTime();\n for (int i = rreps; i > 0; i--) {\n problem.execute();\n }\n final long end = System.nanoTime();\n final long elapsed = end - start;\n\n String actual = problem.getResult();\n\n System.out.printf(\"%-\" + longestname\n + \"s => %s (hot %.5fms - cold %.3fms (total %.3fms))\\n\",\n problem.getName(), actual, (elapsed / MILLION) / rreps,\n btime / MILLION, (end - basetime) / MILLION);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:47:17.467",
"Id": "73313",
"Score": "0",
"body": "That is quite a long response and I really appreciate it. Firstly, I did not intend this code for performance, though still appreciate the remarks on it. Secondly, really thanks a lot of finding the `PrimitiveIterator.OfInt`, I was searching for that one earlier today aswell!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:50:17.520",
"Id": "73315",
"Score": "0",
"body": "Yeah, it is a long response ... and I missed a key thing anyway: you asked if the code was readable? Yes, Yes it is (now that I understand a bit more about it...) Let me edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:19:28.147",
"Id": "42544",
"ParentId": "42473",
"Score": "16"
}
},
{
"body": "<p>It can be easily and clearly resolved by this:</p>\n\n<pre><code>UnaryOperator<BigInteger[]> fibonacci = (m) -> new BigInteger[]{m[1], m[0].add(m[1])};\n\nStream.iterate(new BigInteger[]{BigInteger.ONE,BigInteger.ONE}, fibonacci)\n .limit(32) \n .map(n -> fibonacci.apply(n)[0])\n .filter(n->n.compareTo(BigInteger.valueOf(4000000))<1)\n .filter(n->n.mod(BigInteger.valueOf(2))==BigInteger.ZERO)\n .reduce((m,n)->m.add(n)).ifPresent(System.out::println);\n</code></pre>\n\n<p>First define the Fibonacci operation based on mathematical definition. After begin to iterate defining the seed (1,1). Here for simplicity, we used an array of BigInteger but we could have defined a class (e.g. Tuple). Finally you filter based on upper hypotesis that max value should be less than 4,000,000 and that we only retain odd number. We then sum all the values (reduce operation) and we output it to the user.\nRemind that all stream is infinite. In this case the operation continue until the limit(32) is defined. You can limit by maximux iteration in jdk8 or wait to jdk9 to limit it by value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-14T10:40:14.933",
"Id": "110742",
"ParentId": "42473",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "42544",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T22:44:14.697",
"Id": "42473",
"Score": "18",
"Tags": [
"java",
"project-euler",
"java-8"
],
"Title": "Project Euler \"Even Fibonacci numbers\" in Java 8"
} | 42473 |
<blockquote>
<p>Given an infinite stream with the property, such that after all 0's there are only all 1's, find the index of the last 0.</p>
</blockquote>
<p>I'm looking for code review, best practices, optimizations etc. Verifying complexity to be O (log n) where n is the first 1 encountered in the search (not the first 1 in the stream).</p>
<pre><code>/**
* An infinite list takes in an the number of zeros'.
* After those many zero's only 1's are followed.
* This is a hypothetical class to represent a inifinite stream in real world.
* like lets assume a linkedlist shared my multiple threads which keep appending 1's
*/
class InfiniteList extends ArrayList<Integer> {
InfiniteList(int zeroCount) {
super(zeroCount);
add(zeroCount);
}
private void add (int zeroEnd) {
for (int i = 0; i < zeroEnd; i++) {
super.add(0);
}
}
@Override
public Integer get(int i) {
return super.size() <= i ? 1 : super.get(i);
}
@Override
public int size() {
throw new UnsupportedOperationException("The array size cannot be obtained.");
}
}
public final class FindZeroEndInInfiniteStream {
private FindZeroEndInInfiniteStream() {}
/**
* Takes in a infinite list, such that after stream of all 0's we encounter only all 1's.
* Returns the last index of zero.
* If no zero is found then -1 is returned.
* This code would block until a zero is found in an infinite stream.
* If the infinite has 0's and 1's mixed randomly then output is unpredicatable/
*
* @param infinite the infinite stream of 0's followed by 1's
* @return the last index of zero.
*/
public static int zeroLastIndex(InfiniteList infinite) {
if (infinite == null) throw new NullPointerException("The inifinte array was null");
return modifiedBinarySearch(infinite);
}
private static int modifiedBinarySearch(InfiniteList infinite) {
if (infinite.get(0) == 1) return -1;
if (infinite.get(1) == 1) return 0;
int passive = 0; // does nothing, simply stores previous lower bound.
int active = 1; // does the searching, toggling back and forth
while(!(infinite.get(active) == 0 && infinite.get(active + 1) == 1)) {
if (infinite.get(active) == 0) {
passive = active;
active = active * 2;
} else {
active = (passive + active)/2; // active has gone beyond the 38th parallel :). Now go back to south korea.
}
}
return active;
}
public static void main(String[] args) {
InfiniteList iList = new InfiniteList(15);
Assert.assertEquals(14, zeroLastIndex(iList));
iList = new InfiniteList(27);
Assert.assertEquals(26, zeroLastIndex(iList));
}
}
</code></pre>
| [] | [
{
"body": "<p>You might have misunderstood the program requirements: an ArrayList is not an <a href=\"https://www.google.com/search?q=java+stream\" rel=\"nofollow noreferrer\">infinite Stream</a>.</p>\n\n<hr>\n\n<p>If you don't want a stream and do instead want to assume that multiple-threads are adding to it then you <a href=\"https://stackoverflow.com/a/2716016/49942\">shouldn't use ArrayList because it's not thread-safe</a>; apparently, a <a href=\"https://stackoverflow.com/a/2144900/49942\">better alternative for that purpose would be Vector</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:32:57.313",
"Id": "73135",
"Score": "0",
"body": "And here I was thinking: How on earth to make an infinite stream? Is a good old `InputStream` / `OutputStream` considered infinite? I have to agree though that a class that extends ArrayList is not an infinite stream."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:46:13.223",
"Id": "73137",
"Score": "1",
"body": "@SimonAndréForsberg Another way to represent it would be something like `Iterable<Boolean>`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:23:29.480",
"Id": "42478",
"ParentId": "42475",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:17:31.143",
"Id": "42475",
"Score": "2",
"Tags": [
"java",
"binary-search",
"stream"
],
"Title": "Find last zero in infinite stream of 0's followed by 1's"
} | 42475 |
<p>I have attempted to make a basic version [not complete] of the <code>std::basic_string</code> type in C++, and I would like to make sure that I have done everything correctly, and efficiently, as I can be prone to leaking memory in my programs.</p>
<p>Note: I also created an <code>allocator</code> class, which works the same as the <code>std</code> equivalent, but I have not added it, as I would like to focus on the implementation of the <code>basic_string</code> (and <code>char_traits</code>).</p>
<pre><code>template < typename _Elem > struct char_traits
{
};
template <> struct char_traits<char>
{
typedef char _Elem;
static std::size_t length(const _Elem *_Str)
{
return strlen(_Str);
}
static int compare(const _Elem *_Lhs, const _Elem *_Rhs, std::size_t _Count)
{
return strncmp(_Lhs, _Rhs, _Count);
}
};
template <> struct char_traits<wchar_t>
{
typedef wchar_t _Elem;
static std::size_t length(const _Elem *_Str)
{
return wcslen(_Str);
}
static int compare(const _Elem *_Lhs, const _Elem *_Rhs, std::size_t _Count)
{
return wcsncmp(_Lhs, _Rhs, _Count);
}
};
template < typename _Elem > struct _Char_Traits
{
};
template <> struct _Char_Traits<char>
{
typedef char _Elem;
static int va_printf(_Elem *_Dest, const _Elem *_Format, va_list _Args)
{
return vsprintf(_Dest, _Format, _Args);
}
};
template <> struct _Char_Traits<wchar_t>
{
typedef wchar_t _Elem;
static int va_printf(_Elem *_Dest, const _Elem *_Format, va_list _Args)
{
return vswprintf(_Dest, _Format, _Args);
}
};
template < typename _Elem, typename _Traits = char_traits<_Elem>, typename _Alloc = allocator<_Elem> > class basic_string
{
public:
typedef basic_string<_Elem, _Traits, _Alloc> _Myt;
typedef _Elem value_type;
typedef _Traits traits_type;
typedef _Alloc allocator_type;
typedef value_type *pointer;
typedef const value_type *const_pointer;
typedef value_type *iterator;
typedef const value_type *const_iterator;
typedef value_type &reference;
typedef const value_type &const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
basic_string()
{
__data = _Alloc().allocate(1);
_Alloc().construct(&__data[0], '\0');
}
basic_string(const_pointer _Init)
{
size_type sz = _Traits::length(_Init), i = 0;
__data = _Alloc().allocate(sz + 1);
for (i = 0; i < sz; ++i)
{
_Alloc().construct(&__data[i], _Init[i]);
}
_Alloc().construct(&__data[sz], '\0');
}
basic_string(void *_Init)
{
*this = basic_string(reinterpret_cast<const_pointer>(_Init));
}
basic_string(const _Myt &_Init)
{
if (this != &_Init)
{
*this = basic_string(_Init.c_str());
}
else
{
__data = _Alloc().allocate(1);
_Alloc().construct(&__data[0], '\0');
}
}
~basic_string()
{
for (iterator i = begin(); i != end(); ++i)
{
_Alloc().destroy(i);
}
_Alloc().deallocate(__data, size());
}
_Myt &assign(const_pointer _Rhs)
{
pointer buf = _Alloc().allocate(_Traits::length(_Rhs) + 1);
std::copy(&_Rhs[0], &_Rhs[_Traits::length(_Rhs)], &buf[0]);
_Alloc().construct(&buf[_Traits::length(_Rhs)], '\0');
std::swap(__data, buf);
for (iterator i = &buf[0]; i != &buf[_Traits::length(buf)]; ++i)
{
_Alloc().destroy(i);
}
_Alloc().deallocate(buf, _Traits::length(buf));
return *this;
}
_Myt &operator=(const_pointer _Rhs)
{
return assign(_Rhs);
}
_Myt &append(const_pointer _Rhs)
{
pointer buf = _Alloc().allocate(size() + _Traits::length(_Rhs) + 1);
std::copy(begin(), end(), &buf[0]);
std::copy(&_Rhs[0], &_Rhs[_Traits::length(_Rhs)], &buf[size()]);
_Alloc().construct(&buf[size() + _Traits::length(_Rhs)], '\0');
std::swap(__data, buf);
for (iterator i = &buf[0]; i != &buf[_Traits::length(buf)]; ++i)
{
_Alloc().destroy(i);
}
_Alloc().deallocate(buf, _Traits::length(buf));
return *this;
}
_Myt &operator+=(const_pointer _Rhs)
{
return append(_Rhs);
}
reference operator[](size_type _Base)
{
return __data[_Base];
}
reference at(size_type _Base)
{
if (_Base >= 0 && _Base < size())
{
return __data[_Base];
}
else
{
throw std::out_of_range("rocket::basic_string<>::at() invalid position");
}
}
const_reference operator[](size_type _Base) const
{
return __data[_Base];
}
const_reference at(size_type _Base) const
{
if (_Base >= 0 && _Base < size())
{
return __data[_Base];
}
else
{
throw std::out_of_range("rocket::basic_string<>::at() invalid position");
}
}
iterator begin()
{
return &__data[0];
}
iterator end()
{
return &__data[size()];
}
size_type size()
{
return _Traits::length(__data);
}
_Myt &swap(basic_string<_Elem> &_Rhs)
{
std::swap(__data, _Rhs.__data);
return *this;
}
void resize(size_type _Size)
{
if (_Size < size())
{
for (iterator i = begin(); i != end(); ++i)
{
if (i == &__data[_Size])
{
while (i != end())
{
_Alloc().destroy(i++);
}
}
}
}
else if (_Size > size())
{
reserve(_Size);
}
}
void shrink_to_fit()
{
int count = 0;
for (iterator i = begin(); i != end(); ++i, ++count)
{
if (*i == '\0')
{
resize(count);
}
}
}
void reserve(size_type _Size)
{
if (_Size < size())
{
return; // maybe resize(_Size) instead
}
pointer buf = _Alloc().allocate(_Size);
std::copy(begin(), end(), &buf[0]);
for (int i = size(); i < _Size; ++i)
{
_Alloc().construct(&buf[i], '\0');
}
std::swap(__data, buf);
for (iterator i = &buf[0]; i != &buf[_Traits::length(buf)]; ++i)
{
_Alloc().destroy(i);
}
_Alloc().deallocate(buf, _Traits::length(buf));
}
static const_pointer longest(const_pointer _Lhs, const_pointer _Rhs)
{
return _Traits::length(_Lhs) > _Traits::length(_Rhs) ? _Lhs
: _Traits::length(_Rhs) > _Traits::length(_Lhs) ? _Rhs : _Lhs;
}
static const_pointer shortest(const_pointer _Lhs, const_pointer _Rhs)
{
return _Traits::length(_Lhs) < _Traits().length(_Rhs) ? _Lhs
: _Traits::length(_Rhs) < _Traits().length(_Lhs) ? _Rhs : _Lhs;
}
bool operator==(const_pointer _Rhs)
{
return _Traits::compare(__data, _Rhs, _Traits::length(longest(*this, _Rhs))) == 0;
}
bool operator!=(const_pointer _Rhs)
{
return !(*this == _Rhs);
}
_Myt &format_s(const_pointer _Format, std::initializer_list<const_pointer> _Args)
{
int nsize = 0;
for (const_iterator const *i = _Args.begin(); i != _Args.end(); ++i)
{
nsize += _Traits::length(*i) - 2;
}
reserve(nsize + 24);
for (const_iterator const *i = _Args.begin(); i != _Args.end(); ++i)
{
_Char_Traits<_Elem>::_sprintf(__data, _Format, *i);
}
shrink_to_fit();
return *this;
}
_Myt &format(const_pointer _Format, ...)
{
reserve(_Traits::length(_Format) + 124);
va_list args;
va_start(args, _Format);
_Char_Traits<_Elem>::va_printf(__data, _Format, args);
va_end(args);
shrink_to_fit();
return *this;
}
template < typename _Ty > static const_pointer to_string(_Ty _Value)
{
return static_cast<std::basic_ostringstream<_Elem> *>(&(std::basic_ostringstream<_Elem>() << _Value))->str().c_str();
}
operator const_pointer()
{
return __data;
}
const_pointer data() const
{
return __data;
}
const_pointer c_str() const
{
return __data;
}
private:
pointer __data;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:41:58.373",
"Id": "73211",
"Score": "0",
"body": "Read: http://stackoverflow.com/a/228797/14065"
}
] | [
{
"body": "<p>First stop using underscores like that.</p>\n\n<ol>\n<li>Double underscore is always reserved for the implementation. </li>\n<li>A leading underscore followed by a capital letter is always reserved for the implementation.</li>\n</ol>\n\n<p>There are a couple of more rules. But basically unless you want to memorize stop using identifiers with double or a leading underscore. The problem is most beginners seem to want to learn from the standard library and pick that habit up there. The standard library is part of the implementation and thus they can do it. But you as an application level programmer can not.</p>\n\n<p>Bind the <code>&</code> and <code>*</code> to the type not the variable. They are part of type declaration not part of the variable.</p>\n\n<pre><code> int* x; // x is the variable `int*` is the type.\n</code></pre>\n\n<p>Tidy up your declarations; they are hard to read.</p>\n\n<pre><code>typedef basic_string<_Elem, _Traits, _Alloc> _Myt;\ntypedef _Elem value_type;\ntypedef _Traits traits_type;\ntypedef _Alloc allocator_type;\ntypedef value_type *pointer;\ntypedef const value_type *const_pointer;\ntypedef value_type *iterator;\ntypedef const value_type *const_iterator;\ntypedef value_type &reference;\ntypedef const value_type &const_reference;\ntypedef std::size_t size_type;\ntypedef std::ptrdiff_t difference_type;\n</code></pre>\n\n<p>Much easier to read:</p>\n\n<pre><code>typedef basic_string<_Elem, _Traits, _Alloc> _Myt;\ntypedef Elem value_type;\ntypedef Traits traits_type;\ntypedef Alloc allocator_type;\ntypedef value_type* pointer;\ntypedef const value_type* const_pointer;\ntypedef value_type* iterator;\ntypedef const value_type* const_iterator;\ntypedef value_type& reference;\ntypedef const value_type& const_reference;\ntypedef std::size_t size_type;\ntypedef std::ptrdiff_t difference_type;\n</code></pre>\n\n<p>Your use if allocator is making the code harder to read than necessary. You should have written the code without allocators. Got it reviewed and corrected then added the allocator where necessary.</p>\n\n<pre><code> _Alloc().construct() // Used to call the constructor\n // when doing an inplace new.\n _Alloc(). destroy() // Used to call the destructor on\n // an object that was created by\n // inplace new\n</code></pre>\n\n<p>We are dealing with characters and thus construction and destruction are completely irelavant to a string.</p>\n\n<p>Fundamental flaw in your design is that you don't keep track of the string size as a member of the class. You re-calculate it every time by searching along the string looking for the <code>\\0</code> marker. This is a real problem with your design fix it otherwise your class is little better than a <code>C-String</code>.</p>\n\n<p>Are you really only going to allocate 1 byte in the constructor?</p>\n\n<pre><code>basic_string()\n{\n __data = _Alloc().allocate(1);\n _Alloc().construct(&__data[0], '\\0');\n}\n</code></pre>\n\n<p>Its likely that string will be expanded real soon. usually you see to size variables in this type of container. The amount currently being used (size). The amount we have allocated for use (reserved).</p>\n\n<p>This is a dasterdly and very dangerious thing to do:</p>\n\n<pre><code>basic_string(void *_Init)\n{\n *this = basic_string(reinterpret_cast<const_pointer>(_Init));\n}\n</code></pre>\n\n<p>Most pointers auto convert to <code>void*</code> so your string here will initialize with any pointer and pretend it is a string. <strong>NOT</strong> a good idea. Make people be specific.</p>\n\n<p>Don't need to check for copy construction against yourself.</p>\n\n<pre><code>basic_string(const _Myt &_Init)\n{\n if (this != &_Init) {\n ...\n }\n}\n</code></pre>\n\n<p>You are not constructed yet. So you can not be passed as an argument to another constructor so there can never be copy construction from self.</p>\n\n<p>This is a very expensive copy operation.</p>\n\n<pre><code> *this = basic_string(_Init.c_str());\n</code></pre>\n\n<p>You convert to a <code>C-String</code>. Build a separate object that does not use the intrinsic properties of the class but builds from a native <code>C-String</code> (this is a class I would expect it to know its own size (here you are re-calculating it). Then you perform an assignment (which usually involved creating another copy and destroying it).</p>\n\n<p>It should be as simple as this (add your allocator as needed).</p>\n\n<pre><code> basic_string(Myt const& copy)\n : data(Alloc().allocate(copy.size+1))\n , size(copy.size)\n {\n std::copy(&copy.data[0], &copy.data[copy.size+1], &data[0]);\n }\n</code></pre>\n\n<p>Everywhere else in your code you use <code>Alloc().construct()</code> but in the <code>assign()</code> you use <code>std::copy()</code>.</p>\n\n<pre><code> std::copy(&_Rhs[0], &_Rhs[_Traits::length(_Rhs)], &buf[0]);\n _Alloc().construct(&buf[_Traits::length(_Rhs)], '\\0');\n</code></pre>\n\n<p>Be consistent.</p>\n\n<p>You have defined an assignment operator for <code>C-String</code> but not for real assignment. So you have not fulfilled the rule of three. because you did not define one the compiler generated one for you and it will not work correctly with RAW owned pointers.</p>\n\n<p>Its simple to implement use the copy and swap idum.</p>\n\n<pre><code>Myt &operator=(Myt rhs) // pass by value to get a copy.\n{\n rhs.swap(*this); // Swap the content with the copy.\n return *this;\n}\n</code></pre>\n\n<p><code>std::size</code> is unsigned it can never be negative.</p>\n\n<pre><code>reference at(size_type _Base)\n{\n if (_Base >= 0 && _Base < size())\n // ^^^^^^^^^^ Never be false\n</code></pre>\n\n<p>Violating the DRY principle here</p>\n\n<pre><code>// These two functions are identical to the non const versions.\nconst_reference operator[](size_type _Base) const\nconst_reference at(size_type _Base) const\n</code></pre>\n\n<p>This is a complicated way</p>\n\n<pre><code> for (iterator i = begin(); i != end(); ++i)\n {\n if (i == &__data[_Size])\n {\n while (i != end())\n {\n _Alloc().destroy(i++);\n }\n }\n }\n</code></pre>\n\n<p>of saying</p>\n\n<pre><code> for (iterator i = &data[_Size]; i != end(); ++i)\n {\n _Alloc().destroy(i);\n }\n</code></pre>\n\n<p>Also because you are using the <code>\\0</code> as a terminator to define the end of the string you forgot to move it.</p>\n\n<p>The concept of reserve makes no sense for your class as you have no way of tracking the amount of space you reserved. You have an size marker but no reserve end of space marker.</p>\n\n<pre><code>void reserve(size_type _Size) // makes no sense\n</code></pre>\n\n<p>Reserved space is be definition unused.\nSo you should not be constructing into it.</p>\n\n<pre><code> for (int i = size(); i < _Size; ++i)\n {\n _Alloc().construct(&buf[i], '\\0');\n }\n</code></pre>\n\n<p>You should construct into it when it becomes used. And destroy from it when it becomes unused.</p>\n\n<p>Compiler can't assume the <code>Traits::Length()</code> has no side affects. So worst case you are calculating the length many times here.</p>\n\n<pre><code> return _Traits::length(_Lhs) < _Traits().length(_Rhs) ? _Lhs\n : _Traits::length(_Rhs) < _Traits().length(_Lhs) ? _Rhs : _Lhs;\n</code></pre>\n\n<p>Here you run across the length of the string twice to do a comparison.</p>\n\n<pre><code> return _Traits::compare(__data, _Rhs, _Traits::length(longest(*this, _Rhs))) == 0;\n</code></pre>\n\n<p>You run along the string to find the length. Then you run along the string again to do the comparison. Seems like a lot of wasted effort.</p>\n\n<p>The starting pointer for a container class should look like this:</p>\n\n<pre><code>#include <cstddef>\n#include <algorithm>\n#include <functional>\n\ntemplate<typename C>\nclass mString\n{\n // Keep track of three things\n private:\n C* start; // points first character\n C* finish; // points one past end of used space\n C* reservedEnd; // points one past end of allocated space\n\n // Note: string is also '\\0' terminated.\n // So finish points at '\\0' and thus is never equal to reservedEnd\n public:\n</code></pre>\n\n<p>// Typedef needed for a container.<br>\n// Basic references to storage type. </p>\n\n<pre><code> typedef C value_type;\n typedef value_type* pointer;\n typedef value_type const* const_pointer;\n typedef value_type& reference;\n typedef value_type const& const_reference;\n\n // Iterator types. (not related to storage types)\n typedef C* iterator;\n typedef C const* const_iterator;\n typedef std::reverse_iterator<iterator> reverse_iterator;\n typedef std::reverse_iterator<const_iterator> const_reverse_iterator;\n\n // Utility types.\n typedef std::size_t size_type;\n typedef std::ptrdiff_t difference_type;\n</code></pre>\n\n<p>// Four basic methods required<br>\n// To implement a non leaking class that<br>\n// owns a RAW pointer. </p>\n\n<pre><code> mString()\n : start(new C[15])\n , finish(start)\n , reservedEnd(start + 15)\n {\n start[0] = '\\0';\n }\n mString(mString const& copy)\n : start(new C[copy.size() + 1])\n , finish(start + copy.size())\n , reservedEnd(finish + 1)\n {\n std::copy(copy.start, copy.finish + 1, start);\n }\n mString& operator=(mString rhs)\n {\n rhs.swap(*this);\n return *this;\n }\n ~mString()\n {\n delete [] start;\n }\n</code></pre>\n\n<p>// Methods required to implement the Container concept.</p>\n\n<pre><code> void swap(mString& other) noexcept\n {\n std::swap(start, other.start);\n std::swap(finish, other.finish);\n std::swap(reservedEnd, other.reservedEnd);\n }\n\n iterator begin() { return start;}\n iterator end() { return finish;}\n const_iterator begin() const { return start;}\n const_iterator end() const { return finish;}\n const_iterator cbegin()const { return start;}\n const_iterator cend() const { return finish;}\n\n bool empty() const { return start == finish; }\n std::size_t max_size() const { return 10000;} // Arbitrary (look up numeric limits)\n std::size_t size() const { return finish-start; }\n</code></pre>\n\n<p>// Methods required to implement the Forward Container concept</p>\n\n<pre><code> bool operator==(mString const& rhs) const {return size() == rhs.size() && std::equal(start, finish, rhs.start);}\n bool operator!=(mString const& rhs) const {return !operator==(rhs);}\n bool operator<(mString const& rhs) const {std::less<value_type> t; return size() < rhs.size() ? test(rhs, t) : rhs.test(*this, t);}\n bool operator>(mString const& rhs) const {std::greater<value_type> t; return size() < rhs.size() ? test(rhs, t) : rhs.test(*this, t);}\n bool operator>=(mString const& rhs) const {std::greater_equal<value_type> t; return size() < rhs.size() ? test(rhs, t) : rhs.test(*this, t);}\n bool operator<=(mString const& rhs) const {std::less_equal<value_type> t; return size() < rhs.size() ? test(rhs, t) : rhs.test(*this, t);}\n</code></pre>\n\n<p>// Methods require to implement the Reversible Container concept</p>\n\n<pre><code> reverse_iterator rbegin() { return reverse_iterator(finish); }\n reverse_iterator rend() { return reverse_iterator(start); }\n const_reverse_iterator rbegin() const { return const_reverse_iterator(finish); }\n const_reverse_iterator rend() const { return const_reverse_iterator(start); }\n</code></pre>\n\n<p>// A SINGLE method to convert a C-String into a string</p>\n\n<pre><code> mString(C* cString)\n : start(new C[(cString ? strlen(cString) : 0) + 15])\n , finish(start + (cString ? strlen(cString) : 0))\n , reservedEnd(finish + 15)\n {\n std::copy(cString, cString + size() + 1, start);\n }\n\n\n private:\n template<typename F>\n bool test(mString const& other, F f) const // makes assumptions about length (this must not be larger than other)\n {\n auto mis = std::mismatch(start, finish, other.start);\n return f(mis->first, mis->second);\n }\n\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:17:04.263",
"Id": "73294",
"Score": "0",
"body": "int* x, y; //now what happens? I think about the * as a type modifier, and as it needs to be added to each variable, I tend to use the same standard as OP. int *x, *y; //two pointers! yay"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:19:58.447",
"Id": "73296",
"Score": "3",
"body": "@AlexanderBrevig: Declare one variable per line. Every coding standard I have ever used has that rule. So yes it is an issue if you are not aware but since you will never do (because it breaks every coding standard and every piece of advice on this site) it it is not a problem. `int* x; int* y; /* YAY to pointers much more clearly defined */`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:22:50.040",
"Id": "73300",
"Score": "0",
"body": "@AlexanderBrevig: The style you propose is very C like. The style I propse is what the C++ community has been moving towards over the last 10 years. Its not an absolute and not everybody agrees."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:32:26.330",
"Id": "73307",
"Score": "0",
"body": "@AlexanderBrevig: But everybody agrees. One variable declaration per line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:58:49.297",
"Id": "73443",
"Score": "0",
"body": "Just an example to justify why I feel the * belongs near the variable name, and not the type it modifies. I completely agree that one should have one declaration per line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:09:48.660",
"Id": "73456",
"Score": "0",
"body": "@AlexanderBrevig: Your argument for doing it though is irrelevant in real world programming though. So not a very good one (argument). Basically it boils down to you have a habit that is at odds with my habit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:11:49.293",
"Id": "73457",
"Score": "2",
"body": "I put the '*' with the type. Because the I like all information about the type to be in a single place. So `int* x;` All the type information is on the left the identifier is on the right. That way when reading code I have a column of type information followed by a column of identifiers (I don't need to scan two parts of the sentence to find out all the information)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T22:55:59.167",
"Id": "73463",
"Score": "0",
"body": "PPS. The convention I use is also the one used by the C++ standard library (or at least the version I have on my machine) and boost. So for C++ program this convention seems to be mainly settled. For C programs though your convention is still the one most widely used. But I don't program in C (have not done so for a very long time)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:56:39.240",
"Id": "73500",
"Score": "0",
"body": "@LokiAstari, I have seen both conventions used (pointer/reference by the type, or by the variable). As far as I know, this depends more on chosen conventions for a particular code-base, than a general rule."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:37:43.077",
"Id": "42523",
"ParentId": "42477",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42523",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:21:08.610",
"Id": "42477",
"Score": "4",
"Tags": [
"c++",
"strings",
"reinventing-the-wheel"
],
"Title": "basic_string implementation"
} | 42477 |
<p>I'm trying to implement a TcpListener using the TPL. I'm not sure If I'm doing everything correctly though. I'm trying to keep the code as small as possible as well. It all works fine in a console application.</p>
<pre><code>public async Task RunAsync(CancellationToken cancellationToken)
{
var listener = new TcpListener(ip, port);
listener.Start();
while (!cancellationToken.IsCancellationRequested)
{
await AcceptClientAsync(listener, encoding, progress, cancellationToken);
}
listener.Stop();
}
</code></pre>
<p>Here is the <code>AcceptClientAsync</code> method: (Sorry for the weird formatting. StyleCop likes to do that.)</p>
<pre><code>private async Task AcceptClientAsync(TcpListener tcpListener, Encoding encoding, IProgress<string> progress, CancellationToken cancellationToken)
{
var client = await tcpListener.AcceptTcpClientAsync();
this.Connection = new ConnectionState { TcpClient = client };
while (client.Connected && !cancellationToken.IsCancellationRequested)
{
await
this.ReadStringAsync(this.Connection, encoding, progress)
.ContinueWith(
task =>
progress.Report(
string.Format("Client {0} disconnected.", Connection.TcpClient.Client.RemoteEndPoint)),
TaskContinuationOptions.OnlyOnFaulted);
}
}
</code></pre>
<p>And the <code>ReadStringAsync</code> method:</p>
<pre><code> private async Task ReadStringAsync(ConnectionState connection, Encoding encoding, IProgress<string> progress)
{
var stream = connection.TcpClient.GetStream();
if (connection.Read > 0)
{
var encoded = encoding.GetString(connection.Buffer, 0, connection.Read);
connection.StringBuilder.Append(encoded);
}
var decoded = connection.StringBuilder.ToString();
if (decoded.Contains("<End>"))
{
progress.Report(decoded.Replace("<End>", string.Empty));
}
connection.Read = await stream.ReadAsync(connection.Buffer, 0, connection.Buffer.Length);
}
</code></pre>
<p>I'd also like to keep using the <code>IProgress<></code> interface and support cancellation via <code>CancellationToken</code>s.</p>
| [] | [
{
"body": "<ol>\n<li><p>If you immediately <code>await</code> everything, you're not going to get any concurrency. This means that at any moment, there can be only one connection to this listener. Is this intentional?</p></li>\n<li><p>Because of the way TCP works, <a href=\"http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html\" rel=\"nofollow\">the <code>Connected</code> property may return <code>true</code> even if the other side already disconnected</a>. This means that you should send keep-alive packets, even if all you logically want to do is reading.</p></li>\n<li><p><code>ContinueWith()</code> is useful only rarely when you can use <code>async</code>. <code>OnlyOnFaulted</code> can be easily rewritten using <code>try</code>-<code>catch</code>. Though you should be catching only the specific exception that you need, not all of them. So your code could look something like:</p>\n\n<pre><code>try\n{\n await this.ReadStringAsync(this.Connection, encoding, progress);\n}\ncatch (NotSureWhichException ex)\n{\n progress.Report(\n string.Format(\"Client {0} disconnected.\", Connection.TcpClient.Client.RemoteEndPoint));\n}\n</code></pre></li>\n<li><p>I think the way you're dealing with <code><End></code> is wrong. If there is always going to be only one message per connection, then you should somehow indicate that after reading <code><End></code>. If there can be multiple messages, then an end of one message and start of the following one could be read in the same <code>ReadAsync()</code>, which means you're not going to report partial message.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T02:13:40.633",
"Id": "73155",
"Score": "0",
"body": "So about #1, perhaps I should use a ManualResetEvent to signal to the main thread to listen for another connection if one is active? Also, how often should I send Keep-Alive packets?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T12:57:09.883",
"Id": "73185",
"Score": "0",
"body": "I don't think MRE is a good solution here, especially since it's not async. What I would do is to move the `while` loop from `AcceptClientAsync()` to a separate method and *not* `await` that. But if you do that, be very careful about exceptions (i.e. you should probably add a `catch` around that `while`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T12:58:36.780",
"Id": "73186",
"Score": "0",
"body": "Regarding the timing of keep alive packets, that depends on you, specifically, on how soon do you want to learn about the other side disappearing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:23:27.157",
"Id": "42486",
"ParentId": "42480",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T23:51:36.733",
"Id": "42480",
"Score": "4",
"Tags": [
"c#",
".net",
"async-await",
"tcp"
],
"Title": "Async TcpListener"
} | 42480 |
<p>Can you please review my PHP script below? It is for a contact form. Am I breaking any rules? Does it seem okay to you?</p>
<pre><code><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset(
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['message'],
$_REQUEST['number'],
$_REQUEST['date'],
$_REQUEST['select'],
$_REQUEST['radio'],
$_REQUEST['checkbox'],
$_REQUEST['token'] )){
if($_SESSION['token'] != $_POST['token']){ $response = "0";
} else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
switch (true){
case !filter_var($email, FILTER_VALIDATE_EMAIL):
$response = "<p style='color:red'>Invalid Email Address!</p>";
break;
default:
$to = "support@loaidesign.co.uk";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
Number: $number<br/>
Date: $date<br/>
Select: $select<br/>
Radio: $radio<br/>
Checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
if( isset($_REQUEST['ajax'])){ $response = ($mailed) ? "1" : "0";
}
else{ $response = ($mailed) ? "<h2>Success!</h2>" : "<h2>Error! There was a problem with sending.</h2>";
}
break;
}
echo $response;
}
} else {
echo "Error";
}
ob_flush();
die();
}
?>
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
</code></pre>
<hr>
<pre><code><!--Contact Form-->
<form id="contactForm" name="contactForm" action="contact.php" method="post">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" class="required" autocomplete="off">
</div>
<div class="email-address">
<p>Email Address</p>
<input name="email" class="required email" autocomplete="off">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" rows="5" class="required min3"></textarea>
</div>
<div class="number">
<p>Phone Number</p>
<input name="number" class="number" autocomplete="off">
</div>
<div class="date">
<p>Date <small>(dd/mm/yyyy)</small></p>
<input name="date" class="required date calendar" autocomplete="off">
</div>
<div class="dropdown">
<select name="select" class="required">
<option value="">Select</option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</div>
<div class="radio">
<p>Radios:</p>
<label><input name="radio" type="radio" value="male" class="required">Male</label>
<label><input name="radio" type="radio" value="female" class="required">Female</label>
</div>
<div class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="OptionA" class="required">Option A</label>
<label><input name="checkbox" type="checkbox" value="OptionB" class="required">Option B</label>
</div>
<div>
<p></p>
<input name="" class="required number spamcheck">
</div>
<button id="submit" type="submit">Send</button>
</form>
</code></pre>
| [] | [
{
"body": "<p>Using the <code>token</code> for CSRF protection and spam prevention is a good idea, especially for a form that will be generating e-mail.</p>\n\n<p>This is puzzling: <code><input name=\"ajax\" type=\"hidden\" value=\"1\"></code>. If a very basic, non-JavaScript-enabled user agent submits the HTML form, it will have <code>ajax=1</code> as a parameter. I'd expect such a parameter to be set not by the HTML form, but by the JavaScript code that composes the AJAX request. Even then, it's customary for the JavaScript to set an <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Common_non-standard_request_headers\" rel=\"nofollow\"><code>X-Requested-With</code> header</a> instead of an <code>ajax</code> parameter.</p>\n\n<p>From a zoomed out view, the structure of the program is:</p>\n\n<pre><code><?php\n\n if () {\n ob_start();\n if () {\n if () {\n } else {\n switch (true) {\n blah:\n default:\n // The core functionality lives here.\n }\n }\n }\n ob_flush();\n die();\n }\n?>\n<form>\n …\n</form>\n</code></pre>\n\n<p>That's a <em>lot</em> of nesting, and it's hard to see at a glance how to reach the core functionality. Also, I'm not a fan of <code>ob_start(); …; ob_flush(); die();</code> — any kind of killing, even if it's suicide, is a bad idea for server-side code. Furthermore, that <code>switch</code> is a weird way to write an if-else.</p>\n\n<p>Instead, I suggest wrapping the core functionality and other tests within a functions.</p>\n\n<pre><code><?php\n function isCompletePost() {\n // Check for a POST containing the CSRF-prevention token\n // and the expected content fields. Return TRUE or FALSE.\n }\n\n function hasValidEmailAddress() {\n // Check for valid $_REQUEST['email']\n // Return TRUE or FALSE\n }\n\n function sendEmail() {\n // Core functionality here. Compose mail based on $_REQUEST\n // fields and send it.\n }\n\n if (isCompletePost()) {\n if (!hasValidEmailAddress()) {\n ?><p style='color:red'>Invalid Email Address!</p><?php\n } else {\n sendEmail();\n }\n } else {\n?>\n<form>\n …\n</form>\n<?php\n }\n<?php>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:21:43.123",
"Id": "42485",
"ParentId": "42481",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:24:31.233",
"Id": "42481",
"Score": "3",
"Tags": [
"php",
"html",
"form",
"email"
],
"Title": "Is this contact form code breaking any rules?"
} | 42481 |
<p>Is there a faster way to compute the bounding area between 2 points?</p>
<pre><code>// Minified Version
public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
double dx = p2.x - p1.x, dy = p2.y - p1.y;
return new Rectangle((int) (dx < 0 ? p2.x : p1.x),
(int) (dy < 0 ? p2.y : p1.y), (int) Math.abs(dx), (int) Math.abs(dy));
}
// Readable Version
public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
double dx = p2.x - p1.x;
double dy = p2.y - p1.y;
int x = (int) (dx < 0 ? p2.x : p1.x);
int y = (int) (dy < 0 ? p2.y : p1.y);
int w = (int) Math.abs(dx);
int h = (int) Math.abs(dy);
return new Rectangle(x, y, w, h);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T05:32:13.957",
"Id": "73175",
"Score": "0",
"body": "Why not use a Rectangle2D, by the way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T05:34:30.270",
"Id": "73176",
"Score": "0",
"body": "Didn't think about it."
}
] | [
{
"body": "<p>You're doing two tests to compare <code>p1.x</code> with <code>p2.x</code>:</p>\n\n<ul>\n<li>One here: <code>int x = (int) (dx < 0 ? p2.x : p1.x);</code></li>\n<li>Another here (implicit in the <code>Math.abs</code> method): <code>int w = (int) Math.abs(dx);</code></li>\n</ul>\n\n<p>You also have the overhead of making a subroutine call to <code>Math.abs</code>.</p>\n\n<p>Faster would be:</p>\n\n<pre><code>if (p1.x <= p2.x)\n{\n int x = p1.x;\n int w = p2.x - p1.x;\n if (p1.y <= p2.y)\n {\n int y = p1.y;\n int h = p2.y - p1.y;\n return new Rectangle(x, y, w, h);\n }\n else\n {\n int y = p2.y;\n int h = p1.y - p2.y;\n return new Rectangle(x, y, w, h);\n }\n}\nelse\n{\n ... etc ...\n}\n</code></pre>\n\n<p>Refactoring the above to reduce duplication:</p>\n\n<pre><code>int x;\nint w;\nif (p1.x <= p2.x)\n{\n x = p1.x;\n w = p2.x - p1.x;\n}\nelse\n{\n x = p2.x;\n w = p1.x - p2.x;\n}\nint y;\nint h;\nif (p1.y <= p2.y)\n{\n y = p1.y;\n h = p2.y - p1.y;\n}\nelse\n{\n y = p2.y;\n h = p1.y - p2.y;\n}\nreturn new Rectangle(x, y, w, h);\n</code></pre>\n\n<p>Or refactoring to make it more compact:</p>\n\n<pre><code>if (p1.x <= p2.x)\n{\n if (p1.y <= p2.y)\n {\n return new Rectangle(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);\n }\n else\n {\n return new Rectangle(p1.x, p2.y, p2.x - p1.x, p1.y - p2.y);\n }\n}\nelse\n{\n ... etc ...\n}\n</code></pre>\n\n<p>If you want to implement rolfl's suggestion to have the bounding rectangle outside the points, then use <a href=\"https://stackoverflow.com/a/5685930/49942\"><code>Math.ceil</code></a> for example:</p>\n\n<pre><code>if (p1.x <= p2.x)\n{\n int x = p1.x;\n int w = Math.ceil(p2.x) - x;\n ... etc ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:35:39.317",
"Id": "73207",
"Score": "0",
"body": "Thanks you for this, very helpful. I often find myself using the tertiary operator too much, when I could be grouping multiple lines within an `if-block`..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:23:36.050",
"Id": "42487",
"ParentId": "42484",
"Score": "4"
}
},
{
"body": "<p>There are two problems here... both related to datatypes.</p>\n\n<p>First, though, I don't believe you can get much more in the way of performance. Make sure you have adequately warmed up your system before you take benchmarks though, the Java runtime will get faster with successive compiles. Make sure you are benchmarking it at it's fastest.</p>\n\n<p>OK, now the problems:</p>\n\n<p>First, the inputs are double values, but you are calculating int values for the rectangle.</p>\n\n<p>If you input the data as ints, it will be faster.</p>\n\n<p>The second problem is that, if your input doubles have a fractional component, then your bounding rectangle is wrong... it shoudl be on the outside of the points, but, because you are doing integer conversion, it will not bound the points on all sides, but will sit inside of what would have been the rectangle if the rectangle's coordinates were double too.</p>\n\n<p>I would guess that a large part of your performance hit is from type-conversion.</p>\n\n<p>Finally, it may not help, but I have had success before, from converting the method, and all the values inside it, to be final. This may help the Java JIT compiler to inline the calls in to it's compiled code. Try it, and benchmark.</p>\n\n<p><strong>Edit:</strong> More about the double/int bounding rectangle.</p>\n\n<p>If you have the points <code>(0.0, 0.0)</code> and <code>(0.9,0.9)</code> then your code will compute the bounding rectangle as <code>new Rectangle(0,0,0,0);</code>, but it should be <code>new Rectangle(0,0,1,1)</code> ... (or should it)?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:34:05.447",
"Id": "73150",
"Score": "0",
"body": "Well, sorry for not being clear. I have a component which has a `Point2D.Double` for comparing with other components, but when I draw it, I want to make sure that I am using integer values for the bounding box."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T02:59:24.463",
"Id": "73158",
"Score": "0",
"body": "@Mr.Polywhirl - added an edit to my answer, to illustrate my point"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T05:21:34.997",
"Id": "73173",
"Score": "0",
"body": "Thanks, that would make sense. I will give these a try soon and see how it goes. I am in the process of creating a graph data structure in library. The bounding box is to draw UI components such as verticies and edges. Here is the link if you are interested. https://github.com/ryankane/visgraph"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:37:25.870",
"Id": "73208",
"Score": "0",
"body": "Your latest response is great, thanks. I guess I should have checked the `Line2D` class first. I guess I cared too much about the theory of implementing a bounding area than to solve my problem with the tools I have at my disposal."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:26:11.547",
"Id": "42489",
"ParentId": "42484",
"Score": "6"
}
},
{
"body": "<p>Using a completely different tack... the simplest way to do this would be to use the native mechanisms available in the AWT toolkit....</p>\n\n<p><strong>For a regular Rectangle</strong></p>\n\n<pre><code>public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {\n return new (Line2D.Double(p1, p2)).getBounds();\n}\n</code></pre>\n\n<p><strong>For a Rectangle2D</strong></p>\n\n<pre><code>public static Rectangle2D computeBounds(Point2D.Double p1, Point2D.Double p2) {\n return new (Line2D.Double(p1, p2)).getBounds2D();\n}\n</code></pre>\n\n<p><strong>Results</strong></p>\n\n<p>I have put this all together in a test harness, to measure the performance, and included two additional tests for you to consider:</p>\n\n<pre><code>import java.awt.geom.Line2D;\nimport java.awt.geom.Point2D;\nimport java.awt.geom.Rectangle2D;\nimport java.awt.geom.Point2D.Double;\nimport java.awt.Rectangle;\nimport java.util.Arrays;\nimport java.util.Random;\n\n\n@SuppressWarnings(\"javadoc\")\npublic class Bounds {\n\n private static abstract class BoundIt {\n private final String name;\n public BoundIt(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n abstract Object computeBounds(Point2D.Double p1, Point2D.Double p2);\n }\n\n private static final BoundIt[] solvers = {\n new BoundIt(\"OPMinified\") {\n\n @Override\n // Minified Version\n public Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {\n double dx = p2.x - p1.x, dy = p2.y - p1.y;\n return new Rectangle((int) (dx < 0 ? p2.x : p1.x),\n (int) (dy < 0 ? p2.y : p1.y), (int) Math.abs(dx), (int) Math.abs(dy));\n } \n\n },\n\n new BoundIt(\"OPReadable\") {\n\n @Override\n // Readable Version\n public Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {\n double dx = p2.x - p1.x;\n double dy = p2.y - p1.y;\n\n int x = (int) (dx < 0 ? p2.x : p1.x);\n int y = (int) (dy < 0 ? p2.y : p1.y);\n int w = (int) Math.abs(dx);\n int h = (int) Math.abs(dy);\n\n return new Rectangle(x, y, w, h);\n }\n\n },\n\n new BoundIt(\"KeepDouble\") {\n\n @Override\n // Readable Version\n public Rectangle2D computeBounds(Point2D.Double p1, Point2D.Double p2) {\n double dx = p2.x - p1.x;\n double dy = p2.y - p1.y;\n\n double x = dx < 0 ? p2.x : p1.x;\n double y = dy < 0 ? p2.y : p1.y;\n double w = Math.abs(dx);\n double h = Math.abs(dy);\n\n return new Rectangle2D.Double(x, y, w, h);\n }\n\n },\n\n new BoundIt(\"Native\") {\n\n @Override\n // Readable Version\n public Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {\n return new Line2D.Double(p1, p2).getBounds();\n }\n\n },\n\n new BoundIt(\"Native2D\") {\n\n @Override\n // Readable Version\n public Rectangle2D computeBounds(Point2D.Double p1, Point2D.Double p2) {\n return new Line2D.Double(p1, p2).getBounds2D();\n }\n\n },\n\n };\n\n\n public static final void testRound(int id, boolean print, Point2D.Double[] as, Point2D.Double[] bs) {\n\n Object[] results = new Object[as.length];\n\n for (BoundIt solver : solvers) {\n long time = System.nanoTime();\n for (int i = 0; i < as.length; i++) {\n results[i] = solver.computeBounds(as[i], bs[i]);\n }\n time = System.nanoTime() - time;\n\n int hc = 0;\n for (Object o : results) {\n hc ^= o.hashCode();\n }\n if (print) {\n System.out.printf(\"Solved Rep %d Solver %10s in %.3fms (hash %d)\\n\", id, solver.getName(), time / 1000000.0, hc);\n }\n }\n }\n\n public static void main(String[] args) {\n int datacnt = 409600;\n double span = 100;\n double offset = - span / 2;\n Random rand = new Random(0);\n\n Point2D.Double[] data = new Point2D.Double[datacnt << 1];\n\n for (int i = data.length - 1; i >= 0; i--) {\n data[i] = new Point2D.Double(offset + span * rand.nextDouble(), offset + span * rand.nextDouble());\n }\n\n Point2D.Double[] as = Arrays.copyOfRange(data, 0, datacnt);\n Point2D.Double[] bs = Arrays.copyOfRange(data, datacnt, data.length);\n data = null;\n\n System.gc();\n\n for (int i = 0; i < 100; i++) {\n System.out.println(\"\\n\\nProcessing round \" + i);\n testRound(i, i >= 90, as, bs);\n }\n }\n\n}\n</code></pre>\n\n<p>The reults from that test look like:</p>\n\n<blockquote>\n<pre><code>Processing round 97\nSolved Rep 97 Solver OPMinified in 16.059ms (hash 1545060352)\nSolved Rep 97 Solver OPReadable in 15.169ms (hash 1545060352)\nSolved Rep 97 Solver KeepDouble in 15.726ms (hash -2058404443)\nSolved Rep 97 Solver Native in 26.782ms (hash 1558544384)\nSolved Rep 97 Solver Native2D in 12.478ms (hash -2058404443)\n\n\nProcessing round 98\nSolved Rep 98 Solver OPMinified in 13.386ms (hash 1545060352)\nSolved Rep 98 Solver OPReadable in 16.300ms (hash 1545060352)\nSolved Rep 98 Solver KeepDouble in 13.484ms (hash -2058404443)\nSolved Rep 98 Solver Native in 59.174ms (hash 1558544384)\nSolved Rep 98 Solver Native2D in 14.190ms (hash -2058404443)\n\n\nProcessing round 99\nSolved Rep 99 Solver OPMinified in 14.764ms (hash 1545060352)\nSolved Rep 99 Solver OPReadable in 14.199ms (hash 1545060352)\nSolved Rep 99 Solver KeepDouble in 13.572ms (hash -2058404443)\nSolved Rep 99 Solver Native in 30.009ms (hash 1558544384)\nSolved Rep 99 Solver Native2D in 13.721ms (hash -2058404443)\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T08:31:17.247",
"Id": "73180",
"Score": "0",
"body": "I see a hiccup in round 98 above, and a similar one happened on my machine. You should move `System.gc()` inside `testRound()`, or at least inside the loop that calls `testRound()`. Also, it seems that the performance stabilizes starting at the second round already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:34:34.187",
"Id": "73205",
"Score": "0",
"body": "So simple and fast: `Line2D.Double(p1, p2).getBounds2D();`. Thank you for your response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:34:36.397",
"Id": "73206",
"Score": "0",
"body": "@200_success I was confused by your comment, then realized the code I put in this post is not the ones I used to generate my results... *duh*.... I have moved the System.gc() already... and a couple of other things"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T06:17:32.303",
"Id": "42495",
"ParentId": "42484",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "42495",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:05:19.263",
"Id": "42484",
"Score": "5",
"Tags": [
"java",
"performance",
"awt"
],
"Title": "Compute bounding rectangle given 2 points quickly and efficiently"
} | 42484 |
<p>My goal is to save space occupied by 2D array (sea) that has 3 different values.</p>
<pre><code>Ocean sea; //Ocean class has member 'private int[][] oceanMatrix;'
public final static int EMPTY = 1;
public final static int SHARK = 2;
public final static int FISH = 3;
</code></pre>
<p>by compressing it and place in two one dimensional array.</p>
<pre><code>int[] runType = new int[10]; // each cell stores 1 or 2 or 3
int[] runLength = new int[10]; // corresponding index cell stores its number of occurence of that respective runType.
</code></pre>
<p>I am using <code>Runlength</code> encoding idea and wrote below code, which is yet to be fit into a Java class.</p>
<p>I need feedback/critiques on this logic of the below code and coding style, so that I can optimize and make it better. Constraint is to not use any existing Java library class except (array's length member).</p>
<pre><code>private static int[] doubleTheSize(int[] arg){
int[] temp = new int[2*arg.length];
for(int c = 0; c < arg.length; c++){
temp[c] = arg[c];
}
return temp;
}
public static void main(String[] args) {
Ocean sea;
int[] runType = new int[10];
int[] runLength = new int[10];
int index = 0;
boolean firstCell = true;
//i&j are width & height of a 2d array read from commandline
for(int row = 0; row < j ; row++){
for(int col = 0; col < i ; col++){
if(firstCell){
firstCell=false;
runType[index] = sea.cellContents(0, 0);
runLength[index]++;
continue;
}
switch(sea.cellContents(row, col)){
case Ocean.EMPTY:
if(runType[index] == Ocean.EMPTY){
runLength[index]++;
}else{
index++;
if(index==runType.length){
runType = doubleTheSize(runType);
runLength = doubleTheSize(runLength);
}
runType[index]=Ocean.SHARK;
runLength[index]++;
}
break;
case Ocean.SHARK:
if(runType[index] == Ocean.SHARK){
runLength[index]++;
}else{
index++;
if(index==runType.length){
runType = doubleTheSize(runType);
runLength = doubleTheSize(runLength);
}
runType[index]=Ocean.SHARK;
runLength[index]++;
}
break;
case Ocean.FISH:
if(runType[index] == Ocean.FISH){
runLength[index]++;
}else{
index++;
if(index==runType.length){
runType = doubleTheSize(runType);
runLength = doubleTheSize(runLength);
}
runType[index]=Ocean.FISH;
runLength[index]++;
}
break;
}// end switch
}//end inner for loop
}//end outer for loop
}//end main()
</code></pre>
<p>I wrote the above code for that. Please help me review this code for optimization. One point that I recognized is, <code>firstCell</code> check that I did for every cell doesn't make sense. I need suggestion to better this logic because I need to enter in <code>firstCell i{}</code> block for only (0,0) cell.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T03:12:26.353",
"Id": "73162",
"Score": "0",
"body": "You say `//i&j are width & height of a 2d array` .... but I say [I&J are Fish in the Ocean](http://www.za.all.biz/img/za/catalog/4386.jpeg) ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T03:15:41.067",
"Id": "73163",
"Score": "0",
"body": "How fixed are you on that particular compression format? Would you be interested in a smaller/more compact one?"
}
] | [
{
"body": "<p>This is an interesting problem. Your code looks effective, and there is little that sticks out at me as being a performance problem, except that I feel the two-array RLE is not the most efficient mechanism.</p>\n\n<p>There are ways that you can reduce the code size, but I don't think that will impact the run-time performance though. You can, if you want, isert the three constant values <code>FISH</code>, <code>SHARK</code>, and <code>EMPTY</code> in to an array, and then you can reduce the code repetition by making use of the array. I do something similar in the example at the end.</p>\n\n<p>OK, about the RLE algorithm though...</p>\n\n<p>For every value in your RLE data you need 2 integers (1 in each array). Each time the run-value changes (e.g. from EMPTY to SHARK) you add 2 integers. For the example data:</p>\n\n<pre><code>data -> [1,1,1,1,1,2,1,1,1]\n</code></pre>\n\n<p>you will have two arrays:</p>\n\n<pre><code>code -> [1,2,1]\nlength -> [5,1,3]\n</code></pre>\n\n<p>This is 6 integers worth.</p>\n\n<p>If you change the algorithm to just 1 array, but you force the algorithm to store a possibly empty value for non-existant values, you can have the single output:</p>\n\n<pre><code>encoded -> [5,1,0,3]\n</code></pre>\n\n<p>To decode this, you say, I have <code>5</code> 1's, followed by <code>1</code> 2, followed by <code>0</code> 3's, and then <code>3</code> 1's.</p>\n\n<p>The advantage of this system is that, for about half the transitions, you only need to have 1 extra integer for the transition, instead of always requiring 2. This means that each transition takes an average of 1.5 integers, instead of 2.... so the data encodes down to about 25% less space.</p>\n\n<p>Yu can see that in the data, where the single array stores the data in 4 integers, but the 2-array system stores it in 6 integers (3 in each array).</p>\n\n<p>While this space saving is significant, the real benefit is in the encoding, and decoding speed and simplicity.</p>\n\n<p>I put together these two methods that do the encoding, and decoding system. The methods store the arrays structure as part of the encoded stream.... it is basically a serialization of the data. I imagine that this is why you are doing this process anyway.</p>\n\n<p>Anyway, you will see that the loops are actually much simpler than yours, and the encoding and decoding is quite symmetrical... which is nice.</p>\n\n<pre><code>import java.util.Arrays;\n\n\n@SuppressWarnings(\"javadoc\")\npublic class RLEncode {\n\n public final static int EMPTY = 1;\n public final static int SHARK = 2;\n public final static int FISH = 3;\n\n public static int[] encode(int[][] matrix) {\n final int[] validvalues = {EMPTY, SHARK, FISH};\n\n final int height = matrix.length;\n final int width = height > 0 ? matrix[0].length : 0;\n // start with some reasonable size\n // will resize as necessary\n int[] result = new int[2 + validvalues.length + 1024];\n int cnt = 0;\n\n // save away the core details of the ocean.\n result[cnt++] = height;\n result[cnt++] = width;\n result[cnt++] = validvalues.length;\n for (int vv : validvalues) {\n result[cnt++] = vv;\n }\n\n // The encoding from here cycles through the possible values\n // and stores away the run-length of each value.\n int content = 0;\n for (int[] row : matrix) {\n if (row.length != width) {\n throw new IllegalStateException(\"Irregular matrix\");\n }\n for (int v : row) {\n int ref = content;\n while (v != validvalues[content]) {\n // cycle until we find the matching cell type.\n cnt++; // we move on...\n if (cnt >= result.length) {\n // add 50% to cell size.\n result = Arrays.copyOf(result, result.length + (result.length >>> 1));\n }\n content = (content + 1) % validvalues.length;\n if (content == ref) {\n // we have looped through all our values... oops.\n throw new IllegalStateException(\"Illegal value \" + v);\n }\n }\n // add to run-length\n if (++result[cnt] < 0) {\n throw new IllegalStateException(\"Overflowed during encoding\");\n }\n }\n }\n cnt++;\n return Arrays.copyOf(result, cnt);\n }\n\n public static int[][] decode(int[] encoded) {\n if (encoded.length < 3) {\n throw new IllegalArgumentException(\"Minimum size encoded value is \" + 3);\n }\n int cnt = 0;\n int height = encoded[cnt++];\n int width = encoded[cnt++];\n int[][] result = new int[height][width];\n int validcnt = encoded[cnt++];\n int[] validvalues = new int[validcnt];\n if (encoded.length < cnt + validcnt) {\n throw new IllegalStateException(\"Expect there to be \" + validcnt + \" valid values, but there's not enough data.\");\n }\n for (int i = 0; i < validcnt; i++) {\n validvalues[i] = encoded[cnt++];\n }\n\n int content = 0;\n int cursor = 0;\n for ( ; cnt < encoded.length; cnt++) {\n for (int i = encoded[cnt] - 1; i >= 0; i--) {\n result[cursor / width][cursor % width] = validvalues[content];\n cursor++;\n }\n content = (content + 1) % validcnt;\n }\n\n if (cursor != (width * height)) {\n throw new IllegalStateException(\"Expected to decode exactly \" + (width * height) + \" cells\");\n }\n\n return result;\n }\n\n\n public static void main(String[] args) {\n int[][]matrix = {\n {1,1,1,1,1,1,1,2,1},\n {1,1,1,2,1,1,2,1,1},\n {1,2,3,2,1,1,1,2,1},\n {1,1,1,1,1,1,1,1,1},\n {1,1,1,1,1,2,1,1,2},\n {1,1,1,1,1,1,1,1,1}\n };\n int[] encoded = encode(matrix);\n int[][] decoded = decode(encoded);\n\n if (!Arrays.deepEquals(matrix, decoded)) {\n throw new IllegalStateException(\"Broken\");\n }\n\n }\n\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:34:35.430",
"Id": "42493",
"ParentId": "42488",
"Score": "4"
}
},
{
"body": "<p>Run-length encoding is not always the most efficient way. If the value very changes often (so that length is always <code>1</code>) the RLE encoding method can be longer than the original data (because you're storing the data, plus the extra <code>1</code> for each datum).</p>\n\n<p>Sometimes people recommend that you simply using an industrial-strength 'ZIP' algorithm on the data instead.</p>\n\n<hr>\n\n<p>If you want to make your RLE more compact, a possibility is to use some bits which you're currently not using: you're only using 2 bits within the first int to store the 3-valued data; you could store the length within the free 29-bits of the same integer, and use the last bit to indicate a length overflow into the next int:</p>\n\n<ul>\n<li>1st 2 bits: the data (empty or fish or shark)</li>\n<li>Next 29 bits: the length (can't be zero)</li>\n<li>Last (i.e. 32nd) bit: usually 0; 1 (which probably happens rarely) means that the length doesn't fit into 29 bits, and that the next integer in the array store the rest of the length (or that the 29 bits in this integer aren't used, and that the whole of the length is stored in the next integer).</li>\n</ul>\n\n<p>For example, if your ocean consists of 2 fish and 1 shark, you used to encode that in 4 integers like this:</p>\n\n<pre><code>3, 2, 2, 1\n</code></pre>\n\n<p>With the method I'm suggesting you could encode that in two integers as follows:</p>\n\n<pre><code>3 + (2 << 2), 2 + (1 << 2)\n</code></pre>\n\n<hr>\n\n<p>Taking another idea from rolfl's answer, you only need one bit (not two bits) to store the type of datum:</p>\n\n<ul>\n<li>Remember (separately) the type of the first datum</li>\n<li>Know that the next datum isn't the same as this datum (because this datum is run-length encoded)</li>\n<li>Therefore one bit is enough: for example if the previous datum is FISH, use 0 to specify that the next is EMPTY and 1 to specify that the next is SHARK.</li>\n</ul>\n\n<hr>\n\n<p>You can compress it further by streating it as a stream of bits and ignoring the 32-bit integer boundaries. For example:</p>\n\n<ul>\n<li>1 bit specifies the type of datum</li>\n<li>5 bits specifies the number of bits which encode the length (i.e. up to 32 bits)</li>\n<li>Variable-length 1 to 32 bits (as specified in the previous 5 bits) specifies the run-length</li>\n</ul>\n\n<p>If a typical run-length is for example 1000 (for empty spaces) that takes about 10 bits for the length. 1 + 5 + 10 means you encode each empty space in only about 16 bits; and the runs for fishes and sharks might be shorter (1 to 4 bits-worth of length), so they encode in 7 to 10 bits. In summary you might be able to encode, on average, two run-lengths in each 32-bits of data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T08:45:27.950",
"Id": "42496",
"ParentId": "42488",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>One point that I recognized is, <code>firstCell</code>\n check that I did for every cell doesn't make sense. \n I need suggestion to better this logic because I \n need to enter in <code>firstCell i{}</code> block for only (0, 0) cell.</p>\n</blockquote>\n\n<p>You should measure it and if it's a <em>really real bottleneck</em> do something about it. Otherwise it's just bad <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimization</a> and will lead to harder to read and unmaintainable code. JVM is smart, I guess it will optimize it for you at runtime if it's really necessary. It can unroll loops and eliminate dead code.</p>\n\n<hr>\n\n<p>DON'T DO THIS, just for fun, let's unroll the some iteration from the loop manually to save some boolean checks at runtime:</p>\n\n<p>Initial loop:</p>\n\n<pre><code>boolean firstCell = true;\nfor (int row = 0; row < j; row++) {\n for (int col = 0; col < i; col++) {\n if (firstCell) {\n firstCell = false;\n runType[index] = sea.cellContents(0, 0);\n runLength[index]++;\n continue;\n }\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>After unrolling one iteraton of the outer loop:</p>\n\n<pre><code>if (j > 0) {\n int row = 0;\n for (int col = 0; col < i; col++) {\n if (firstCell) {\n firstCell = false;\n runType[index] = sea.cellContents(0, 0);\n runLength[index]++;\n continue;\n }\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\nfor (int row = 1; row < j; row++) { // initial value changes\n for (int col = 0; col < i; col++) {\n if (firstCell) { // dead code\n firstCell = false;\n runType[index] = sea.cellContents(0, 0);\n runLength[index]++;\n continue;\n }\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>Unrolling the first iteration of the inner loop:</p>\n\n<pre><code>if (j > 0) {\n int row = 0;\n if (i > 0) {\n if (firstCell) {\n firstCell = false;\n runType[index] = sea.cellContents(0, 0);\n runLength[index]++;\n // continue; // not necessary anymore \n }\n // not necessary anymore\n // switch (sea.cellContents(row, col)) {\n // // ...\n // }\n }\n\n for (int col = 1; col < i; col++) { // initial value changes\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\nfor (int row = 1; row < j; row++) {\n for (int col = 0; col < i; col++) { // don't need to change\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>Removing <code>firstCell</code> check and dead code:</p>\n\n<pre><code>if (j > 0) {\n if (i > 0) {\n firstCell = false;\n runType[index] = sea.cellContents(0, 0);\n runLength[index]++;\n }\n\n for (int col = 1; col < i; col++) {\n int row = 0;\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\nfor (int row = 1; row < j; row++) {\n for (int col = 0; col < i; col++) {\n switch (sea.cellContents(row, col)) {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>Once again, don't do this, it's harder to read and understand, contains lots of duplication and hard to maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:39:16.273",
"Id": "73498",
"Score": "0",
"body": "i need more feedback on firstCell check that am doing. i really want to remove it from inner loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T07:08:45.697",
"Id": "74024",
"Score": "0",
"body": "can i declare runType as enum type, because, i know have 3 values to store there ."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T12:09:47.580",
"Id": "42499",
"ParentId": "42488",
"Score": "3"
}
},
{
"body": "<p>A few notes about the original code.</p>\n\n<ol>\n<li><p>If the ocean mostly empty it's actually a sparse matrix. If you are allowed to use more arrays or another primitive data structures check the <a href=\"https://en.wikipedia.org/wiki/Sparse_matrix#Storing_a_sparse_matrix\" rel=\"nofollow noreferrer\">Spare matrix Wikipedia article</a> about it, it contains other, maybe more effective storage structures.</p></li>\n<li><p>The second switch case contains the same logic three times. You could extract it out to a method to remove duplication:</p>\n\n<pre><code>private static int encode(int[] runType, int[] runLength, int currentType, int index) {\n if (runType[index] == currentType) {\n runLength[index]++;\n } else {\n index++;\n if (index == runType.length) {\n runType = doubleTheSize(runType);\n runLength = doubleTheSize(runLength);\n }\n runType[index] = currentType;\n runLength[index]++;\n }\n return index;\n}\n</code></pre>\n\n<p>And use it in the switch:</p>\n\n<pre><code>switch (sea.cellContents(row, col)) {\ncase Ocean.EMPTY: {\n final int currentType = Ocean.EMPTY;\n index = encode(runType, runLength, currentType, index);\n break;\n}\ncase Ocean.SHARK: {\n int currentType = Ocean.SHARK;\n index = encode(runType, runLength, currentType, index);\n break;\n}\ncase Ocean.FISH: {\n int currentType = Ocean.FISH;\n index = encode(runType, runLength, currentType, index);\n break;\n}\n</code></pre>\n\n<p>After that it's easier to notice that the whole switch-case could be eliminated since the body of every <code>case</code> statement is very similar to each other and depends on only the <code>sea.cellContents(row, col)</code> value.</p>\n\n<pre><code>final int currentType = sea.cellContents(row, col);\nindex = encode(runType, runLength, currentType, index);\n</code></pre></li>\n<li>\n\n<pre><code>int[] runLength = new int[10]; // corresponding index cell stores its number of occurence of that respective runType.\n</code></pre>\n\n<p>I'd put the comment before the line it comments:</p>\n\n<pre><code>// corresponding index cell stores its number of occurrence of that respective runType.\nint[] runLength = new int[10];\n</code></pre>\n\n<p>It's easier to work with because it requires less horizontal scrolling.</p></li>\n<li><p>A comment says the following:</p>\n\n<pre><code>// i&j are width & height of a 2d array read from commandline\n</code></pre>\n\n<p>Then you can use <code>width</code> and <code>height</code> as variable names for better readabilty (you don't have to remember what <code>i</code> or <code>j</code> mean nor check the comment for it) and could get rid of the comment.</p></li>\n<li><p>The <code>temp</code> variable in <code>doubleTheSize</code> could be called <code>doubledArray</code> or <code>newArray</code>, <code>arg</code> is <code>oldArray</code> or <code>originalArray</code>. It would express the purpose of them.</p></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs could show blocks.</p>\n\n<pre><code> }// end outer for loop\n}// end main()\n</code></pre>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/53274/36726\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T12:19:58.530",
"Id": "42500",
"ParentId": "42488",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T01:24:01.627",
"Id": "42488",
"Score": "6",
"Tags": [
"java",
"optimization",
"performance"
],
"Title": "Save space occupied by 2D array"
} | 42488 |
<p>I have regrettably been away from C programming for a very long time, so I'd like to get a quick code review of a first proof of concept, before I get too far into adding capabilities, using the getopt library for arguments, alternate output and input character sets, a PolarSSL implementation, and so on and so forth.</p>
<p>Target platforms: gcc 4.5+ for MinGW for Windows, gcc 4.7+ for Linux.</p>
<p>My ranking of concerns:</p>
<ul>
<li>Security holes</li>
<li>Incorrect use of OpenSSL</li>
<li>Memory leaks</li>
<li>Performance</li>
<li>Suboptimal or incorrect compilation commands</li>
<li>Inefficient code</li>
<li>deviations from ANSI C/portability</li>
<li>Unclean code</li>
<li>Suggestions for improvement</li>
<li>other</li>
</ul>
<p>As a purely secondary interest, if anyone has advice on the getopt library, C code for Base32/Base64/etc output formats, or PolarSSL use, I'd appreciate it.</p>
<p>Linux compilation:</p>
<pre><code>gcc -O3 -lssl pbkdf2.c -o pbkdf2
</code></pre>
<p>Windows compilation:</p>
<pre><code>gcc -O3 -I OpenSSLLibraryPath\include -L OpenSSLBinariesPath -leay32 pbkdf2.c -o pbkdf2
</code></pre>
<p>The code:</p>
<pre><code>#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
// Originally from http://stackoverflow.com/questions/10067729/fast-sha-2-authentication-with-apache-is-it-even-possible
void PBKDF2_HMAC_SHA_256(const char* pass, const unsigned char* salt, int32_t iterations, uint32_t outputbytes, char* HexResult)
{
unsigned int i;
unsigned char digest[outputbytes];
PKCS5_PBKDF2_HMAC(pass, strlen(pass), salt, strlen(salt), iterations, EVP_sha256(), outputbytes, digest);
for (i = 0; i < sizeof(digest); i++)
sprintf(HexResult + (i * 2), "%02x", 255 & digest[i]);
}
void PBKDF2_HMAC_SHA_512(const char* pass, const unsigned char* salt, int32_t iterations, uint32_t outputbytes, char* HexResult)
{
unsigned int i;
unsigned char digest[outputbytes];
PKCS5_PBKDF2_HMAC(pass, strlen(pass), salt, strlen(salt), iterations, EVP_sha512(), outputbytes, digest);
for (i = 0; i < sizeof(digest); i++)
sprintf(HexResult + (i * 2), "%02x", 255 & digest[i]);
}
int main(int argc, char *argv[])
{
printf("Usage: %s SHA-512|SHA-256 password salt iterations outputlengthinbytes\nSHA-512 is recommended (for password hashing, outputlengthinbytes <= 64)\nSHA-256 is not as good, (for password hashing, outputlengthinbytes <= 32)\n",argv[0]);
if(argc != 6){printf("Incorrect number of parameters.\n");return 2;};
char pass[strlen(argv[2])];
unsigned char salt[strlen(argv[3])];
int32_t iterations;
uint32_t outputbytes;
strcpy(pass,argv[2]);
strcpy(salt,argv[3]);
iterations = atoi(argv[4]);
outputbytes = atoi(argv[5]);
printf("\n%s\n",argv[1]);
char HexResult[2*outputbytes-1];
// printf("Computing PBKDF2(HMAC-SHA512, '%s', '%s', %d, %d) ...\n", pass, salt, iterations, outputbytes);
memset(HexResult, 0, outputbytes);
if (strcmp(argv[1],"SHA-512")==0)
{
PBKDF2_HMAC_SHA_512(pass, salt, iterations, outputbytes, HexResult);
}
else if (strcmp(argv[1],"SHA-256")==0)
{
PBKDF2_HMAC_SHA_256(pass, salt, iterations, outputbytes, HexResult);
}
else
{
printf("Invalid value for hash - choose one of:\nSHA-512\nSHA-256\n");
return 1;
}
printf("Result: in Base16 (hex)\n%s\n", HexResult);
return 0;
}
</code></pre>
| [] | [
{
"body": "<h1>Things you did well on:</h1>\n\n<ul>\n<li><p>Looks like you weren't too rusty based on this code. Looks very nice organizationally.</p></li>\n<li><p>You <code>return</code> different values for different error conditions.</p></li>\n</ul>\n\n<h1>Things you could improve on:</h1>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p>Initialize <code>i</code> in your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for (unsigned int i = 0; i < sizeof(digest); i++)\n</code></pre></li>\n</ul>\n\n<h3>Syntax</h3>\n\n<ul>\n<li><p>Don't over-compact your code.</p>\n\n<blockquote>\n<pre><code>if(argc != 6){printf(\"Incorrect number of parameters.\\n\");return 2;};\n</code></pre>\n</blockquote>\n\n<p>Let it breathe a bit.</p>\n\n<pre><code>if(argc != 6)\n{\n printf(\"Incorrect number of parameters.\\n\");\n return 2;\n}\n</code></pre></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\"><code>puts()</code></a> instead of <code>printf()</code> when you aren't formatting a string.</p>\n\n<pre><code>puts(\"Incorrect number of parameters.\");\n</code></pre></li>\n<li><p>You don't follow proper C naming conventions.</p>\n\n<blockquote>\n<pre><code> char HexResult[2*outputbytes-1];\n</code></pre>\n</blockquote>\n\n<p>Either use <a href=\"https://en.wikipedia.org/wiki/CamelCase\">camelCase</a>, or <a href=\"https://en.wikipedia.org/wiki/Snake_case\">snake_case</a> with variable names.</p></li>\n<li><p>Your indentation is a bit odd.</p>\n\n<blockquote>\n<pre><code>if (strcmp(argv[1],\"SHA-512\")==0)\n {\n PBKDF2_HMAC_SHA_512(pass, salt, iterations, outputbytes, HexResult);\n }\n</code></pre>\n</blockquote>\n\n<p>But that could be a copy-paste issue.</p></li>\n</ul>\n\n<h3>Commenting:</h3>\n\n<ul>\n<li><p>The only comments I see are a link to a Stack Overflow post, and a commented-out bit of old code. Use more comments to explain what your code does, and how it accomplishes that/why it works.</p>\n\n<p>Look at it as if a new developer was going to look at your code. You should try to explain it so that he could understand it's basic function and how it works right away. You might thank yourself when you return back to this project in the future, forgetting completely how it works. ;)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:49:20.237",
"Id": "73170",
"Score": "1",
"body": "Hah! I'd forgotten to convert over to puts() or fputs(). Credit the good stuff to the original author (except the CLI arguments). Thank you for the good comments!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:41:29.720",
"Id": "42494",
"ParentId": "42492",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>A buffer overflow:</p>\n\n<pre><code>char HexResult[2*outputbytes-1];\n</code></pre>\n\n<p>Why the <code>-1</code>? There are <code>2 * outputbytes</code> hex digits. So you need at least <code>2*outputbytes</code> chars. Since you want a null terminated string (the rest of your code assumes it is), you even need an extra character for the <code>\\0</code> terminator. So this should be char <code>HexResult[2 * outputbytes + 1];</code></p></li>\n<li><p>A partial initialization:</p>\n\n<pre><code>memset(HexResult, 0, outputbytes);\n</code></pre>\n\n<p>You're filling the first half of <code>HexResult</code> with <code>\\0</code>, but you're missing the rest. This can't be right.</p></li>\n<li><p>A useless mask:</p>\n\n<pre><code>255 & digest[i]\n</code></pre>\n\n<p>What's the point of the masking? If a byte of the output were larger than that, that'd mean that you're running on an unusual architecture with large <code>char</code>s <em>and</em> OpenSSL has a bug.</p>\n\n<p>You could use <code>uint8_t</code> if you want to be explicit about using 8 bit bytes. Many crypto libraries use these typedefs.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T01:04:00.613",
"Id": "74386",
"Score": "0",
"body": "Thank you, CodesInChaos, for two critical points and for the performance improvement. As it happens, I'd fixed the first two and not noticed the third in my quest to get argument parsing and x64 compilation working."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T15:42:04.260",
"Id": "43071",
"ParentId": "42492",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "42494",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T04:13:09.537",
"Id": "42492",
"Score": "8",
"Tags": [
"c",
"security",
"cryptography",
"cli",
"openssl"
],
"Title": "OpenSSL PBKDF2-HMAC-SHAx proof of concept"
} | 42492 |
<p>The old function was:</p>
<pre><code><?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
?>
</code></pre>
<p>I have changed in this way:</p>
<pre><code><?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$conn = new mysqli('localhost', 'username', 'password', 'dbname');
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
$theValue = $conn->real_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
?>
</code></pre>
<p>Is what I've made correct?</p>
<p>Can I remove <code>get_magic_quites_gpc()</code> if I use PHP version 5.3.2?</p>
| [] | [
{
"body": "<p>PHP is not my area of expretise, so just some generic notes:</p>\n\n<ol>\n<li><p>The function create a new MySQL connection on every call which could be a bottleneck in your application. You could use <a href=\"http://www.php.net/manual/en/mysqli.persistconns.php\" rel=\"nofollow\">persistent connections with a <code>p:</code> prefix</a> but others usually suggest PDO as a better alternative of database handling.</p></li>\n<li><p>The <code>$the</code> prefix on most of the variables seem redundant (it doesn't add too much to them), I'd avoid it.</p></li>\n<li><p>If you intended to return the original value when its not text, long, int etc. you should make it explicit with a <code>default</code> case inside the switch statement. If not, throw an exception in the <code>default</code> case and sign the error. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><p><code>case \"text\"</code> and <code>case \"date\"</code> contains the same logic, you could use fall through there too.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T11:13:44.543",
"Id": "45077",
"ParentId": "42497",
"Score": "2"
}
},
{
"body": "<p>Your motivation is justified, but the revised code isn't quite right either.</p>\n\n<p>Magic quotes was an <a href=\"http://www.php.net/manual/en/security.magicquotes.php\" rel=\"nofollow\">ill-conceived idea</a> that in fact has been deprecated in PHP 5.3 and will be removed altogether in 5.4. The only good reason for calling <code>get_magic_quotes_gpc()</code> would be to detect whether you are running on a server that has this unfortunate feature enabled, and <a href=\"http://www.php.net/manual/en/security.magicquotes.disabling.php#example-347\" rel=\"nofollow\">undo its ill effects with <code>stripslashes()</code> if it is</a>. (Include the <code>stripslashes()</code> routine early in your script so that your entire program benefits.)</p>\n\n<p>Revising the function to use <code>$conn->real_escape_string()</code> protects you from SQL injection problems. Get rid of the conditional call to <code>addslashes()</code>, because it redundantly tries to do the same thing as <code>real_escape_string()</code>, but inaccurately.</p>\n\n<p>You still have three problems, though:</p>\n\n<ul>\n<li><strong>Performance:</strong> <code>new mysqli()</code> opens a new connection to the database. That's a very heavy price to pay just to escape a string.</li>\n<li><strong>Connection leak:</strong> You open the connection without closing it when you're done. If you call this function dozens of times, you would have dozens of connections that remain open until your script terminates.</li>\n<li><strong>Locale:</strong> The reason <code>real_escape_string()</code> requires a connection is that its behaviour depends on the <a href=\"http://php.net/mysqli.set-charset\" rel=\"nofollow\">character set of the connection</a>. To be strictly correct, you should be using whatever existing connection you may have so that you apply the correct escaping for the relevant character set.</li>\n</ul>\n\n<p>To solve all three issues, this function should use an existing mysqli connection object.</p>\n\n<p>It's good that your application is using some kind of database abstraction layer, but I get the feeling that you are reinventing the wheel, poorly.\nIf at all possible, I suggest that you consider replacing it all with a standard solution such as <a href=\"http://php.net/pdo\" rel=\"nofollow\">PDO</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T06:10:10.300",
"Id": "45128",
"ParentId": "42497",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T08:54:42.233",
"Id": "42497",
"Score": "5",
"Tags": [
"php",
"mysqli"
],
"Title": "Update PHP function GetSQLValueString"
} | 42497 |
<p>I've been reading a lot about repository patterns these days. At first, the pattern seemed easy.</p>
<p>Most of the examples I read over the web use an ORM like below.</p>
<pre><code>interface MemberRepositoryInterface {
public function find($id);
}
class MemberRepository implements MemberRepositoryInterface {
// here we're passing framework sepific ORM implementation
public function __construct(Model_Member $model)
{
$this->model = $model;
}
public function find($id)
{
return $this->model->find($id);
}
}
</code></pre>
<p><strong>// In a controller</strong></p>
<pre><code>class Test_Controller {
public function __construct(MemberRepositoryInterface $memberRepository)
{
$this->repository = $memberRepository;
}
public function show()
{
$member = $this->repository->find(1);
$this->template->content = View::factory("testView")->set('member', $member)->render();
}
}
</code></pre>
<p>It looks fine up to this point. Now..when you pass $member variable to a view then you can access all the framework specific methods of the ORM such as...delete(), save(), and so on.</p>
<p>what's the best way to prevent people from using framework specific ORM methods?</p>
<p>I thought about it..then the answer is to use a plain old PHP object.</p>
<p><strong>// Modified Repository</strong></p>
<pre><code>class MemberModel {
public $id;
public $firstName;
public $lastName;
public function __construct(array $data)
{
foreach($data as $key=>$value)
{
if(isset($this->$key))
{
$this->$key = $value;
}
}
}
}
class ContactModel {
public $id;
public $firstName;
public $lastName;
public function __construct(array $data)
{
foreach($data as $key=>$value)
{
if(isset($this->$key))
{
$this->$key = $value;
}
}
}
}
class MemberRepository implements MemberRepositoryInterface {
// here we're passing framework sepific ORM implementation
public function __construct(Model_Member $model)
{
$this->model = $model;
}
public function find($id)
{
$record = $this->model->find($id)->as_array();
return new MemberModel($record);
}
public function find_with_contacts($id)
{
//find a member and contacts then use MemberModel and ContactModel
// then return the data
}
}
</code></pre>
<p>Is this good enough? or are there other best practices?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T10:00:50.217",
"Id": "73181",
"Score": "0",
"body": "What's the purpose of `Model_Member` (and the difference to `MemberModel`)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T10:30:02.140",
"Id": "73182",
"Score": "0",
"body": "@Fge // Model_Member is an object that extends ORM (framework object), which provides database access."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T13:02:12.430",
"Id": "73187",
"Score": "0",
"body": "Are you you trying to build a repository on top of an existing (3rd party) ORM? What Framework do you use as ORM? What class of this framework is the `Model_Member`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T23:20:58.400",
"Id": "73329",
"Score": "0",
"body": "@Fge // not necessarily. I'm just using this ORM because I need a database connection. I think it doesn't matter what framework I'm using. Does it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:17:50.163",
"Id": "73336",
"Score": "0",
"body": "The framework itself does not matter, but how you use it. If its an ORM framework it most likely already has repositories to use. I'd guess you are already using the framework's repository then and your are building just another layer of the same abstraction around it (which is duplication in abstraction -> bad :)). If its a dbal framework the approach is mostly fine. Either way, the naming of this class is confusing. Names should indicate the responsibility just by reading it, without having to look at the implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:22:52.730",
"Id": "73341",
"Score": "0",
"body": "@Fge // I'm using PHP Kohana framework. It has find_all(), find()..those usual active record methods if that's what you're talking about."
}
] | [
{
"body": "<p>You are already using the repository of Kohana. They hide their repository behind static factory methods though (copied from the <a href=\"http://kohanaframework.org/3.3/guide/orm/using#finding-an-object\" rel=\"nofollow\">documentation</a>):</p>\n\n<pre><code>// Find user with ID 20\n$user = ORM::factory('User')\n ->where('id', '=', 20)\n ->find();\n// Or\n$user = ORM::factory('User', 20);\n</code></pre>\n\n<p>Yet they fail to achieve the important thing about ORM and repositories: decoupling the application from the database. This is actually two-fold: the SQL-syntax leaks into the application space (the querybuilder) and the database-structure is mapped 1:1 on the model. Changing the model or database requires to change the other respectively. Comparing this to the great explanation at <a href=\"http://msdn.microsoft.com/en-us/library/ff649690.aspx\" rel=\"nofollow\">MSDN</a>: the mapper is missing and the client business logic has access to the query object (and therefore to the datasource). A major (not related) issue is the all-presence of static method calls.</p>\n\n<p>What you try is to fix this (thumbs up ;)). You have your business entities (<code>MemberModel</code> and <code>ContactModel</code>) and a repository <code>MemberRepository</code>. But instead of delegating the the ORMs repository you should use the <a href=\"http://kohanaframework.org/3.3/guide/database/query/builder\" rel=\"nofollow\">query builder</a> directly:</p>\n\n<pre><code>class MemberRepository implements MemberRepositoryInterface {\n public function find($id) \n {\n $record = DB::select(...);\n }\n}\n</code></pre>\n\n<p>The second important task is the mapping of database fields to entity fields (and vice versa). This should not be done in your business entity! The business entity does not know anything about how it is saved:</p>\n\n<pre><code>class MemberRepository implements MemberRepositoryInterface {\n public function find($id) \n {\n $record = DB::select(...);\n // map $record to $entity;\n return $entity;\n }\n}\n</code></pre>\n\n<p>Other means to manage your model in the repository as well (e.g. delete, update, create), not in your business entity!</p>\n\n<p>Last your model. For now it is fine. But soon it should contain your business logic (no, not in your services or controllers ;)). You'll probably start with some data validation when setting properties. I'd suggest to use setters/getters right away, saves you refactoring later on. </p>\n\n<p>Two final remarks about ORM at the end:</p>\n\n<ul>\n<li>Repositories tend to be very repetitive. Especially when they only provide only the basic CRUD methods. Pretty much every ORM Framework provides a general repository for these methods (as Kohana does and what you used). </li>\n<li>Some explanations on ORM pass query objects to the repository. Those are not to be confused with the query builder from your dbal. The query passed to the repository is written in the business language (e.g. the fields of your model) and mapped to a query of the querybuilder by the repository. This avoids leaking of database details into the business logic. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:51:31.230",
"Id": "73358",
"Score": "0",
"body": "That's such a great answer that I've been looking for the last couple of weeks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:17:23.993",
"Id": "42560",
"ParentId": "42498",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42560",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T09:39:37.610",
"Id": "42498",
"Score": "4",
"Tags": [
"php",
"design-patterns"
],
"Title": "Repository pattern with plain old PHP object"
} | 42498 |
<p>I need to wait for short intervals of time in my program, but I really don't want to include <code>unistd.h</code> just to use <code>sleep</code>, so I'm doing it this way:</p>
<pre><code>int main()
{
for(int i=0; i<=100000000000; i++); // <----- note that the loop doesn't do anything
return 0;
}
</code></pre>
<p>I do this when I don't really have a specific interval to set for sleep.</p>
<p>Is there anything wrong with this? Would this harm the program in any way?</p>
<p>In C I know that if I did include <code>unistd.h</code>, and that if I used <code>sleep()</code>, that the following code would also make the program wait for a short interval of time:</p>
<pre><code>int main()
{
sleep(2); //or whatever the number (in seconds)
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:42:54.740",
"Id": "73194",
"Score": "10",
"body": "See also [What are trade offs for “busy wait” vs “sleep”?](http://stackoverflow.com/questions/1107593/what-are-trade-offs-for-busy-wait-vs-sleep)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:54:32.273",
"Id": "73317",
"Score": "18",
"body": "Do you have any actual reason for not wanting to type \"#include <unistd.h>\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T04:09:21.923",
"Id": "73363",
"Score": "5",
"body": "Using 100000000000 for an int is not very portable, some compilers wouldn't like it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T06:29:49.523",
"Id": "73372",
"Score": "3",
"body": "I did the same with a program and it nearly killed the computer. Internally, sleep will take the load off the program and put it really to sleep."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-26T06:58:58.167",
"Id": "172815",
"Score": "1",
"body": "It will likely be optimized out as you wrote it: http://stackoverflow.com/questions/7083482/how-to-prevent-compiler-optimization-on-a-small-piece-of-code"
}
] | [
{
"body": "<p>The biggest problem with using a for-loop to do this is that you are wasting CPU power.</p>\n\n<p>When using <code>sleep</code>, the CPU can, in a sense, take a break (hence the name \"sleep\") from executing your program. This means that the CPU will be able to run other programs that have meaningful work to do while your program waits.</p>\n\n<p>But in the for-loop the CPU continuously have to do work to increase a variable. For what purpose? Nothing. But the CPU doesn't know that. It's told to increase the variable, so that's what it will do. Meanwhile, other programs aren't given as much time to do their work because your program is taking up time.</p>\n\n<p>Please don't waste CPU power, use the <code>sleep</code> approach.</p>\n\n<p>As stated in a comment, additionally, the compiler may optimize out an empty loop, and the attempt to pause may be lost. So either you will waste CPU power, or you will not pause at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:45:38.530",
"Id": "73251",
"Score": "58",
"body": "In addition, the compiler may optimize out an empty loop, and the attempt to pause may be lost"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T23:08:22.140",
"Id": "73328",
"Score": "1",
"body": "In further addition, if the compiler left it, it would be bad for scheduling, since the scheduler will see `for` as a long but active process."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:06:37.460",
"Id": "42508",
"ParentId": "42506",
"Score": "89"
}
},
{
"body": "<p>Back in the day, home computers used to have a <a href=\"https://en.wikipedia.org/wiki/Turbo_button\">“turbo” button</a>, which (when activated), made the processor <em>slower</em>. The problem was that games were coded around an input loop that was expected to take a specific number of milliseconds. If the loop was executed faster, the whole game would speed up, becoming unplayable.</p>\n\n<p>Today, computers have vastly different speeds and performance characteristics, so NOPping isn't reliable in any way (will it take half a second? half a year?). Furthermore, compilers are generally free to remove code that doesn't do anything – compiling your snippet under <code>-O3</code> would hopefully remove that loop.</p>\n\n<p>Don't use an ugly kludge just to achieve better compilation speed. Do it <em>right</em> – consider yourself a <a href=\"http://abstrusegoose.com/467\">code craftsman</a>, not a <a href=\"https://en.wikipedia.org/wiki/Monkeys_typing_Shakespeare\">code monkey</a> (no offense, rolfl).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:37:19.520",
"Id": "73236",
"Score": "10",
"body": "No offense taken... ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T05:46:05.047",
"Id": "73371",
"Score": "0",
"body": "Eh, my computer is fairly recent and have a Turbo button. However it behaves differently, it does a soft overclock on the GPU."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:10:00.377",
"Id": "42510",
"ParentId": "42506",
"Score": "35"
}
},
{
"body": "<p>This is called <a href=\"http://en.wikipedia.org/wiki/Busy_waiting\">'busywaiting' or 'spinning'</a>, and will work but has the following disadvantages:</p>\n\n<ol>\n<li><p>It will perform 'work' on your program instead of yielding control to OS and other programs - so it doesn't \"play nice\" with others; on a common computer there are many programs running at the same time that could also like to use that CPU instead.</p></li>\n<li><p>Busywaiting creates unneeded load on CPU, preventing it from idling - this results in extra heat, fan noise and lower battery life on laptop computers or mobile devices.</p></li>\n<li><p>The delay is unpredictable - it will vary greatly depending on the computer and also the compiler, which may \"optimize it away\" to no delay at all, as other answers noted.</p></li>\n</ol>\n\n<p>In short - it will function, so if it's a one-off script for your own use then it can be okay, but if it's code meant for production use or something that will need to be maintained in the future, then don't do it this way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T03:26:46.313",
"Id": "73361",
"Score": "0",
"body": "+1 for the mention of battery impact, a relatively significant issue when so much computing is done on mobile devices these days."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:42:52.437",
"Id": "42529",
"ParentId": "42506",
"Score": "26"
}
},
{
"body": "<p>This technic is called <a href=\"http://en.wikipedia.org/wiki/Spinlock\">Spinlock</a> or <a href=\"http://en.wikipedia.org/wiki/Busy_waiting\">busy waiting</a>. It is implemented for example in Oracle database software to coordinate access to memory structures between different processes (<a href=\"http://andreynikolaev.wordpress.com/2009/10/04/general-spin-lock/\">latches</a>).</p>\n\n<p>It seems to be useful if the overhead of sleeping which results from <a href=\"http://en.wikipedia.org/wiki/Context_switch\">context switching</a> is larger than waste of CPU time when spinning. This is the case if the expected wait time is very short. Very short means some clock cycles and is far less than 2000 ms that you use in your example.</p>\n\n<p>The compiler will not optimize the loop away if it is implemented correctly. This C example using a <a href=\"http://en.wikipedia.org/wiki/Volatile_variable\">volatile variable</a> is from <a href=\"http://en.wikipedia.org/wiki/Busy_waiting\">busy waiting</a> .</p>\n\n<pre><code>...\nvolatile int i=0;\n...\nwhile (i==0);\n...\n</code></pre>\n\n<p><code>volatile</code> tells the compiler that the value of the variable <code>i</code> can be changed from outside the current thread and so the compiler does not throw away the <code>while</code>-loop. </p>\n\n<p>Busy waiting is listed as <a href=\"http://en.wikipedia.org/wiki/Antipattern\">antipattern here</a>. So you should not use it if you are not completely aware of its consequences.</p>\n\n<p>Trying to avoid the inclusion of <code>unistd.h</code> seems not to be a valid reason to use <a href=\"http://en.wikipedia.org/wiki/Busy_waiting\">busy waiting</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:22:32.553",
"Id": "42557",
"ParentId": "42506",
"Score": "16"
}
},
{
"body": "<p>Two big reasons why that's a bad idea:</p>\n\n<ol>\n<li><p>The time spent on a given loop is very dependent on the computer running it. Ever played Quake on a modern computer? The <a href=\"http://www.sharkyforums.com/showthread.php?104211-how-to-show-fps-in-quake-1\">frame rates</a> are through the roof, and I hope that's not a surprise. More powerful computers can perform more calculations in a set time. If your computer takes 10 seconds to complete a loop, a more powerful computer might finish in 5 or less, and an older computer might take significantly longer.</p>\n\n<p>So, couldn't I just do this?</p>\n\n<pre><code>#include <Mmsystem.h> //timeGetTime\nvoid Stall(unsigned long ms)\n{\n unsigned long start = timeGetTime();\n unsigned long passed = 0;\n while (passed < ms)\n passed = timeGetTime() - start;\n}\n</code></pre>\n\n<p>Yeah, that would ensure that the same time is taken to finish the function. But don't get too excited; I said two big reasons.</p></li>\n<li><p>Sleep functions set your thread in a sort of \"do not disturb\" state, allowing your operating system to perform other tasks (handling other threads, cleaning up your thread) while your thread daydreams. While a human could look at the line and interpret it as \"do nothing\", your computer is wasting power blowing through that empty loop as fast as it can.</p>\n\n<p>So, I can do this?</p>\n\n<pre><code>#include <Mmsystem.h> //timeGetTime\n#include <WinBase.h> //Sleep\nvoid Stall(unsigned long ms)\n{\n unsigned long start = timeGetTime();\n unsigned long passed = 0;\n while (passed < ms)\n {\n passed = timeGetTime() - start;\n Sleep(0);\n }\n}\n</code></pre>\n\n<p>Better, but it still wastes CPU resources when it doesn't have to. And if there are no other threads running, <code>Sleep(0)</code> immediately returns to your thread, meaning your CPU is <em>still</em> running at maximum speed.</p></li>\n</ol>\n\n<p>Conclusion: for most applications, stick with sleep functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T03:56:35.670",
"Id": "42571",
"ParentId": "42506",
"Score": "11"
}
},
{
"body": "<p>The other answers here address the specific issues with your loop, and hopefully have convinced you that it is not the right approach. I want to comment on your motivations.</p>\n\n<p>Why do you want to avoid <em>unistd.h</em>? It is entirely reasonable to include a header for just one function, and in the vast majority of cases there is no compelling reason not to.</p>\n\n<p>If you are concerned about portability, just do something like this:</p>\n\n<pre>\n#if defined(__linux__)\n# include <unistd.h>\n#elif defined(_WIN32)\n# include <windows.h>\n# define sleep(s) Sleep((s)*1000)\n#endif\n</pre>\n\n<p>Then use <code>sleep(seconds)</code> everywhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T07:40:33.123",
"Id": "42579",
"ParentId": "42506",
"Score": "15"
}
},
{
"body": "<p>The biggest single issue with this approach, other than eating processor cycles, is that the for loop will be removed by the optimiser if you enable any level of optimisation in the compiler. Suddenly you find that code that ran just fine in debug mode, stops working.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T22:02:55.167",
"Id": "73461",
"Score": "0",
"body": "That is no really a valid argument against the usage of this technic. If programmed carefully this probleem can be avoided. Here is a discussion about avoiding optimization for a piece of code when using gcc: http://stackoverflow.com/questions/2219829/how-to-prevent-gcc-optimizing-some-statements-in-c\nhelp"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:54:37.947",
"Id": "42605",
"ParentId": "42506",
"Score": "5"
}
},
{
"body": "<p>Avoiding calling certain proper OS API functions just because of reluctance to include a <code>.h</code>-file is not a fair tradeoff.\nYou have to include a <code>.h</code>-file with OS API calls or use assembler instructions. It depends on whether you wish to wait for some event to occur, e.g., a file finished writing or data finished sending via a socket. In this case, it’s better to call an OS API that simply waits for the event to occur. If you need just to wait a certain amount of time, it also depends on how long do you need to wait. If you need to wait up to about 50 thousand CPU cycles, then use a combination of <code>PAUSE</code> and <code>RDTSC</code> instruction, call <code>RDTSC</code> once after calling <code>PAUSE</code> about 500 times. If you need delays longer than 50 thousand of CPU cycles, create a waitable high-resolution timer and wait for it. For windows, there is a function CreateWaitableTimer. You can find an example at <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms687008(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/windows/desktop/ms687008(v=vs.85).aspx</a></p>\n<p>If you need to wait at least 1 millisecond or more, you can just call Sleep(). But make sure you call sleep with at least 1 millisecond parameter, don’t call Sleep(0) since it will not let CPU rest while you are waiting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-06T13:49:03.617",
"Id": "193782",
"ParentId": "42506",
"Score": "4"
}
},
{
"body": "<p>I strongly disagree with the accepted answer, which says</p>\n<blockquote>\n<p>The biggest problem with using a for-loop to do this is that you are wasting CPU power.</p>\n</blockquote>\n<p>That is a problem, but it isn't the biggest problem by far. The biggest problem is that <code>int</code> is 32 bits on many platforms, including 64-bit Windows, and <code>100000000000</code> is out of the range of a 32-bit <code>int</code>. Depending on how such constants are handled, <code>i</code> may be incremented until it overflows. The behavior of <code>int</code> on overflow is undefined.</p>\n<p>Modern optimizing compilers are smart enough to recognize that this code has undefined behavior, but many are not smart enough to do anything sane with that information. Clang, particularly, is notorious for doing crazy things with undefined code, such as emitting no machine language instructions at all for the entire function, not even a <code>ret</code> instruction, leaving the instruction pointer to wander off into no man's land and perhaps execute code from some unrelated function that happens to be nearby in memory.</p>\n<p>The answers that imply that the worst thing the compiler could do is delete the loop are wrong. <em>Much worse things can happen.</em></p>\n<p>On platforms where <code>100000000000</code> is a valid <code>int</code>, the compiler will probably just delete the loop, so wasting CPU power still isn't the biggest problem on those platforms; the biggest problem is that it just won't work. If you disable optimizations, it will probably work as intended, but writing code that only works when optimizations are disabled is not considered good programming practice, unless the reason is that the optimizer is buggy, which is not the case here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-21T18:56:20.990",
"Id": "526018",
"Score": "0",
"body": "The 100000000000 was just an example. The question is asking specifically about using the for loop instead of the sleep function regardless of the number you use for the loop. If overflowing was the problem, one could just use long long for example."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-21T17:50:33.257",
"Id": "266271",
"ParentId": "42506",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42508",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-22T14:58:38.780",
"Id": "42506",
"Score": "35",
"Tags": [
"c",
"performance"
],
"Title": "Using a for-loop or sleeping to wait for short intervals of time"
} | 42506 |
<p>This is the C++ code of my implementation of Knuth's algorithm M that produces mixed-radix numbers:</p>
<pre><code>#include "visit.h"
void algorithmM(vector<int>& m)
{
m.insert(m.begin(),2);
const int n=m.size();
vector<int> a(n,0);
M2:
visit(false,a);
int j=n-1;
M4:
if (a[j]==m[j]-1) {a[j]=0;--j;goto M4;}
if (j==0) return;
else {a[j]++;goto M2;}
}
int main()
{
vector<int> m;
int i;
while(std::cin>>i)
{if(i<0) continue;
m.push_back(i);
}
algorithmM(m);
return 0;
}
</code></pre>
<p>This is the code of "visit.h":</p>
<pre><code>#include <iostream>
#include <vector>
using std::vector;
using std::cout;
template<class T> void visit(bool first,vector<T>& l)
{
size_t dt=first?0:1;
for(typename vector<T>::iterator i=l.begin()+dt;i!=l.end();++i)
cout<<*i;
cout<<'\n';
}
</code></pre>
<p>The C++ code is very close to the Knuth's pseudocode.
And now this is an imperative Haskell implementation using mutable arrays:</p>
<pre><code>import Data.Array.IO
import Control.Monad.State
import Data.IORef
data CountList = CountList {intlist::[Int],count::Int}
lenarr arr = do
b<-getBounds arr
return (snd b)
takeInput :: State (String,Int) [Int]
takeInput = do
(s,count)<-get
let g=reads s
if g==[] then return []
else do
put (snd(head g),count+1)
l<-takeInput
return $ (fst(head g)):l
takeInput2 :: String->CountList
takeInput2 s = let (l,ss)=runState (takeInput) (s,0)
in CountList l (snd ss)
fillArray :: CountList->IO((IOArray Int Int),(IOArray Int Int))
fillArray l = do
arr<-newArray (0,(count l)) 0
x<-nowfill 1 (intlist l) arr
y<-newArray (0,(count l)) 0
writeArray x 0 2
return (x,y)
where nowfill i l arr = do
if l==[] then return arr
else do
writeArray arr i (head l)
nowfill (i+1) (tail l) arr
visit ::(IOArray Int Int)->Int->IO ()
visit x i = do
c<-lenarr x
if i>c then putStrLn ""
else do
a<-readArray x i
putStr (show a)
visit x (i+1)
maj :: (IOArray Int Int)->(IOArray Int Int)->Int->IO((IOArray Int Int),Int)
maj m a j = do
valaj <- readArray a j
valmj <- readArray m j
if valaj==valmj-1 then
do
writeArray a j 0
maj m a (j-1)
else
return (a,j)
m5 :: (IOArray Int Int)->Int->IO((IOArray Int Int),Int)
m5 a j = if j==0 then
return (a,j)
else do
valaj<-readArray a j
writeArray a j (valaj+1)
return (a,j)
algorithmM0 m a = do
visit a 1
n<-lenarr m
(a',j)<-maj m a n
(a'',j')<-m5 a' j
if j'==0 then
return ()
else
algorithmM0 m a''
algorithmM = do
l<-getLine
let mycountlist = takeInput2 l
(m,a)<-fillArray mycountlist
algorithmM0 m a
main :: IO ()
main = algorithmM
</code></pre>
<p>I also have and a more functional approach using lists in Haskell which is smaller but I don't want to enlarge the post.</p>
<p>Can you please give me some advice on how to shrink the Haskell code?</p>
<p>I think that the main reason of using a high-level language like Haskell is to write less code but I don't think this happens here so I suppose that I am doing something wrong.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:02:29.497",
"Id": "73220",
"Score": "0",
"body": "For the C++ code, I'd recommend indenting by four spaces as it's more readable. Two isn't enough, plus some of your curly braces are placed strangely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:58:43.673",
"Id": "73239",
"Score": "0",
"body": "Thanks for the comment, but for now my problem is the Haskell code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:59:11.017",
"Id": "73240",
"Score": "0",
"body": "I understand. That's mainly why I left that as a comment."
}
] | [
{
"body": "<p>Below is a more idiomatic to Haskell version that still follows your original imperative logic. I know elsewhere on SO you have been shown how to do this efficiently and functionally. I did this to show what could be done if the design requirements remained in place.</p>\n\n<p>This version is 52 lines long with all of the whitespace you see. The original was 84 lines after whitespace between the functions was added.</p>\n\n<p>The entire <code>takeInput</code> design using State was not needed. As shown, <code>map read . words</code> is sufficient. If you are concerned about poor input then a version could quickly be put in place using <code>reads</code> but without State.</p>\n\n<p><code>case</code> replaces the <code>if</code> usage. This is more idiomatic in my experience and is still very readable. You get pattern matching along the way too.</p>\n\n<p>Note that <code>nowfill</code> was replaced by <code>newListArray</code> and the entire CountList was discarded as unneeded. If it was valuable then <code>fillArray</code> could still use CountList without the need for <code>nowfill</code>. The entire function could be about two lines if Applicative style was used. But that would definitely veer pretty far from the straight forward imperative style.</p>\n\n<p><code>visit</code> was updated to move the <code>putStrLn</code> call outside of the recursion and uses a helper function instead of the old if/else style. Again, the same exact logic just using a more idiomatic layout.</p>\n\n<p>The calls to <code>uncurry</code> could be removed if <code>m5</code> and <code>algorithmM0</code> took tuples instead of separated arguments. This does lend it a more functional flavor but I did not want to disturb the function types where possible.</p>\n\n<p>There are no cute tricks in this code. It is pretty reasonable for even a beginner level Haskell developer to read and understand I think. A C coder unfamiliar with the language would have more difficulty following this version than the original I suspect.</p>\n\n<pre><code>import Data.Array.IO\n\ntype AlgoArray = IOArray Int Int -- allows for experimentation with IOUArray or others\n\nlenarr :: AlgoArray -> IO Int -- simplified type\nlenarr arr = getBounds arr >>= return . snd\n\nfillArray :: [Int] -> IO (AlgoArray, AlgoArray)\nfillArray ns = do -- could be Applicative style: (,) <$> newListArray <*> newArray\n x <- newListArray (0, lcount) (2:ns)\n y <- newArray (0, lcount) 0\n return (x, y)\n where\n lcount = length ns\n\nvisit :: AlgoArray -> Int -> IO ()\nvisit x i = lenarr x >>= visit' x i >> putStrLn \"\"\n where\n visit' x i c\n | i > c = return ()\n | otherwise = readArray x i >>= putStr . show >> visit' x (i + 1) c\n\nmaj :: AlgoArray -> AlgoArray -> Int -> IO (AlgoArray, Int)\nmaj m a j = do\n valaj <- readArray a j\n valmj <- readArray m j\n maj' valaj valmj\n where\n maj' valaj valmj\n | valaj == (valmj - 1) = writeArray a j 0 >> maj m a (j - 1)\n | otherwise = return (a, j)\n\nm5 :: AlgoArray -> Int -> IO (AlgoArray, Int)\nm5 a 0 = return (a, 0)\nm5 a j = readArray a j >>= writeArray a j . (+1) >> return (a, j)\n\nalgorithmM0 :: AlgoArray -> AlgoArray -> IO ()\nalgorithmM0 m a = do\n visit a 1\n v <- lenarr m >>= maj m a >>= uncurry m5\n case v of\n (_, 0) -> return ()\n (a', _) -> algorithmM0 m a'\n\nalgorithmM :: IO ()\nalgorithmM = getLine >>= fillArray . takeInput >>= uncurry algorithmM0\n where\n takeInput = map read . words\n\nmain :: IO ()\nmain = algorithmM\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T21:37:12.907",
"Id": "45349",
"ParentId": "42509",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45349",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:08:32.760",
"Id": "42509",
"Score": "3",
"Tags": [
"optimization",
"algorithm",
"haskell"
],
"Title": "Knuth's algorithm M that produces mixed-radix numbers"
} | 42509 |
<p>I am a very beginning in PHP and Design Patterns. I have been studying the amazing Head First Design patterns. So, I have been trying to translate the original into PHP. The class is working well, however, I would like to ask:</p>
<ol>
<li><p>Is this considered good PHP?</p></li>
<li><p>Someone mentioned that this is not a Strategy Pattern. Head First's definition: "Strategy lets the algorithm vary independently from clients that use it". Is this not correct?</p></li>
</ol>
<pre class="lang-php prettyprint-override"><code><?php
interface FlyBehavior{
public function fly();
}
class FlyWithWings implements FlyBehavior{
public function fly(){
echo "I am flying!<br>";
}
}
class FlyNoWay implements FlyBehavior{
public function fly(){
echo "I cannot fly!";
}
}
interface QuackBehavior{
public function quack();
}
class QuackQuack implements QuackBehavior{
public function quack(){
echo "Quack<br>";
}
}
class MuteQuack implements QuackBehavior{
public function quack(){
echo "Silence";
}
}
class Squeak implements QuackBehavior{
public function quack(){
echo "Squeak";
}
}
abstract class Duck{
protected $quackBehavior;
protected $flyBehavior;
public function performQuack(){
$this->quackBehavior->quack();
}
public function performFly(){
$this->flyBehavior->fly();
}
abstract public function display();
public function swim(){
echo "All ducks float, even decoy";
}
}
class MallardDuck extends Duck{
public function __construct(){
$this->quackBehavior=new QuackQuack();
$this->flyBehavior=new FlyWithWings();
}
public function display(){
echo "I am real Mallard duck!";
}
}
$mallard=new MallardDuck();
$mallard->performQuack();
$mallard->performFly();
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:26:22.883",
"Id": "73190",
"Score": "2",
"body": "You are not really implementing the Strategy Pattern here. But don't feel bad, you are actually doing something even better (it's *almost* Dependency Injection, with a touch of Command Pattern)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:32:14.677",
"Id": "73192",
"Score": "1",
"body": "First thing is to get rid of the error. Atm you have $this->$quackBehavior=new Quack(); The $ should be omissed here. So it should be $this->quackBehavior ... Next error is there is no fly class to initiate. Look into SOLID, it helps alot, but it really takes time to consume."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:33:45.487",
"Id": "73193",
"Score": "2",
"body": "Turn on PHP error reporting and make fields $quackBehavior, $flyBehavior protected instead of private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T16:12:54.723",
"Id": "73196",
"Score": "1",
"body": "@RonniSkansing Daniel has a `fly` function inside of `FlyWithWings` but never creates it inside of the Duck Class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T16:38:45.360",
"Id": "73197",
"Score": "0",
"body": "@SimonAndréForsberg sorry I just realized that the question is off-topic. I would like to use the same space to ask the new edited question that is now on-topic I guess. Is it possible?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:30:31.903",
"Id": "73233",
"Score": "0",
"body": "@DanielTheRocketMan that is fine. Did you get it to function nicely?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:19:52.617",
"Id": "73244",
"Score": "0",
"body": "@Malachi Yes! It is working correctly now!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T12:39:49.407",
"Id": "98115",
"Score": "0",
"body": "I dont know why this question appeared in my newsletter today - considering how old it is to be included - but if I'm not wrong this is an example problem from `Head first design patterns` book ?"
}
] | [
{
"body": "<p>Syntax errors aside, there's a major pitfall in your design choices that you need to watch out for. Namely, if you want to figure out if your animal is capable of some behaviour, you'll need to add an identifier function for every animal. This will limit you down the road.</p>\n\n<p>For example, say you are iterating over a bunch of different types of animals, you'd need something like:</p>\n\n<pre><code>foreach ($noahs_ark->animals() as $animal) {\n if ($animal->canFly()) {\n $animal->performFly();\n }\n}\n</code></pre>\n\n<p>The problem here is that if you want to be able to check that an animal can fly, every single animal will need a \"canFly()\" method otherwise you'll end up with an error. If you're dealing only with birds, this probably isn't a big deal. But when you add dogs to the mix, then you have to add a <code>->canFly()</code> method for every dog object too!</p>\n\n<p>The solution to this is to implement your interfaces directly on your animal classes. For example:</p>\n\n<pre><code>// Assuming all birds classes extend Avian\nabstract class Avian implements Flier, Quacker { ... }\n\nforeach ($noahs_ark->animals() as $animal) {\n if ($animal instanceof Flier) {\n $animal->performFly();\n }\n]\n</code></pre>\n\n<p>This way you can use reflection to determine types, and along with it, make assumptions that if it possesses(implements) a certain behaviour(interface), your animal can perform that action.</p>\n\n<p>I'd still recommend that you make your modules implement interfaces as well to ensure consistency across specialized modules though. It'll help in cases where you might want to create factories for creating animals or in other cases as well. Hope that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T01:26:14.083",
"Id": "73657",
"ParentId": "42511",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "73657",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:14:53.883",
"Id": "42511",
"Score": "4",
"Tags": [
"php",
"design-patterns",
"beginner"
],
"Title": "Is this a good PHP strategy pattern?"
} | 42511 |
<p>I'd made a project using pygame in python around 3 months ago. This was my first big project after I started learning how to program in college.</p>
<p>Now I'd like to know just how good my programming syntax and style is. Whether there are any weird irritants that simply defy the unwritten rules of programming in python. I'd like to know them so that I can nip the evil in the bud.</p>
<p>Could someone please go through the code, and tell me where somethings have been implemented as they should have been and where something else might work better... Or if in general a better (read 'more pythonic'- I've never really understood what people mean when they say that btw.), style would work and what is it.</p>
<p>As of now, the chess works. The only thing is you gotta control both the black and white pieces by yourself.</p>
<p>Please just review the code.</p>
<p><a href="https://github.com/darkryder/Chess-python" rel="nofollow">Full code source</a></p>
<p>For the parts I think might not be implemented the way they could be: </p>
<hr>
<p><strong>1) Implementing a timer as:</strong></p>
<pre><code>import time
time_change_var=time.asctime().split()[3].split(":")[2]
time_elapsed=0
</code></pre>
<p>then in the main loop of game cycles:</p>
<pre><code>time_change_check=time.asctime().split()[3].split(":")[2]
if time_change_var!=time_change_check:
time_elapsed+=1
time_change_var=time_change_check
time_elapsed_print=font.render("%d:%d"%(time_elapsed/60,time_elapsed%60),True,white)
screen.blit(time_elapsed_print,[730,600])
screen.blit(font.render("Time Elapsed",True,black),[660,565])
</code></pre>
<hr>
<p><strong>2) Taking 2 consecutive clicks from the user that are valid</strong></p>
<p>A click is valid when:
(i). First click is on a box containing a piece
(ii). Second click is on a box containing either a piece of other colour or is empty
I am doing it like this:</p>
<pre><code>input_read=0
if len(m)==4:
X1=m[0] #assigning final inputs
Y1=m[1]
X2=m[2]
Y2=m[3]
m=[] # empty the buffer input list
input_read=1
if not input_read:
event=pygame.event.wait()
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if len(m)==2:
if event.button==1:
x1,y1=-1,-1
pos = pygame.mouse.get_pos()
x2 = pos[0]/80+1
y2 = pos[1]/80+1
m += [x2] + [y2]
moves=[]
else:
if event.button==1:
pos = pygame.mouse.get_pos()
x1 = pos[0]/80+1
y1 = pos[1]/80+1
for elements in pieces_in_play:
if x1 == elements.x and y1 == elements.y:
if elements.colour==col:
f=elements
m += [x1] + [y1]
</code></pre>
<hr>
<p><strong>3) Building classes for the different pieces</strong></p>
<p>I have built a class for each of the different type of piece. The class contains the object's name, colour,type,survival,x,y positions and the corresponding function which checks whether its possible to move the piece according to the input.It also kills the opponents piece if its already there on the destination box.</p>
<pre><code>class BlackBishop(object):
n=1
def __init__(self):
self.name=int("2"+str(BlackBishop.n)+"0")
self.colour = 0
self.type = 2
self.survive = 1
self.y=8
if BlackBishop.n==1:
self.x=3
else:
self.x=6
BlackBishop.n += 1
self.image = pygame.image.load("./images/bishop_b.png")
def check(self,X1,Y1,X2,Y2):
if (1<=X1<=8 and 1<=Y1<=8 and 1<=X2<=8 and 1<=Y2<=8):
if abs(Y2-Y1)==abs(X2-X1):
m=(Y2-Y1)/(X2-X1)
q=[]
t=[]
if X2>X1:
x=X1
if Y2>Y1:
y=Y1
q.append((x,y))
while (x!=X2 and y!=Y2)and(x>0 and y>0):
x+=1
y+=1
q.append((x,y))
else:
y=Y1
q.append((x,y))
while (x!=X2 and y!=Y2)and(x>0 and y>0):
x+=1
y-=1
q.append((x,y))
else:
x=X1
if Y2>Y1:
y=Y1
q.append((x,y))
while (x!=X2 and y!=Y2)and(x>0 and y>0):
x-=1
y+=1
q.append((x,y))
else:
y=Y1
q.append((x,y))
while(x!=X2 and y!=Y2)and(x>0 and y>0):
x-=1
y-=1
q.append((x,y))
for coordinate in q:
for check_piece in pieces_in_play:
if coordinate==(check_piece.x,check_piece.y):
if check_piece!=self:
if check_piece.colour==0:
return 0
elif check_piece.colour==1 and coordinate==(X2,Y2):
check_piece.survive=0
killcount(check_piece)
return 1
else:
return 0
else:
return 1
else:
return 0
else:
return -1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T16:46:14.653",
"Id": "73200",
"Score": "4",
"body": "The code seems to lack comments and has very high cyclomatic code complexity. Without debugging and scraping in the code, it is very hard to read. For example. if (1<=X1<=8 and 1<=Y1<=8 and 1<=X2<=8 and 1<=Y2<=8):\n if X1==X2:\n if (Y2==Y1+1 or (Y1==2 and Y2==Y1+2)):\n for t in pieces_in_play: .."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:20:33.687",
"Id": "73298",
"Score": "0",
"body": "How do i improve it then..?? I do have to check for all the possible errors(incorrect input) the user might give me..right...?? This way...there's no bug. Can i do it in some other more elegant way such that i still don't have to sacrifice the cases in which i check whether the input i receive i correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:29:44.277",
"Id": "73305",
"Score": "0",
"body": "I think a great way to improve it would be to add loads more comments. Another way is to write unittests for you code, when doing this you would come to the conclusion that some of the methods are very complex and take many tests to cover (when you do this, check code coverage / c.r.a.p level). So to avoid this, you spread them into more methods/classes with clearer responsibility. Also it seems there are a couple of places where the same algorythmes are reused, this should be abit more dry. But nice work anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:11:44.837",
"Id": "75241",
"Score": "0",
"body": "Please do not add \"thanks\" to posts. You may thank each helpful answerer with upvotes and comments."
}
] | [
{
"body": "<h2>Pythonic</h2>\n\n<p>Basically, a code is pythonic when <a href=\"http://blog.startifact.com/posts/older/what-is-pythonic.html\">it uses common Python idioms</a>. In Python, there is usually one (and only one) way to do things, so you should try to know what this thing is, and use it. You won't fight against the language, the code will be easier to read and modify by other programmers.</p>\n\n<p>A good way to start writing pythonic code is to follow <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a>. It is a standard for Python indentation. If you follow PEP 8, your code will look more pythonic, and will be easier to read by fellow Python programmers. Of course, it's only the tip of the icerberg!</p>\n\n<h2>Timers</h2>\n\n<pre><code>import time\ntime_change_var=time.asctime().split()[3].split(\":\")[2]\ntime_elapsed=0\n\n...\n\ntime_change_check=time.asctime().split()[3].split(\":\")[2] \nif time_change_var!=time_change_check:\n time_elapsed+=1\n time_change_var=time_change_check\ntime_elapsed_print=font.render(\"%d:%d\"%(time_elapsed/60,time_elapsed%60),True,white)\nscreen.blit(time_elapsed_print,[730,600])\nscreen.blit(font.render(\"Time Elapsed\",True,black),[660,565])\n</code></pre>\n\n<p>You're off to a good start because 1/ you want to improve 2/ you're noticing yourself the parts that can be improved in your code. Congratulations! So what can be improved here?</p>\n\n<ul>\n<li>You're manipulating your time as strings, which is unnecessary and dangerous. Strings are designed to be read by humans, not computers.</li>\n<li>You're not counting time, but the number of frames. On a computer which is twice as fast, time will fly twice as fast!</li>\n<li>You're not too careful about not mixing time logic and display logic.</li>\n</ul>\n\n<p>Don't use <code>time.asctime()</code>, but <code>time.gmtime()</code>:</p>\n\n<pre><code>import time\nstart_seconds = time.gmtime()\n\n# In the main loop, look at elapsed time\nseconds_elapsed = time.gmtime() - starts_seconds\n\n# Somewhere else, print seconds_elapsed\nscreen.blit(...)\n</code></pre>\n\n<p>I didn't review other parts of your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T09:23:10.950",
"Id": "42850",
"ParentId": "42514",
"Score": "6"
}
},
{
"body": "<p>One thought ...\nInstead of having all those else blocks that only have a return statement,\nswitch your if statements around, so that the if block only has a return statement, and then there doesn't need to be an else block for it. E.g., instead of ...</p>\n\n<pre><code>if 1<=X1<=8:\n original_contents_of_if_block\nelse:\n return -1\n</code></pre>\n\n<p>write ...</p>\n\n<pre><code>if not(1<=X1<=8):\n return -1\noriginal_contents_of_if_block\n</code></pre>\n\n<p>Also, when you have several loops that do the same thing, you can convert them to a single function that gets called wherever needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T15:24:47.590",
"Id": "74074",
"Score": "0",
"body": "Welcome to 200! You are now officially an *avid user*! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T21:46:41.387",
"Id": "42903",
"ParentId": "42514",
"Score": "8"
}
},
{
"body": "<p>I spent some time last night reviewing this code. Here are some specific suggestions I can make:</p>\n\n<ol>\n<li><p>Move your game loop into an if <code>__name__= \"__main__\":</code> statement at the bottom of the code. Currently, if the module is imported, the person who imports it will immediately start playing chess, which isn't desirable (they may just want to know about the piece classes.</p></li>\n<li><p>Group variables which go together in classes. By \"go together\", I mean that they share a common purpose, like score counting. It will help keep track of where those variables are used.</p></li>\n<li><p>Use parameters on class init methods to reduce duplication. There is no reason to have a <code>BlackPawn</code> class and a <code>WhitePawn</code> class, when they're only different by a few characters. The only difference between a white pawn and a black pawn is the colour and direction, so pass those in as parameters and have one <code>Pawn</code> class.</p></li>\n<li><p>Group common functionality into functions. The queen and rook both move and capture horizontally, so that code only needs to be written once and can be shared between both classes. The queen and bishop both move diagonally, so that functionality can be shared between both classes. All of the pieces are checking for boundary conditions, so that functionality can be shared among all of them. Breaking your functions up in this way will really help readability, since instead of <code>1<=X1<=8 and 1<=Y1<=8 and 1<=X2<=8 and 1<=Y2<=8</code>, you will have <code>coord_is_within_bounds()</code>, which says exactly what it does and what it's used for.</p></li>\n<li><p>Reduce and combine duplicate code in general. If two pieces of code are identical except for one variable, extract that part of the code as a method and pass the variable in. The less code you have, the more readable and maintainable it is. Looking at the queen class, there are 200 lines of code that could easily be reduced to 50 or even less just by breaking down each section (the contents of if statements are usually a good place to extract a method from).</p></li>\n<li><p>Reduce or remove magic values. In python it's better to use strings (<code>'black'</code> and <code>'white'</code>) rather than integers to signify properties. That will make the code more self documenting. <code>if colour == 'white':</code> is a lot clearer than 'if colour == 1:' .People reading your code shouldn't need to look around for the definitions of your magic numbers. </p></li>\n<li><p>I found this: \"if it is possible to kill the other opponent. My function automatically kills the opponent while checking for valid moves. Hence I had to make the kill_count function to ensure that the opponent stays alive even when his box is checked for a possible move.\" This is the strongest argument that \"check\" and \"kill\" should be split into separate methods. You mentioned that you wanted to add AI? Then you will definitely want to do that, or else you will kill every pieces the AI thinks it might be able to capture. In general, split up methods that do more than one thing (check AND kill) unless you're completely sure that you'll never want to do one without doing the other. As soon as you're thinking \"man, it sure is inconvenient that <em>other thing</em> happens when I do <em>thing</em>, split <em>thing</em> and <em>other thing</em> into separate methods to relieve the tension. </p></li>\n<li><p><code>except ZeroDivisionError: pass</code> Never never let errors pass silently. Instead, fix the bug which is causing the error. Trust me, having debugged codebases that do this a lot, this is the surest road to insanity there is.</p></li>\n<li><p>Reduce the number of global variables in general. Ideally, global variables should be constants, if they exist at all. Too many global variables can make a module difficult to debug, since it's not easy to see when each variable is being modified. This will be easier if you follow 1 and group your variables into classes.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T15:23:30.103",
"Id": "74072",
"Score": "5",
"body": "Welcome to code review, and congratulations on a good answer. Passed the ['Fist Answer' review](http://codereview.stackexchange.com/help/privileges/access-review-queues) with flying colours."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T15:02:54.860",
"Id": "42962",
"ParentId": "42514",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "42962",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:57:59.190",
"Id": "42514",
"Score": "10",
"Tags": [
"python",
"timer",
"pygame",
"chess"
],
"Title": "First Chess project"
} | 42514 |
<p><strong>C# code</strong></p>
<pre><code>static int KEY_NOT_FOUND = -1;
private void Form1_Load(object sender, EventArgs e)
{
int[] A = createArray(1, 100000);
Stopwatch sw1 = performCalcs(1, A);
Stopwatch sw2 = performCalcs(2, A);
TimeSpan lag = TimeSpan.FromTicks(sw1.Elapsed.Ticks - sw2.Elapsed.Ticks);
}
public static int[] createArray(int minVal, int maxVal)
{
if (minVal >= maxVal) return null;
int[] A = new int[maxVal - minVal + 1];
int i = -1;
for (int curVal = minVal; curVal <= maxVal; curVal++)
{
i = i + 1;
A[i] = curVal;
}
return A;
}
private Stopwatch performCalcs(int curFunction, int[] A)
{
Stopwatch sw = new Stopwatch();
int max = 10000;
int count = 0;
sw.Start();
while (count < max)
{
count = count + 1;
if (curFunction == 1) binary_search_improved2(A, 222, 0, A.Length - 1);
else binary_search(A, 222, 0, A.Length - 1);
}
sw.Stop();
return sw;
}
private static int binary_search_improved2(int[] A, int key, int imin, int imax)
{
if (imax < imin) return KEY_NOT_FOUND;
int imid;
while (true)
{
imid = imin + ((imax - imin) >> 1);
if (imin == imax || A[imid] == key) return imid;
if (A[imid] < key) imin = imid;
else imax = imid;
}
}
private static int binary_search(int[] A, int key, int imin, int imax)
{
if (imax < imin)
return KEY_NOT_FOUND;
else
{
int imid = midpoint(imin, imax);
if (A[imid] > key)
return binary_search(A, key, imin, imid - 1);
else if (A[imid] < key)
return binary_search(A, key, imid + 1, imax);
else
return imid;
}
}
private static int midpoint(int imin, int imax)
{
return imin + ((imax - imin) / 2);
}
</code></pre>
<p><strong>VB.NET code</strong></p>
<pre><code> Shared KEY_NOT_FOUND As Integer = -1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim A() As Integer = createArray(1, 100000)
Dim sw1 As Stopwatch = performCalcs(1, A)
Dim sw2 As Stopwatch = performCalcs(2, A)
Dim lag As TimeSpan = TimeSpan.FromTicks(sw1.Elapsed.Ticks - sw2.Elapsed.Ticks)
End Sub
Public Shared Function createArray(minVal As Integer, maxVal As Integer) As Integer()
If (minVal >= maxVal) Then Return Nothing
Dim A(maxVal - minVal) As Integer
Dim i As Integer = -1
For curVal As Integer = minVal To maxVal
i = i + 1
A(i) = curVal
Next
Return A
End Function
Private Function performCalcs(curFunction As Integer, A() As Integer) As Stopwatch
Dim sw As Stopwatch = New Stopwatch
Dim max As Integer = 10000
Dim count As Integer = 0
sw.Start()
While (count < max)
count = count + 1
If curFunction = 1 Then
binary_search_improved2(A, 222, 0, A.Length - 1)
Else
binary_search(A, 222, 0, A.Length - 1)
End If
End While
sw.Stop()
Return sw
End Function
Private Shared Function binary_search_improved2(A() As Integer, key As Integer, imin As Integer, imax As Integer) As Intege
If imax < imin Then Return KEY_NOT_FOUND
Dim imid As Integer
While True
imid = imin + ((imax - imin) >> 1)
If imin = imax OrElse A(imid) = key Then Return imid
If A(imid) < key Then
imin = imid
Else
imax = imid
End If
End While
Return imid 'Never reached; just to avoid the warning
End Function
Private Shared Function binary_search(A() As Integer, key As Integer, imin As Integer, imax As Integer) As Integer
If imax < imin Then
Return KEY_NOT_FOUND
Else
Dim imid As Integer = midpoint(imin, imax)
If A(imid) > key Then
Return binary_search(A, key, imin, imid - 1)
ElseIf A(imid) < key Then
Return binary_search(A, key, imid + 1, imax)
Else
Return imid
End If
End If
End Function
Private Shared Function midpoint(imin As Integer, imax As Integer) As Integer
Return imin + Convert.ToInt32(Math.Floor((imax - imin) / 2))
'Return imin + Math.Floor((imax - imin) / 2)
'The one being used is the "Strict On alternative", as suggested by ChrisW
'In "one-run" the performance is undoubtedly better; but when testing for multiple runs,
'it is still unclear which version is 100% better: the first option seems to get more instable
'Also note that for the given value 222 (within a 1-100000 consecutive array), you can also use:
'Return imin + (imax - imin) / 2
'This is faster but does not work always as the C# version (and the lag continues being there anyway)
End Function
</code></pre>
<p>If you run both pieces of code, you would see that the C# lag is always smaller (and that the difference is pretty notable). Also you would see that the first functions (optimised version of binary search relying on a loop) are always more or less equivalent in both languages and that all the differences are provoked by the second ones (standard, recursive binary search algorithm from Wikipedia).</p>
<p>The question is: <strong>why is there a so big difference between both languages in the recursive version?</strong></p>
<p><strong>UPDATE</strong></p>
<p>If the reliance on <code>midpoint</code> is replaced with the corresponding bitwise operation (<code>imin + ((imax - imin) >> 1)</code>), the differences between both codes seem to disappear and thus, the true responsible seems to be the division. This fact can be confirmed by replacing the recursive function with a loop performing just divisions: the VB.NET version would always be slower (?!). Note that this update has resulted from a pretty quick, small test; the exact origin of the performance differences between both codes is still not clear.</p>
<p><strong>SOLUTION</strong></p>
<p>Both answers have delivered the right solution (well... pointed to the right direction; the final solution came from a comment to this post), although they also include further (not always too relevant and even completely wrong) information, which might avoid future readers to get a clear enough picture. Additionally, this question comes from a different "testing framework" and I want to comment the (different) conclusions from it. That's why I am not writing my answer: I do accept as the right answer one of the posted ones (as far as both deliver the right solution, I marked the one which IMO contains a higher amount of relevant information); this is just a <strong>summary for future readers</strong>.</p>
<ul>
<li>The notable performance difference between both posted codes would disappear by removing the division in <code>midpoint</code> (e.g., by replacing it with the aforementioned bitwise alternative). The reason for this, as explained in the answers below, is that when using the <code>/</code> operator with integers in VB.NET, an internal, automatic conversion to <code>double</code> is performed every time. As said above, you might <strong>avoid</strong> this by relying on the <strong>shift operator</strong>, for example.
<strong>Update:</strong> as rightly pointed out by ChrisW in a comment to this question, the right VB.NET operator for integer division is <code>\</code> (honestly, I rarely use it; equivalent to the <code>Convert.ToInt32</code> part explained below, when dealing with <code>Option Strict Off</code>; this kind of situations prove that what might seem evident is really not... -> I will start using both alternatives every time from now on). After performing more proper tests, I have confirmed that this operator delivers exactly the same performance than its C# version, also that the generated ILs are identical. After some preliminary tests yesterday, I observed a pretty bad performance with this operator; but this was due to have performed quick, simple tests, not too adequate to accurately assess what is really happening under so highly-variable conditions (also I wasn't expecting this operator, which I do never use, to be so influential). Thus, the <strong>right answer to the question</strong> is: the relevant performance lag between the original codes was provoked by using the <strong>wrong integer division operator</strong>. The right conversion of the C# code <code>return imin + (imax - imin) / 2;</code> to VB.NET is: <code>Return imin + (imax - imin) \ 2</code>. Any other option would provoke automatic, intermediate conversions from/to <code>double</code>, what under these conditions ("tick level") would be enough to output notable differences between both languages.</li>
<li>This code comes from a different testing framework, where it has also been observed a performance lag while dealing with <strong>recursion/loops</strong> (this is the reason for the original title of this question). On the other hand, the posted codes cannot replicate this situation and, in the aforementioned external code, the effects from this issue are not too important (and the code is big and its behaviour difficult to be emulated with a simplistic code like the one here). Thus, I have changed the title of this post and focused the problem here on the division. In any case, I did have observed this problem at various points during the development and I am reasonably sure that there might also be an independent (i.e., not related with the division part) recursion/loops "miscoordination VB.NET-C#". I will let this here as a warning for anyone interested in investigating this issue further.</li>
<li>Just to make everything clear regarding some of the posted suggestions:
<ul>
<li>Both versions (VB.NET & C#) <strong>are identical</strong> with the sole exception
of the additional in-built calls in VB.NET inside <code>midpoint</code> (e.g.,
<code>Convert.ToInt32</code> and <code>Math.Floor</code>); there are various comments in
this code explaining the reasons for these calls (and confirming that
<code>Math.Floor</code> (or equivalent) is required to deliver the same results
than C# every time). In any case, note that all the testing has been
done without these calls (<code>Return imin + (imax - imin) / 2</code>, which
does deliver the same results than C#, under this specific input
conditions: array of consecutive integers upto 100000 and 222 as
target value); on the other hand, this is valid just to test the
exact conditions and get a better insight into the problem, but it is
NOT the valid conversion from the C# code, that's why, I have
preferred to let the <code>Math.Floor</code> as the only right/uncommented line.</li>
<li>Also it is worthy to know that the only <code>Option Strict On</code> effect (well... as explained in one of the answers below, <code>Option Strict On</code>
does not have any real performance effect per se; it just indicates
the most adequate way to write the code: you can include the
mentioned <code>Convert.ToInt32</code> with <code>Option Strict On</code>/<code>Off</code>: the second
alternative allows you to choose what to do and the first one forces
you to use it) on this code (e.g., forcing to add the
<strong><code>Convert.ToInt32</code></strong> bit) does <strong>affect the speed</strong> with respect to the <code>Option Strict Off</code> version (i.e., without the <code>Convert.ToInt32</code>
bit): the first alternative is appreciably faster. On the other hand,
I have done some tests with multiple calls to this code (i.e.,
multiple, consecutive time measurements) which seem to indicate that
the <code>Convert.ToInt32</code> part increases the instability (i.e., big
increases/decreases in time between different calls). In any case,
this issue hasn't been adequately tested and thus this comment
represents a mere warning for any future interested reader (like the
recursion/loop mention above).</li>
</ul></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:58:14.783",
"Id": "73216",
"Score": "0",
"body": "Pure speculation: I'm guessing it has something to do with compiler optimization, and you could verify by examining the CLR that each generates. Microsoft had experience in writing optimizing compilers for C syntax, but I doubt they ever spent much effort in optimizations for VB syntax."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:01:26.533",
"Id": "73219",
"Score": "0",
"body": "@Comintern As a pure speculative approach, sounds reasonable. But what I find more difficult to understand is the fact the problem only occurs under specific conditions (recursion). In the optimised version (with loops) the VB.NET is as quick as the C# one (even, quicker, at some points)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:21:56.040",
"Id": "73229",
"Score": "0",
"body": "@Comintern Thanks. Note that there was a small error in my original post. The wrong timings are 800-900; not 7000."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:28:58.923",
"Id": "73268",
"Score": "0",
"body": "I'm not an expert here and I didn't download your code. So this is just an idea. The performance can from version 1 of the binary search and version 2 could be partly due to less code branching in version 2. Another thing is that the recursive function requires, pushing and popping new frames on the stack. This thread on stack overflow on branch prediction may be somewhat related: http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array/11227902#11227902"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:39:13.303",
"Id": "73273",
"Score": "0",
"body": "@MarkAtRamp51 This seems to point more in the right direction. Unfortunately your link is for a different language, what avoids to give an accurate answer to the question: why C# & VB.NET behave differently here? In any case, I will take a look at this link and share any relevant information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:41:57.007",
"Id": "73274",
"Score": "0",
"body": "Right, but it demonstrates a performance improvement by removing branches with binary arithmetic, which is a universal concept. However it certainly doesn't speak to language differences. Also, i didn't intend to answer your question, or I would have posted an answer instead of a comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:47:30.090",
"Id": "73276",
"Score": "0",
"body": "@MarkAtRamp51 Don't misunderstand me: thanks. So far this is the most valuable information. The final goal of my question is knowing why VB.NET and not C#? but knowing what might be the exact reason will certainly be helpful. As said, I will share any relevant information (perhaps tomorrow, because now is a bit late)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:50:02.793",
"Id": "73278",
"Score": "0",
"body": "Gotcha. It seems like ChrisW's answer would have some merit when reviewing the 600ms discrepancy there. Have you tried it with Option Strict On?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:01:38.953",
"Id": "73287",
"Score": "0",
"body": "@MarkAtRamp51 Please, read my comments to Chris: Option Strict On is meant for other thing (writing proper code and thus avoid crashes). There might be a (really, really) slight difference when coming to implicit casting (one in this code); but I wouldn't ever expect this to be so influential, that is: Dim var As Integer = \"5\" vs. Dim Var as Integer Convert.ToInt32(\"5\") -> in both cases the conversion would occur; so... why one option would be faster? As said to Chris: I will do some testing anyway (cannot be 100%)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:14:45.350",
"Id": "73291",
"Score": "0",
"body": "Casting can be a costly process, especially when you consider that you can overload implicit and explicit. Wouldn't you agree that writing proper code provides the compiler with hints that can be used to optimize the performance of the IL that it outputs? If writing better code helps the compiler output better peforming IL code, than we can argue the option strict produces better performing code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:26:50.600",
"Id": "73304",
"Score": "0",
"body": "@MarkAtRamp51 Actually, I did perform the tests and there are appreciable differences. Although it is not completely clear to me which alternative is better (i.e., the explicit conversion is a bit faster but much more instable). Also bear in mind that I have already replaced the middle calculation with the bitwise alternative to avoid all these problems and remain a lag always: until the recursion is not converted into a loop, the performances are not equal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T10:02:27.450",
"Id": "73381",
"Score": "1",
"body": "You said, \"Thus integer division is ALWAYS slower in VB.NET than in C#\". But [VB.NET vs C# integer division](http://stackoverflow.com/questions/6013626/vb-net-vs-c-sharp-integer-division) suggests that VB.NET does support an integer division operator, which is \\ instead of / ... I suggest you test the performance of (and/or compare the IL of) that operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T10:14:52.477",
"Id": "73384",
"Score": "0",
"body": "@ChrisW Thanks for pointing this out. Actually, I did test the integer division operator when you firstly suggested it and observed equivalent performance to the plain VB.NET \"imin + (imax - imin) / 2\" one. Although you are completely right: I have to do a proper testing of all this. Now I am busy with something else; but will come back in some hours after having performed more detailed tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T12:50:20.420",
"Id": "73392",
"Score": "0",
"body": "@ChrisW Just to confirm that you were completely right this time. Using the \\ operator is enough to avoid any problem. My tests yesterday where done too quickly and without respecting the minimum rules to deliver accurate measurements under so demanding conditions (e.g., high number of repetitions, not running tests on form load, etc.), but honestly wasn't expecting this to be so influential (I never use this operator!!). Anyway... thanks again, I have learned quite a few things from this post and I hope that future readers will do too."
}
] | [
{
"body": "<p>Now that we have code to review - the first issue that I see is that you are not comparing identical source code, and that makes it impossible to get an accurate benchmark. The problem is likely this line in the VB source that isn't in the C# source:</p>\n\n<pre><code>Return imid 'Never reached; just to avoid the warning\n</code></pre>\n\n<p>The C# code doesn't have a return statement outside of the loop. I don't have VB.NET installed in Visual Studio so I can't test it, but this is probably defeating optimization code in the compiler because it assumes that the return instruction can be reached. In fact, C# will give you a different warning if it is include in its source and warn you that unreachable code is detected if you include the corresponding code:</p>\n\n<pre><code>return imid; //Never reached; gives warning \"Unreachable code detected\".\n</code></pre>\n\n<p>This illustrates the second issue - you are not actually benchmarking the code itself, but the performance of each of the underlying compilers. Assuming that the syntax is analogous between the two languages doesn't mean that it <em>compiles the same</em> in the C# compiler as it does in the VB.NET compiler. In fact, the different warnings between the two compilers make this quite obvious. Remember, just because the <em>IDE</em> is the same doesn't mean it does the same thing when you compile it. A proper benchmark has to be compiled under the same conditions. This is essentially like comparing benchmarks between identical C code compiled with gcc and Visual Studio.</p>\n\n<p>I am curious how similar the compilers are though - try removing the return instruction (or adding one in the C# code), ignore the warnings, run the benchmarks again.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Finally had time to look at the IL, and the recursion doesn't have anything to do with the performance - both of them have exactly the same IL:</p>\n\n<pre><code>default int32 binary_search_improved2 (int32[] A, int32 key, int32 imin, int32 imax) cil managed \n {\n // Method begins at RVA 0x6598\n // Code size 46 (0x2e)\n .maxstack 3\n .locals init (\n int32 V_0)\n IL_0000: ldarg.3 \n IL_0001: ldarg.2 \n IL_0002: bge.s IL_000a\n\n IL_0004: ldsfld int32 improvedBinary._Standard::KEY_NOT_FOUND\n IL_0009: ret \n IL_000a: ldarg.2 \n IL_000b: ldarg.3 \n IL_000c: ldarg.2 \n IL_000d: sub \n IL_000e: ldc.i4.1 \n IL_000f: shr \n IL_0010: add \n IL_0011: stloc.0 \n IL_0012: ldarg.2 \n IL_0013: ldarg.3 \n IL_0014: beq.s IL_001c\n\n IL_0016: ldarg.0 \n IL_0017: ldloc.0 \n IL_0018: ldelem.i4 \n IL_0019: ldarg.1 \n IL_001a: bne.un.s IL_001e\n\n IL_001c: ldloc.0 \n IL_001d: ret \n IL_001e: ldarg.0 \n IL_001f: ldloc.0 \n IL_0020: ldelem.i4 \n IL_0021: ldarg.1 \n IL_0022: bge.s IL_0029\n\n IL_0024: ldloc.0 \n IL_0025: starg.s 2\n IL_0027: br.s IL_000a\n\n IL_0029: ldloc.0 \n IL_002a: starg.s 3\n IL_002c: br.s IL_000a\n\n } // end of method _Standard::binary_search_improved2\n</code></pre>\n\n<p>The differences are in the midpoint function:</p>\n\n<p>C#:</p>\n\n<pre><code>ldarg.0 \nldarg.1 \nldarg.0 \nsub \nldc.i4.2 \ndiv \nadd \nret \n</code></pre>\n\n<p>VB:</p>\n\n<pre><code>ldarg.0\nconv.r8\nldarg.1\nldarg.0\nsub.ovf\nconv.r8\nldc.r8\ndiv\ncall float64 [mscorlib]System.Math::Floor(float64)\nadd\ncall float64 [mscorlib]System.Math::Round(float64)\nconv.ovf.i4\nret\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:39:59.097",
"Id": "42528",
"ParentId": "42522",
"Score": "5"
}
},
{
"body": "<p>Your <a href=\"https://github.com/varocarbas/snippets_improvedBinary_VB/blob/master/improvedBinary/improvedBinary.vbproj\" rel=\"nofollow noreferrer\">improvedBinary.vbproj</a> specifies ...</p>\n\n<pre><code><PropertyGroup>\n <OptionStrict>Off</OptionStrict>\n</PropertyGroup>\n</code></pre>\n\n<p>... and your <a href=\"https://codereview.stackexchange.com/questions/42522/relevant-performance-difference-c-vb-net-recursion-vs-loops#comment73252_42528\">comment to Comintern</a> said,</p>\n\n<blockquote>\n <p>VB.NET with Strict Off (the case in this code), does allow you to write a function without return statement (although shows a warning).</p>\n</blockquote>\n\n<p>Beware that <a href=\"https://stackoverflow.com/questions/1223660/is-c-sharp-code-faster-than-visual-basic-net-code#comment1048729_1223662\">this comment on StackOverflow</a> says,</p>\n\n<blockquote>\n <p>I agree, but with one small caveat: if you have Option Strict off, you're essentially doing extra conversions everywhere, which often makes code significantly slower. <strong>You can't make this same mistake with C#, which can lead to performance improvements if you rewrite VB.NET code in C#.</strong></p>\n</blockquote>\n\n<p>With Option Strict On, type conversions (which affect performance) are more apparent.</p>\n\n<p>Microsoft's description of the <a href=\"http://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx\" rel=\"nofollow noreferrer\">Option Strict Statement</a> warns that implicit type conversions affect performance. It doesn't explicitly mention conversion from double to int (it talks more about conversion from Object), but using Strict Off allowed you to ignore conversions from double to int, which nevertheless affect performance.</p>\n\n<hr>\n\n<p>A difference between the C# and VB.NET version is that the VB.NET version includes <code>Math.Floor</code> and (depending on whether Option Strict is enabled) <code>Convert.ToInt32</code>.</p>\n\n<p>It would be more like the C# version if you used using <a href=\"http://msdn.microsoft.com/en-us/library/0e16fywh.aspx\" rel=\"nofollow noreferrer\">VB.NET's <code>\\</code> integer division operator</a> instead, which doesn't convert to double.</p>\n\n<p>If you do convert to double, according to <a href=\"https://stackoverflow.com/a/14693081/49942\">Cleanest way to convert a <code>Double</code> or <code>Single</code> to <code>Integer</code>, without rounding</a> VB.NET has (unlike C#) no fast way to convert double to int.</p>\n\n<hr>\n\n<p>I also suggest that, instead of guessing, you look at the emitted IL (perhaps using ILSpy) to see what the differences are between your C# and VB.NET versions.</p>\n\n<hr>\n\n<p>There may be things you can do to make your performance timing more accurate and reliable:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.priority(v=vs.110).aspx\" rel=\"nofollow noreferrer\">Increase the priority of your thread</a> so that it's less pre-empted</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.priorityclass(v=vs.110).aspx\" rel=\"nofollow noreferrer\">Increase the priority of your process</a></li>\n<li>Consider <a href=\"http://kristofverbiest.blogspot.fr/2008/10/beware-of-stopwatch.html\" rel=\"nofollow noreferrer\">measuring Process.TotalProcessorTime instead of ellapsed time</a></li>\n<li>Make each tests much slower (a longer time might be easier/more accurate to measure), e.g. modify your code very slightly so that test the performance of linear search instead of binary search</li>\n</ul>\n\n\n\n<pre><code> if (A[imid] > key)\n // return binary_search(A, key, imin, imid - 1);\n return binary_search(A, key, imin, imax - 1);\n else if (A[imid] < key)\n // return binary_search(A, key, imid + 1, imax);\n return binary_search(A, key, imin + 1, imax);\n else\n return imid;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:26:07.790",
"Id": "42534",
"ParentId": "42522",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "42534",
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T17:40:20.233",
"Id": "42522",
"Score": "5",
"Tags": [
"c#",
"performance",
"recursion",
"vb.net"
],
"Title": "Relevant performance difference C#-VB.NET - Integer Division"
} | 42522 |
<p>I'm trying to solve <a href="http://www.gutenberg.org/files/27635/27635-h/27635-h.htm#p1" rel="nofollow">the Reve's puzzle</a> (a variant of the <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="nofollow">Tower of Hanoi puzzle</a> with four pegs). This is what I've come up with so far:</p>
<pre><code>def solve(disk, source, temppeg1, temppeg2, destination):
if disk == 1:
print((source, destination))
elif disk == 2:
print((source, temppeg1))
print((source, destination))
print((temppeg1, destination))
else:
solve(disk - 2, source, temppeg2, destination, temppeg1)
print((source, temppeg2))
print((source, destination))
print((temppeg2, destination))
solve(disk - 2, temppeg1, source, temppeg2, destination)
>>> solve(16, 'a', 'b', 'c', 'd')
('a', 'c')
... 763 lines deleted ...
('a', 'd')
</code></pre>
<p>While this works fine, I was wondering if there's a better solution (more optimal) than what I have so far. Currently with what I have, I can solve 16 disk in 765 moves.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:08:12.763",
"Id": "73242",
"Score": "1",
"body": "one question that comes immediately to mind is \"are you trying to actually solve? or just find the __minimum number of moves__ to solve?"
}
] | [
{
"body": "<p>if you are just trying to find the <strong>minimum number of moves</strong> and not necessarily a solution you can use the <a href=\"http://en.wikipedia.org/wiki/Tower_of_Hanoi#Frame.E2.80.93Stewart_algorithm\" rel=\"nofollow\">Frame–Stewart algorithm</a> that you linked to earlier</p>\n\n<p>this builds up a solution to the number of moves to achieve a solution. </p>\n\n<pre><code>def FrameStewart(ndisks,npegs):\n if ndisks ==0: #zero disks require zero moves\n return 0\n if ndisks == 1 and npegs > 1: #if there is only 1 disk it will only take one move\n return 1\n if npegs == 3:#3 pegs is well defined optimal solution of 2^n-1\n return 2**ndisks - 1\n if npegs >= 3 and ndisks > 0:\n potential_solutions = (2*FrameStewart(kdisks,npegs) + FrameStewart(ndisks-kdisks,npegs-1) for kdisks in range(1,ndisks))\n return min(potential_solutions) #the best solution\n #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)\n return float(\"inf\") \n\nprint FrameStewart(16,4) #prints 161\n</code></pre>\n\n<p>this tells us that the <strong>optimal</strong> solution for 16 disks and 4 pegs is 161 moves, <em>note that it does not tell us what those moves are</em></p>\n\n<p>if you actually need the moves you will have to heavily modify this solution.</p>\n\n<p>start by solving the towersofhanoi with 3 pegs as that is the traditional layout and has well defined algorithms to solve</p>\n\n<pre><code>def towers3(ndisks,start=1,target=3,peg_set=set([1,2,3])):\n if ndisks == 0 or start == target: #if there are no disks, or no move to make\n return [] #no moves\n my_move = \"move(%s,%s)\"%(start,target) \n if ndisks == 1: #trivial case if there is only one disk, just move it\n return [my_move]\n helper_peg = peg_set.difference([start,target]).pop()\n moves_to_my_move = towers3(ndisks-1,start,helper_peg)\n moves_after_my_move = towers3(ndisks-1,helper_peg,target)\n return moves_to_my_move + [my_move] + moves_after_my_move\n</code></pre>\n\n<p>you can easily verify that this is returning optimal solutions by knowing that the optimal solution to the towers of hanoi with 3 pegs is <strong>2<sup>ndisks</sup> - 1</strong></p>\n\n<p>all thats left is to change <code>FrameStewart</code> to also return moves</p>\n\n<pre><code>def FrameStewartSolution(ndisks,start=1,end=4,pegs=set([1,2,3,4])):\n if ndisks ==0 or start == end: #zero disks require zero moves\n return []\n if ndisks == 1 and len(pegs) > 1: #if there is only 1 disk it will only take one move\n return [\"move(%s,%s)\"%(start,end)] \n if len(pegs) == 3:#3 pegs is well defined optimal solution of 2^n-1\n return towers3(ndisks,start,end,pegs)\n if len(pegs) >= 3 and ndisks > 0:\n best_solution = float(\"inf\")\n best_score = float(\"inf\")\n for kdisks in range(1,ndisks):\n helper_pegs = list(pegs.difference([start,end]))\n LHSMoves = FrameStewartSolution(kdisks,start,helper_pegs[0],pegs)\n pegs_for_my_moves = pegs.difference([helper_pegs[0]]) # cant use the peg our LHS stack is sitting on\n MyMoves = FrameStewartSolution(ndisks-kdisks,start,end,pegs_for_my_moves) #misleading variable name but meh \n RHSMoves = FrameStewartSolution(kdisks,helper_pegs[0],end,pegs)#move the intermediat stack to \n if any(move is None for move in [LHSMoves,MyMoves,RHSMoves]):continue #bad path :(\n move_list = LHSMoves + MyMoves + RHSMoves\n if(len(move_list) < best_score):\n best_solution = move_list\n best_score = len(move_list)\n if best_score < float(\"inf\"): \n return best_solution\n #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)\n return None\n</code></pre>\n\n<p>note that this is going to be much slower than the version that does not need to find the actual solution (this being codereview maybe some folks have suggestions to make it run faster)\nTimings from this experiment</p>\n\n<pre><code>towers3(16) # 0.09 secs\nFrameStewart(16) #0.04 secs\nFrameStewartSolution(16) #67.04 secs!!!\n</code></pre>\n\n<p>really slow as you can see</p>\n\n<p>you can speed it up alot by memoizing it</p>\n\n<pre><code>import json\n\ndef fsMemoizer(f): #just a junky quick memoizer\n cx = {}\n def f2(*args):\n try:\n key= json.dumps(args)\n except:\n key =json.dumps(args[:-1] + (sorted(list(args[-1])),))\n if key not in cx:\n cx[key] = f(*args)\n return cx.get(key)\n return f2\n@fsMemoizer\ndef FrameStewartSolution(ndisks,start=1,end=4,pegs=set([1,2,3,4])):\n ...\n</code></pre>\n\n<p>after memoization the time to calculate became much faster (less than a second)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:35:47.103",
"Id": "73245",
"Score": "0",
"body": "Thank you Joran, however now that I know what the minimum number of moves are is there a way to print what the moves are like what I currently have but with your suggested algorithm instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:37:38.770",
"Id": "73247",
"Score": "1",
"body": "thats why I asked in the comment ... and you said you were trying to find the minimum number of moves ... it is certainly possible but its going to be very difficult ... this algorithm is not really designed around finding an actual solution ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:58:07.953",
"Id": "73318",
"Score": "0",
"body": "this seems to find the optimal solution ... its not very fast and its not very pretty but it works"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T06:38:33.863",
"Id": "73373",
"Score": "0",
"body": "In `towsers3`, `helper_peg = peg_set.difference([start,target])` produces a `set`, which breaks the recursion. The memoizer also crashes as a result. To fetch the right element, use `helper_peg = peg_set.difference([start,target]).pop()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T06:41:56.410",
"Id": "73374",
"Score": "0",
"body": "Your `towers3()` had a `start == target` base case; your `FrameStewartSolution()` should also check for `start == end`. (Why the naming inconsistency?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T06:42:43.460",
"Id": "73375",
"Score": "1",
"body": "`None` is a more natural return value than `\"NaN\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T07:40:26.873",
"Id": "73379",
"Score": "0",
"body": "@200_success the naming inconsistency is because I was already writing the function and decided to use target for the other one as it was more descriptive... but was too lazy to refactor the one using end :P ... I implemented all the other changes in this solution :) thanks!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:32:58.697",
"Id": "42527",
"ParentId": "42524",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42527",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:53:39.173",
"Id": "42524",
"Score": "7",
"Tags": [
"python",
"performance",
"algorithm",
"tower-of-hanoi"
],
"Title": "Solving the Reve's puzzle"
} | 42524 |
<p>Is there a more cleaner approach to this? I'm doing the String calculator Kata posted by Roy Osherove. I realized that my calculator has no way of clearing out a previous expression after calling add. How can I handle this, and also how can I cut down the number of methods?</p>
<p>Here's a valid string: <code>calc.add("//+\n1+2")</code></p>
<p>Here's an invalid string: <code>calc.add("//b\n1b2")</code></p>
<pre><code>class StringCalculator
attr_reader :numbers
def initialize(numbers = '')
@numbers = numbers
end
def add(expression)
@numbers << expression
return nil if @numbers.end_with("\n")
@numbers.gsub!(/\n/, delimiter)
@numbers.empty? ? 0 : solution
end
private
def valid_delimiters
[*(33..46), *(58..64)].map(&:chr).join
end
def solution
numerics = @numbers.split(delimiter).map(&:to_i)
find_negatives(numerics)
numerics.reduce(:+)
end
def find_negatives(numerics)
negatives = numerics.select { |n| n < 0 }
fail "negatives not allowed: #{negatives.join(', ')}" if negatives.any?
end
def supports?
valid_delimiters.include?(@numbers[2, 1])
end
def delimiter
return ',' unless @numbers.match(%r{^//})
supports? ? @numbers[2, 1] : fail('Unsupported delimiter')
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:48:42.883",
"Id": "73428",
"Score": "0",
"body": "so, delimiter is set only on the first `add` (or in the constructor)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:52:16.190",
"Id": "73430",
"Score": "0",
"body": "It's set in add, the constructor only creates the string I want to evaluate. @UriAgassi"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:02:24.400",
"Id": "73434",
"Score": "0",
"body": "But it is set only on the _first_ time you call `add`, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:03:43.887",
"Id": "73435",
"Score": "0",
"body": "Could you add the requirements for the class (what happens when a string ends in `\\n`, etc...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:04:43.160",
"Id": "73436",
"Score": "0",
"body": "I have tests for this, but here's the specs for the code: http://osherove.com/tdd-kata-1/ @UriAgassi"
}
] | [
{
"body": "<p>Some of the code seems to be missing - I can't see where you assign <code>@numbers</code>. I'm going to assume that it is set to <code>\"//+\\n1+2\"</code> or the like.</p>\n\n<p><strong>DRY</strong> - twice in your code you calculate the delimiter (<code>@numbers[2,1]</code>), either pass it as an argument, or make it a method.</p>\n\n<p>Btw, you seem to have a syntax error there, you might have meant to say <code>supports? ? @numbers...</code> instead.</p>\n\n<p><strong>Be clear, not clever</strong> you show good control in ranges, array, chars, etc., but still the following will be much clearer to future readers of your code (you included!)</p>\n\n<pre><code>ValidDelimiters = \"!\\\"\\\\#$%&'()*+,-.:;<=>?@\"\n</code></pre>\n\n<p>(if you don't like to see escaped sequences, you can use <code>%{!\"\\#$%&'()*+,-.:;<=>?@}</code> instead)</p>\n\n<p><strong>Be Ruby</strong> - when you need to return a boolean, which is returned on a condition, there is no need to explicitly say <code>.. ? true : false</code>, simply return the condition result</p>\n\n<p><strong>Harness the power of regular expressions</strong> - when matching strings, captures are set to <a href=\"https://stackoverflow.com/questions/9441152/ruby-what-does-1-mean\"><code>$n</code></a> variables - you can use this to check your delimiter more elegantly:</p>\n\n<pre><code>ValidDelimiters = \"!\\\"\\\\#$%&'()*+,-.:;<=>?@\"\n\ndef supports?(delim)\n ValidDelimiters.include? delim\nend\n\ndef delimiter\n return ',' unless @numbers.match(%r{^//(.)})\n delim = $1\n supports?(delim) ? delim : fail('Unsupported delimiter')\nend\n</code></pre>\n\n<p><strong>Edit</strong> - with the new code</p>\n\n<p><strong>Naming</strong> - choose names that convey the meaning of the member - <code>@numbers</code> implicitly say it is a group of numbers, although it is actually a string... better name might be <code>input_expression</code> or something like that.</p>\n\n<p><strong>Redundant code with side-effects</strong> - your constructor accepts a string as input, which you assign to <code>@numbers</code>. This is not part of the requirements, and you probably don't have tests for that, but it may have serious impact on your result!</p>\n\n<p>Also, for each time you call <code>add</code>, the input is concatenated to the end of the previous result (also not part of the requirements), which <em>will</em> break your code.</p>\n\n<p><strong>Assume nothing</strong> - Ruby's <code>to_i</code> method is very liberal - anything that is not a number will be parsed to - <code>0</code>, so an input like <code>\"1,2,goat,3\"</code> will give a valid result of 6...</p>\n\n<p><strong>When state is redundant</strong> - when assuming each add is supposed to be a separate calculation - no state is needed. You can simply pass the expression around to your helper methods, and return the result. You can even turn your class into a <a href=\"http://ruby-doc.org/core-2.1.0/Module.html\" rel=\"nofollow noreferrer\"><code>module</code></a>, with all methods being class methods, and the usage will be `StringCalculator.add('//+\\n1+2')</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:29:26.460",
"Id": "73423",
"Score": "0",
"body": "I'll update this with how I append numbers. Sorry about that. Give me just a second, don't go anywhere!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:52:35.877",
"Id": "73440",
"Score": "0",
"body": "I thought about making this procedural after realizing that when my tests broke after calling add twice. So I'm assuming a module would just include methods without being object-oriented (which is what you're saying about the object state.) What exactly are you saying about ```to_i```. Did I do something wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:54:03.327",
"Id": "73441",
"Score": "0",
"body": "What would your code return if I called `calc.add('1,2,goat,3')`? Is this what you expect it to return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:58:29.713",
"Id": "73442",
"Score": "0",
"body": "It returned six. So it did in fact parse goat into zero. By converting this into a module, this would be all procedural, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T19:00:32.850",
"Id": "73444",
"Score": "0",
"body": "It won't be object-oriented, but for simple code like this, you doesn't have to be. If a requirement will come, which will require state - you could refactor it then, according to the new requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T19:02:07.523",
"Id": "73445",
"Score": "0",
"body": "Got it, thanks for the insight. This problem was trivial at first and then I lost control flow as I started moving down on the specs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T23:34:35.720",
"Id": "73467",
"Score": "0",
"body": "One last question, how do I test this with rspec? Do I just include the module when describing StringCalculator? I can't find an example that just tests a module."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T04:43:09.147",
"Id": "73480",
"Score": "1",
"body": "Since all your methods should be class methods (`def self.add(expression)`, you don't need to include the module, simply call the method is your test (`expect(StringCalculator.add(...)).to ...`)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:16:36.177",
"Id": "42612",
"ParentId": "42525",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42612",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T18:57:32.697",
"Id": "42525",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Refactoring a Delimiter"
} | 42525 |
<p>I've written some Python code to generate a random hexadecimal string using 31 playing cards drawn without replacement (so no card appears more than once). This is sufficient to provide more than 160 random bits, which is considered sufficient for a bitcoin private key.</p>
<p>I'm interested to know whether anything in the code or the way it is presented would make life difficult for a programmer using it elsewhere. I would like to hear ways that it can be improved in this specific respect - ease of re-use. Any other types of criticism are also welcome.</p>
<p>The full code is <a href="https://github.com/phagocyte/Playing-card-entropy-source/blob/master/PlayingCardEntropySource.py">here</a> and I include the main functional parts below (I've omitted the long doc string and exception classes).</p>
<p>What would make this more useful for other programmers?</p>
<pre><code>from math import factorial
factorial52 = factorial(52)
upperLimit = factorial52//factorial(52-31) - 1
cardRanks = "A23456789TJQK"
cardSuits = "SHDC"
cardCharacters = cardRanks + cardSuits
hexCharacters = "0123456789ABCDEF"
recognisedCharacters = set(i for i in (cardCharacters + hexCharacters))
allCards = []
for s in cardSuits:
for t in cardRanks:
allCards.append(t+s)
def request_input():
print(
"\n"
"Enter a list of 31 playing cards in the format\n"
"AS 2H 3D 4C 5S 6H 7D 8C 9S TH JD QC KS ...\n"
"\n"
"or a hexadecimal number in the range\n"
"0 to 114882682E46B11EADE9F57C1E3E0BBD47FFFFFFF (52! / (52-31)! - 1)\n"
"\n"
"In either case you may include spaces or not as you wish.\n"
"Use T rather than 10. For example TH for ten of hearts.\n"
"Upper and lower case letters are equivalent.\n"
"\n"
)
return input()
def process(argument):
"""Convert the argument from cards to hex or hex to cards.
Decide whether the argument is hexadecimal or a list of cards.
Ambiguity is possible, as some of the characters used to
represent cards are valid hexadecimal characters. However, a
valid list of 31 cards will contain no duplicate cards, and will
therefore contain some hearts or spades, represented by H or S.
A valid list of 31 cards will therefore never be a valid
hexadecimal string.
"""
cleanArgument = nonwhitespace(argument).upper()
check_for_unrecognised_characters(cleanArgument)
try:
value = int(cleanArgument, 16) # Gives error if not hex.
except ValueError:
print(convert_to_hex(cleanArgument))
else:
print(convert_to_cards(value))
def nonwhitespace(argument):
"""Return argument with all whitespace removed.
This includes removing any single spaces within the string.
"""
return "".join(argument.split())
def check_for_unrecognised_characters(argument):
"""Raise an exception if a character is unrecognised.
The only recognised characters in this context are hexadecimal
characters and card ranks and suits.
"""
for i in argument:
if i not in recognisedCharacters:
message = ("Character '" + i +
"' not recognised as part of card or hexadecimal.")
raise UnrecognisedCharacterError(message)
def convert_to_hex(argument):
check_number_of_characters(argument)
listOfCards = [argument[i:i+2] for i in range(0, 62, 2)]
check_if_cards(listOfCards)
check_for_card_repetition(listOfCards)
return hex_representation(listOfCards)
def convert_to_cards(value):
check_hex_is_in_range(value)
return corresponding_cards(value)
def check_number_of_characters(argument):
"""Raise an exception if not exactly 31 cards."""
length = len(argument)
if length < 62:
message = (
"31 cards required, each 2 characters.\n"
"62 characters required in total.\n"
"Only " + str(length) + " nonwhitespace characters provided."
)
raise TooFewCardsError(message)
if length > 62:
message = (
"31 cards required, each 2 characters.\n"
"62 characters required in total.\n"
"" + str(length) + " nonwhitespace characters provided."
)
raise TooManyCardsError(message)
def check_if_cards(listOfCards):
"""Raise an exception if not valid cards.
Every card should be a rank character followed by a suit character.
"""
for i in listOfCards:
if i[0] not in cardRanks:
message = (
"'" + str(i) + "' is not a recognised card rank.\n"
"A valid rank is a single character as follows:\n"
"'A' (ace)\n"
"'2' (two)\n"
"'3' (three)\n"
"'4' (four)\n"
"'5' (five)\n"
"'6' (six)\n"
"'7' (seven)\n"
"'8' (eight)\n"
"'9' (nine)\n"
"'T' (ten)\n"
"'J' (jack)\n"
"'Q' (queen)\n"
"'K' (king)"
)
raise UnrecognisedCardRankError(message)
if i[1] not in cardSuits:
message = (
"'" + str(i) + "' is not a recognised card suit.\n"
"A valid suit is a single character as follows:\n"
"'S' (spades)\n"
"'H' (hearts)\n"
"'D' (diamonds)\n"
"'C' (clubs)"
)
raise UnrecognisedCardSuitError(message)
def check_for_card_repetition(listOfCards):
"""Check that there are 31 unique pairs of characters.
The list is already known to contain exactly 31 pairs. Just check
that each is unique.
"""
uniqueCards = set(listOfCards)
if not len(uniqueCards) == 31:
message = (
"No two cards should be the same.\n"
"Cards should be drawn from a single deck of 52 cards.\n"
"Cards should be drawn without replacement."
)
raise DuplicatedCardsError(message)
def check_hex_is_in_range(value):
"""Check 0 <= value <= 52!/(52-31)! - 1
As Python's arbitrary precision integers cannot be represented
in hexadecimal as negative without using a minus sign, which has
already been precluded, check only the upper limit.
"""
if value > upperLimit:
message = (
"The hexadecimal value is too large to be represented by 31 cards.\n"
"The maximum valid value is 52!/(52-31)! - 1\n"
"In hexadecimal this maximum is\n"
"114882682E46B11EADE9F57C1E3E0BBD47FFFFFFF"
)
raise HexValueTooLargeError(message)
def hex_representation(listOfCards):
"""Return a hexadecimal string defined by the 31 cards.
The 52 cards in the full deck are numbered from 0 to 51.
The order used here is defined by allCards.
The 1st card in listOfCards therefore gives a number from 0 to 51.
Remove this card from the deck so the deck is now numbered from
0 to 50.
The 2nd card in listOfCards now gives a number from 0 to 50.
Continue in the same way, to convert the 3rd card to a number
from 0 to 49, and so on.
The final (31st) card will be converted to a number from 0 to 21.
There is now a list of 31 numbers, each in a smaller range than
the last.
Keep the 1st number as it is (multiply by 1).
Multiply the 2nd number by 52.
Multiply the 3rd number by 52 * 51.
Multiply the 4th number by 52 * 51 * 50.
Continue until all 31 numbers have been updated in this way.
The required result is the sum of this list of 31 numbers.
"""
listOfNumbers = []
deck = allCards
for card in listOfCards:
number = deck.index(card)
listOfNumbers.append(number)
deck.remove(card)
for n in range(31):
listOfNumbers[n] *= factorial52 // factorial(52-n)
result = sum(listOfNumbers)
return hex(result)[2:]
def corresponding_cards(value):
"""Return a string of 31 cards representing the value.
Divide the value by 52 making a note of quotient and remainder.
The remainder will be a number from 0 to 51.
Start a list of numbers with this remainder.
Use the quotient to continue the process.
Divide the quotient by 51 making a note of quotient and remainder.
The remainder will be a number from 0 to 50.
Append this remainder to the list of numbers.
Use the new quotient to continue the process.
Continue until the list contains 31 numbers.
The 1st number will be from 0 to 51, and defines a card from the
full deck of 52 cards (in the order defined by allCards).
The 2nd number will be from 0 to 50, and defines a card from the
remaining 51 cards.
Continue in the same way to convert the remaining numbers to cards.
"""
deck = allCards
listOfNumbers = []
listOfCards = []
for i in range(31):
divisor = 52 - i
quotient = value // divisor
remainder = value % divisor
listOfNumbers.append(remainder)
value = quotient
for cardNumber in listOfNumbers:
card = deck.pop(cardNumber)
listOfCards.append(card)
return " ".join(listOfCards)
# Handle the case where this program is called from the command line.
if __name__ == "__main__":
import sys
arguments = sys.argv
if len(arguments) < 2:
argument = request_input()
else:
argument = "".join(arguments[1:])
process(argument)
</code></pre>
<p>I'd also be interested in any feedback on the way I've phrased the question and the amount of code I've left out and left in.</p>
| [] | [
{
"body": "<pre><code>from math import factorial\n\nfactorial52 = factorial(52)\n</code></pre>\n\n<p>Why do this? Its probably better to just call <code>factorial(52)</code> in the next line</p>\n\n<pre><code>upperLimit = factorial52//factorial(52-31) - 1\n</code></pre>\n\n<p>The python convention is make constants in ALL_CAPS</p>\n\n<pre><code>cardRanks = \"A23456789TJQK\"\ncardSuits = \"SHDC\"\ncardCharacters = cardRanks + cardSuits\nhexCharacters = \"0123456789ABCDEF\"\nrecognisedCharacters = set(i for i in (cardCharacters + hexCharacters))\n</code></pre>\n\n<p>This is the same as <code>set(cardCharacters + hexCharacters)</code> except slower.</p>\n\n<pre><code>allCards = []\nfor s in cardSuits:\n for t in cardRanks:\n allCards.append(t+s)\n</code></pre>\n\n<p>You can use <code>allCards = list(itertools.product(cardSuits, cardRanks))</code>. </p>\n\n<pre><code>def request_input():\n print(\n \"\\n\"\n \"Enter a list of 31 playing cards in the format\\n\"\n \"AS 2H 3D 4C 5S 6H 7D 8C 9S TH JD QC KS ...\\n\"\n \"\\n\"\n \"or a hexadecimal number in the range\\n\"\n \"0 to 114882682E46B11EADE9F57C1E3E0BBD47FFFFFFF (52! / (52-31)! - 1)\\n\"\n \"\\n\"\n \"In either case you may include spaces or not as you wish.\\n\"\n \"Use T rather than 10. For example TH for ten of hearts.\\n\"\n \"Upper and lower case letters are equivalent.\\n\"\n \"\\n\"\n )\n return input()\n\ndef process(argument):\n</code></pre>\n\n<p><code>process</code> and <code>argument</code> are both very generic names. Its better to have a more informative name.</p>\n\n<pre><code> \"\"\"Convert the argument from cards to hex or hex to cards.\n\n Decide whether the argument is hexadecimal or a list of cards.\n Ambiguity is possible, as some of the characters used to \n represent cards are valid hexadecimal characters. However, a \n valid list of 31 cards will contain no duplicate cards, and will \n therefore contain some hearts or spades, represented by H or S. \n A valid list of 31 cards will therefore never be a valid \n hexadecimal string.\n \"\"\"\n cleanArgument = nonwhitespace(argument).upper()\n check_for_unrecognised_characters(cleanArgument)\n</code></pre>\n\n<p>Does this really help you? Can you get away with just checking for valid hex or valid cards?</p>\n\n<pre><code> try:\n value = int(cleanArgument, 16) # Gives error if not hex.\n except ValueError:\n print(convert_to_hex(cleanArgument))\n else:\n print(convert_to_cards(value))\n\ndef nonwhitespace(argument):\n \"\"\"Return argument with all whitespace removed.\n\n This includes removing any single spaces within the string.\n \"\"\"\n return \"\".join(argument.split())\n</code></pre>\n\n<p>That's not a very efficient way to do that. Instead, I'd suggest using a regex replace to find all the whitespace and remove it.</p>\n\n<pre><code>def check_for_unrecognised_characters(argument):\n \"\"\"Raise an exception if a character is unrecognised.\n</code></pre>\n\n<p>A \"check\" function should probably return True or False to indicate the value checked. An exception should indicate that the function failed to accomplish what was asked. In terms of checking, its not failure to have that be check came up false.</p>\n\n<pre><code> The only recognised characters in this context are hexadecimal \n characters and card ranks and suits.\n \"\"\"\n for i in argument:\n</code></pre>\n\n<p><code>i</code> is bad name. Firstly, I'd suggest avoiding single letter variable names, they are hard to determine what they are. Also, i usually is taken to stand for index, and this isn't an index.</p>\n\n<pre><code> if i not in recognisedCharacters:\n message = (\"Character '\" + i + \n \"' not recognised as part of card or hexadecimal.\")\n raise UnrecognisedCharacterError(message)\n</code></pre>\n\n<p>I suggest using <code>repr(i)</code> to add the quotes. Also look at string formatting rather than concatenating strings.</p>\n\n<pre><code>def convert_to_hex(argument):\n check_number_of_characters(argument)\n listOfCards = [argument[i:i+2] for i in range(0, 62, 2)]\n check_if_cards(listOfCards)\n check_for_card_repetition(listOfCards)\n return hex_representation(listOfCards)\n</code></pre>\n\n<p>I'd suggest that you really want something like:</p>\n\n<pre><code>cards = string_to_cards(text_input) # throws exception if not valid cards\nreturn cards_to_hex(cards)\n</code></pre>\n\n<p>Whereas this function mixes the idea of reading the card representation with it overall logic.</p>\n\n<pre><code>def convert_to_cards(value):\n check_hex_is_in_range(value)\n return corresponding_cards(value)\n\ndef check_number_of_characters(argument):\n</code></pre>\n\n<p>The function name is confusing, because it gives no hints about what character limit is going on.</p>\n\n<pre><code> \"\"\"Raise an exception if not exactly 31 cards.\"\"\"\n length = len(argument)\n if length < 62:\n message = (\n \"31 cards required, each 2 characters.\\n\"\n \"62 characters required in total.\\n\"\n \"Only \" + str(length) + \" nonwhitespace characters provided.\"\n )\n raise TooFewCardsError(message)\n if length > 62:\n message = (\n \"31 cards required, each 2 characters.\\n\"\n \"62 characters required in total.\\n\"\n \"\" + str(length) + \" nonwhitespace characters provided.\"\n )\n raise TooManyCardsError(message)\n\ndef check_if_cards(listOfCards):\n \"\"\"Raise an exception if not valid cards.\n\n Every card should be a rank character followed by a suit character.\n \"\"\"\n for i in listOfCards:\n if i[0] not in cardRanks:\n message = (\n \"'\" + str(i) + \"' is not a recognised card rank.\\n\"\n \"A valid rank is a single character as follows:\\n\"\n \"'A' (ace)\\n\"\n \"'2' (two)\\n\"\n \"'3' (three)\\n\"\n \"'4' (four)\\n\"\n \"'5' (five)\\n\"\n \"'6' (six)\\n\"\n \"'7' (seven)\\n\"\n \"'8' (eight)\\n\"\n \"'9' (nine)\\n\"\n \"'T' (ten)\\n\"\n \"'J' (jack)\\n\"\n \"'Q' (queen)\\n\"\n \"'K' (king)\"\n )\n raise UnrecognisedCardRankError(message)\n if i[1] not in cardSuits:\n message = (\n \"'\" + str(i) + \"' is not a recognised card suit.\\n\"\n \"A valid suit is a single character as follows:\\n\"\n \"'S' (spades)\\n\"\n \"'H' (hearts)\\n\"\n \"'D' (diamonds)\\n\"\n \"'C' (clubs)\"\n )\n raise UnrecognisedCardSuitError(message)\n</code></pre>\n\n<p>You don't really need to create so many exception classes. Also putting the user interface text in the exception is problematic. </p>\n\n<pre><code>def check_for_card_repetition(listOfCards):\n \"\"\"Check that there are 31 unique pairs of characters.\n\n The list is already known to contain exactly 31 pairs. Just check \n that each is unique.\n \"\"\"\n uniqueCards = set(listOfCards)\n if not len(uniqueCards) == 31:\n message = (\n \"No two cards should be the same.\\n\"\n \"Cards should be drawn from a single deck of 52 cards.\\n\"\n \"Cards should be drawn without replacement.\"\n )\n raise DuplicatedCardsError(message)\n\ndef check_hex_is_in_range(value):\n \"\"\"Check 0 <= value <= 52!/(52-31)! - 1\n\n As Python's arbitrary precision integers cannot be represented\n in hexadecimal as negative without using a minus sign, which has\n already been precluded, check only the upper limit.\n \"\"\"\n if value > upperLimit:\n message = (\n \"The hexadecimal value is too large to be represented by 31 cards.\\n\"\n \"The maximum valid value is 52!/(52-31)! - 1\\n\"\n \"In hexadecimal this maximum is\\n\"\n \"114882682E46B11EADE9F57C1E3E0BBD47FFFFFFF\"\n )\n raise HexValueTooLargeError(message)\n\ndef hex_representation(listOfCards):\n \"\"\"Return a hexadecimal string defined by the 31 cards.\n\n The 52 cards in the full deck are numbered from 0 to 51.\n The order used here is defined by allCards.\n The 1st card in listOfCards therefore gives a number from 0 to 51.\n Remove this card from the deck so the deck is now numbered from \n 0 to 50.\n The 2nd card in listOfCards now gives a number from 0 to 50.\n Continue in the same way, to convert the 3rd card to a number \n from 0 to 49, and so on.\n The final (31st) card will be converted to a number from 0 to 21.\n There is now a list of 31 numbers, each in a smaller range than \n the last.\n Keep the 1st number as it is (multiply by 1).\n Multiply the 2nd number by 52.\n Multiply the 3rd number by 52 * 51.\n Multiply the 4th number by 52 * 51 * 50.\n Continue until all 31 numbers have been updated in this way.\n The required result is the sum of this list of 31 numbers.\n \"\"\"\n listOfNumbers = []\n deck = allCards\n for card in listOfCards:\n number = deck.index(card)\n listOfNumbers.append(number)\n deck.remove(card)\n\n for n in range(31):\n listOfNumbers[n] *= factorial52 // factorial(52-n)\n result = sum(listOfNumbers)\n return hex(result)[2:]\n\ndef corresponding_cards(value):\n \"\"\"Return a string of 31 cards representing the value.\n\n Divide the value by 52 making a note of quotient and remainder.\n The remainder will be a number from 0 to 51.\n Start a list of numbers with this remainder.\n Use the quotient to continue the process.\n Divide the quotient by 51 making a note of quotient and remainder.\n The remainder will be a number from 0 to 50.\n Append this remainder to the list of numbers.\n Use the new quotient to continue the process.\n Continue until the list contains 31 numbers.\n The 1st number will be from 0 to 51, and defines a card from the \n full deck of 52 cards (in the order defined by allCards).\n The 2nd number will be from 0 to 50, and defines a card from the \n remaining 51 cards.\n Continue in the same way to convert the remaining numbers to cards.\n \"\"\"\n deck = allCards\n listOfNumbers = []\n listOfCards = []\n for i in range(31):\n divisor = 52 - i\n quotient = value // divisor\n remainder = value % divisor\n listOfNumbers.append(remainder)\n value = quotient\n for cardNumber in listOfNumbers:\n card = deck.pop(cardNumber)\n listOfCards.append(card)\n return \" \".join(listOfCards)\n\n# Handle the case where this program is called from the command line.\nif __name__ == \"__main__\":\n import sys\n arguments = sys.argv\n if len(arguments) < 2:\n argument = request_input()\n else:\n argument = \"\".join(arguments[1:])\n process(argument)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:25:30.407",
"Id": "73345",
"Score": "0",
"body": "Thanks very much for all the improvements. I use factorial52 in some of the later functions, so I can see now how this would benefit from being explicitly a constant in CAPS. Otherwise it just looks like a pointless variable for just that one line. It's great to have reasons for all the improvements so I can apply them elsewhere too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:38:07.710",
"Id": "73356",
"Score": "0",
"body": "I haven't used your suggestion of `itertools.product` as it gives me a different card order and tuples instead of strings of 2 characters. Instead I've replaced the nested for loops you highlighted with a one line list comprehension which hopefully looks less cluttered."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T23:22:34.770",
"Id": "42554",
"ParentId": "42526",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42554",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T19:24:19.083",
"Id": "42526",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"random",
"playing-cards",
"bitcoin"
],
"Title": "Produce bitcoin private key from 31 playing cards"
} | 42526 |
<p>I would like to execute code for many views whenever the window is unloaded.</p>
<p>For instance, I could have something like this in a view's initialize:</p>
<pre><code>initialize: function() {
$(window).unload(this.stopListening.bind(this));
}
</code></pre>
<p>I'm wondering if it would be better to have a manager which aggregates all of the view's requests into one event like:</p>
<pre><code>define(function () {
'use strict';
var ForegroundViewManager = Backbone.Model.extend({
defaults: function () {
return {
views: []
};
},
initialize: function() {
$(window).unload(function () {
this.allViewsStopListening();
}.bind(this));
},
allViewsStopListening: function() {
_.each(this.get('views'), function(view) {
view.stopListening();
});
},
subscribe: function (view) {
var views = this.get('views');
var index = views.indexOf(view);
if (index === -1) {
views.push(view);
console.log("Subscribed a view:", view, views.length);
} else {
console.log("Already subscribed!");
}
},
unsubscribe: function (view) {
var views = this.get('views');
var index = views.indexOf(view);
if (index > -1) {
views.splice(index, 1);
}
}
});
return new ForegroundViewManager();
});
</code></pre>
<p>The second way is a lot more code, but results in just one unload event being bound to the window and then iterating over a collection. Is this preferred? Or is it better to have each view bind itself to window.unload?</p>
| [] | [
{
"body": "<p>An opinion question, always tricky;</p>\n\n<p>I think we can all agree that the second approach is not <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">KISS</a> and requires more bandwidth to download to the browser. As far as I can tell, this will not save any memory either..</p>\n\n<p>I would strongly suggest to use the first approach.</p>\n\n<p>Furthermore:</p>\n\n<ul>\n<li><p><code>unsubscribe</code> could be reduced to:<br></p>\n\n<pre><code>unsubscribe: function (view) {\n this.get('views') = _without( this.get('views') , view );\n}\n</code></pre></li>\n<li>Production code should not use <code>console.log</code></li>\n<li><code>subscribe</code> could use <code>_.union()</code></li>\n<li><p><code>subscribe</code> could be reduced to:<br></p>\n\n<pre><code>subscribe: function (view) {\n this.get('views') = _union( this.get('views') , view );\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:11:32.923",
"Id": "42657",
"ParentId": "42531",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42657",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:13:39.123",
"Id": "42531",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"backbone.js",
"event-handling"
],
"Title": "Proper techniques for allowing many views to subscribe to window.unload?"
} | 42531 |
<p>I have this batch that builds some projects using msbuild.</p>
<p>What I want to do is to skip building my-last.proj if any of the above builds fail: my-proj1.proj to my-proj5.proj using environment variables.</p>
<p>I'm sure that there is another cleaner way to do this, but so far I just can't figure it out.</p>
<pre><code>msbuild /target:Win32 my-proj1.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED32=1
)
msbuild /target:X64 my-proj1.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED64=1
)
msbuild /target:ManagedWin32 my-proj1.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED32=1
)
msbuild /target:ManagedX64 my-proj1.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED64=1
)
msbuild /target:Win32 my-proj2.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED32=1
)
msbuild /target:X64 my-proj2.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED64=1
)
msbuild /target:Win32 my-proj3.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED32=1
)
msbuild /target:Win32 my-proj4.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED32=1
)
msbuild /target:Win32 my-proj5.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED32=1
)
IF NOT "%FAILED32%" == "1" (
msbuild /target:setup32 my-last.proj
)
msbuild /target:X64 my-proj3.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED64=1
)
msbuild /target:X64 my-proj4.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED64=1
)
msbuild /target:X64 my-proj5.proj
IF NOT ERRORLEVEL 0 (
set /p BUILDFAILED64=1
)
IF NOT "%FAILED64%" == "1" (
msbuild /target:setup64 my-last.proj
)
</code></pre>
<p>Does anyone have any ideas?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:48:38.200",
"Id": "73277",
"Score": "1",
"body": "Welcome to Code Review! It looks like you have figured out exactly what this site is about. You just passed the \"first post\" test with ease!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:55:59.267",
"Id": "73286",
"Score": "1",
"body": "@Simon André Forsberg - Thanks, I'm glad that Code Review exists."
}
] | [
{
"body": "<p>You probably meant <code>set %BUILDFAILEDxx%=1</code>? <code>/p</code> is for prompting interactively (or reading from a file).</p>\n\n<p>Otherwise, except a minor typo <code>%BUILDFAILED32%</code> instead of just <code>%FAILED32%</code> (and same for 64bit builds), this looks good (and \"clean\") enough for me.</p>\n\n<p>You could get rid of the parentheses (for the sake of it?) if you wrote each <code>if</code> on a single line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:24:39.433",
"Id": "73302",
"Score": "0",
"body": "@Jamal oops, thanks for the \"codifying\", I'll look up how to do it properly. As for the space before the question mark, sorry I'm French :-) so I may do it again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T09:23:12.643",
"Id": "73380",
"Score": "0",
"body": "Did you expect more ? Apart from reorganizing the order of builds (either by number 32b-1,64b-1,32b-2,... or by regrouping all the 32 and 64bit ones) I think this is the optimal & \"cleanest\" solution (with environment variables, in cmd)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:15:12.667",
"Id": "42542",
"ParentId": "42536",
"Score": "2"
}
},
{
"body": "<p>You probably want to localize any environment changes.</p>\n\n<p>You should initialize your variables to a known state at the beginning, otherwise you could get the wrong result.</p>\n\n<p>You have a lot of redundant code that can be eliminated by using a CALLed subroutine</p>\n\n<p>You can use the <code>||</code> operator to conditionally execute code if the previous command failed. I find it simpler than using IF ERRORLEVEL.</p>\n\n<p>You can save a bit of typing by storing code in a variable to be used as a simple macro.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>@echo off\nsetlocal\nset \"failed32=\"\nset \"failed64=\"\nset \"build=call :build\"\n\n%build% Win 32 my-proj1\n%build% X 64 my-proj1\n%build% ManagedWin 32 my-proj1\n%build% ManagedX 64 my-proj1\n%build% Win 32 my-proj2\n%build% X 64 my-proj2\n%build% Win 32 my-proj3\n%build% Win 32 my-proj4\n%build% Win 32 my-proj5\n\nif not defined failed32 msbuild /target:setup32 my-last.proj\n\n%build% X 64 my-proj3\n%build% X 64 my-proj4\n%build% X 64 my-proj5\n\nif not defined failed64 msbuild /target:setup64 my-last.proj\nexit /b\n\n\n:build target size proj\nmsbuild /target:%1%2 %3.proj || set failed%%2=1\nexit /b\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T04:30:16.513",
"Id": "47433",
"ParentId": "42536",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42542",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:30:13.933",
"Id": "42536",
"Score": "3",
"Tags": [
"batch"
],
"Title": "Msbuild batch - if any build fails than skip the last one"
} | 42536 |
<blockquote>
<p>Write the program <code>expr</code>, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument.</p>
<p>For example:</p>
<pre><code>expr 2 3 4 + *
</code></pre>
</blockquote>
<p>There are 4 files:</p>
<p><code>calc.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
int main(int argc, char *argv[]) {
double tmpOp;
char c;
if(argc > 3) {
while(--argc) {
c = getOp(*++argv);
switch(c) {
case NUMBER:
push(atof(*argv));
break;
case '+':
push(pop() + pop());
break;
case '-':
tmpOp = pop();
push(pop() - tmpOp);
break;
case '*':
push(pop() * pop());
break;
case '\\':
tmpOp = pop();
if(!tmpOp) {
printf("error: can't divide by 0\n");
}
else {
push(pop()/tmpOp);
}
break;
default:
printf("error: invalid expression %s\n", *argv);
}
}
printf("%g\n", pop());
}
else {
printf("invalid call\n");
}
return 0;
}
</code></pre>
<p>This file consist in a while loop that runs <code>argc-1</code> times. At each iteration an argument is analized. If it is a number, it is pushed to the stack. If it is an operator, 2 numbers are popped from the stack and the operator is applied to these operands. If the argument is not valid, an error is printed.</p>
<p><code>argc</code> should allways be bigger than 3 because, at this moment, the calculator needs at least 2 operands and 1 operator for an valid call.</p>
<p>The file <code>getop.c</code>:</p>
<pre><code>#include <ctype.h>
#include "calc.h"
static int isNumber(const char *s) {
int i = 0;
if(isdigit(s[i])) {
for(; isdigit(s[i]); i++)
;
}
if(s[i] == '.') {
i++;
for(; isdigit(s[i]); i++)
;
}
if(s[i] == 'e' || s[i] == 'E') {
i++;
for(; isdigit(s[i]); i++)
;
}
if(s[i] != '\0') {
return 0;
}
return 1;
}
char getOp(const char *op) {
int i;
if(!isdigit(op[0]) && op[0] != '.') {
return op[0];
}
i = 0;
/* support for negative number */
if(op[0] == '-' && !isdigit(op[1])) {
return op[0];
}
else {
i++;
}
if(isNumber(op + i)) {
return NUMBER;
}
return op[0];
}
</code></pre>
<p>The function <code>getOp</code> returns <code>'n'</code> if <code>op</code> contains an valid number or the first charachter of <code>op</code> if it is not a number - for example when we are dealing with operators.
The function <code>getOp</code> uses a helper to check if the the value of <code>op</code> is a valid number. Also, the call <code>getOp(op + i)</code> is intended to validate checks for negative number.</p>
<p>The file <code>stack.c</code>:</p>
<pre><code>#include <stdio.h>
#define STACKVALUE 100
static double stack[STACKVALUE];
static double *pStack = stack; /* next free position in stack */
void push(double value) {
if(pStack - stack > STACKVALUE) {
printf("error: there is not enough psace in stack");
}
else {
*(pStack++) = value;
}
}
double pop(void) {
if((pStack - stack) > 0) {
return *--pStack;
}
printf("warning: the stack is free");
return 0.0;
}
</code></pre>
<p>And the file <code>calc.h</code>:</p>
<pre><code>#define NUMBER 'n'
int getOp(const char *s);
void push(double value);
double pop(void);
</code></pre>
| [] | [
{
"body": "<h2>What you did well</h2>\n\n<p>Taking advantage of the shell to split your expression into tokens is smart. It saves you from the trouble of having to write a tokenizer.</p>\n\n<p>Beware, though, of a usability issue with Unix shells, where <code>*</code> and <code>\\</code> have special significance and need to be quoted or escaped.</p>\n\n<h2>Bugs</h2>\n\n<ol>\n<li><p><strong>Compilation error:</strong> This was just carelessness.</p>\n\n<blockquote>\n<pre><code>getop.c:31:6: error: conflicting types for 'getOp'\nchar getOp(const char *op) {\n ^\n./calc.h:3:5: note: previous declaration is here\nint getOp(const char *s);\n ^\n1 error generated.\n</code></pre>\n</blockquote></li>\n<li><p><strong>Error handling:</strong> You treat errors like warnings. If there's an error, I would expect the program to print nothing to stdout, and for the program to exit with a non-zero status code. Error and warning messages should be printed to stderr instead of stdout.</p></li>\n<li><p><strong>Picky validation:</strong> In my opinion, this should successfully evaluate to 1:</p>\n\n<blockquote>\n<pre><code>$ ./expr 1\ninvalid call\n</code></pre>\n</blockquote>\n\n<p>By the way, if you find an insufficient number of command-line arguments, just return early.</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n if (argc <= 1) {\n fprintf(stderr, \"invalid call\\n\");\n return 1;\n }\n\n while (--argc) {\n …\n }\n printf(\"%g\\n\", pop());\n return 0;\n}\n</code></pre></li>\n<li><p><strong>Mishandling of negative numbers:</strong> I would expect the following calculation to yield -1:</p>\n\n<blockquote>\n<pre><code>$ ./expr 3 -4 +\nwarning: the stack is freewarning: the stack is free-3\n</code></pre>\n</blockquote></li>\n<li><p><strong>Unconventional division operator:</strong> It is customary to use <code>/</code> for division. I don't know why you use <code>\\</code> instead.</p></li>\n<li><p><strong>Division-by-zero paranoia:</strong> In contrast to integer arithmetic, where division by zero is undefined behaviour, division by zero in IEEE 754 floating point arithmetic should just return infinity. Perhaps you could remove the check for division by zero.</p></li>\n</ol>\n\n<h2>Number parsing</h2>\n\n<p>I suggest the following implementation for <code>getop.c</code>, which is simpler and handles negative numbers.</p>\n\n<pre><code>#include <ctype.h>\n#include \"calc.h\"\n\nstatic int isNumber(const char *s) {\n if (*s == '-' || *s == '+') s++;\n if (*s == '\\0') {\n return 0;\n }\n\n while (isdigit(*s)) s++;\n\n if (*s == '.') {\n s++;\n while (isdigit(*s)) s++;\n }\n\n if (*s == 'e' || *s == 'E') {\n s++;\n while (isdigit(*s)) s++;\n }\n\n return *s == '\\0';\n}\n\n\nchar getOp(const char *op) {\n return isNumber(op) ? NUMBER : *op;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T12:43:13.060",
"Id": "43055",
"ParentId": "42537",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43055",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:37:21.087",
"Id": "42537",
"Score": "7",
"Tags": [
"c",
"beginner",
"console",
"math-expression-eval"
],
"Title": "Command line reverse polish calculator"
} | 42537 |
<p>For practice I decided that I wanted to write an animation class for SpriteSheets. The problem is that a single Sprite can have different widths depending on the action they are drawn to act. A tool called <a href="http://spritesheetpacker.codeplex.com/" rel="nofollow noreferrer">Sprite Sheet Packer</a> creates a Map file documenting the index and bounds of each sprite. This file looks a little like this:</p>
<pre><code>0 = 157 184 123 189
1 = 187 0 177 183
2 = 402 181 105 189
3 = 495 0 111 180
4 = 710 0 102 171
walking = 1 2 3 4
</code></pre>
<p>Note that the <code>walking = 1 2 3 4</code> is actually <strong>not</strong> part of the map file, but I want to add some extra information, such as which animation is comprised of which frames. This I convert into the following yaml:</p>
<pre><code>Frames:
- Index: 0
Bounds: [157, 184, 123, 189]
- Index: 1
Bounds: [187, 0, 177, 183]
- Index: 2
Bounds: [402, 181, 105, 189]
- Index: 3
Bounds: [495, 0, 111, 180]
- Index: 4
Bounds: [710, 0, 102, 171]
Animations:
- Name: walking
Frames: [1, 2, 3, 4]
</code></pre>
<p>This is my code (which uses Guava):</p>
<pre><code>data class TextParseException(message: String = "", cause: Throwable? = null): RuntimeException(message, cause)
/**
* <h2>Converts a Metadata .txt file into a .yaml file.</h2>
*
* <b>Format of a metadata text file:</b>
* <pre>
* <index>: <x> <y> <width> <height>
* ...
*
* <name>: <frame1> <frame2> ... <frameN>
* ...
* </pre>
*
* <p>Be aware that a blank line (between ... and <name>) is the separator between
* frame and animation entries. Trailing newspaces are ok, but any others will break
* the parsing.</p>
*
* <b>Output format:</b>
* <pre>
* Frames:
* - Index: <index>
* Bounds: [<x>, <y>, <width>, <height>]
* ...
* Animations:
* - Name: <name<
* Frames: [<frame1>, <frame2>, ..., <frameN>
* </pre>
*
* @param metadata path to metadata file for parsing
* @returns formatted .yaml string of metadata contents
* @throws TextParseException if an error occurs parsing a frame or animation entry
* @throws IllegalArgumentException if the metadata file does not exist
* @throws IOException if the file could not be accessed or read
*/
fun convertToYaml(metadata: Path): String {
Preconditions.checkArgument(Files.exists(metadata),
"The file ${metadata.getFileName()} does not exist")
val lines = Files.readAllLines(metadata, StandardCharsets.UTF_8).map { it.trim() }
if (lines.all { it.isEmpty() })
return ""
val yamlFrameEntries = gatherRawFrameEntries(lines)
.map(::split)
.map(::toFrameEntry)
.sortBy { it.index }
.map(::createYamlFrameEntry)
val yamlAnimationEntries = gatherRawAnimationEntries(lines)
.map(::split)
.map(::toAnimationEntry)
.map(::createYamlAnimationEntry)
return buildCompleteYaml(yamlFrameEntries, yamlAnimationEntries)
}
private fun gatherRawFrameEntries(lines: List<String>): List<String> {
return lines.takeWhile { it.isNotEmpty() }
}
private fun gatherRawAnimationEntries(lines: List<String>): List<String> {
return lines.dropWhile { it.isNotEmpty() }.drop(1).filter { it.isNotEmpty() }
}
private fun split(line: String): List<String> {
val normalizedEntry = line.replace("=", " ")
val parts = Splitter.on(' ')!!
.trimResults()!!
.omitEmptyStrings()!!
.split(normalizedEntry)!!
return parts.toList()
}
private data class FrameEntry(val index: Int, val bounds: List<Int>)
private data class AnimationEntry(val name: String, val frames: List<Int>)
private fun toFrameEntry(entryPieces: List<String>): FrameEntry {
try {
val frameIndex = entryPieces.first!!
val frameBounds = entryPieces.drop(1).map { it.toInt() }
return FrameEntry(frameIndex.toInt(), frameBounds)
} catch (e: Exception) {
throw TextParseException("Could not parse a Frame entry.", e)
}
}
private fun toAnimationEntry(entryPieces: List<String>): AnimationEntry {
try {
val animationName = entryPieces.first!!
val animationFrames = entryPieces.drop(1).map { it.toInt() }
return AnimationEntry(animationName, animationFrames)
} catch (e: Exception) {
throw TextParseException("Could not parse an Animation entry.", e)
}
}
private fun createYamlFrameEntry(frameEntry: FrameEntry): String {
val yamlFrameEntryBuilder = StringBuilder()
yamlFrameEntryBuilder.append(" - Index: ${frameEntry.index}\n")
yamlFrameEntryBuilder.append(" Bounds: [")
yamlFrameEntryBuilder.append("${Joiner.on(", ")!!.join(frameEntry.bounds)}]\n")
return yamlFrameEntryBuilder.toString()
}
private fun createYamlAnimationEntry(animationEntry: AnimationEntry): String {
val yamlFrameEntryBuilder = StringBuilder()
yamlFrameEntryBuilder.append(" - Name: ${animationEntry.name}\n")
yamlFrameEntryBuilder.append(" Frames: [")
yamlFrameEntryBuilder.append("${Joiner.on(", ")!!.join(animationEntry.frames)}]\n")
return yamlFrameEntryBuilder.toString()
}
private fun buildCompleteYaml(yamlFrameEntries: List<String>,
yamlAnimationEntries: List<String>): String {
val completeYamlBuilder = StringBuilder()
appendYamlEntries(completeYamlBuilder, "Frames:", yamlFrameEntries)
if (yamlAnimationEntries.isNotEmpty())
appendYamlEntries(completeYamlBuilder, "Animations:", yamlAnimationEntries)
return completeYamlBuilder.toString()
}
private fun appendYamlEntries(builder: StringBuilder,
sectionName: String,
entries: List<String>) {
builder.append("${sectionName}\n")
entries.forEach { builder.append(it) }
}
</code></pre>
<p>These are my tests:</p>
<pre><code>class ConverterSpec: Spek() {{
given("A .txt -> .yaml converter") {
on("loading a non-existent file") {
it("throws an IllegalArgumentException") {
failsWith(javaClass<IllegalArgumentException>()) {
convertToYaml(Paths.get("Missing.txt")!!)
}
}
}
on("loading an empty file") {
val emptyFileUrl = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/Empty.txt")!!
it("produces empty yaml") {
val output = convertToYaml(Paths.get(emptyFileUrl.toURI())!!)
assertTrue(output.isEmpty(),
"YAML output not empty, but: $output")
}
}
on("loading file with on frame entry") {
val frameFileUrl = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/Frame.txt")!!
it("produces corresponding yaml for frame") {
val expected = "Frames:\n" +
" - Index: 0\n" +
" Bounds: [157, 184, 123, 189]\n"
val output = convertToYaml(Paths.get(frameFileUrl.toURI())!!)
assertEquals(expected, output,
"The YAML did not conform to the expected output.")
}
}
on("loading file with multiple frame entries") {
val framesFileUrl = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/Frames.txt")!!
it("produces corresponding yaml for all frames") {
val expected = "Frames:\n" +
" - Index: 0\n" +
" Bounds: [157, 184, 123, 189]\n" +
" - Index: 1\n" +
" Bounds: [187, 0, 177, 183]\n" +
" - Index: 2\n" +
" Bounds: [402, 181, 105, 189]\n"
val output = convertToYaml(Paths.get(framesFileUrl.toURI())!!)
assertEquals(expected, output,
"The YAML did not conform to the expected output.")
}
}
on("loading file with frames and animations") {
val frameAnimationFileUrl = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/FrameAnimation.txt")!!
it("produces corresponding yaml incorporating an animation name and number of frames") {
val expected = "Frames:\n" +
" - Index: 0\n" +
" Bounds: [157, 184, 123, 189]\n" +
" - Index: 1\n" +
" Bounds: [187, 0, 177, 183]\n" +
" - Index: 2\n" +
" Bounds: [402, 181, 105, 189]\n" +
"Animations:\n" +
" - Name: Walking\n" +
" Frames: [0, 1, 2]\n"
val output = convertToYaml(Paths.get(frameAnimationFileUrl.toURI())!!)
assertEquals(expected, output,
"The YAML did not conform to the expected output.\nPerhaps the Animations section is malformed?")
}
}
on("loading file with no frames but animations") {
val onlyAnimationFileUrl = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/OnlyAnimation.txt")!!
it("throws a TextParseException") {
failsWith(javaClass<TextParseException>()) {
convertToYaml(Paths.get(onlyAnimationFileUrl.toURI())!!)
}
}
}
on("loading file with trailing newlines") {
val trailingNewlines = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/TrailingNewlines.txt")!!
it("loads normally and ignores trailing newlines") {
val expected = "Frames:\n" +
" - Index: 0\n" +
" Bounds: [157, 184, 123, 189]\n" +
" - Index: 1\n" +
" Bounds: [187, 0, 177, 183]\n" +
" - Index: 2\n" +
" Bounds: [402, 181, 105, 189]\n" +
"Animations:\n" +
" - Name: Walking\n" +
" Frames: [0, 1, 2]\n"
val output = convertToYaml(Paths.get(trailingNewlines.toURI())!!)
assertEquals(expected, output)
}
}
on("Loading a file with unnatural ordering") {
val unnaturalOrdering = javaClass<ConverterSpec>().getClassLoader()!!.getResource("converter/UnsortedFrames.txt")!!
it("loads and sorts frames into natural order") {
val expected = "Frames:\n" +
" - Index: 0\n" +
" Bounds: [157, 184, 123, 189]\n" +
" - Index: 1\n" +
" Bounds: [187, 0, 177, 183]\n" +
" - Index: 2\n" +
" Bounds: [402, 181, 105, 189]\n" +
" - Index: 10\n" +
" Bounds: [187, 0, 177, 183]\n"
val output = convertToYaml(Paths.get(unnaturalOrdering.toURI())!!)
assertEquals(expected, output)
}
}
}
}}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-30T06:28:06.200",
"Id": "291232",
"Score": "0",
"body": "If you're using Google Guava, please state so and add the tag [tag:guava]."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:39:38.187",
"Id": "42538",
"Score": "2",
"Tags": [
"guava",
"kotlin",
"yaml"
],
"Title": "Converting SpriteSheet Metadata .txt to .yaml"
} | 42538 |
<p>I have two files. </p>
<ol>
<li>File 1. Has a list of all the dictionary words </li>
<li>File 2. Has a list of
all prepositions.</li>
</ol>
<p>I want to remove all the prepositions from the dictionary.
I want to reduce the number of lines in my code and also make it more elegant, idiomatic and readable. </p>
<pre><code> #!/usr/bin/env ruby
path = "/Users/../Desktop/";
file_original_wordlist = File.open("#{path}" + "dictionary.txt", "r")
file_remove_wordlist = File.open("#{path}" + "prepositions.txt", "r")
# Need to initialize the variables else I get errors
delete_word = false
word_orig = ''
word_rem = ''
count = 0
file_original_wordlist.each_line do |line1|
file_remove_wordlist.each_line do |line2|
word_orig = line1
word_rem = line2
if word_orig.eql?(word_rem)
puts "Deleting the word " + word_rem
delete_word = true
count++
end
end
if delete_word == false
File.open(path + "scrubbed_list.txt", "a") {|f| f.write(word_orig) }
end
# Need to reopen the file otherwise after the first iteration to start from the beginning
file_remove_wordlist = File.open("#{path}" + "prepositions.txt", "r")
delete_word = false
end
puts "Deleted " + count + " words in total"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T06:26:44.467",
"Id": "73486",
"Score": "0",
"body": "I ran some benchmarks that I reported in my answer."
}
] | [
{
"body": "<p>You can do this in Ruby with very little code. Here's one way:</p>\n\n<pre><code>DICT_FNAME = \"#{path}\" + \"dictionary.txt\"\nNEW_DICT_FNAME = \"#{path}\" + \"new_dictionary.txt\"\nPREP_FNAME = \"#{path}\" + \"prepositions.txt\"\n\nall_words = File.read(DICT_FNAME).split($/).map(&:strip)\nprepositions = File.read(PREP_FNAME).split($/).map(&:strip)\nFile.write(NEW_DICT_FNAME, (all_words - prepositions).join($/))\n\nputs \"#{all_words.size} words in the dictionary\"\nputs \"#{prepositions.size} prepositions to be removed\"\n</code></pre>\n\n<p>Let's try it out. First, write some words to the dictionary file and to the file containing the prepositions:</p>\n\n<pre><code>all = <<_\nNow\nis\nthe\ntime\nfor\nall\nRubyists\nto\ndebug\n_\n\npreps = <<_\nfor\nto\n_\n\nall #=> \"Now\\nis\\nthe\\ntime\\nfor\\nall\\nRubyists\\nto\\ndebug\\n\"\npreps #=> \"for\\nto\\n\"\n\npath = ''\n\nDICT_FNAME = \"#{path}\" + \"dictionary.txt\" #=> \"dictionary.txt\"\nPREP_FNAME = \"#{path}\" + \"prepositions.txt\" #=> \"prepositions.txt\"\n\nFile.write(DICT_FNAME, all) #=> 42\nFile.write(PREP_FNAME, preps) #=> 7\n</code></pre>\n\n<p>Now we read the two input files [<code>$/</code> is the end-of-line character(s)]:</p>\n\n<pre><code>NEW_DICT_FNAME = \"#{path}\" + \"new_dictionary.txt\"\n\nall_words = File.read(DICT_FNAME).split($/).map(&:strip)\n #=> [\"Now\", \"is\", \"the\", \"time\", \"for\", \"all\", \"Rubyists\", \"to\", \"debug\"] \nprepositions = File.read(PREP_FNAME).split($/).map(&:strip)\n #=> [\"for\", \"to\"]\n\nputs \"#{all_words.size} words in the dictionary\"\n #=> 9 words in the dictionary\nputs \"#{prepositions.size} prepositions to be removed\"\n #=> 2 prepositions to be removed\n</code></pre>\n\n<p>...then remove the elements of the <code>prepositions</code> array from the <code>all_words</code> array:</p>\n\n<pre><code>diff = all_words - prepositions\n #=> [\"Now\", \"is\", \"the\", \"time\", \"all\", \"Rubyists\", \"debug\"]\n</code></pre>\n\n<p>...format it for writing:</p>\n\n<pre><code>joined = diff.join($/)\n #=> \"Now\\nis\\nthe\\ntime\\nall\\nRubyists\\ndebug\"\n</code></pre>\n\n<p>...write the output file:</p>\n\n<pre><code>File.write(NEW_DICT_FNAME, joined)\n</code></pre>\n\n<p>...and confirm it it was written correctly:</p>\n\n<pre><code>File.read(NEW_DICT_FNAME).split($/).map(&:strip)\n #=> [\"Now\", \"is\", \"the\", \"time\", \"all\", \"Rubyists\", \"debug\"] \n</code></pre>\n\n<p>Edit: In view of @Tokland's suggestion of constructing a set of prepositions when processing the words one at a time, I thought it might be interesting to run some benchmarks. You'll see that I just used random arrays and words, rather than read and write to files. </p>\n\n<pre><code>L = Array('a'..'z')\n\nrequire 'set'\n\ndef make_samples(n,m,k,s)\n s.times.with_object([]) do |_,a|\n # Construct a sample of n unique words, each of length k\n all_words = make_sample(n,k)\n # Assume the first m words are prepositions\n preps = all_words[0,m]\n # Shuffle the words (no need to further randomize the prepositions) \n a << [all_words.shuffle, preps]\n end\nend \n\ndef make_sample(n,k)\n set_words = Set.new\n while set_words.size < n do\n set_words << k.times.with_object('') { |_,w| w << L.sample }\n end\n set_words.to_a\nend\n</code></pre>\n\n<p>Here is an example of test data with 8 4-character words, of which 3 are prepositions, and a sample size of 2.</p>\n\n<pre><code>make_samples(8,3,4,2)\n #=> [[[\"fexz\", \"gxrv\", \"acte\", \"namz\", \"cpqw\", \"txsm\", \"zonm\", \"tvjz\"],\n # [\"zonm\", \"gxrv\", \"fexz\"]],\n # [[\"nfdf\", \"djnv\", \"inqk\", \"tbgc\", \"asfb\", \"nqbg\", \"dnyb\", \"ywtv\"],\n # [\"djnv\", \"tbgc\", \"inqk\"]]]\n</code></pre>\n\n<p>These are the parameters I used for the results I report below:</p>\n\n<pre><code>n = 200_000 # number of words, inckluding prepositions\nm = 40 # number of prepositions\nk = 8 # length of each string\ns = 20 # sample size\n\nsamples = make_samples(n,m,k,s)\n\nBenchmark.bm('reject - arr'.size) do |bm|\n # words array - preps array \n bm.report 'arr - arr' do\n samples.each { |(wa,pa)| wa - pa }\n end\n\n # reject words in preps array\n bm.report 'reject - arr' do\n samples.each { |(wa,pa)| wa.reject { |w| pa.include? w } }\n end\n\n # reject words in preps set\n bm.report 'reject - set' do\n samples.each { |(wa,pa)| ps = pa.to_set; wa.reject { |w| ps.include? w } }\n end\nend\n\n user system total real\narr - arr 0.860000 0.030000 0.890000 ( 0.884945)\nreject - arr 10.180000 0.020000 10.200000 ( 10.217233)\nreject - set 1.830000 0.040000 1.870000 ( 1.913069)\n</code></pre>\n\n<p>I ran a few additional tests with different parameters, but these results are indicative.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:36:46.007",
"Id": "74658",
"Score": "0",
"body": "This would be my first choice if both files fit into memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:32:36.117",
"Id": "42563",
"ParentId": "42539",
"Score": "2"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>I guess you come from imperative languages. Try to write in a more functional style (more expressions, less statements). </p></li>\n<li><p>Use libraries (<code>File</code>) to manipulate paths.</p></li>\n<li><p>This double <code>each_line</code> is bad news for performance: O(n*m). Avoid it by building a data structure that has O(1) checks for inclusion. I'd create a <code>set</code> of the prepositions (it's the smaller set). The overall performance is now O(n).</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>prepositions = open(File.join(path, \"prepositions.txt\")).lines.to_a \nwords = open(File.join(path, \"dictionary.txt\")).lines.to_a\nfiltered_words = words - prepositions\nFile.write(\"dictionary_without_prepositions.txt\", filtered_words.join)\n</code></pre>\n\n<p>If the input file <code>dictionary.txt</code> is very, very large, this is a more lazy aproach:</p>\n\n<pre><code>require 'set'\nprepositions = open(File.join(path, \"prepositions.txt\")).lines.to_set\n\nopen(\"dictionary_without_prepositions.txt\", \"w\") do |output| \n open(File.join(path, \"dictionary.txt\")).lines.each do |line|\n unless prepositions.include?(line)\n output.write(line)\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:05:51.263",
"Id": "73449",
"Score": "1",
"body": "+1 for the use of `to_set` for the prepositions - you should expand on why you chose it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:42:37.210",
"Id": "73452",
"Score": "0",
"body": "@UriAgassi. Done!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T04:45:06.013",
"Id": "73481",
"Score": "0",
"body": "Great @tokland. Performance is actually O(n+m), though - you need to build the set..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T09:27:34.680",
"Id": "73493",
"Score": "0",
"body": "@UriAgassi: it's my understanding that O(n+m), m<=n -> O(n) (at worst what would be \"O(2n)\", but constants are ignored, so O(n))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:01:20.633",
"Id": "73494",
"Score": "0",
"body": "if you know that m<=n, you are right. More generally, though `O(n+m)==O(max(n,m))`. If you have a big preposition file, and a small dictionary, the preposition file will be the dominant factor in your complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:12:42.190",
"Id": "73495",
"Score": "0",
"body": "From what OP said, I think it's safe to assume `n >> m`: \"File 1. Has a list of all the dictionary words. File 2. Has a list of all prepositions\"."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T19:44:28.560",
"Id": "42619",
"ParentId": "42539",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42619",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:50:35.883",
"Id": "42539",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Removing list of words from a text file in Ruby"
} | 42539 |
<p>I need to implement something like "attached properties" from WPF that targets WinForms.</p>
<p>What I came up with seems to work. Can you find any issues with it? The helper class and example are shown below.</p>
<ul>
<li>Not thread-safe since all access should be performed from the UI thread.</li>
<li>Attach a value (SetAttachedValue) or getter/+setter (AttachProperty).</li>
<li>All properties are un-attached when the target component is disposed.</li>
<li>The primary use-case is that an <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.iextenderprovider%28v=vs.100%29.aspx" rel="nofollow">IExtenderProvider</a> will attach properties to various controls/components of a form and then other code will be able to access those attached properties without having to have a reference to the original IExtenderProvider.</li>
</ul>
<p>Note:</p>
<ul>
<li><p>This is <em>experimental</em> code that I'm doing to port Prism to WinForms. There are very few changes needed to do the port, but unfortunately to really complete the job I just need something like attached properties.</p></li>
<li><p>The code lives at <a href="https://github.com/misct/prism-winforms/tree/prism4/src/PrismWinForms/Desktop/Prism" rel="nofollow">github.com/misct/prism-winforms</a> where I have already posted a <em>slightly</em> improved implementation and where I will soon post a much better implementation.</p></li>
</ul>
<p><strong>ExtenderHelper.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace TryAttachedProps
{
public static class ExtenderHelper
{
#region Property Data Classes
class AttachedProperty
{
public Func<Component, object> Getter;
public Action<Component, object> Setter;
public object Value;
}
class AttachedPropertyMap : Dictionary<string, AttachedProperty> { }
#endregion
static Dictionary<Component, AttachedPropertyMap> _attachedProperties =
new Dictionary<Component, AttachedPropertyMap>();
public static void AttachProperty(this Component component, string name, Func<Component, object> getter)
{
AttachProperty(component, name, getter, ReadOnlySetter);
}
public static void AttachProperty(this Component component, string name, Func<Component, object> getter, Action<Component, object> setter)
{
AttachedPropertyMap props;
if (!_attachedProperties.TryGetValue(component, out props))
{
props = new AttachedPropertyMap();
props.Add(name, new AttachedProperty { Getter = getter, Setter = setter });
AttachPropertyMap(component, props);
return;
}
AttachedProperty prop;
if (!props.TryGetValue(name, out prop))
{
props.Add(name, new AttachedProperty { Getter = getter, Setter = setter });
return;
}
prop.Getter = getter;
prop.Setter = setter;
prop.Value = null;
}
static void AttachPropertyMap(Component component, AttachedPropertyMap props)
{
if (component == null)
throw new ArgumentNullException("component");
_attachedProperties.Add(component, props);
component.Disposed += component_Disposed;
}
static void component_Disposed(object sender, EventArgs e)
{
var component = sender as Component;
component.Disposed -= component_Disposed;
if (component != null)
_attachedProperties.Remove(component);
// CONSIDER: Should we dispose any IDisposable properties attached to the component or do other cleanup? (I think no. See updated Questions section edit in post.)
}
public static object GetAttachedValue(this Component component, string name)
{
AttachedPropertyMap props;
if (_attachedProperties.TryGetValue(component, out props))
{
AttachedProperty prop;
if (props.TryGetValue(name, out prop))
{
var getter = prop.Getter;
if (getter != null)
return getter(component);
return prop.Value;
}
}
return null;
}
static void ReadOnlySetter(Component component, object value)
{
throw new InvalidOperationException("The property is read-only.");
}
public static void SetAttachedValue(this Component component, string name, object value)
{
AttachedPropertyMap props;
if (!_attachedProperties.TryGetValue(component, out props))
{
props = new AttachedPropertyMap();
props.Add(name, new AttachedProperty { Value = value });
AttachPropertyMap(component, props);
return;
}
AttachedProperty prop;
if (!props.TryGetValue(name, out prop))
{
props.Add(name, new AttachedProperty { Value = value });
return;
}
var setter = prop.Setter;
if (setter != null)
setter(component, value);
else
prop.Value = value;
}
}
}
</code></pre>
<p><strong>Form1.cs</strong></p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Uncomment one of the next three lines to try different tactics.
this.SetAttachedValue("Test", "Hello");
//this.AttachProperty("Test", c => _test);
//this.AttachProperty("Test", c => _test, SetTestValue);
}
string _test = "Hello";
void SetTestValue(Component component, object value)
{
_test = value as string;
}
private void button1_Click(object sender, EventArgs e)
{
var value = this.GetAttachedValue("Test") as string;
this.SetAttachedValue("Test", value + " again!");
button1.Text = value;
button1.AutoSize = true;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:36:37.973",
"Id": "73280",
"Score": "0",
"body": "Whats the point if you don't have the databinding and change notification?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:37:58.550",
"Id": "73281",
"Score": "0",
"body": "I believe you can do data binding with IExtenderProvider provided properties and I think I could add change notification to this. Even if I can't do the data binding, it's alright with me because I want to attach something like Microsoft Prism's RegionManager (but my own implementation) to controls/forms/etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:39:28.197",
"Id": "73282",
"Score": "0",
"body": "I guess my other question would be - what else would you do if you wanted to associate one or more values or getter/setters with a control/form/etc...but be able to access them from any code that has a reference to the control?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:44:53.410",
"Id": "73283",
"Score": "0",
"body": "How is this any different than having a `public List<Object> AttachedValues` on the form?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:45:57.037",
"Id": "73284",
"Score": "0",
"body": "This is different from having a list attached to the form because I can attach values to classes that I have not created myself. The example shown is a very simplified. It does not show the true use-case. Do you think I should I expand it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:29:58.053",
"Id": "73306",
"Score": "1",
"body": "You can attach values to classes you didn't create by extending/inheriting from them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:40:58.790",
"Id": "73310",
"Score": "0",
"body": "That is not what I want to do though because it's impractical for me to customize every control that I want to extend. Have you ever worked with attached properties in WPF? That's basically what I want to do here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:45:00.370",
"Id": "73312",
"Score": "0",
"body": "I guess since this has now been moved to codereviews, I'd like to just get this code reviewed instead of debating the usefullness or the idea itself. I think the basic pattern has already been vetted with WPF. This is admittedly a much, much simpler implementation - but that's what I want to start out. I can add features later."
}
] | [
{
"body": "<h2>WinForms is not WPF.</h2>\n<p>Sad, boring truth. The correct way of extending WinForms controls is, as was mentioned, through inheritance.</p>\n<p>What you've got here is a set of <em>extension methods</em> in a dual-purpose <code>static</code> class that's asking for trouble in the sense that it's also a state-holding bag of <code>static</code> objects that have "attached properties" - I think this code is abusing extension methods and static classes, be it only because the static class itself has two non-static "child" classes.</p>\n<p>That said...</p>\n<pre><code> class AttachedProperty\n {\n public Func<Component, object> Getter;\n public Action<Component, object> Setter;\n public object Value;\n }\n</code></pre>\n<p>You're exposing <code>object</code>, which incurs boxing of value types. And then you're storing state in a <em>dictionary of dictionaries</em> - which is a code smell IMO (begging for a type/class here).</p>\n<p>I think the static class with the extension methods should be called <code>ComponentExtensions</code>, but its dual purpose defeats that. I think the class is breaking SRP.</p>\n<p>I can't think of other ways to do this though... because <em>I don't think I get the point</em>. If you want to do WPF, drop WinForms and do WPF, don't try to turn a Corolla into an Audi!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:13:12.080",
"Id": "73993",
"Score": "0",
"body": "Have you looked at the WPF implementation of DependencyObject/Property? I've been using it as a reference for a newer/better implementation of this and it's really not much different than what I'm doing here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:15:46.277",
"Id": "73995",
"Score": "0",
"body": "Furthermore and with all due respect - I do know exactly what I'm getting into here. I am in the middle of porting Microsoft Prism from WPF to WinForms and I've got 80% of it done. Regions is the other 20% and I just need a replacement for Attached/DependencyProperty. Check it out - https://github.com/misct/prism-winforms I will soon be commiting a much better implementation of the code shown here. (I have named it \"AssignedProperty\" and it's syntactically equivalent to what happens in WPF.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:18:13.580",
"Id": "73996",
"Score": "1",
"body": "The thing is, WPF is so much more than DependencyProperties. Perhaps you can succeed in reinventing that wheel, but IMO it's like mounting a silver-plated wheel on an old rusted car - it can work, but one can tell that something just isn't right. A nice car is much more than shiny wheels."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:18:37.133",
"Id": "73997",
"Score": "1",
"body": "Lastly, I know WPF and Silverlight very well but it's certainly not the best choice for many apps, particularly quick little IT operations apps that I need. However, I like to use Prism and MVVM so I'm doing this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:19:54.217",
"Id": "73998",
"Score": "1",
"body": "Well I'm sorry, but you don't know what you're talking about. You haven't seen what I can do with MVVM and WinForms. I can build apps very, very quickly this way, much quicker than WPF and honestly - they work better. No wierd focus lines and font problems. So please, stop patronizing me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:20:40.250",
"Id": "73999",
"Score": "0",
"body": "And no, I'm not trying to implement WPF in WinForms - I'm simply porting Prism and I need something that works like DependencyProperty. That is all I need - not the rest of WPF."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:26:04.897",
"Id": "74000",
"Score": "0",
"body": "I'm sorry to read this, I don't mean to patronize you, and no, I haven't seen what you do with WinForms & MVVM - most people that know patterns will expect WinForms to go by MVP, not MVVM. Congrats if you succeeded doing so. Cheers!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:28:17.673",
"Id": "74001",
"Score": "1",
"body": "Well I'm sorry, it's just that I already argued this with someone in the comments above and I thought I made it clear that I don't care to discuss that aspect of the work. I'm not the first person to use MVVM with WinForms and I'm not even the first person to port Prism to WinForms. With the work I'm doing, code will be very easily portable between WinForms and WPF if I choose to port it later. Thanks for your input about the data structures. I will clean that up and come back here when I finished the port some more. Thanks."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T17:59:17.943",
"Id": "42788",
"ParentId": "42540",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:29:58.110",
"Id": "42540",
"Score": "3",
"Tags": [
"c#",
"winforms"
],
"Title": "Naive implementation of attached properties for WinForms"
} | 42540 |
<p>I am trying to implement an AngularJS directive that would count the number of characters entered into a textarea and display it to the user. </p>
<p><strong><em>Note</strong>: it will actually become much more complex later on and will become a full-fledged component that will be similar to the js component used by Stack Overflow for user comments: users will be notified how many more characters they may or must enter with different font colors.</em></p>
<p>Here is how the markup would look for the initial version:</p>
<pre><code><div ng-app>
<div ng-controller="myController">
<cmp>
<enhanced-textarea ng-model="name"></enhanced-textarea>
<h3>{{name}}</h3>
<notice></notice>
<cmp>
</div>
</div>
</code></pre>
<p>My js code is as follows:</p>
<pre><code>var myModule = angular.module('myModule', []);
myModule.directive('cmp', function(){
return {
restrict: 'E',
controller: 'cmpCtrl',
replace: true,
transclude: true,
scope: {
name: '='
},
template: '<div ng-transclude></div>'
};
})
.controller('cmpCtrl', function ($scope, $element, $attrs) {
$scope.$parent.$watch('name', function(newVal){
if(newVal){
$scope.$parent.updatedSize = newVal.length;
console.log(newVal.length);
}
}, true);
})
.directive('enhancedTextarea', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<textarea ng-transclude></textarea>'
};
})
.directive('notice', function () {
return {
restrict: 'E',
require: '^cmp',
replace: true,
scope: {
updatedSize: '='
},
template: '<div>{{size}}</div>',
link: function($scope, $element, $attrs, cmpCtrl){
console.log(cmpCtrl);
$scope.$parent.$watch('updatedSize', function(newVal){
if(newVal){
$scope.size = newVal;
}
}, true);
}
};
});
function myController($scope) {
$scope.name = 'test';
};
</code></pre>
<p>I find it overly complex and I am sure it can be simplified.</p>
<p>Can anyone please advise and help perhaps by providing alternatives together with explanations?</p>
<p><a href="http://jsfiddle.net/balteo/K4t7P/110/" rel="nofollow">Here is the fiddle</a></p>
| [] | [
{
"body": "<p>Massive overkill indeed,</p>\n\n<pre><code><span>{{name.length}}</span>\n</code></pre>\n\n<p>will do the trick.</p>\n\n<p>On the whole, I am not sure why you would use Angular to write an editor if you are not an expert in Angular. It adds a layer of complexity and eats into performance. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T20:40:37.537",
"Id": "73581",
"Score": "0",
"body": "Thanks. Please take into account my note in italics. The directive will become much more complex with business logic in it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T20:43:12.180",
"Id": "73582",
"Score": "0",
"body": "@balteo We can only review what you submit, I would invite you to come back once the functionality is more complex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T20:51:23.923",
"Id": "73583",
"Score": "0",
"body": "Of course. No worries. I will do so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:05:43.323",
"Id": "73635",
"Score": "1",
"body": "\"I am not sure why you would use Angular to write an editor if you are not an expert in Angular.\" I agree the solution is overkill, but the quoted sentiment is against the spirit of this site. He's posting it here because he's trying to learn angular and get better at it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:19:20.640",
"Id": "73668",
"Score": "0",
"body": "@Jonah He is trying to write a complex editor, that's hard enough without throwing Angular in the mix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:51:39.867",
"Id": "73717",
"Score": "0",
"body": "Maybe, maybe not. If his only goal is to write an editor widget, I agree with you. But the post begins \"I am trying to implement an AngularJs directive...\" which to me implies someone whose goal is to do this, specifically, with angular. And possibly who has a larger goal of improving his angular skills -- this is code review, after all, not SO."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:06:52.860",
"Id": "42665",
"ParentId": "42543",
"Score": "1"
}
},
{
"body": "<p>You are using isolated scope, whose purpose is to encapsulate it from outside world, so best <code>$scope.$parent</code> is to be avoided, <a href=\"https://stackoverflow.com/a/17900556/1614973\">see here</a>. </p>\n\n<p>In your case, you two-way-bind with parent scope, so this should work just fine without breaking your encapsulation:</p>\n\n<pre><code>$scope.$watch('updatedSize', function(){});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T08:02:23.623",
"Id": "47634",
"ParentId": "42543",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:17:33.793",
"Id": "42543",
"Score": "4",
"Tags": [
"javascript",
"html",
"angular.js"
],
"Title": "Simplifying an AngularJs directive that counts the number of characters entered in a textarea"
} | 42543 |
<p>I have the following scenario:</p>
<p>The (web-) application is built with Java/Spring. I have several REST-endpoints which deliver data prepared to be consumed by a frontend by <code>datatables.net</code>. Each of this endpoint has a somehow similar signature (sEcho, iDisplayStart, iDisplayLength etc.) which are standardparameters necessary to work with datatables. Some of the controllers need additional Information, which are provided in extra variables.</p>
<p>So I made a <code>DatatablesOptions</code> class for the general usecase and if I need additional fields I extend the <code>DatatablesOptions</code> class. </p>
<p>My question is now about the <em>naming</em> of the extended classes.</p>
<p>There are two approaches:</p>
<ol>
<li><p>I have a package for each of the endpoints, where all additional classes for a topic are stored: e.g. "CustomerComplaints". In such a package you would find the derived class which is used for the additional fields exactly for the usecase of "customer complaints". Hence it is in the "CustomerComplaints"-package the name of e.g. "ViewOptions" would be enough to say what it is used for: »This object is used for the options of a view in the context of "CustomerComplaints"«.</p>
<p>So my code in the Controller looks like this:</p>
<pre><code>@Controller
@RequestMapping("/")
public class CustomerComplaints {
[...]
@RequestMapping(value="/customercomplaints/datatable", method= RequestMethod.GET)
@ResponseBody
public AjaxTableModel getCustomerComplaintsForDataTable(@RequestParam (value="sEcho")int echo,
@RequestParam (value="iDisplayStart")int startLine,
@RequestParam (value="iDisplayLength")int linesPerPage,
@RequestParam (value="iSortCol_0")int columnToSort,
@RequestParam (value="sSearch", required = false) String searchString,
@RequestParam (value="statusfilter")FilterOptions filterOptions,
@RequestParam (value="sSortDir_0")String sortingDirection
[...]
ViewOptions o = new ViewOptions()
.setLinesPerPage(linesPerPage)
.setStartLine(startLine)
.setSortColumn(getSortingKeyForColumnNumber(columnToSort))
.setSortingDirection(sortingDirection)
.setFilterOptions(filterOptions)
.setSearchString(searchString);
</code></pre>
<p>The job of the <code>ViewOptions</code>-class is in every controller the same and for the understanding of the code neglectable.</p>
<p>So a further specification via the classes name is not necessary. It seems to me like some kind of "Hungarian Notation". The name <code>CustomerComplaintsViewOptions</code> provides not more Information in this context. And the package makes it unambigous enough. Every smart IDE should resolve the definition for that.</p></li>
<li><p>The second approach, which is more texteditor-friendly, is to make it easy to find the definition of this class and name it <code>CustomerComplaintsViewOptions</code>. So a coworker sees from the variable name, where to look, when he wants to know more.</p></li>
</ol>
<p>What kind of naming is better style?</p>
| [] | [
{
"body": "<ol>\n<li><p>Actually #1 is called smurf naming (<a href=\"https://softwareengineering.stackexchange.com/q/191929/36726\">here is a question about it on Programmers.SE</a>). </p>\n\n<p>One thing to consider: Do you have to work with more than one <code>ViewOptions</code> at the same time (or at the same source file)? If that's true having a more specific name would help. Two possible advantages of smurfier names:</p>\n\n<ul>\n<li>There aren't multiple editor tabs with the same filename.</li>\n<li>You don't have to use full package names to declare two <code>ViewOptions</code> in the same source file.</li>\n</ul></li>\n<li><blockquote>\n <p>So I made a DatatablesOptions class for the general usecase and if \n I need additional fields I extend the DatatablesOptions class. </p>\n</blockquote>\n\n<p>Check <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em> if you don't know already.</p></li>\n<li><p>Try to format the code in a way which avoid unnecessary horizontal scrolling. It would make it esasier to read.</p></li>\n<li><pre><code>@RequestParam (value=\"iDisplayStart\")int startLine,\n@RequestParam (value=\"iDisplayLength\")int linesPerPage,\n@RequestParam (value=\"iSortCol_0\")int columnToSort,\n@RequestParam (value=\"sSearch\", required = false) String searchString,\n</code></pre>\n\n<p>Some of the parameters have a space between the closing parentheses (<code>...false) String</code>) , some of them doesn't (<code>...th\")int linesPerPage</code>). You can find another inconsistencies too. It should be consistent. Modern IDEs have autoformat, they do a really good job here, use them.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T10:06:35.140",
"Id": "73382",
"Score": "0",
"body": "Sorry for the bad formatting - I made this quickly up and fiddeled in a texteditor not my IDE. I have to deal only with one kind of optionset at a time - therefore I came up with (1). Dealing with FQNs would in my eyes be worse than smurfnames. But you are right in another direction: Perhaps I should refactor the whole Options classes and make only one class, which has a `Map` as the underlying structure (each option's name is unique)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T10:33:16.233",
"Id": "73385",
"Score": "1",
"body": "@ThomasJunk: The current `ViewOpions` with type-safe options looks better to me than a non-type-safe `Map`, so I wouldn't bother it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T10:40:45.120",
"Id": "73386",
"Score": "0",
"body": "Mhm. Okay. But how could I benefit from refactoring the options to a composition? Simple case: I have an extra demand for adding dates, so my extended Options would inherit the common fields and add `from Date` and `toDate`. What would a refactored/composited version look like? Injecting the `DatatablesOptions` in the constructor and adding getters and setters which point to the injected object? what would be the advantage? With inheritance I have to type less ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T11:06:00.997",
"Id": "73387",
"Score": "0",
"body": "@ThomasJunk: I don't say that you should use composition (I don't know too much about the context). I'm just saying that consider it. Inheritance trees could become nightmare to maintain. I've better experience with composition but it depends on the context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T11:09:44.310",
"Id": "73388",
"Score": "0",
"body": "@ThomasJunk: Typing doesn't count, the time which is required to understand and maintain code counts. (Otherwise we wouldn't use whitespace, just one big main method with one-letter variable names :) Wikipedia seems quite good about the advantages: https://en.wikipedia.org/wiki/Composition_over_inheritance#Benefits"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:25:07.073",
"Id": "73409",
"Score": "1",
"body": "Okay, agreed. In general I prefer composition - only in this case it isn't appropriate. I have one parent and exactly one child which adds some getters and setters. And the whole object is only to encapsulate these options to keep the signature of called functions small. And you are right: the time to understand the code matters. And as a lazy (but caring) programmer for me less writing and less reading is easier. Time's too short to spend it on typing ;)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T05:20:06.647",
"Id": "42575",
"ParentId": "42546",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:26:19.163",
"Id": "42546",
"Score": "2",
"Tags": [
"java",
"spring"
],
"Title": "Class naming conventions"
} | 42546 |
<p>I have written a script that allows a user to walk around a dungeon pick up gold and once they have picked it all up they can exit the game through an exit.</p>
<p>What I am doing now is writing a bot to do the same. So far I have come up with a 'stupid' bot that is based mainly on randomness. The bot has has actions to the following functions;</p>
<p><code>look()</code> - Can see around the ASCII map in a radius of 2. The function prints it out so the bot cant actually store it in memory(I am allowed to store it memory).</p>
<p><code>move <direction>()</code> - move in the direction these include N E S W.</p>
<p><code>pickUp()</code> - If the bot is standing on gold this picks it up.</p>
<p><code>exitGame()</code> - If the bot is standing on an exit, has all the gold and this command is ran he will exit the game.</p>
<p>Here is my bot code so far.</p>
<pre><code>import java.io.IOException;
import java.util.Random;
public class Bot{
public GameLogic bot;
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
GameLogic bot = new GameLogic("map2.txt");
bot.startGame();
int gold = bot.gold();
System.out.println(gold);
int turn = 0;
char[][] myWorld = bot.getMap();
while(true){
int posX = bot.getPosX();
int posY = bot.getPosY();
Random rn = new Random();
int min = 0;
int max = 3;
int n = max - min + 1;
int i = rn.nextInt(n);
if(myWorld[posX][posY] == 'G'){
bot.pickUp();
}
if(myWorld[posX][posY] == 'E'){
boolean y = bot.exitGame();
if(y){break;}
}
turn++;
if(i == 0){
bot.moveN();
}else if(i == 1){
bot.moveE();
}else if(i == 2){
bot.moveS();
}else if(i == 3){
bot.moveW();
}else{
System.out.println("SOMETHING WENT WRONG!!!");
}
}
System.out.println(turn);
}
}
</code></pre>
<p>What I am asking is what would be a better way to do this. How can I improve my bot so it takes less turns to complete? How can I make my bot 'smarter'?</p>
| [] | [
{
"body": "<h3>Overall</h3>\n<p>I think you have too much code in the main method. You should split that into more digestible segments. Perhaps some more methods in your <code>GameLogic</code> class (which probably should be split into one <code>Game</code> class and one <code>GameBot</code> / <code>Player</code> class). (At least) one method for determining the next move, one method for choosing the proper action based on the current tile, etc..</p>\n<h3>Improving your bot</h3>\n<p>Assuming the gold never moves once it is placed, you could use a <code>Set</code> of all the tiles you have visited. You could then try to not move to a tile you have already visited.</p>\n<p>The tiles themselves could be represented as a <code>Point</code> class that contains <code>x</code> and <code>y</code>, or it could be represented as an int if you do a little mathematics to represent a column and row by one single int (I do recommend the <code>Point</code> class though). Or you could make a <code>Tile</code> class, since each tile also has some content (wall, exit, gold, empty space...)</p>\n<h3>Random</h3>\n<pre><code>Random rn = new Random();\nint min = 0;\nint max = 3;\nint n = max - min + 1;\nint i = rn.nextInt(n);\n</code></pre>\n<ul>\n<li>Since <code>min</code> is zero, there's no need to do <code>- min</code>.</li>\n<li>As max is a constant, it'd be easier to declare max as 4 from the start rather than using <code>+ 1</code></li>\n<li>As <code>n</code> only is used once, you could just use <code>int i = rn.nextInt(4);</code></li>\n<li><strong>Random objects are meant to be re-used.</strong> Initialize your Random object outside the loop. This is because randomization will be different when creating the object over and over again.</li>\n</ul>\n<h3>Moving</h3>\n<p>You can move in four directions, this is telling me that you should use a <a href=\"https://codereview.stackexchange.com/questions/34054/random-walk-on-a-2d-grid/34056#34056\">Direction enum</a> and replace your four methods with one <code>move(Direction4 dir);</code> By using this enum, you could also simplify your random process:</p>\n<pre><code>Direction4 chosenDirection = Direction4.values()[rn.nextInt(Direction4.values().length)];\n</code></pre>\n<p>This line grabs all the possible directions and randomizes an int from 0 (inclusive) to length (exclusive) and grabs the direction with that index.</p>\n<h3>When something goes wrong</h3>\n<pre><code>System.out.println("SOMETHING WENT WRONG!!!");\n</code></pre>\n<p>I can assure you, this will never happen. And even if it would, Exceptions are meant to be for... well, exceptions. <code>throw new AssertionError("Something went wrong.");</code> is what I would have done here. Or rather... I would have removed the entire line, as it will never happen. Especially when you use the Direction4 approach.</p>\n<h3>Spacing</h3>\n<p>This is one of the things I mention most often in my reviews probably, but please:</p>\n<pre><code>}else if(i == 1){\n</code></pre>\n<p>change to</p>\n<pre><code>} else if (i == 1) {\n</code></pre>\n<p>It makes the code more readable with proper spacing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T22:08:11.633",
"Id": "42551",
"ParentId": "42548",
"Score": "9"
}
},
{
"body": "<p>+1 to <em>@Simon</em> and some other notes:</p>\n\n<ol>\n<li><p>The current design does not enforce that bots are playing fair game. A cheating bot could iterate over the whole map <code>myWorld</code>, find the exit point and goes there straight. The same is true for gold. You should create the mentioned <code>look</code> method which returns only the partial map in 2 blocks away and hide the whole map from the bot.</p></li>\n<li><p>I'd try to create a design where a bot just returns its next action (<code>nextAction()</code>) and the game evaluate actions in a loop and call <code>nextAction</code> again until the bot reaches the exit point. It would help when a dumb bot never finds the exit point. The evaluation logic could kill the bot, no need to duplicate this logic in every bot. The current code contains a similar thing: counting turns. It could be the game's responsibility to count how many turns have been used to find the exit (and how much gold have been picked up).</p>\n\n<p>It would also remove logic from bots, like this:</p>\n\n<pre><code>final boolean y = game.exitGame();\nif (y) {\n break;\n}\n</code></pre>\n\n<p>It shouldn't be the bot's responsibility to decide if it really reached the exit point or not.</p></li>\n<li><p>The <code>main</code> method contain too much logic, try to separate it. If you want to test two or more different bots what would be duplicated? If you eliminate that duplication you will have a better design.</p></li>\n<li><pre><code>public GameLogic bot;\n</code></pre>\n\n<p>This field is not used. Remove it if it is not necessary. (Public fields usually leads to harder maintenance. See: <a href=\"https://stackoverflow.com/q/7959129/843804\">What's the deal with Java's public fields?</a>)</p></li>\n<li><p>The variable for <code>GameLogic</code> is called <code>bot</code>. It's a little bit misleading.</p></li>\n<li><p>I would use more descriptive variable names and wouldn't abbreviate. Longer names would make the code more readable since readers/maintainers don't have to decode or memorize the abbreviations.</p>\n\n<ul>\n<li><code>moveW</code> - <code>moveWest</code></li>\n<li><code>moveN</code> - <code>moveNorth</code></li>\n<li><code>moveE</code> - <code>moveEast</code></li>\n<li><code>moveS</code> - <code>moveSouth</code></li>\n<li><code>rn</code> - <code>random</code></li>\n<li><code>i</code> - <code>nextDirection</code></li>\n<li><code>min</code> - <code>minDirection</code></li>\n<li><code>max</code> - <code>maxDirection</code></li>\n<li><code>y</code> - <code>exitPointReached</code></li>\n</ul>\n\n<p>(I agree with <em>@Simon</em> that an enum is better here.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T04:58:38.887",
"Id": "42574",
"ParentId": "42548",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T21:54:57.977",
"Id": "42548",
"Score": "11",
"Tags": [
"java",
"game",
"ai",
"cli"
],
"Title": "AI bot Java dungeon game"
} | 42548 |
<p>I got a random image rotator working by using the following script (<a href="http://painfulmouth.com/index4.php" rel="nofollow">demo</a>). But I was told that it is a bad practice to extend <code>Array.prototype</code>. And it does. It conflicts with the chained select box unless I modify the selected box script. So I guess it's better to not use <code>Array.prototype.shuffle</code> ,isn't it? </p>
<p>Here's The script:</p>
<pre><code> Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1));
while (s.length) this.push(s.pop());
return this;
}
var picData = [
['img1','url_1'],
['img2','url_2'],
['img3','url_3'],
picO = new Array();
randIndex = new Array();
for(i=0; i < picData.length; i++){
picO[i] = new Image();
picO[i].src = picData[i][0];
picO[i].alt = picData[i][1];
randIndex.push(i);
}
randIndex.shuffle();
window.onload=function(){
var mainImgs = document.getElementById('carouselh').getElementsByTagName('img');
for(i=0; i < mainImgs.length; i++){
mainImgs[i].src = picO[randIndex[i]].src;
mainImgs[i].parentNode.href = picData[randIndex[i]][1];
mainImgs[i].alt = picData[randIndex[i]][1];
}
}
</code></pre>
<p>I'm not sure where to start. I'm reading this <a href="http://ejohn.org/blog/javascript-array-remove/" rel="nofollow">article</a>, should I do something like</p>
<pre><code> Array.shuffle = function() {for(var
a=[];this.length;)a.push(array.splice(Math.random()*array.length,1));
for(;a.length;)this.push(a.pop());return this};
</code></pre>
<p>Would anyone please point me in some directions to rewrite that part?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T23:35:25.227",
"Id": "73332",
"Score": "1",
"body": "Don't forget to declare your variables, `i` is global. Also literal syntax is always preferred, so `[]` instead of `new Array()`."
}
] | [
{
"body": "<p>My advice is to use a known shuffle algorithm for this. </p>\n\n<p>This stackoverflow answer describes the Fisher-Yates shuffle and provides a function for you to use.</p>\n\n<p><a href=\"https://stackoverflow.com/a/2450976/423413\">https://stackoverflow.com/a/2450976/423413</a></p>\n\n<p>Bottom line use that function and replace your <code>Array.prototype.shuffle</code> function and call it something like <code>shuffleArray</code></p>\n\n<pre><code>var shuffleArray = function(arr) {\n ...\n}\n</code></pre>\n\n<p>Then replace the line that says <code>randIndex.shuffle()</code> with a call to the new function.</p>\n\n<pre><code>shuffleArray(randIndex);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T22:36:21.153",
"Id": "42553",
"ParentId": "42550",
"Score": "3"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>As <em>elclanrs</em> mentions, <code>randIndex = [];</code> is preferred over <code>randIndex = new Array();</code></li>\n<li>Also as <em>elclanrs</em> mentions, you have global variables: <code>i</code>, <code>picO</code>, and <code>randIndex</code>.</li>\n<li><p>If you like to <code>randIndex.shuffle();</code>, then you could add the <code>shuffle</code> to <code>randIndex</code> straight. This is only a good idea if you will only ever shuffle <code>randIndex</code> which seems to be the case. So then you can do this:<br></p>\n\n<pre><code>randIndex.shuffle = function shuffle(array) {\n var currentIndex = this.length,\n temporaryValue,\n randomIndex;\n\n // While there remain elements to shuffle...\n while (currentIndex) {\n // Pick a remaining element...\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex--;\n\n // And swap it with the current element.\n temporaryValue = this[currentIndex];\n this[currentIndex] = this[randomIndex];\n this[randomIndex] = temporaryValue;\n }\n}\n</code></pre></li>\n<li>This: <code>picO[i] = new Image();</code> does not seem to make sense, since you are not using the generated image anywhere. You might as well use <code>picO[i] = {}</code>;</li>\n<li>It does not make sense to randomize an array with indexes, you might as well randomize <code>picO</code> and not use <code>randIndex</code> at all</li>\n<li>In fact, it does not make sense to have an array of arrays which you then convert to an array of objects with the same data points, why not have the array of objects from the start ?</li>\n<li><p><code>mainImgs[i].alt = picData[randIndex[i]][1];</code> should at least be<br></p>\n\n<pre><code>`mainImgs[i].alt = picO[randIndex[i]].alt;`\n</code></pre></li>\n<li><p>All in all, your code could be written as:</p>\n\n<pre><code>var picData = [\n {src: 'img1', url: 'url_1'},\n {src: 'img2', url: 'url_2'},\n {src: 'img3', url: 'url_3'},\n];\n//Perfect shuffling routine, I must say yours is shorter and might suffice\npicData.shuffle = function shuffle() {\n var currentIndex = this.length,\n temporaryValue,\n randomIndex;\n // While there remain elements to shuffle...\n while (currentIndex) {\n // Pick a remaining element...\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex--;\n // And swap it with the current element.\n temporaryValue = this[currentIndex];\n this[currentIndex] = this[randomIndex];\n this[randomIndex] = temporaryValue;\n }\n};\n\npicData.shuffle();\n\nwindow.onload=function(){\n var mainImgs = document.getElementById('carouselh').getElementsByTagName('img');\n\n for(var i=0; i < mainImgs.length; i++){\n mainImgs[i].src = picData[i].src;\n mainImgs[i].parentNode.href = picData[i].url;\n mainImgs[i].alt = picData[i].url;\n }\n};\n</code></pre></li>\n</ul>\n\n<p>The only problem I still see is stuffin <code>window.onload</code> instead of using an <a href=\"https://stackoverflow.com/questions/6902033/element-onload-vs-element-addeventlistenerload-callbak-false\">EventListener</a>, I will leave that up to you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:39:57.843",
"Id": "42659",
"ParentId": "42550",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T22:05:23.553",
"Id": "42550",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"array"
],
"Title": "Trying to convert an extended Array.prototype to a function"
} | 42550 |
<p>I have written the following function to concatenate the parts of a name to produce the full name:</p>
<pre><code>/**
* Returns the full name of the Person.
* @param boolean $includeTitle Whether to include the Person's title.
* @param boolean $includeMiddleNames Whether to include the Person's middle names.
* @param string $separator Separator character.
* @return string Full name of the Person.
*/
public function getFullName($includeTitle = false, $includeMiddleNames = false, $separator = ' ') {
if ($includeTitle && $this->getTitle()) {
$name = $this->title;
} else {
$name = '';
}
if ($this->forename) {
if ($name) {
$name .= $separator;
}
$name .= $this->forename;
}
if ($includeMiddleNames && $this->middlenames) {
if ($name) {
$name .= $separator;
}
if ($separator != ' ') {
// multiple middle names will be separated by spaces and so will need to be converted to $separator
$name .= str_replace(' ', $separator, $this->middlenames);
} else {
$name .= $this->middlenames;
}
}
if ($this->surname) {
if ($name) {
$name .= $separator;
}
$name .= $this->surname;
}
return $name;
}
</code></pre>
<p>I changed it to use an array and implode the parts - which has made it less lines, but I'm not really sure if it is written better as a result:</p>
<pre><code>$nameParts = array();
if ($includeTitle && $this->getTitle()) {
$nameParts[] = $this->title;
}
if ($this->forename) {
$nameParts[] = $this->forename;
}
if ($includeMiddleNames && $this->middlenames) {
if ($separator != ' ') {
$middlenames = str_replace(' ', $separator, $this->middlenames);
} else {
$middlenames = $this->middlenames;
}
$nameParts[] = $middlenames;
}
if ($this->surname) {
$nameParts[] = $this->surname;
}
return implode($separator, $nameParts);
</code></pre>
<p>I'm sure there must also be a better way but I can't think what. Any suggestions?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:32:26.283",
"Id": "73348",
"Score": "0",
"body": "Welcome to Code Review! Just wanted to tell you that it's a nice little first-post you have here. It seems like you have understood exactly what this site is about."
}
] | [
{
"body": "<p>I assume the class this method resides in represents a person's full name (and title). </p>\n\n<p>Two remarks before suggesting major refactorings:</p>\n\n<ul>\n<li>You are using a getter <code>getTitle</code> and direct access to <code>$this->title</code>: stick for one. Usually I prefer to use getters within the class as well (as usual they contain some logic beside returning). Your other variables don't have getters at all. Also, getting a value just for checking for its existence is bad practice. Introduce some existence method for this (e.g. <code>hasTitle</code>). </li>\n<li>Don't store information serialized during runtime (<code>$middlenames</code>). As you obviously need the middle names as an array, store them accordingly. </li>\n</ul>\n\n<p>Now looking at your class, it has two responsibilities: (1) representing a name, and (2) formating a name. Moving the name formatting into a separate class decouples representation and formating. It allows you to have different means to format at name at the same time and when you want to change the formatting you don't have to touch the name class at all. This is how such a formatter might look like (untested):</p>\n\n<pre><code>class NameFormater {\n private $seperator;\n private $includeTitle;\n private $includeMiddleNames;\n\n public function __construct($seperator, $includeTitle, $includeMiddleNames) {\n // argument validation here\n $this->seperator = $seperator;\n $this->includeTitle = $includeTitle;\n $this->includeMiddleName = $includeMiddleName;\n }\n\n public function format(Name $name) {\n $nameParts = array();\n\n if ($this->includeTitle && $name->hasTitle()) {\n $nameParts[] = $name->getTitle();\n }\n if ($name->hasForName()) {\n $nameParts[] = $name->getForName();\n }\n if ($this->includeMiddleNames && $name->hasMiddleNames()) {\n $nameParts = array_merge($nameParts, $name->getMiddleNames());\n }\n if ($name->hasLastName()) {\n $nameParts[] = $name->getLastName;\n }\n\n return implode($this->seperator, $nameParts);\n }\n}\n</code></pre>\n\n<p>Now this method could be refined further. E.g. we first could allow <code>$nameParts</code> to contain <code>null</code> values if the respective part was not set and filter them before <code>implode</code>ing. This would make it more challenging to read though and I prefer a bit more verbosity over compactness. The current version is trivial to follow and understand. This is due to no complex nesting or logic and names that speak for themselves (e.g. <code>hasTitle</code>) - and in my opinion this is the most important point in programming :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:12:47.967",
"Id": "73395",
"Score": "0",
"body": "Thanks for the feedback.\nI was using the `get` methods but realised I didn't want to use their logic so changed to getting them directly - guess I missed one.\nI agree, the `has` methods do read better. I will start using then from now on.\nI'm not sure I really see the benefit in having the `NameFormatter` class.\nI have standard get/set methods, then additional methods such as `getFullName`, `getFullLegalName` (which just calls `getFullName`, passing the relevant parameters), etc. and finally methods for db interaction – `load`, `save`, etc.\nWould you put these methods into different classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:35:08.440",
"Id": "73397",
"Score": "0",
"body": "Yes I definitely would. One class represents the object you want to model (your domain model/entity, in your case the name). When deciding about what is part of your model, and what not it sometimes helps to imagine \"being the object\" you want to model. As a name, I don't care how I am formatted or how I am stored. Separating your concerns really helps to keep your classes small, makes changes to a class less likely, and easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:02:18.207",
"Id": "73406",
"Score": "0",
"body": "This has opended up a whole can of worms! So I've posted a related topic: http://codereview.stackexchange.com/questions/42599/best-structure-for-a-person-in-php-classes-and-databse."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T11:30:36.300",
"Id": "42583",
"ParentId": "42555",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42583",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:19:58.820",
"Id": "42555",
"Score": "5",
"Tags": [
"php",
"strings"
],
"Title": "String concatenation of name parts"
} | 42555 |
<p>I'm creating a PHP website for a non-profit. They have some restrictions (no MySQL or pre-installed CMS) so I'm creating a CSS menu displayed by an unordered list where all of the elements are stored in a multi-dimensional array.</p>
<p>I've gotten it to work but being new to PHP, I'm certain it's not optimized to run as smoothly as possible. Also, I feel I've hacked my way through the first and last elements.</p>
<p>Here's the array:</p>
<pre><code><?php
$siteURL = "http://www.mysite.org/";
$menu = array
(
//"Name","URL",ID,Level,Seq,Under,Target,Display
//First Menu
array("TOP1",$siteURL."top1.php",1,1,1,0,0,true),
array("SUB1a",$siteURL."sub1a.php",2,2,1,1,0,true),
array("SUB1b",$siteURL."sub1b.php",3,2,2,1,0,true),
array("SUB1c",$siteURL."sub1c.php",4,2,3,1,0,true),
array("SUB1d","http://www.externalsite.org/",5,2,4,1,1,true),
array("SUB1e","http://www.externalsite.org/",6,2,5,1,1,true),
array("SUB1f",$siteURL."sub1f.php",7,2,6,1,0,true),
//Second Menu
array("TOP2",$siteURL."top2.php",8,1,2,0,0,true),
array("SUB2a","http://www.externalsite.org/",9,2,1,8,1,true),
array("SUB2b",$siteURL."sub2b.php",10,2,2,8,0,true),
array("SUB2c","http://www.externalsite.org/",11,2,3,8,1,true),
array("SUB2d","http://www.externalsite.org/",12,2,4,8,1,true),
//Third Menu
array("TOP3",$siteURL."top3.php",13,1,3,0,0,true),
array("SUB3a","http://www.externalsite.org/",14,2,1,13,1,true),
array("SUB3b","http://www.externalsite.org/",15,2,2,13,1,true),
array("SUB3c","http://www.externalsite.org/",16,2,3,13,1,true),
array("SUB3d","http://www.externalsite.org/",17,2,4,13,1,true),
//Fourth Menu
array("TOP4",$siteURL."top4.php",18,1,4,0,0,true),
array("SUB4a",$siteURL."downloads/sub4a.pdf",19,2,1,18,0,true),
array("SUB4b",$siteURL."sub4b.php",20,2,2,18,0,true),
//Fifth Menu
array("TOP5",$siteURL."top5.php",21,1,5,0,0,true),
//Sixth Menu
array("TOP6",$siteURL."top6.php",22,1,6,0,0,false),
//Seventh Menu
array("TOP7",$siteURL."top7.php",23,1,7,0,0,false),
//Eighth Menu
array("TOP8","http://www.externalsite.org/",24,1,8,0,1,true),
);
?>
</code></pre>
<p>And here's the logic:</p>
<pre><code><ul>
<?php
$count = count($menu);
$i = 0;
while ($i < $count) {
if (($menu[$i][3]===1) && ($menu[$i][7]===true)) {
if ($menu[$i][6]===1) {
echo "<li><a href=\"".$menu[$i][1]."\" target=\"_blank\">".$menu[$i][0]."</a><ul>\n";
}
else {
echo "<li><a href=\"".$menu[$i][1]."\">".$menu[$i][0]."</a><ul>\n";
}
for ($j = 0; $j < $count; $j++){
if (($menu[$j][5]===$menu[$i][2]) && ($menu[$j][7]===true)) {
if ($menu[$j][6]===1) {
echo "<li><a href=\"".$menu[$j][1]."\" target=\"_blank\">".$menu[$j][0]."</a></li>\n";
}
else {
echo "<li><a href=\"".$menu[$j][1]."\">".$menu[$j][0]."</a></li>\n";
}
}
}
echo '</ul></li>';
}
$i++;
}
?>
</ul>
</code></pre>
<p>I had a hard time finding a relevant post. I'd appreciate some help or even just validation that I'm doing this correctly.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:32:44.553",
"Id": "73350",
"Score": "0",
"body": "Welcome to Code Review! Just wanted to tell you that it's a nice little first-post you have here. It seems like you have understood exactly what this site is about."
}
] | [
{
"body": "<p>I'm not sure for optimization but for readability and maintenance I would use a Class and create the menu items as objects instead of multi-dimension arrays.</p>\n\n<pre><code>class MenuItem {\n\n protected $id;\n protected $name;\n protected $url;\n protected $level;\n protected $seq;\n protected $under;\n protected $target;\n protected $display;\n\n public function __construct($name, $url, $id, $level, $seq, $under, $target, $display) {\n $this->id = $id;\n $this->name = $name;\n $this->url = $url;\n $this->level = $level;\n $this->seq = $seq;\n $this->under = $under;\n $this->target = $target;\n $this->display = $display;\n }\n\n public function getId() {\n return $this->id;\n }\n\n public function getName() {\n return $this->name;\n }\n\n public function getUrl() {\n return $this->url;\n }\n\n public function getLevel() {\n return $this->level;\n }\n\n public function getSeq() {\n return $this->seq;\n }\n\n public function getUnder() {\n return $this->under;\n }\n\n public function getTarget() {\n return $this->target;\n }\n\n public function getDisplay() {\n return $this->display;\n }\n\n}\n</code></pre>\n\n<p>And so your creation code would become:</p>\n\n<pre><code>$siteURL = \"http://www.mysite.org/\";\n\n$menu = array\n (\n //\"Name\",\"URL\",ID,Level,Seq,Under,Target,Display\n //First Menu\n new MenuItem(\"TOP1\",$siteURL.\"top1.php\",1,1,1,0,0,true),\n new MenuItem(\"SUB1a\",$siteURL.\"sub1a.php\",2,2,1,1,0,true),\n new MenuItem(\"SUB1b\",$siteURL.\"sub1b.php\",3,2,2,1,0,true),\n new MenuItem(\"SUB1c\",$siteURL.\"sub1c.php\",4,2,3,1,0,true),\n new MenuItem(\"SUB1d\",\"http://www.externalsite.org/\",5,2,4,1,1,true),\n new MenuItem(\"SUB1e\",\"http://www.externalsite.org/\",6,2,5,1,1,true),\n new MenuItem(\"SUB1f\",$siteURL.\"sub1f.php\",7,2,6,1,0,true),\n\n //Second Menu\n new MenuItem(\"TOP2\",$siteURL.\"top2.php\",8,1,2,0,0,true),\n new MenuItem(\"SUB2a\",\"http://www.externalsite.org/\",9,2,1,8,1,true),\n new MenuItem(\"SUB2b\",$siteURL.\"sub2b.php\",10,2,2,8,0,true),\n new MenuItem(\"SUB2c\",\"http://www.externalsite.org/\",11,2,3,8,1,true),\n new MenuItem(\"SUB2d\",\"http://www.externalsite.org/\",12,2,4,8,1,true),\n\n //Third Menu\n new MenuItem(\"TOP3\",$siteURL.\"top3.php\",13,1,3,0,0,true),\n new MenuItem(\"SUB3a\",\"http://www.externalsite.org/\",14,2,1,13,1,true),\n new MenuItem(\"SUB3b\",\"http://www.externalsite.org/\",15,2,2,13,1,true),\n new MenuItem(\"SUB3c\",\"http://www.externalsite.org/\",16,2,3,13,1,true),\n new MenuItem(\"SUB3d\",\"http://www.externalsite.org/\",17,2,4,13,1,true),\n\n //Fourth Menu\n new MenuItem(\"TOP4\",$siteURL.\"top4.php\",18,1,4,0,0,true),\n new MenuItem(\"SUB4a\",$siteURL.\"downloads/sub4a.pdf\",19,2,1,18,0,true),\n new MenuItem(\"SUB4b\",$siteURL.\"sub4b.php\",20,2,2,18,0,true),\n\n //Fifth Menu\n new MenuItem(\"TOP5\",$siteURL.\"top5.php\",21,1,5,0,0,true),\n\n //Sixth Menu\n new MenuItem(\"TOP6\",$siteURL.\"top6.php\",22,1,6,0,0,false),\n\n //Seventh Menu\n new MenuItem(\"TOP7\",$siteURL.\"top7.php\",23,1,7,0,0,false),\n\n //Eighth Menu\n new MenuItem(\"TOP8\",\"http://www.externalsite.org/\",24,1,8,0,1,true),\n\n );\n</code></pre>\n\n<p>Then you can access values in a more readable way. E.g.</p>\n\n<pre><code>foreach ($menu as $menuItem) {\n if (($menuItem->getLevel() === 1) && ($menuItem->getDisplay() === true)) {\n ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:02:07.097",
"Id": "73353",
"Score": "0",
"body": "You could extend MenuItem by adding a subMenu property - which is of type MenuItem - and instead of creating all your MenuItems in an array, add the sub menus to the parent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:26:36.200",
"Id": "73681",
"Score": "0",
"body": "Thanks! This works great for the the top-level menu items but I'm lost when it comes to the loop for the sub-menu items."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:58:50.360",
"Id": "42558",
"ParentId": "42556",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T00:21:13.290",
"Id": "42556",
"Score": "3",
"Tags": [
"php",
"html",
"array"
],
"Title": "Display PHP Menu Stored in an Array and Looped"
} | 42556 |
<p>Here is an "enhanced" Listview class. You can just add it your project and you're good to go. Most of the code came from here and there. It's not perfect by any means, so any input is appreciated.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Globalization;
namespace ChangeThisNamespace
{
partial class EnhancedListView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// EnhancedListView
//
this.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.EnhancedListView_ColumnClick);
this.ResumeLayout(false);
}
#endregion
}
}
namespace ChangeThisNamespace
{
public partial class EnhancedListView : ListView
{
enum lvEvents : uint
{
ItemAdded = 0x104D,
ItemRemoved = 0x1008
}
private ListViewColumnSorter lvwColumnSorter;
public event EventHandler ItemAdded;
public event EventHandler ItemRemoved;
/// <summary>
/// Sets or Gets alternate color for the listview rows.
/// </summary>
public Color AlternateColor { get; set; }
/// <summary>
/// Sets or Gets DateTimeFormat for sorting columns that contain DateTime.
/// </summary>
public string DateTimeFormat { set; get; }
public EnhancedListView()
{
AlternateColor = Color.Empty;
lvwColumnSorter = new ListViewColumnSorter();
this.ListViewItemSorter = lvwColumnSorter;
ItemAdded += ItemAddedToLV;
ItemRemoved += ItemRemovedFromLV;
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
InitializeComponent();
}
protected override void InitLayout()
{
lvwColumnSorter.timeFormat = DateTimeFormat;
base.InitLayout();
}
protected override void OnPaint(PaintEventArgs e)
{
lvwColumnSorter.timeFormat = DateTimeFormat;
base.OnPaint(e);
}
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch ((lvEvents)m.Msg)
{
case lvEvents.ItemAdded:
if (ItemAdded != null)
{
ItemAdded(this, null);
}
break;
case lvEvents.ItemRemoved:
if (ItemRemoved != null)
{
ItemRemoved(this, null);
}
break;
default:
break;
}
}
public void SetAlternateColor()
{
try
{
if (!AlternateColor.IsEmpty && this.Items.Count != 0)
{
if (this.Items.Count > 1)
{
for (int ix = 0; ix < this.Items.Count; ++ix)
{
var item = this.Items[ix];
item.BackColor = (ix % 2 == 0) ? AlternateColor : Color.White;
}
}
}
}
catch (Exception)
{
}
}
void ItemAddedToLV(object sender, EventArgs e)
{
SetAlternateColor();
}
void ItemRemovedFromLV(object sender, EventArgs e)
{
MessageBox.Show("Removed");
SetAlternateColor();
}
private void EnhancedListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (this.Items.Count != 0)
{
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.SortColumn)
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.Order == System.Windows.Forms.SortOrder.Ascending)
{
lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Descending;
}
else
{
lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Ascending;
}
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Ascending;
}
// Perform the sort with these new sort options.
this.Sort();
SetAlternateColor();
}
}
}
public class ListViewColumnSorter : IComparer
{
public string timeFormat { set; get; } // = "HH:mm:ss - dd-MM-yyyy";
//private string dtFormat;
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int columnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder orderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary>
private CaseInsensitiveComparer objectCompare;
//private CaseInsensitiveComparer xNumber;
/// <summary>
/// Class constructor. Initializes various elements
/// </summary>
public ListViewColumnSorter()
{
// Initialize the column to '0'
columnToSort = 0;
// Initialize the sort order to 'none'
orderOfSort = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
objectCompare = new CaseInsensitiveComparer();
}
/// <summary>
/// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison.
/// </summary>
/// <param name="x">First object to be compared</param>
/// <param name="y">Second object to be compared</param>
/// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
// Compare the two items
int valueX;
int valueY;
string txtValueX = listviewX.SubItems[columnToSort].Text;
string txtValueY = listviewY.SubItems[columnToSort].Text;
double xNumber, yNumber;
bool parsed = double.TryParse(txtValueX, out xNumber);
parsed = parsed && double.TryParse(txtValueY, out yNumber);
if (parsed)
{
compareResult = objectCompare.Compare((int.TryParse(listviewX.SubItems[columnToSort].Text, out valueX) ? valueX : 0), (int.TryParse(listviewY.SubItems[columnToSort].Text, out valueY) ? valueY : 0));
}
else
{
compareResult = objectCompare.Compare(listviewX.SubItems[columnToSort].Text, listviewY.SubItems[columnToSort].Text);
}
DateTime dateX;
DateTime dateY;
if (timeFormat != "" && timeFormat != null)
{
if (
DateTime.TryParseExact(listviewX.SubItems[columnToSort].Text, timeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateX)
&& DateTime.TryParseExact(listviewY.SubItems[columnToSort].Text, timeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateY)
)
{
compareResult = objectCompare.Compare(dateX, dateY);
}
}
// Calculate correct return value based on object comparison
if (orderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (orderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
}
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn
{
set { columnToSort = value; }
get { return columnToSort; }
}
/// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary>
public SortOrder Order
{
set { orderOfSort = value; }
get { return orderOfSort; }
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T22:58:27.630",
"Id": "73464",
"Score": "0",
"body": "why two column sorter references? lvwColumnSorter = new ListViewColumnSorter();this.ListViewItemSorter = lvwColumnSorter; why not just set thisListViewColumnSorter = new ListViewColumnSorter()?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:04:32.907",
"Id": "73987",
"Score": "0",
"body": "Thanks for your feedback, I tried that out and it does not work for some weird reason, unless I do it that way. Thanks again."
}
] | [
{
"body": "<h3>Random observations...</h3>\n<p>Why is the <code>ListViewColumnSorter</code> class <code>partial</code>?</p>\n<p><strong>Compare</strong></p>\n<p>I think the code could get clearer here. First thing I'd address, I'd declare a <code>int result;</code> and <code>return</code> only once.</p>\n<p>Then the declarations and casting:</p>\n<pre><code>ListViewItem listviewX, listviewY;\n// Cast the objects to be compared to ListViewItem objects\nlistviewX = (ListViewItem)x;\nlistviewY = (ListViewItem)y;\n</code></pre>\n<p>Not sure what this is buying you. Wouldn't it be more readable like this?</p>\n<pre><code>var listViewX = x as ListViewItem;\nvar listViewY = y as ListViewItem;\n\nif (listViewX == null || listViewY == null) throw new ArgumentException();\n</code></pre>\n<p>Throwing an <code>ArgumentException</code> (perhaps with a more detailed message) would be less surprising than the <code>InvalidCastException</code> thrown by the explicit cast if <code>x</code> or <code>y</code> isn't a <code>ListViewItem</code>.</p>\n<p>The naming of the variables is confusing. You have <code>int valueX</code> and then <code>string xValue</code>:</p>\n<pre><code>// Compare the two items\nint valueX;\nint valueY;\nstring xValue = listviewX.SubItems[ColumnToSort].Text;\nstring yValue = listviewY.SubItems[ColumnToSort].Text;\n</code></pre>\n<p>If <code>xValue</code> is <em>the text value of the column to sort for ListViewX</em>, wouldn't <code>textValueX</code> and <code>textValueY</code> be more descriptive names?</p>\n<hr />\n<p>Instead of <code>timeFormat != ""</code> you should be testing for <code>!String.IsNullOrEmpty(timeFormat)</code>.</p>\n<hr />\n<p><strong>Private fields</strong></p>\n<p>Your private fields don't follow C# naming conventions:</p>\n<pre><code>private SortOrder OrderOfSort;\n</code></pre>\n<p>Should be <code>orderOfSort</code> or <code>_orderOfSort</code>... although I don't see a reason for it not to be <code>_sortOrder</code> or <code>sortOrder</code>.</p>\n<p><strong>#region</strong></p>\n<p><code>#region</code> is usually a code smell in itself. It's not so bad in this case, because it's wrapping an entire class, but then why wrap a class in a <code>#region</code> anyway? Move the class into its own file!</p>\n<hr />\n<pre><code>switch (m.Msg)\n</code></pre>\n<p>I think I'd try to convert that to an enum with the values you're expecting, so as to eliminate the cryptic <code>0x1007</code>, <code>0x104D</code> and <code>0x1008</code> "magic numbers", making your cases look like:</p>\n<pre><code>case WndProcMessage.ListViewItemAddedA:\ncase WndProcMessage.ListViewItemAddedW:\ncase WndProcMessage.ListViewItemRemoved:\n</code></pre>\n<hr />\n<p><strong>Swallowed Exceptions</strong></p>\n<p><code>SetAlternateColor</code> has this <code>catch</code> block:</p>\n<pre><code> catch (Exception)\n {\n }\n</code></pre>\n<p>Are you expecting a particular exception type? This code is swallowing <strong>all</strong> exceptions, which is bad. At least output it somewhere (log, debug output, whatever):</p>\n<pre><code> catch (Exception exception)\n {\n Console.WriteLine(exception);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:10:43.577",
"Id": "73992",
"Score": "0",
"body": "Thanks for your detailed feedback, \n1.The partial class was done by mistake.\n2. That didn't work for some reason.\n3. Changed the variable names as you pointed it out.\n4. Again changed the names.\n5. Created enums as pointed out.\n6. I've done it like that for the code just to try and not to return any exceptions.\n\nThanks again, I really do appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:24:19.347",
"Id": "42778",
"ParentId": "42559",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42778",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:12:59.313",
"Id": "42559",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "Winforms Enhanced ListView Class"
} | 42559 |
<p>I wrote this quick script to convert a genotype file into a BED file. Running it seems to be taking a very long time. </p>
<pre><code>#BED file format
#http://genome.ucsc.edu/FAQ/FAQformat.html#format1
#1.chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random) or scaffold (e.g. scaffold10671).
#2.chromStart - The starting position of the feature in the chromosome or scaffold. The first base in a chromosome is numbered 0.
#3.chromEnd - The ending position of the feature in the chromosome or scaffold. The chromEnd base is not included in the display of the feature. For example, the first 100 bases of a chromosome are defined as chromStart=0, chromEnd=100, and span the bases numbered 0-99.
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
from __future__ import print_function
genotype = open("<file>", "rU")
def listToRange(list):
ranges = []
for k, g in groupby(enumerate(list), lambda (i,x):i-x):
group = map(itemgetter(1), g)
ranges.append((group[0], group[-1]))
return ranges
#Create Dictionary with all positions for each chrom
chromDict = defaultdict(list)
genotypeLines = list(genotype.readlines()[1:])
for item in genotypeLines:
objects = item.split()
chromDict[objects[0]].append(int(objects[1]))
#print() implemented in python 3 for use in python 2 need to: from __future__ import print_function
for key, value in chromDict.iteritems():
if len(listToRange(value)) > 1:
for i in range(0,(len(listToRange(value)))):
print(key, listToRange(value)[i][0],listToRange(value)[i][1], sep="\t")
else:
print(key, listToRange(value)[0][0], listToRange(value)[0][1], sep="\t")
#need to capture output to terminal i.e. python script.py > myfile.bed
genotype.close()
</code></pre>
<p>Input file example:</p>
<pre><code>Chr Position 1 2 3
HE669507 9752 C C C
HE669507 9753 T T T
HE669507 9755 A A A
</code></pre>
<p>This is what the output looks like. It turns positions into intervals</p>
<pre><code>HE669507 9752 9753
HE669507 9755 9755
</code></pre>
<p>I am not sure what is causing it to be so inefficient, but I suspect it might be something to do with the way I print the output.</p>
| [] | [
{
"body": "<p>I do not know python, so I should probably restrain from answering. But my initial observation by looking at your code is the repeated call to <code>listToRange</code> in the last <code>for</code> loop.</p>\n\n<p>We can also skip the <code>if len() > 1</code>.</p>\n\n<h3><em>Rewrite:</em></h3>\n\n<blockquote>\n<pre><code>for key, value in chromDict.iteritems():\n chrom_range = listToRange(value)\n chrom_len = len(chrom_range)\n for i in range(0, chrom_len):\n print(key, chrom_range[i][0], chrom_range[i][1], sep=\"\\t\")\n</code></pre>\n</blockquote>\n\n<p>Some other notes:</p>\n\n<ul>\n<li><p>There is also the question about variable names. In your\n<code>listToRange(list)</code>, <code>list</code> is a python keyword.</p></li>\n<li><p><code>import __future__</code> statements should be served before\nanything else.</p></li>\n<li><p>Comments and code should be within a width limit. I stay with the 80\nrule.</p></li>\n<li><p>Space after comma.</p></li>\n</ul>\n\n<p>As you tag question with <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a> I would also recommend <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8 – Style Guide for Python Code</a>. It is one of those things that when one accumulate experience one better see where and when it is appropriate to deviate from. Start out strict and lax later if appropriate.</p>\n\n<p>There is also a <a href=\"https://pypi.python.org/pypi/pep8\" rel=\"nofollow\"><code>pep8</code> command line tool</a> for easy validation.</p>\n\n<p>As such I can add the bullet point:</p>\n\n<ul>\n<li>Function names should be lowercase, with words separated \nby underscores as necessary to improve readability.</li>\n</ul>\n\n<p>That is: if this is not part of a bigger code-base where the norm is to use camel-case.</p>\n\n<hr>\n\n<p>For file read <a href=\"http://docs.python.org/2/reference/compound_stmts.html#with\" rel=\"nofollow\"><code>with</code></a> can be nice to use. I simply quote <a href=\"http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects\" rel=\"nofollow\">python.org by</a>:</p>\n\n<blockquote>\n <p>It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:</p>\n</blockquote>\n\n<p>As noted, I do not know python, but add a simple writeup anyway, you might find some of it useful:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>\"\"\" GENO TO BED \"\"\"\n# BED file format\n# http://genome.ucsc.edu/FAQ/FAQformat.html#format1\n# 1.chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random) or\n# scaffold (e.g. scaffold10671).\n# 2.chromStart - The starting position of the feature in the chromosome or\n# scaffold. The first base in a chromosome is numbered 0.\n# 3.chromEnd - The ending position of the feature in the chromosome or\n# scaffold. The chromEnd base is not included in the display of\n# the feature. For example:\n# The first 100 bases of a chromosome are defined as\n# chromStart=0, chromEnd=100, and span the bases numbered 0-99.\n\nfrom __future__ import print_function\nfrom collections import defaultdict\nfrom operator import itemgetter\nfrom itertools import groupby\nimport sys\n\n\ndef list_to_range(list_):\n \"\"\" List to range \"\"\"\n ranges = []\n for k, groups in groupby(enumerate(list_), lambda (i, x): i - x):\n group = map(itemgetter(1), groups)\n ranges.append((group[0], group[-1]))\n return ranges\n\n\ndef dump_bed(chrom_dict):\n \"\"\" Print BED to stdout \"\"\"\n for key, value in chrom_dict.iteritems():\n chrom_range = list_to_range(value)\n chrom_len = len(chrom_range)\n for i in range(0, chrom_len):\n print(key, chrom_range[i][0], chrom_range[i][6], sep=\"\\t\")\n\n\ndef dict_from_file(filename):\n \"\"\" Generate dictionary from file \"\"\"\n chrom_dict = defaultdict(list)\n with open(filename, \"rU\") as handle:\n next(handle) # Skip first line\n for line in handle:\n if line == \"\\n\":\n continue\n try:\n key, val = line.split()[0:2]\n chrom_dict[key].append(int(val))\n except ValueError:\n # Here you likely want to print some error.\n # Use except ValueError, err: to get the\n # error description.\n pass\n\n return chrom_dict\n\n\ndef main():\n \"\"\" Main routine \"\"\"\n chrom_dict = dict_from_file(sys.argv[1])\n dump_bed(chrom_dict)\n return 0\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print(\"Missing filename.\", file=sys.stderr)\n sys.exit(1)\n sys.exit(main())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T02:13:24.350",
"Id": "42566",
"ParentId": "42561",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "42566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T01:21:15.310",
"Id": "42561",
"Score": "3",
"Tags": [
"python",
"performance",
"beginner"
],
"Title": "Speed up file format conversion"
} | 42561 |
<p>The Wikipedia article on the <a href="http://en.wikipedia.org/wiki/Union_find" rel="nofollow">union find problem</a> gives a very simple implementation, which I ported to C# and tested.</p>
<p>I know that the code should be, in the aggregate, asymptotically almost linear. But is it a practical implementation? Are there optimizations I should have used? Is there a way to cut down on the worst-case complexity of single operations?</p>
<pre><code>using System;
/// <summary>
/// A UnionFindNode represents a set of nodes that it is a member of.
///
/// You can get the unique representative node of the set a given node is in by using the Find method.
/// Two nodes are in the same set when their Find methods return the same representative.
/// The IsUnionedWith method will check if two nodes' sets are the same (i.e. the nodes have the same representative).
///
/// You can merge the sets two nodes are in by using the Union operation.
/// There is no way to split sets after they have been merged.
/// </summary>
public class UnionFindNode {
private UnionFindNode _parent;
private uint _rank;
/// <summary>
/// Creates a new disjoint node, representative of a set containing only the new node.
/// </summary>
public UnionFindNode() {
_parent = this;
}
/// <summary>
/// Returns the current representative of the set this node is in.
/// Note that the representative is only accurate untl the next Union operation.
/// </summary>
public UnionFindNode Find() {
if (!ReferenceEquals(_parent, this)) _parent = _parent.Find();
return _parent;
}
/// <summary>
/// Determines whether or not this node and the other node are in the same set.
/// </summary>
public bool IsUnionedWith(UnionFindNode other) {
if (other == null) throw new ArgumentNullException("other");
return ReferenceEquals(Find(), other.Find());
}
/// <summary>
/// Merges the sets represented by this node and the other node into a single set.
/// Returns whether or not the nodes were disjoint before the union operation (i.e. if the operation had an effect).
/// </summary>
/// <returns>True when the union had an effect, false when the nodes were already in the same set.</returns>
public bool Union(UnionFindNode other) {
if (other == null) throw new ArgumentNullException("other");
var root1 = this.Find();
var root2 = other.Find();
if (ReferenceEquals(root1, root2)) return false;
if (root1._rank < root2._rank) {
root1._parent = root2;
} else if (root1._rank > root2._rank) {
root2._parent = root1;
} else {
root2._parent = root1;
root1._rank++;
}
return true;
}
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>If I read the wikipedia article correctly then the algorithm should have amortized constant cost - and you have implemented it pretty much 1:1. Given that with your implementation you always start with disjoint nodes and any call to any of the public methods ends up calling <code>Find</code> which will automatically flatten the tree I doubt you can get much better.</p></li>\n<li><p><code>UnionFindNode</code> is not a particularly good name for the data structure: intermingles operations with the data structure in the name. Just <code>Node</code> or maybe <code>DisjointSetNode</code> would be better.</p></li>\n<li><p>You could use <code>==</code> or <code>!=</code> instead of <code>ReferenceEquals</code> which would make the code a bit easier to read.</p></li>\n<li><p>Consider making your node class generic and add a <code>T value</code> property - right now your nodes are not all that useful as they don't hold any data.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T07:24:37.527",
"Id": "73377",
"Score": "0",
"body": "Considering that the data structure is commonly called the Union-Find data structure, I think the class name is OK."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T07:26:26.193",
"Id": "73378",
"Score": "0",
"body": "For #4: The idea I had in mind is to put the node *inside* the target class, to hide implementation details, instead of putting the target inside the node. Because you can't explore the set, given a node, it's not very useful to put the value there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T06:45:12.433",
"Id": "73487",
"Score": "0",
"body": "@Strilanc: Well, with a little bit more effort and some memory you can explore the set without changing the basic properties of the algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T06:45:47.603",
"Id": "73488",
"Score": "0",
"body": "@200_success: Hm, fair enough, I guess in this case the kind of structure and the operations you perform on it are very closely related."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T03:12:39.560",
"Id": "210912",
"Score": "0",
"body": "Do you think, that the fact that `Find` method is recursive may be a problem (stack overflow) with deep trees?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T07:18:36.503",
"Id": "42578",
"ParentId": "42573",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T04:26:45.033",
"Id": "42573",
"Score": "6",
"Tags": [
"c#",
"algorithm",
"set",
"union-find"
],
"Title": "UnionFind implementation"
} | 42573 |
<p>I'm building a binary tree.</p>
<p>Example: key AAAA1.ETR, value 1.</p>
<p>I'm reading files with this structure:</p>
<pre><code>DataLength Block-SequenceNummer FLag Start Data Ende
4 Bytes 8 Bytes 1 Byte S Datalength E
</code></pre>
<p>Data can be compressed or uncompressed (this is saved in flag). Data contain more messages. Could you have a look and give me hints on what I can do better?</p>
<pre><code>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <stdio.h>
#include <glib.h>
#include <sys/stat.h>
#define MYMAXSIZE 10000000
#define MAXFILESIZE 6000000
#define OBJNAME "8"
#define MSGTYPE "1"
const uint8_t broadcast[] = { 0x36, 0x33 };
const uint8_t status[] = { 0x34 };
const char dir0[]= "/home/frog/reader/feed.0/";
const char dir1[]= "/home/frog/reader/feed.1/";
const char dir2[]= "/home/frog/reader/feed.2/";
const char dir3[]= "/home/frog/reader/feed.3/";
typedef struct mtmheader_t
{
unsigned char objName[20]; //8
unsigned char msgType[3]; //1
}mtmheader_t;
typedef struct analyzer_t
{
unsigned char *buff;
size_t s;
}analyzer_t;
typedef struct analyzers_t
{
analyzer_t anal1;
analyzer_t anal2;
analyzer_t anal3;
unsigned char* seq;
}analyzers_t;
int readFilec(GTree *tree)
{
FILE * fp = fopen("cfg/InstrumentList_FULL.csv", "rb" );
char * line = NULL;
size_t len = 0;
ssize_t read;
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1)
{
char *p1;
int *p2 = malloc(sizeof (int));
printf("%s", line);
p1 = strtok(line, "|");
*p2 = atoi(strtok(NULL, "|"));
g_tree_insert(tree, (gpointer) g_strdup(p1), (gpointer)p2);
//TrieAdd(&root, strdup(p1), p2);
printf("-%s%d ", p1, *p2);
}
if (line)
free(line);
//exit(EXIT_SUCCESS);
}
int readFile( char *name,unsigned char *buffp)
{
int fileSize = 0;
//int n, i, j;
printf("Opening file: \"%s\"\n", name);
FILE *pFile = fopen(name, "rb");
if(pFile == NULL)
{
printf("error: fopen()");
return -1;
}
fseek(pFile, 0, SEEK_END);
fileSize = ftell(pFile);
printf ("%d\n", fileSize);
rewind(pFile);
//unsigned char *data = (unsigned char*) calloc(sizeof(unsigned char), fileSize + 20);
int bytes = fread(buffp, 1, fileSize, pFile);
if(ferror(pFile))
{
printf("error: fread()");
return -1;
}
return bytes;
}
int processMTMHeader(unsigned char *datap, mtmheader_t *h, unsigned char *endmmsgp)
{
unsigned char *nextFsp;
unsigned char *nextRsp;
//nextRs
size_t size = endmmsgp - datap;
//Den Header komplett abarbeiten (bis GS (x1D) oder ETX (x03) kommt)
//Byte lesen = RS (x1E)
while ( (datap = (memchr(datap, 0x1E, size))) != NULL)//datap < endmmsgp)//= strchr(datap, '\x1E') != NULL )
{
datap++;
//next Fs
//Byte lesen = FS (x1C)
nextFsp = memchr(datap, 0x1C,size);
//Byte lesen = RS (x1C)
nextRsp = memchr(datap, 0x1E, size);
size = endmmsgp - nextRsp;
if ( nextFsp - datap != 1)continue;
if( *datap == 0x38 )
{
//Objectnamen generieren() (Nur die ersten beiden Felder des Objectnamens verwenden)
memcpy (h->objName, nextFsp+1, nextRsp - ( nextFsp+1) );
h->objName[ nextRsp - ( nextFsp+1)]='\0';
//Abbruch der Schleife da ich jetzt den Objectnamen habe (Den Header komplett abarbeiten )
return 1;
}
else if ( *datap == 0x31 )
{
memcpy (h->msgType, nextFsp+1, nextRsp - ( nextFsp+1) );
h->msgType[nextRsp - ( nextFsp+1)]='\0';
if( (memcmp(h->msgType, broadcast, sizeof broadcast) != 0) && (memcmp(h->msgType,status, sizeof( status))!=0 )) return 2;
}
}
return -1;
}
int processData(unsigned char *datap, size_t size, GTree* t, analyzers_t *anals)
{
int headerOk=0;
unsigned char *nextmtmmsgp;
unsigned char *endmmsgp ;
int * qsp;
int s;
//Solange alle MTM durcharbeiten bis keine mehr da sind
while ( (datap = memchr (datap, 0x02, size))!= NULL )
{
//datap++;
//printf("data\n%s", datap);
endmmsgp = memchr (datap, 0x03, size);
mtmheader_t h;
//Alle HeaderFieldDataPairs abarbeiten
headerOk = processMTMHeader(datap, &h, endmmsgp );
int headersSize1 = 10;
int headersSize2 = 10;
int headersSize3 = 10;
if (headerOk == 1)
{
//QOT-Status zu dem Objectnamen bestimmen
if ((qsp = (int *) g_tree_lookup(t, h.objName)) != NULL )
{
s = (endmmsgp - datap )+ 1;
printf("found: %s %d\n", h.objName, *qsp);
//Den Header inklusiv eventuell vorhanden Body dem ensprechenden Analyzer zuordnen
//Dazu den kompletten Block von STX bit ETX auf den MTMcache des Analyzers kopieren
switch (*qsp)
{
case 1:
memcpy(anals->anal1.buff + anals->anal1.s + headersSize1, datap, s);
anals->anal1.s = s + headersSize1 + anals->anal1.s ;
headersSize1=0;
break;
case 2:
memcpy(anals->anal2.buff + anals->anal2.s + headersSize2, datap, s);
anals->anal2.s= s + headersSize2 + anals->anal2.s ;
headersSize2=0;
break;
case 3:
memcpy(anals->anal3.buff + anals->anal1.s + headersSize3, datap, s);
anals->anal3.s= s + headersSize3 + anals->anal3.s ;
headersSize3=0;
break;
}
}
//Den Header inklusiv eventuell vorhanden Body ALLEN Analyzern weitermelden
//Dazu den kompletten Block von STX bit ETX auf den MTMcache ALLER Analyzers kopieren
else if (headerOk == 2)
{
memcpy(anals->anal1.buff + anals->anal1.s + headersSize1, datap, s);
anals->anal1.s = s + headersSize1 + anals->anal1.s ;
headersSize1=0;
memcpy(anals->anal2.buff + anals->anal2.s + headersSize2, datap, s);
anals->anal2.s= s + headersSize2 + anals->anal2.s ;
headersSize2=0;
memcpy(anals->anal3.buff + anals->anal1.s + headersSize3, datap, s);
anals->anal3.s= s + headersSize3 + anals->anal3.s ;
headersSize3=0;
}
}
datap++;
printf("Name, type: %s %s\n",(char *) &h.objName,(char *) &h.msgType);
}
return -1;
}
gboolean iter_all(gpointer key, gpointer value, gpointer data) {
int *s = (int *)value;
printf("\n%s%d \n", (char *)key, *s);
return FALSE;
}
int writeFile(char *name, unsigned char *buff, size_t *size, char *dir )
{
FILE * pFile;
char fullName[50];
//fullName[0]='\0';
//strcat(fullName, dir);
//strcat(fullName, name);
chdir (dir);
pFile = fopen ( name, "wb");
//pFile = fopen (strcat ( strcat( strcat("feed.",anal), "/") , name ), "wb");
fwrite (buff , sizeof(unsigned char), *size, pFile);
fclose (pFile);
}
int writeFiles(char *name, analyzers_t *anals )
{
if (anals->anal1.s > 10)writeFile(name, anals->anal1.buff, &anals->anal1.s, dir1);
if (anals->anal2.s > 10)writeFile(name, anals->anal2.buff, &anals->anal2.s, dir2);
if (anals->anal3.s > 10)writeFile(name, anals->anal3.buff, &anals->anal3.s, dir3);
}
int addHeader(size_t *start_size, size_t *end_size,unsigned char *buff, unsigned char *seq)
{
*(buff+*start_size+ 9) ='S';
uint32_t s = ((*end_size - *start_size) - 10);
//size_t s_be = htonl(s);
memcpy(buff+*start_size, &s, sizeof(s));
memcpy(buff+4+*start_size, seq, 8 );
buff[*start_size+8] = '\x00';
*(buff + *end_size ) = 'E';
}
int key_compare_func (gconstpointer a, gconstpointer b) {
return g_strcmp0 ((const char*) a, (const char*) b);
}
int main()
{
analyzers_t anals;
anals.anal1.buff = malloc(MYMAXSIZE);
anals.anal2.buff = malloc(MYMAXSIZE);
anals.anal3.buff = malloc(MYMAXSIZE);
unsigned char *bytesp = malloc (MAXFILESIZE);
unsigned char *datap = malloc (MYMAXSIZE);
//char dir[] = "feed.0/";
DIR *dirp;
char currDir[]=".";
char parentDir[]="..";
//unsigned char bytesp[MYMAXSIZE];
GTree* t = g_tree_new_full (key_compare_func, NULL, g_free, NULL);
readFilec(t);
g_tree_foreach(t, (GTraverseFunc)iter_all, NULL);
struct dirent *direntp;
if ((dirp = opendir(dir0)) == NULL)
{
perror("opendir");
return 0;
}
struct stat status;
chdir(dir0);
//Filesystem nach Dump-Files des Reader suchen
int pos=0;
uint32_t seq;
size_t size;
int flag;
if (datap == NULL)return -1;
unsigned char *datapor = datap;
int compressOk=0;
int loop =0;
size_t oldSize1=0;
size_t oldSize2=0;
size_t oldSize3=0;
//unsigned char *anal1or = anal.anal1;
//unsigned char *anal2or = anal.anal2;
//unsigned char *anal3or = anal.anal3;
//Solange die BMB abarbeiten bis keine mehr da sind; Startflag ueberpruefen
while( (direntp = readdir(dirp)) != NULL)
{
if(strcmp(direntp->d_name, currDir) == 0)continue;
if(strcmp(direntp->d_name, parentDir) == 0)continue;
lstat(direntp->d_name, &status);
if(S_ISDIR(status.st_mode))continue;
compressOk=0;
loop =0;
pos=0;
anals.anal1.s = 0;
anals.anal2.s = 0;
anals.anal3.s = 0;
oldSize1 = 0;
oldSize2 = 0;
oldSize3 = 0;
anals.anal1.buff[0]='\0';//anal1or;
anals.anal2.buff[0]='\0';//anal2or;
anals.anal3.buff[0]='\0';//al3or;
readFile(direntp->d_name, bytesp);
while(bytesp[pos+9] == 'S')
{
datap = datapor;
printf("----------------------------\n");
printf("| LOOP %d, POSITION %d |\n", loop, pos);
printf("----------------------------\n\n");
//Datenlaenge des BMB bestimmen
size = ntohl(bytesp[pos+0]<<24| bytesp[pos+1]<<16| bytesp[pos+2]<<8| bytesp[pos+3]);
//Endeflag E ueberpruefen
if (bytesp[pos+10+ size]!='E')
{
pos = pos + 11 + size;
continue;
}
//Block-Sequencenummer speichern
seq = ntohl(bytesp[pos+4]<<24| bytesp[pos+5]<<16| bytesp[pos+6]<<8| bytesp[pos+7]);
anals.seq = bytesp +pos+4;
//Flag lesen
flag = bytesp[pos+8];
if( bytesp[pos+8]=='\x01')
{
size_t size_uncompress = MYMAXSIZE * sizeof(unsigned char);
compressOk = uncompress(datap, &size_uncompress, &bytesp[pos+10], size);
datap[size_uncompress]='\0';
printf ("%zu %zu :\n", size, size_uncompress) ;
}
else
{
datap = &bytesp[pos+10];
//datap[pos+10+ size] ='\0';
}
printf("---------------------------- \n");
printf("| Message as String: |\n");
printf("---------------------------- \n");
printf("%s\n\n\n", datap);
processData(datap, size, t, &anals);
pos = pos + 11 + size;
if (anals.anal1.s > oldSize1 )
{
addHeader( &oldSize1,&anals.anal1.s, anals.anal1.buff, anals.seq );
anals.anal1.s++;
oldSize1 = anals.anal1.s;
}
if (anals.anal2.s > oldSize2 )
{
addHeader( &oldSize2,&anals.anal2.s, anals.anal2.buff, anals.seq );
anals.anal2.s++;
oldSize2 = anals.anal2.s;
}
if (anals.anal3.s > oldSize3 )
{
addHeader( &oldSize3,&anals.anal1.s, anals.anal3.buff, anals.seq );
anals.anal3.s++;
oldSize3 = anals.anal1.s;
}
loop++;
}
writeFiles(direntp->d_name, &anals);
}
free(datap);
free(bytesp);
free(anals.anal1.buff);
free(anals.anal2.buff);
free(anals.anal3.buff);
}
</code></pre>
| [] | [
{
"body": "<p>Just a few tidbits (mainly about error handling):</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1941323/always-check-malloced-memory\">Depending on the architecture</a>, you may want to check whether your <code>malloc</code>s return <code>NULL</code>. It is generally not useful though.</li>\n<li>In the function <code>writeFile</code>, you never check whether <code>fopen</code> succeded before using <code>fwrite</code>.</li>\n<li>You could use <code>perror</code> more often to improve your error messages.</li>\n<li>You made your program <code>return 0</code> when then function <code>opendir</code> fails. Is it normal? Generally, you return any value, but not 0 on a failure.</li>\n<li>Just to add some extra pedantry: you use <code>uint8_t</code> and <code>uint32_t</code>. That's generally fine, unless the architecture where your program runs has a <code>char</code> of more than 8 bits (less than 8 bits is not allowed by the standard). While it is extremely uncommon, C is often used for embedded software, so you might want to use <code>uint_least8_t</code> and <code>uint_least32_t</code> instead, whose presence is mandatory (as per the C99 standard).</li>\n</ul>\n\n<p>Unfortunately, all of these are mere details and probably not the comprehensive answer your were expecting. Hope that helps you anyway :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T11:09:17.307",
"Id": "42949",
"ParentId": "42577",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T07:13:40.620",
"Id": "42577",
"Score": "4",
"Tags": [
"c",
"tree",
"csv"
],
"Title": "Reading messages with binary tree"
} | 42577 |
<p>I have an array of integers and a number <code>n</code>. I want to sum the elements of the array and return the index where the sum passes <code>n</code>, <em>as efficiently as possible</em>.</p>
<p>For example, assume:</p>
<pre><code>theString = "6-7-7-10-7-6"
theNumber = 33
expected result: 5
</code></pre>
<p>This does the trick but not very efficiently: (and error prone; will check for errors when I've found the best solution)</p>
<pre><code>Public Function getIndexFromSum(theString As String, theNumber As Integer) As Integer
Dim theSides As Variant
Dim sum As Integer
Dim index As Integer
theSides = Split(theString, "-")
While sum <= theNumber
sum = sum + theSides(index)
index = index + 1
Wend
getIndexFromSum = index
End Function
</code></pre>
<p>I haven't been able to describe this to google succinctly enough to get any meaningful results, and searching for any combination of the keywords involved produces links to tons of unrelated stuff. I'm sure this problem will have been encountered before (and likely has a smart solution out there somewhere), but I haven't been able to find any sites that can help.</p>
<p>Any help/advice would be very much appreciated!</p>
<p><strong>EDIT - more info</strong></p>
<p>1) <code>theString</code> will always be stored in the format "x-x-x".</p>
<p>2) <code>theNumber</code> will always be smaller than or equal to the sum of the numbers in <code>theString</code>.</p>
<p>3) The length of <code>theString</code> will be short - usually between 2 and 10 numbers, each less than 100.</p>
<p>4) The function will be called with small inputs, but many times. Low overhead is top priority.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:09:41.467",
"Id": "73655",
"Score": "0",
"body": "1. Is `theString` always stored in a String format \"x-x-x\"? Where does it come from? 2. Rough idea how big `theString` is? Rough idea how big `theNumber` generally will be? 3. How often and in what circumstances is this function going to be used? 4. Have you measured how long the function takes to run? Can you provide some data of calculations? You really need to provide more content along with your question to get a better performing algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:48:25.980",
"Id": "73788",
"Score": "0",
"body": "My apologies - I've added what I consider further relevant information to the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:11:25.710",
"Id": "73839",
"Score": "0",
"body": "Thanks for updating the question. In this case I would go with Comintern's approach as optimizing your function even more would have been an overkill. You could have a read on Trie structure (create a map and then nodes etc) if you wanted but seriously that would have been an overkill for this simple case."
}
] | [
{
"body": "<p>I'm not sure what you mean by \"This does the trick but not very efficiently\". I don't really see a way to make the algorithm more efficient, as it is just making a single pass over the array and exits early when it gets the answer. If the input is really long, you could convert it to a byte array instead of splitting it to cut down on the casts, but then you would have to nest the loops, add a subtraction to convert the ascii codes to numbers, add multiplications to keep track of multiples of 10, etc. This would likely be a lot slower than the current method unless you were working with strings on the order of kilobytes.</p>\n\n<p>That said, a couple of observations about the code. I'd personally use a For loop instead of a While loop to prevent you from running outside of the array bounds for inputs where the target number you are looking for is higher than the sum of the complete array. For example, with the input string of \"6-7-7-10-7-6\", a target higher than 43 will overrun the array bound and throw an error. You'll get a similar error if it is passed an empty string (Split will happily give you an array with an upper bound of -1 in that case).</p>\n\n<p>Also note that you are not returning the zero based index, you are returning the one based position of the token in the string. If this is the desired behavior, I'd rename the function to make it obvious that you can't use the return value to index into the array. </p>\n\n<p>About the only thing that I would do to make this a tiny bit more efficient would be to use a String array instead of a Variant and use explicit casting so the run-time doesn't have to resolve the Variants for you more than once. Even this improvement will likely be unnoticeable on any reasonable sized input (you'll overflow an Integer long before you'd notice the performance increase anyway).</p>\n\n<p>Maybe something like this:</p>\n\n<pre><code>Public Function getPositionFromSum(source As String, target As Integer) As Integer\n\n Dim sides() As String\n Dim sum As Integer\n Dim index As Integer\n\n getPositionFromSum = -1 'Or whatever the \"not found\" condition is.\n sides = Split(source, \"-\")\n\n For index = 0 To UBound(sides)\n sum = sum + CInt(sides(index))\n If sum > target Then\n getPositionFromSum = index + 1\n Exit For\n End If\n Next\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T22:52:09.280",
"Id": "42628",
"ParentId": "42580",
"Score": "5"
}
},
{
"body": "<p>One inefficient line of code is this one:</p>\n\n<pre><code>Split(theString, \"-\")\n</code></pre>\n\n<p>It's slow because:</p>\n\n<ul>\n<li>It splits the entire string, even though you're only interested in the first part of the string.</li>\n<li>It allocates a new array and creates many new string objects, instead of parsing the existing string in-place.</li>\n</ul>\n\n<p>Therefore a faster algorithm, if the string is longer than you need, might be:</p>\n\n<pre><code> while not found\n look for the next hyphen\n get the substring up to the next hyphen\n convert the substring to an integer\n add the number\n exit the loop if the sum is large enough\n</code></pre>\n\n<p>However, if you need to parse the whole (or most of) the string, the implementation of <code>Split</code> might be faster than your implementation of the above algorithm.</p>\n\n<hr>\n\n<p>Another possible inefficiency is the conversion from string to number. My guess is that VB.NET implicitly uses <a href=\"http://msdn.microsoft.com/en-us/library/s2dy91zy.aspx\" rel=\"nofollow\">CInt</a> which is a complicated function. Another method like <a href=\"http://msdn.microsoft.com/en-us/library/sf1aw27b%28v=vs.110%29.aspx\" rel=\"nofollow\">Convert.ToInt32</a> or Int32.Parse might be faster, but even that might be slow because, according to MSDN,</p>\n\n<blockquote>\n <p>\"... value is interpreted by using the formatting conventions of the current thread culture.\"</p>\n</blockquote>\n\n<p>Other people get <a href=\"https://www.google.com/search?q=.net+fast+string+to+int\" rel=\"nofollow\">faster results by writing their own converters</a>.</p>\n\n<hr>\n\n<p>In summary (further to Comintern's suggestion) I suspect that something like the following would be faster (forgive me if I code this in C# instead of VB) (untested code ahead):</p>\n\n<pre><code>int number = 0;\nint total = 0;\nint count = 0;\nforeach (char c in theString) // For Each c As Char in theString\n{\n if (c == '-')\n {\n total = total + number;\n if (total > theNumber)\n return count;\n // else prepare for the next number\n count = count + 1;\n number = 0;\n }\n else\n {\n // continue to parse this number\n // assume that c is an ASCII digit\n int digit = (c - '0'); // But is converting char to int slow or difficult?\n number = (10 * number) + digit;\n }\n}\n\n// didn't find the number; return count anyway?\nreturn count;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:16:43.510",
"Id": "73656",
"Score": "0",
"body": "+1 for pointing out the `Split()` fn splitting the entire string. For me this is too little info from the OP to actually come up with a much more efficient way"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:42:04.603",
"Id": "73846",
"Score": "0",
"body": "Thank you very much - I think I'll use what I've got for now, but will move towards this as `theString` gets longer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-19T01:00:42.613",
"Id": "109413",
"Score": "0",
"body": "This is tagged VB6, not VB.Net. `Convert.ToInt32` isn't available."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T23:11:21.717",
"Id": "42629",
"ParentId": "42580",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42629",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T08:54:05.427",
"Id": "42580",
"Score": "6",
"Tags": [
"array",
"vba"
],
"Title": "Return index of array where sum first passes n"
} | 42580 |
<p>While trying to create an "admin" backend (to allow for CMS like functionality) to a site using AngularJS on the frontend, I came across an issue with routes.</p>
<p>In order to allow the admin to create new content, ie install new component (view/controller), change menu item href locations etc, I would have to go in and edit the code that defines the <code>$routeProvider</code> routes manually.</p>
<p>So normally you would do(with angular's own route module):</p>
<pre><code>$routeProvider.
when('/somepage', {
templateUrl: '/templates/somepage.html',
controller: 'SomeCtrl'
}).
when('/otherpage', {
templateUrl: '/templates/someotherpage.html',
controller: 'SomeOtherCtrl'
});
</code></pre>
<p>So if a new component was installed that wanted to say use <code>/Gallery</code> route i would have to go in and add in </p>
<pre><code>when('/Gallery',...)
</code></pre>
<p>So in order to solve this I added in <a href="http://ify.io/lazy-loading-in-angularjs/" rel="nofollow noreferrer">lazy loading</a> capabilities, but even still I would have to go in and add in the route manually. So I modified the <code>resolve</code> <code>deps</code> function to check the server to see if there were any defined routes (ie defined in a menu database, or other places), if it finds a defined route it then returns the dependencies which are then lazy loaded and then add the components routes to the <code>$routeProvider</code> and then trigger a <code>$locationChangeSuccess</code> so that it will reprocess the url path.</p>
<pre><code> app.controllerProvider = $controllerProvider.register;
app.compileProvider = $compileProvider.register;
app.routeProvider = $routeProvider;
$routeProvider.
when('/404',{
templateUrl:"/templates/404.html",
controller:"PageErrorCtrl"
}).
//Catchall for all other paths
otherwise({
resolve:{
deps:function($q, $rootScope, $location) {
var deferred = $q.defer();
var path = $location.path();
//Code to prevent infinite loop
...
//Make a call to server backend find if there is a defined route for this path
//Or if there is a custom route for this path
getRouteDependencies(path,function(err,data){
if(err){ //No route found
$location.path("/404");
return;
}
//JSLoader is a custom function to load in the dependencies
//ie add script tag to head
JSLoader.load(data.dependencies, function() {
$rootScope.$apply(function() {
//call deffered.resolve()?
//reprocess the route
$rootScope.$broadcast('$locationChangeSuccess', path, path);
});
});
});
return deferred.promise;
}
}
});
</code></pre>
<p>So if the admin adds a Gallery template/controller that had a route defined as <code>/Gallery</code> defined in the database, and a user goes to <code>http://example.com/Gallery</code> the <code>otherwise</code> part of <code>$routeProvider</code> would be triggered and in effect trigger the resolve function which would then load in the dependencies, ie gallery.js:</p>
<pre><code>app.controllerProvider('GalleryCtrl',['$scope','$route','$routeParams',
function ($scope,$route,$routeParams) {
$scope.data = {};
$scope.actions = {};
$scope.events = {};
}
]);
//TODO: modify to allow changing of base path (ie /Gallery part) dynamically
app.routeProvider.
when('/Gallery/:galleryId', {
templateUrl: '/templates/gallery.html',
controller: 'GalleryCtrl'
}).
when('/Gallery/:galleryId/:imageId', {
templateUrl: '/templates/galleryImage.html',
controller: 'GalleryCtrl'
});
</code></pre>
<p>So after the loader loads in the above code the new routes are defined on <code>$routeProvider</code> and then the </p>
<pre><code>$rootScope.$broadcast('$locationChangeSuccess', path, path);
</code></pre>
<p>call in the resolve function will tell angular to reprocess the url, which angular should then see as having a route and execute the controller and load in the template associated with that route.</p>
<p>But I was wondering if there is already a part of angular that is supposed to handle this type of scenario( tried searching but searches i tried just returned lazy loading stuff ), a better way of doing it, or if there is something wrong with my approach that would need changing?</p>
<p>There is this <a href="https://stackoverflow.com/questions/13681116/angularjs-dynamic-routing">question</a> on Stack Overflow, but most of the answers are for just loading in the html templates, and do not take into account the need to load different controllers that have not been already defined.</p>
| [] | [
{
"body": "<p>I don't think Angular has such CMS functions. Writing your own was probably the right call.</p>\n\n<p>The little code you provided is well written, JsHint could not find any fault and it is well commented.</p>\n\n<p>We can give more valuable feedback when you provide unsanitized code samples ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:56:53.243",
"Id": "42662",
"ParentId": "42581",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T11:10:38.120",
"Id": "42581",
"Score": "8",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Dynamic routing with lazy load controllers"
} | 42581 |
<p>I was working with <a href="http://www.codechef.com/problems/FCTRL/" rel="nofollow">this</a> problem, which is to find the number of zeros at the end of any factorial.</p>
<p>Here's my solution:</p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
int main(){
int numCases,num,zeroCount=0,mulFive,temp,i=0;
cout<<numeric_limits<int>::max()-1000000000<<endl;
cin>>numCases;
int solutionArray[numCases];
temp=numCases;
while(numCases--)
{
zeroCount=0;
cin>>num;
mulFive=5;
while(num/mulFive!=0)
{
zeroCount=zeroCount+ (num/mulFive);
mulFive=mulFive*5;
}
solutionArray[i]=zeroCount;
i++;
//cout<<zeroCount;
}
for(int k=0;k<temp;k++)
cout<<solutionArray[k]<<endl;
return 0;
}
</code></pre>
<p>This is the most basic code that I could come up with. How should I make it more efficient using the same logic? Perhaps I should use different logic? </p>
| [] | [
{
"body": "<p>There is a problem with your solution for large numbers ( >= 5^13 to be exact) because <code>mulFive=mulFive*5;</code> will go negative as the <code>int</code> overflows. </p>\n\n<p>To protect against this, you could do </p>\n\n<pre><code> while(num/5!=0)\n {\n zeroCount=zeroCount+ (num/5);\n num = num/5;\n }\n</code></pre>\n\n<p>i.e. divide the number rather than multiply the divisor, then only the size of num is a limit (2^31-1) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:15:32.850",
"Id": "42601",
"ParentId": "42582",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T11:29:08.640",
"Id": "42582",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"mathematics"
],
"Title": "Number of zeroes at the end of a factorial"
} | 42582 |
<p>Kotlin is an OSS statically typed programming language that runs on the JVM and also can be compiled to JavaScript or directly to native binaries. The language is inspired by existing languages such as Java, C#, JavaScript, Scala, and Groovy. It's developed by JetBrains.</p>
<h2>Background</h2>
<p><a href="https://en.wikipedia.org/wiki/Kotlin_(programming_language)" rel="nofollow noreferrer">Kotlin</a> is an OSS statically typed programming language that targets the JVM, Android, JavaScript, and Native. It's developed by <a href="https://www.jetbrains.com/" rel="nofollow noreferrer">JetBrains</a>. The project started in 2010 and was open source from early on. The first official 1.0 release was in February 2016.</p>
<p>It has both object-oriented and functional constructs, which gives the developer the possibility to use it in both OO and FP styles or even mix elements of the two.</p>
<p>The language is 100% interoperable with the Java programming language and major emphasis has been placed on making sure that existing code can interact properly with Kotlin.</p>
<p>As Java can only be run directly by very few computers the first step to do before using Kotlin is to download the Java environment which is normally made available by installing a suitable software component.</p>
<p>Some main advantages that Kotlin has over Java is that null references are controlled by the type system, no checked exceptions, extension functions, data classes and the fact arrays in Kotlin are invariant.</p>
<h2>Versions</h2>
<p><strong>Notable Kotlin versions and release dates include:</strong></p>
<pre><code>Kotlin 1.0 (February 15, 2016)
Kotlin 1.1 (March 1, 2017)
Kotlin/Native v0.1 (April 4, 2017)
Kotlin 1.2 [Early access] (June 27, 2017)
</code></pre>
<p>To see release notes for each version of Kotlin, visit the <a href="https://blog.jetbrains.com/kotlin/category/releases/" rel="nofollow noreferrer">blog page</a> on the releases. </p>
<p>The End Of Public Updates (formerly called End Of Life) dates are:</p>
<pre><code>Kotlin 1.0.x - April 4, 2017
</code></pre>
<h2>Initial help</h2>
<ul>
<li>New to Kotlin - need help to get your first program running? See the <a href="https://dogwood008.github.io/kotlin-web-site-ja/docs/tutorials/" rel="nofollow noreferrer">JetBrains Kotlin Tutorials section on Getting Started</a>.</li>
</ul>
<h2>Naming conventions</h2>
<p>Kotlin programs should adhere to the following naming conventions to increase the readability and decrease the chance of accidental errors. By following these conventions, you will make it easier for the community to understand your code and help you.</p>
<ul>
<li>Type names (classes, interfaces, enums, etc.) should begin with a capital letter and capitalize the first letter of each subsequent word. Examples include: <code>Int</code>, <code>NoSuchFileException</code>, and <code>ByteArray</code>. This is called PascalCase.</li>
<li>Method names should be camelCased; what means, that they begin with a lowercase letter and capitalize the first letter of each subsequent word. Examples: <code>count</code>, <code>copyOf</code>, <code>filter</code>.</li>
<li>Field names should be camelCased just like the method names.</li>
<li>Values of an <code>Enum</code> class should be written in ALL_CAPS with underscores separating each word. Examples: <code>WARNING</code>, <code>SYNCHRONIZED</code>, <code>BOTTON_UP</code>.</li>
</ul>
<h2>Hello World</h2>
<pre><code>fun main(args : Array<String>) {
println("Hello, world!")
}
</code></pre>
<p>A package-level function <code>main</code> which returns <code>Unit</code> and takes in an <code>Array</code> of strings as a parameter is defined. In it the method <code>println(string : String)</code> prints <code>Hello, world!</code> to the console.</p>
<p>Compilation of Hello World and running it:</p>
<pre class="lang-bsh prettyprint-override"><code>$ kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
$ java -jar HelloWorld.jar
</code></pre>
<p>The first line creates a <code>.jar</code> file that is self-contained and runnable by including the Kotlin runtime library in it.</p>
<p>More information:</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Kotlin_(programming_language)" rel="nofollow noreferrer">Wikipedia on Kotlin</a></li>
<li><a href="https://github.com/JetBrains/kotlin/releases/tag/v1.1.3-2" rel="nofollow noreferrer">Download the Compiler from GitHub</a></li>
</ul>
<h2>Beginners' resources</h2>
<ul>
<li><a href="https://dogwood008.github.io/kotlin-web-site-ja/docs/reference/faq.html" rel="nofollow noreferrer">Common Questions</a></li>
<li><a href="https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Hello,%20world!/Task.kt" rel="nofollow noreferrer">Kotlin Koans</a> - A "hands-on" learning experience to get familiar with Kotlin.</li>
<li><a href="https://www.youtube.com/watch?v=H_oGi8uuDpA" rel="nofollow noreferrer">Derek Banas' Kotlin tutorial</a> - A video tutorial that tries to teach you everything about the programming language but not too much in depth. </li>
<li><a href="https://kotlinlang.org/docs/reference/" rel="nofollow noreferrer">Kotlin Reference Page</a> - After learning some basics, dig deeper with the page that provides a complete reference to the Kotlinn language and the standard library.
<ul>
<li><a href="https://kotlinlang.org/docs/reference/coding-conventions.html" rel="nofollow noreferrer">Coding Conventions for the Kotlin Programming Language</a></li>
</ul></li>
<li><a href="https://hackr.io/tutorials/learn-kotlin?sort=upvotes&tags%5B%5D=1" rel="nofollow noreferrer"><code>hackr.io</code> free courses on Kotlin</a></li>
</ul>
<h2>Day-to-day resources</h2>
<ul>
<li><a href="https://kotlinlang.org/docs/kotlin-docs.pdf" rel="nofollow noreferrer">Official Kotlin documentation PDF</a></li>
<li><a href="https://kotlinlang.org/api/latest/jvm/stdlib/index.html" rel="nofollow noreferrer">Kotlin API documantation</a></li>
</ul>
<h2>Books and other resources</h2>
<ul>
<li><a href="https://www.manning.com/books/kotlin-in-action" rel="nofollow noreferrer">Kotlin in Action</a> (Some free chapters)</li>
<li><a href="https://www.youtube.com/results?search_query=Kotlin+on+Android" rel="nofollow noreferrer">YouTube</a> - This search for "Kotlin on Android" provides a variety of high-quality technical talks.</li>
</ul>
<h2>Social channels</h2>
<ul>
<li><a href="https://twitter.com/kotlin" rel="nofollow noreferrer">@kotlin</a> - The official Kotlin Twitter account.</li>
<li><a href="https://kotlinlang.org/community/" rel="nofollow noreferrer">Kotlin Community</a> - A list of offline events anf groups from kotlinlang.org.</li>
<li><a href="http://slack.kotlinlang.org/" rel="nofollow noreferrer">Kotlin Slack</a> - A Slack chat community for Kotlin developers.</li>
<li><a href="http://talkingkotlin.com/" rel="nofollow noreferrer">Talking Kotlin</a> - A bi-monthly podcast on Kotlin and more.</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T12:23:24.013",
"Id": "42584",
"Score": "0",
"Tags": null,
"Title": null
} | 42584 |
Kotlin is a statically typed programming language that compiles to JVM bytecode, JavaScript, or native binaries. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T12:23:24.013",
"Id": "42585",
"Score": "0",
"Tags": null,
"Title": null
} | 42585 |
<p>Program must to find duplicate files (by content) in a given directory(and subdirectories).</p>
<p>I collect all data in <code>Map<Long, ArrayList<String>> map</code> where Key is the size of file and Value is the List of paths to files with the same size.</p>
<pre><code>public static void main(String[] args) {
long start = System.currentTimeMillis();
new FileScanner("/").searchFiles();
System.out.println(System.currentTimeMillis() - start);
}
</code></pre>
<p>I tested program on root directory (Linux) <code>/</code> where total count of files is: <strong>281091</strong>. The time is of scanning: <strong>3131064</strong> milliseconds. In my opinion it's may be more faster.</p>
<pre><code>/boot/grub/biosdisk.mod
/usr/lib/grub/i386-pc/biosdisk.mod
/usr/lib/ruby/vendor_ruby/1.8/rubygems/command_manager.rb
/usr/lib/ruby/1.9.1/rubygems/command_manager.rb
/usr/share/pixmaps/openjdk-7.xpm
/usr/share/app-install/icons/_usr_share_icons_sun-java5.xpm
...
</code></pre>
<p>Also the program make <code>log/files.log</code> files where outputting paths of files the same contents separated groups on one blank line.</p>
<pre><code>import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;
import java.nio.file.Files;
public class FileScanner {
private String path, canonPath;
private static final int BUFFER_SIZE_SMALL = 1024; // 1024 byte
private static final int BUFFER_SIZE_MEDIUM = 1048576; // 1 mb
private static final int BUFFER_SIZE_BIG = 10485760; // 10 mb
private static Logger log = Logger.getLogger(FileScanner.class);
/*
* Data structure where keys is a size of file and
* value is list of canonical path to files the same size
*/
private Map<Long, ArrayList<String>> mapFiles;
/*
* Constructor using the specified path
*/
public FileScanner(String path) {
this.path = path;
mapFiles = new HashMap<>();
}
/*
* Constructor with the specified initial capacity
*/
public FileScanner(String path, int capacity) {
this.path = path;
mapFiles = new HashMap<>(capacity);
}
/*
* Getter and Setter for path
*/
String getPath() {
return path;
}
void setPath(String path) {
this.path = path;
}
/*
* Get canonical path from File
*/
private String toCanonicalPath(File file) {
try {
canonPath = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
return canonPath;
}
/*
* Get an input stream that reads bytes from a file
*/
protected InputStream getInputStream(File file) throws FileNotFoundException {
return new BufferedInputStream(new FileInputStream(file));
}
/*
* Define buffer size by file length
*/
protected int defineBufferLength(long length) {
if (length < BUFFER_SIZE_MEDIUM) // file size less than 1mb
return BUFFER_SIZE_SMALL; // 1bt
if (length < BUFFER_SIZE_BIG) // file size less than 10mb
return BUFFER_SIZE_SMALL * 10; // 10bt
if (length < BUFFER_SIZE_BIG * 10) // file size less than 100mb
return BUFFER_SIZE_MEDIUM; // 1mb
if (length < BUFFER_SIZE_BIG * 100) // file size less than 1gb
return BUFFER_SIZE_BIG; // 10mb
return BUFFER_SIZE_BIG * 10; // 100mb
}
/*
* Search similar files by length in the directory and subdirectories
*/
private void scanner(String path) {
File[] subDirs = new File(path).listFiles(new FileFilter() {
@Override
public boolean accept(final File file) {
if (file.isFile() && file.canRead()) {
long size = file.length(); // length of the file is a key in map
if (mapFiles.containsKey(size))
mapFiles.get(size).add(toCanonicalPath(file));
else mapFiles.put(size, new ArrayList<String>(25) {{
add(toCanonicalPath(file));
}});
return false;
}
return file.isDirectory() && file.canRead() && !Files.isSymbolicLink(file.toPath());
}
});
for (int i = 0; i < subDirs.length; i++)
scanner(toCanonicalPath(subDirs[i]));
}
/*
* Compare binary files
*/
protected boolean compareFiles(String path1, String path2) {
if (path1.equals(path2)) return false;
boolean isSimilar = true;
final File f1 = new File(path1), f2 = new File(path2);
int size = defineBufferLength(f1.length());
byte[] bytesF1 = new byte[size], bytesF2 = new byte[size];
try (InputStream in1 = getInputStream(f1); InputStream in2 = getInputStream(f2)) {
while (in1.read(bytesF1) != -1 && in2.read(bytesF2) != -1) {
if (!Arrays.equals(bytesF1, bytesF2)) {
isSimilar = false;
break;
}
}
} catch (IOException e) {
log.error("Error:", e);
}
return isSimilar;
}
public void searchFiles() {
scanner(path);
for (ArrayList<String> paths : mapFiles.values()) {
if (paths.size() == 1) continue;
for (int i = 0; i < paths.size(); i++) {
String path1 = paths.get(i);
boolean isFound = false;
for (int j = 0; j < paths.size(); j++) {
String path2 = paths.get(j);
if (compareFiles(path1, path2)) {
log.info(path2);
paths.remove(path2);
isFound = true;
}
}
if (isFound) log.info(path1 + "\n");
paths.remove(path1);
}
}
}
}
</code></pre>
<p>How I can optimize any pieces of code or algorithm to be as fast as possible ?</p>
| [] | [
{
"body": "<p>Another approach: Currently if you have three big files (with the same size) the algorithm will compare A with B and A with C. It reads A twice which could be avoided. Read each file once, store a hash value (MD5, SHA1, etc.) of the content and compare the hash only.</p>\n\n<p>About the current implementation: If I'm right it contains a bug. In the following code <code>paths.remove(path2)</code> modifies the list during iteration:</p>\n\n<pre><code> for (ArrayList<String> paths : mapFiles.values()) {\n if (paths.size() == 1) continue;\n for (int i = 0; i < paths.size(); i++) {\n String path1 = paths.get(i);\n boolean isFound = false;\n for (int j = 0; j < paths.size(); j++) {\n String path2 = paths.get(j);\n if (compareFiles(path1, path2)) {\n log.info(path2);\n paths.remove(path2);\n isFound = true;\n }\n }\n if (isFound) log.info(path1 + \"\\n\");\n paths.remove(path1);\n }\n }\n</code></pre>\n\n<p>I've created a directory with four files with the same content. It looks to me that the code does not read one of them. (I've put a log statement before <code>compareFiles</code> call.)</p>\n\n<p>Some other notes about the code:</p>\n\n<ol>\n<li><p>Instead of</p>\n\n<pre><code>private final Map<Long, ArrayList<String>> mapFiles;\n</code></pre>\n\n<p>use a <code>Multimap</code>. Guava has great implementations. (<a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained\">Doc</a>, <a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap\">Javadoc</a>)</p></li>\n<li><p><code>canonPath</code> should be a local variable inside <code>toCanonicalPath</code> since no other method uses it.\nFurthermore, currently in case of an error the method returns the path of the previous file. It looks like a bugs.</p></li>\n<li><p>Comments like this almos unnecessary:</p>\n\n<pre><code>/*\n * Get canonical path from File\n */\nprivate String toCanonicalPath(final File file) { ... }\n</code></pre>\n\n<p>It says nothing more that the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>In the <code>FileFilter</code> subclass you could use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">guard clauses</a> to flatten the arrow code.</p></li>\n<li><p>I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:33:30.447",
"Id": "73396",
"Score": "0",
"body": "But I don't have exceptions: `java.util.ConcurrentModificationException`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:37:37.757",
"Id": "73398",
"Score": "3",
"body": "@DozortsevAnton - the issue is not that obvious.... You are not using an iterator , but `for (int j = 0; j < paths.size(); j++) {` ... then, if you later do `paths.remove(path1)`, and that removes something before `j`, then you will skip a member in the loop because everything shuffles forward by one (what was at `j+1` is now at `j`, so on the next loop, that member is skipped)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:57:43.780",
"Id": "73400",
"Score": "1",
"body": "@rolfl You right the loop have bug."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:27:13.137",
"Id": "42588",
"ParentId": "42587",
"Score": "7"
}
},
{
"body": "<p>For your performance problems, taking nearly an hour really is a problem.</p>\n\n<p>The reality is that your code is not the biggest problem, but the overall algorithm.... Making parts of your code faster will not do much, but making your code do things in different ways will help.</p>\n\n<h2>Non-performance problems</h2>\n\n<ul>\n<li><p>the path on the FileScanner should not be modifiable... it should be a final variable, and there should not be a setter.</p></li>\n<li><p>palacsint has already pointed out a bug, but that just means that you may not be finding all the duplicates. </p></li>\n<li><p>There is another bug in your code:</p>\n\n<blockquote>\n<pre><code> while (in1.read(bytesF1) != -1 && in2.read(bytesF2) != -1) {\n\n if (!Arrays.equals(bytesF1, bytesF2)) {\n isSimilar = false;\n break;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This code assumes that the <code>InputStream.read(...)</code> function will read as much data as possible.... which is just not true.</p>\n\n<blockquote>\n <p>Reads up to b.length bytes of data from this input stream into an array of bytes.</p>\n</blockquote>\n\n<p>Note the 'up to'... I have found that occasionally the system will not read them all, but just as much as is convenient.</p>\n\n<p>Your code will need to save away the actual number of bytes read, and adjust the compare process accordingly.....</p></li>\n</ul>\n\n<h2>Performance</h2>\n\n<p>The parts of your code that I can see as being a performance problem are</p>\n\n<ul>\n<li><p><strong>compareFiles()</strong> you should not be reading from two files at the same time. This will require (if the files are large) the disk to be reading from two places at once. Consider using a hashing function to read one file fully, hash it (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html#getInstance%28java.lang.String%29\">say SHA-256</a>), and then read the other file fully. This will reduce the amount of head-scanning the disk has to do.</p>\n\n<pre><code>MessageDigest sha256 = MessageDigest.getInstance(\"SHA-256\");\n.....\n\nint len = 0;\nsha256.reset();\nwhile ((len = stream.read(buffer)) >= 0) {\n sha256.update(buffer, 0, len);\n}\nbyte[] filehash = sha256.digest();\n</code></pre>\n\n<p>If it was me I would compare both the first 16 or so bytes of the file and also the hash of the file. It <strong>is</strong> possible for there to be a hash collision (a extremely, extremely remote possibility), but the possiblity of two files that are different, but have both the same hash, and the same first 16 bytes is even more remote.</p>\n\n<p>So, I would create a function that appends the file hash, and the first 16 bytes together, and calls that the file fingerprint.... If the fingerprints of two same-sized files are the same, then the files are the same.</p></li>\n<li><p><strong>scanner()</strong> The scanner is using a relatively slow process.... you should consider using the new and faster <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/package-frame.html\">java.nio.file</a> classes (spcifically a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#walkFileTree%28java.nio.file.Path,%20java.nio.file.FileVisitor%29\">Files.walkFileTree(...)</a>) new in Java7. This is your best bet.</p>\n\n<p>Additionally, when looping, calling the method <code>toCanonicalPath()</code> on every file is a problem. I would recommend that you do not do that until you have files that are the same size.... it is a very slow thing to do, and is probably a huge part of your performance problem. Doing it only on files that are the same size will save a lot of work.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:26:31.167",
"Id": "73402",
"Score": "0",
"body": "Grateful for your good answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:09:36.633",
"Id": "42592",
"ParentId": "42587",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "42588",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:03:30.490",
"Id": "42587",
"Score": "7",
"Tags": [
"java",
"optimization",
"performance"
],
"Title": "Optimization of file scanner"
} | 42587 |
<p>I have written an implementation of the merge sort algorithm in Java.</p>
<p>Here is the <code>MergeSort</code> class that I created.</p>
<pre><code>public class MergeSort{
public static void sort(Comparable[] a){
Comparable[] b = new Comparable[a.length];
sort(a, b, 0, a.length-1);
}
private static void sort(Comparable[] a, Comparable[] b, int lo, int hi){
if(lo>=hi) return;
int mid = lo+(hi-lo)/2;
sort(a, b, lo, mid);
sort(a, b, mid+1, hi);
merge(a, b, lo, hi, mid);
}
private static void merge(Comparable[] a, Comparable[] b, int lo, int hi, int mid){
int i=lo;
int j=mid+1;
for(int k=lo;k<=hi;k++){
if(i<=mid && j<=hi){
if(a[i].compareTo(a[j])>0) {b[k]=a[j++];continue;}
else if(a[i].compareTo(a[j])<0) {b[k]=a[i++]; continue;}
else {
b[k]=a[i++];
j++;
continue;
}
}
if(j>hi && i<=mid) {b[k]=a[i++];continue;}
if(i>mid && j<=hi) {b[k]=a[j++];continue;}
}
for(int n=lo;n<=hi;n++){
a[n]=b[n];
}
}
}
</code></pre>
<p>The code passed some simple tests. I wonder is there anything wrong or missing out? Anywhere to improve?</p>
| [] | [
{
"body": "<h2>Generics</h2>\n\n<p>In Java, it is not safe to create an array of a generic type. This is what you are doing...</p>\n\n<p><code>Comparable</code> is really <code>Comparable<T></code>, and you are creating an array of <code>Comparable[]</code>.</p>\n\n<p>Because the generic types get removed when you compile the code (see <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/erasure.html\" rel=\"nofollow\">Type Erasure</a>), there is no safe way for Java to ensure that you have the same types of data in your array.</p>\n\n<p>For example, you could have specified your input as:</p>\n\n<pre><code>Integer[] data = new Integer[10];\n</code></pre>\n\n<p>Then, even though it is an array of Integer, the java compiler only knows it is an array of Comparable, so it can allow you to say <code>data[0] = \"broken\";</code>, but that will fail, at runtime, because you cannot put a String in to an array of Integer. because Java can only tell <strong>at runtime</strong> whether the data is valid input to a Generically typed array, it warns you whenever you use one.</p>\n\n<p>This leads to ugly warnings. The right solution is to use an appropriately typed collection <code>List<Integer> data</code> will be type-checkable at compile time, and java can 'do things right'.</p>\n\n<p>An alternate solution is to specify the full type of the Comparable as part of the method definition (a Generic Method... ):</p>\n\n<pre><code>public static <T extends Comparable<?>> void sort(T[] a){\n ....\n}\n</code></pre>\n\n<p>... and then follow that same generic method in to your inner methods </p>\n\n<p>It is complicated. There is some reference material here:</p>\n\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays\" rel=\"nofollow\">Cannot create arrays of Parameterized Types</a></li>\n<li><a href=\"http://docs.oracle.com/javase/tutorial/extra/generics/methods.html\" rel=\"nofollow\">Generic Methods</a></li>\n</ul>\n\n<h2>Style</h2>\n\n<p>You are not using white-space to help make things readable. Consider this line of code:</p>\n\n<blockquote>\n<pre><code> int mid = lo+(hi-lo)/2;\n</code></pre>\n</blockquote>\n\n<p>This should be:</p>\n\n<pre><code> int mid = lo + (hi - lo) / 2;\n</code></pre>\n\n<p>See the java <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html#682\" rel=\"nofollow\">Code-Style guidelines</a> for this:</p>\n\n<blockquote>\n <p>All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (\"++\"), and decrement (\"--\") from their operands</p>\n</blockquote>\n\n<p>Additionally, you have a number of complex 1-liners that should be split on to multiple lines:</p>\n\n<blockquote>\n<pre><code> if(i>mid && j<=hi) {b[k]=a[j++];continue;}\n</code></pre>\n</blockquote>\n\n<p>That should be:</p>\n\n<pre><code> if(i > mid && j <= hi) {\n b[k]=a[j++];\n continue;\n }\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p><strong>MidPoint</strong></p>\n\n<p>You have also copied your code from some reference texts, or otherwise done some mid-point research:</p>\n\n<blockquote>\n<pre><code>int mid = lo+(hi-lo)/2\n</code></pre>\n</blockquote>\n\n<p>This mechanism for getting the mid point of the array is the right pattern to use. Anyone who does it this way is either <a href=\"http://googleresearch.blogspot.ca/2006/06/extra-extra-read-all-about-it-nearly.html\" rel=\"nofollow\">copying the code, has run in to the bug, or has been well-educated</a>. This is a <em>good thing</em>, but, in case you did not know why you were doing it this way, now you know.</p>\n\n<p><strong>Bug</strong></p>\n\n<p>I believe you have a bug in the code when you have two values the same, one in each part of the merge....</p>\n\n<p>... part of the reason this is hard to see is because your code is often doing more than one thing on each line:</p>\n\n<blockquote>\n<pre><code> if(a[i].compareTo(a[j])>0) {b[k]=a[j++];continue;} \n else if(a[i].compareTo(a[j])<0) {b[k]=a[i++]; continue;}\n else {\n b[k]=a[i++];\n j++;\n continue;\n }\n</code></pre>\n</blockquote>\n\n<p>If I space out that code block, there are a number of things in there that are apparent:</p>\n\n<pre><code> if(a[i].compareTo(a[j]) > 0) {\n b[k]=a[j++];\n continue;\n } else if(a[i].compareTo(a[j]) < 0) {\n b[k]=a[i++];\n continue;\n } else {\n b[k]=a[i++];\n j++;\n continue;\n }\n</code></pre>\n\n<p>First up, for some <code>Comparable</code> classes the <code>compareTo</code> method can be expensive. and, you will be doing it twice for many checks. You should do it once, and save away the result:</p>\n\n<pre><code>int comparison = a[i].compareTo(a[j])\nif (comparison > 0) {\n ...\n} else if (comparison < 0) {\n ...\n} else {\n ...\n}\n</code></pre>\n\n<p>OK, back to the bug.... in the final else block, you have:</p>\n\n<blockquote>\n<pre><code> } else {\n b[k]=a[i++];\n j++;\n continue;\n }\n</code></pre>\n</blockquote>\n\n<p>This block increments <strong>both</strong> the <code>i</code> and the <code>j</code> pointers, but it only adds the <code>i</code> value to the merged set, which means the equal value at <code>j</code> is 'lost'.</p>\n\n<p>There are two ways to solve this, but I prefer treating the equals values as if the one is larger than the other.... if you convert the one comparison check to be <code>>= 0</code> instead of just <code>> 0</code>, you will successfully merge results.... then you can get rid of the whole last block entirely....</p>\n\n<p>it also means you only need one <code>compareTo</code> check:</p>\n\n<pre><code> if(a[i].compareTo(a[j]) >= 0) {\n b[k]=a[j++];\n continue;\n } else {\n b[k]=a[i++];\n continue;\n }\n</code></pre>\n\n<h2>ReWrite</h2>\n\n<p>I am not one of those people who thinks 'continue' is a bad thing. I like it for the job it can do, but your use of the <code>continue</code> is excessive.... <strong>Every</strong> path through the loop is a 'continue... this is something easily solved with a little planning. Consider this rewrite:</p>\n\n<pre><code>private static void merge(Comparable[] a, Comparable[] b, int lo, int hi,\n int mid) {\n int i = lo;\n int j = mid + 1;\n\n for (int k = lo; k <= hi; k++) {\n if (i <= mid && j <= hi) {\n if (a[i].compareTo(a[j]) >= 0) {\n b[k] = a[j++];\n } else {\n b[k] = a[i++];\n }\n } else if (j > hi && i <= mid) {\n b[k] = a[i++];\n } else if (i > mid && j <= hi) {\n b[k] = a[j++];\n }\n }\n\n for (int n = lo; n <= hi; n++) {\n a[n] = b[n];\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:22:04.510",
"Id": "42615",
"ParentId": "42590",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42615",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T13:33:53.603",
"Id": "42590",
"Score": "3",
"Tags": [
"java",
"mergesort"
],
"Title": "Is there anything to improve in this MergeSort code in Java?"
} | 42590 |
<p>The code is no longer relevant but I want to know how I can make it faster. It uses only about 10% of my CPU. Any advice about best practices, better algorithms, or how to make the existing one faster are welcome. This is purely for the purpose of personal learning.</p>
<pre><code>public class BruteForce {
public static void main(String[] args) throws Exception {
// Password dictionary
FileInputStream fstream = new FileInputStream("C:/list.txt");
BufferedReader BufferedReader1 = new BufferedReader(new InputStreamReader(new DataInputStream(fstream)));
// Read File Line By Line
String input;
long counter = 0;
Long start = System.currentTimeMillis();
while ((input = BufferedReader1.readLine()) != null) {
if(counter%1000000 == 0){
System.out.println(counter + ": " + input);
}
counter++;
// Generate ID using published class
byte[] pub = ppg.Indors.getPublicKey(input);
// We could use getId, but we get a weird signed/unsigned problem
byte[] pub2 = MessageDigest.getInstance("SHA-256").digest(pub);
// Get account ID
BigInteger BigInteger = new BigInteger(1, new byte[]{pub2[7],pub2[6],pub2[5],pub2[4],pub2[3],pub2[2],pub2[1],pub2[0]});
// Request balance for ID
String url = "http://localhost:1811/ppg?request=egtBalance=" + BigInteger.toString();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader BufferedReader2 = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = BufferedReader2.readLine()) != null) {
response.append(inputLine);
}
BufferedReader2.close();
// Check balance bigger than 0
if (!response.toString().contains("balance\":0")) {
System.out.println("Found:" + input);
}
}
System.out.println("Speed (tries/sec): " + counter*1000/(System.currentTimeMillis()-start));
BufferedReader1.close();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:50:11.230",
"Id": "73453",
"Score": "1",
"body": "My recommendation is don't waste your time brute forcing over the network. The bottleneck will never be optimization of code (unless incredibly bad) it will be your connection."
}
] | [
{
"body": "<p>A huge amount of you work is just plain work that has to be done.... (the joys of brute-forcing).</p>\n\n<h2>MessageDigest</h2>\n\n<p>On the other hand, this work is unnecessary:</p>\n\n<pre><code>byte[] pub2 = MessageDigest.getInstance(\"SHA-256\").digest(pub);\n</code></pre>\n\n<p>This should be replaced with:</p>\n\n<pre><code>MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n\nfor (..... ) {\n\n digest.reset();\n byte pub2 = digest.digest(pub);\n</code></pre>\n\n<p>Accessing the security API's in every loop is a lot of wasted time, and MessageDigest classes are designed to be reused.</p>\n\n<h2>Parallelism...</h2>\n\n<p>A lot of the work you do involves getting and managing URL's... this is slow work that can be done in parallel with the hard work of generating the key hashes.</p>\n\n<p>I would recommend one thread that builds a stream of hashes (with the relevant input stored) and feeds them in to a BlockingQueue with a limited queue size... then, have the controlling thread read these off the queue, and 'farm' them out to a number of other threads that create and check the URL's against the server.</p>\n\n<p>The parallelsim could give you orders-of-magnitude performance improvements.... (but will heavily load the server you are bruting...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T05:48:40.247",
"Id": "73483",
"Score": "0",
"body": "Very nice, speed increased in 2 times when I replaced \"MessageDigest\". Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T05:51:27.413",
"Id": "73484",
"Score": "0",
"body": "Parallelism is too hard for me."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:17:28.020",
"Id": "42593",
"ParentId": "42591",
"Score": "11"
}
},
{
"body": "<p>+1 to <em>@rolfl</em> and a few other notes: </p>\n\n<ol>\n<li><p><del>You are creating a new <code>URLConnection</code> in every iteration. I guess it results a new TCP connection too. With a better HTTP library (<a href=\"http://hc.apache.org/httpcomponents-client-4.3.x/index.html\">Apache HttpClient</a>, for example) you could reuse the same connection for multiple HTTP requests and save the time of connection open and close.</del> Sorry, that's not true, <a href=\"http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html\">JDK supports keep-alive</a>.</p></li>\n<li><p>You should close the streams in a <code>finally</code> block or use try-with-resources. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><p>I don't think that you need the thread-safe capability of <code>StringBuffer</code>, so you could use the faster <code>StringBuilder</code>.</p></li>\n<li><p>Furthermore, instead of the while loop you could use <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream,%20java.nio.charset.Charset%29\"><code>IOUtils.toString()</code></a> which also does the buffering for you.</p>\n\n<pre><code>final String response;\nfinal InputStream inputStream = con.getInputStream();\ntry {\n response = IOUtils.toString(inputStream, \"UTF-8\");\n} finally {\n inputStream.close();\n}\n</code></pre></li>\n<li><p>Your statistics could show invalid data because if you change the system date <code>System.currentTimeMillis()</code> will reflect that. I suggest using <code>System.nanoTime()</code> or a stopwatch class (<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html\">Guava</a>, <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html\">Apache Commons</a>).</p></li>\n<li><p>The variable names should be more expressive. For example, <code>BigInteger</code> should express the purpose of the variable. Furthermore, try to follow the <a href=\"http://hc.apache.org/httpcomponents-client-4.3.x/index.html\">Code Conventions for the Java Programming Language</a>.</p></li>\n<li><p>Check <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/LineIterator.html\"><code>LineIterator</code></a> in Apache Commons IO. It would save you a few statements and would provide easier maintenance and better readability.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T05:06:39.460",
"Id": "73482",
"Score": "0",
"body": "Thank you for the notes. I'll try to implement all of them. It will not be easy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:30:23.967",
"Id": "42595",
"ParentId": "42591",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "42593",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:08:47.550",
"Id": "42591",
"Score": "10",
"Tags": [
"java",
"performance"
],
"Title": "Speeding up brute force algorithm"
} | 42591 |
<p>I am very beginning in PHP and Design Patterns. I have been studying the beautiful book "Head first: Design pattern" and I have been working in some of the codes originally presented in Java in order to learn more about PHP-OOP. The code below presents a kind of Observer Pattern. It is working well, however there are still some design choices that bother me? Can one help me improve this piece of code.</p>
<p>Questions:</p>
<ol>
<li><p>Am I using a good PHP practice?</p></li>
<li><p>The entire code seems to be based on the idea that there are three pieces of information that are relevant, namely $temperature, $humidity and $ pressure. However, it seems that this is not a good design, since I may eventually in the future need another piece of information such as for instance pluviometric index... Is there a good way to avoid this kind of dependency?</p></li>
<li><p>Is it a good choice the class <code>currentConditionsDisplay</code> to implement both Observer and <code>DisplayElement</code>? It seems to be another undesirable dependency.</p></li>
<li><p>Are there other kinds of undesirable dependencies?</p></li>
<li><p>Is a better design pattern to define <code>currentConditionsDisplay</code> as <code>static</code>?</p></li>
</ol>
<p>Any help is very welcome.</p>
<pre><code><?php
interface Observer{
public function update($temp,$humidity,$pressure);
}
interface Subject{
public function registerObserver(Observer $o);
public function removeObserver(Observer $o);
public function notifyObserver();
}
interface DisplayElement{
public function display();
}
class WeatherData implements Subject{
private $observers;
private $temperature;
private $humidity;
private $pressure;
public function __construct(){
$this->observers=array();
}
public function registerObserver(Observer $o){
array_push($this->observers,$o);
}
public function removeObserver(Observer $o) {
unset($this->observers["$o"]);
}
public function notifyObserver(){
foreach($this->observers as &$o){
$o->update($this->temperature,$this->humidity,$this->pressure);
}
}
public function measurementsChanged(){
$this->notifyObserver();
}
public function setMeasurements($temperature,$humidity,$pressure){
$this->temperature=$temperature;
$this->humidity=$humidity;
$this->pressure=$pressure;
$this->measurementsChanged();
}
}
class CurrentConditionsDisplay implements Observer, DisplayElement{
private $temperature;
private $humidity;
private $weatherData;
public function __construct(Subject $weatherData){
$this->weatherData=$weatherData;
$weatherData->registerObserver($this); // $this reffers to the currentConditionsDisplay
}
public function display(){
echo "Current conditions: "."$this->temperature"." F degrees and "."$this->humidity"." humidity";
}
public function update($temperature,$humidity,$pressure){
$this->temperature=$temperature;
$this->humidity=$humidity;
$this->display();
}
}
$weatherData=new WeatherData();
$currentConditionsDisplay=new currentConditionsDisplay($weatherData);
$weatherData->setMeasurements(80,60,30.45);
?>
</code></pre>
| [] | [
{
"body": "<ol>\n<li>Your are using the observer-pattern in a right way. The pattern itself is probably one of the most important ones. In PHP it is not used that much though as applications have a rather quick life-cycle. Yet good to know the pattern of course. Some minor remarks about your code though:\n<ul>\n<li>All methods in an <a href=\"http://php.net/manual/en/language.oop5.interfaces.php\" rel=\"nofollow\">interface are public</a>, no need to repeat yourself (in interfaces).</li>\n<li>The name <code>Observer</code> and <code>Subject</code> indicate an use-case independent use. Yet your <code>Observer</code> are coupled to your Weather component. Better names would be <code>WeatherDataObserver</code> and <code>WeatherDataSubject</code>.</li>\n<li>I'd consider it standard to have at least a whitespace between the function's header and the opening bracket: <code>registerObserver(Observer $o) {</code></li>\n<li>Not sure if your <code>WeatherData</code> is actually a service. For me the name <code>WeatherData</code> indicates a set of values, not necessarily the current values. I'd probably rename it to <code>WeatherDataService</code>. </li>\n<li><code>notifyObserver</code> should not be public. I don't want anyone else to trigger (possibly false positives) notifications. Better remove it from the interface too.</li>\n<li><code>measurementsChanged</code> serves no purpose yet. Replace it with <code>notifyObserver</code>.</li>\n</ul></li>\n<li><p>Your concerns are right. If I remember the book correct, they present an alternative approach on this pattern: instead of pushing the changed values to the observers, just inform them something has changed and let them pull the new values from the subject. This changes the signature of your observer to <code>function update(Subject $weatherData)</code> and in the update method of your <code>CurrentConditionsDisplay</code> you get the new values by: </p>\n\n<pre><code>public function update(Subject $subject){\n $this->temperature = $subject->getTemperature();\n // and so on\n}\n</code></pre>\n\n<p>Another approach would be some event'ed one. Send an event-object about what has changed. This pushed the changes to your observers and still avoids dependencies. This approach is a bit more work though. </p></li>\n<li><p>This is a pattern from java user-interfaces (or any views that can update themselves). In PHP you usually don't use this pattern to update user interfaces as PHP can't update the UI :). You'd access the <code>WeatherData</code> directly when rendering the view. Nothing really bad about this here though. </p></li>\n<li>Fine for me from what I can see.</li>\n<li>No. Generally there are very very very few proper uses for static methods. Static methods are completely independent from others and object internal state. Successive calls to static methods should always have the same result (and should be side-effect free), no matter what happened in the application meanwhile. Usually this applies for simple helper functions only (e.g. <code>abs</code> or other math. helpers). Even this could be discussed though. <code>CurrentConditionsDisplay</code> has some internal state though, therefore static is a no-go.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T18:37:01.390",
"Id": "73920",
"Score": "0",
"body": "thank you!!! Is there a list of essencial patterns that one should know in PHP? Let me try: Registry, MCV, Strategy, Template, Command? I heard something about Dependency Injection, but I was not able to find it classified in any book. Is it one of these before-mentioned?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T19:06:00.520",
"Id": "73921",
"Score": "1",
"body": "Its probably a good idea to know \"all\" of them. Pretty much any pattern can be used in PHP. You're going a very good way with the head first book and applying them for PHP :). Dependency Injection is not a pattern but a principle. Basically it says: every class (or constant) you require in you class must either be passed by constructor or by setter. Dependencies should not be created (`new`) or fetched by a global registry (singletone, registry pattern). You are following this principle in your `CurrentConditionsDisplay ` class: the required Subject is passed at construction time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T17:10:45.223",
"Id": "42882",
"ParentId": "42594",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42882",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:27:37.593",
"Id": "42594",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"php5"
],
"Title": "How to deal with some of the dependencies?"
} | 42594 |
<p>For YAML the data serialization standard visit: <a href="http://www.yaml.org/" rel="nofollow">http://www.yaml.org/</a></p>
<p>For YAML the CSS framework visit: <a href="http://www.yaml.de/" rel="nofollow">http://www.yaml.de/</a></p>
<p>Wiki link - <a href="http://en.wikipedia.org/wiki/YAML" rel="nofollow">http://en.wikipedia.org/wiki/YAML</a></p>
<p>Features:</p>
<ul>
<li>Its familiar indented outline and lean appearance make it especially suited for tasks where humans are likely to view or edit data structures, such as configuration files, dumping during debugging, and document headers.</li>
<li>Although well-suited for hierarchical data representation, it also has a compact syntax for relational data as well.</li>
<li>A major part of its accessibility comes from eschewing the use of enclosures like quotation marks, brackets, braces, and open/close-tags, which can be hard for the human eye to balance in nested hierarchies.</li>
</ul>
<p><strong>See also</strong></p>
<ul>
<li><a href="/questions/tagged/json" class="post-tag" title="show questions tagged 'json'" rel="tag">json</a></li>
<li><a href="http://nodeca.github.com/js-yaml/" rel="nofollow">YAML JavaScript Parser</a></li>
<li><a href="http://yaml.org/spec/1.2/spec.html#id2759572" rel="nofollow">Relation to JSON</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:36:45.350",
"Id": "42597",
"Score": "0",
"Tags": null,
"Title": null
} | 42597 |
YAML: YAML Ain't Markup Language. YAML is a human friendly data serialization standard for all programming languages. In some cases it can also refer to YAML: Yet Another Multicolumn Layout. An open source CSS framework. See http://www.yaml.de | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T14:36:45.350",
"Id": "42598",
"Score": "0",
"Tags": null,
"Title": null
} | 42598 |
<p>I am (in the process of) creating a system to store People and their details - names, date of birth (dob), addresses, phone numbers, etc. - and I'm curious how it is best achieved. Below is an an example of some of the SQL code with test data (the PHP classes match the structure in the db):</p>
<pre><code>CREATE TABLE IF NOT EXISTS `person` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(16) DEFAULT NULL,
`forename` varchar(50) DEFAULT NULL,
`middlenames` varchar(50) DEFAULT NULL,
`surname` varchar(50) DEFAULT NULL,
`display` varchar(100) NOT NULL,
`dob` datetime DEFAULT NULL,
`dod` datetime DEFAULT NULL,
`numViews` int(4) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `person` (`id`, `title`, `forename`, `middlenames`, `surname`, `display`, `dob`, `dod`, `views`) VALUES
(1, 'Miss', 'Julie', 'Nicola Louise', 'Smith', 'Mum', '1958-09-21 00:00:00', NULL, 1),
(2, 'Mr', 'David', NULL, 'Jones', 'Dave', '1932-06-19 00:00:00', NULL, 0);
CREATE TABLE IF NOT EXISTS `email` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`contactId` int(10) unsigned DEFAULT NULL,
`address` varchar(250) DEFAULT NULL,
`type` enum('Personal','Work') DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
INSERT INTO `email` (`id`, `contactId`, `address`, `type`) VALUES
(1, 1, 'j.smith@example.com', 'Personal');
CREATE TABLE IF NOT EXISTS `address` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`line1` varchar(50) NOT NULL,
`line2` varchar(50) DEFAULT NULL,
`city` varchar(30) DEFAULT NULL,
`county` varchar(25) DEFAULT NULL,
`postcode` varchar(8) DEFAULT NULL,
`type` enum('Home','Office','Holiday','Other') DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `address` (`id`, `line1`, `line2`, `city`, `county`, `postcode`, `type`) VALUES
(1, '32 Test Road', NULL, 'Some City', NULL, 'PO1 2ST', 'Home'),
(2, '6 High Street', 'New Road', 'Chatham', NULL, 'TN6 8BL', 'Home');
CREATE TABLE IF NOT EXISTS `personaddress` (
`contactId` int(10) unsigned NOT NULL,
`addressId` int(4) unsigned NOT NULL,
PRIMARY KEY (`contactId`,`addressId`),
KEY `addressId` (`addressId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `personaddress` (`contactId`, `addressId`) VALUES
(1, 1),
(2, 2);
</code></pre>
<p>I did move the dob & dod fields into another Personal table, as I realised that at times - such as showing email addresses for a Person - that it wasn't necessary to load the dob & dod fields. However, when I did this and when I then wanted to get People with upcoming birthdays, to display the person's name I either had to load a Person object at the same time or add the <code>display</code> field to the Personal class and join the tables in the SQL - which I really didn't want to do (loose coupling). So I ended up moving the fields back to Person.</p>
<p>So my question is what is the best way of implementing this structure?</p>
<p>Note that in a class I currently have standard <code>getter/setter</code> methods, then additional methods (such as <code>getFullName</code>, <code>getFullLegalName</code>, etc. for Person) and finally methods for db interaction – <code>load</code>, <code>save</code>, etc. I've also been informed that really I should put these other methods into different classes. So my second question (which I suppose is tied to the first really) is should I also have separate classes for different sets of methods?</p>
| [] | [
{
"body": "<p><strong>First Question</strong>: Don't let potential use-cases of your application drive how you model the data. As you experienced, this causes a lot of headache later on. </p>\n\n<p>Extracting the dob & dod for performance reasons is premature in this case. It is absolutely ok to load data even when not sure if it will be required. Every (un-optimized) application has a percentage of data it doesn't load. That's fine until you really experience performance issues. And then this probably is not the bottle neck you are going to optimize first. Loading those two extra values goes almost for free .</p>\n\n<p>If you have larger data-structures (e.g. huge object tress by relations), you can use the lazy-loading pattern for this (which is what many ORM do to avoid joins). This keeps your model intact but avoids loading too much data. Lazy-loading scalars probably is more expensive then just loading them in the first place.</p>\n\n<p><strong>Excursus</strong>: What you tried to do is to model two different roles of the same entity. This is a valid approach some times. Yet this doesn't say the information is not loaded, it's just limiting the available interface. To be able to use its full power, generic functions are required though. An example might look like: </p>\n\n<pre><code>interface Person {\n // shared information\n}\n\ninterface PersonName extends Person {\n // names\n}\n\ninterface PersonDates extends Person {\n // dob & dob\n}\n\npublic find<? extends Person>(int id) {\n return PersonImpl();\n}\n\nclass PersonImpl implements PersonName, PersonDates {\n}\n\nrepository.find<PersonName>(1);\nrepository.find<PersonDates>(1);\n</code></pre>\n\n<p>This is some very expensive pattern though, in terms of complexity and effort to create. You'll rarely use this. Especially as this doesn't make data loading faster. The entity is always loaded completely too. </p>\n\n<p><strong>Second Question</strong>: Well, you know my opinion here :). Separate your model from how it is stored. The repository (its mapper) should be the only one to know how to save the model to the database. </p>\n\n<p><strong>Database structure</strong>: </p>\n\n<ul>\n<li>I prefer to to name tables in plural (as they represent collections). Other do as you. Some kind a personal, stick to one convention though. </li>\n<li>Use InnoDb's foreign keys in your model. They help greatly to enforce data integrity.</li>\n<li>Normalization would require to extract <code>city</code>, <code>postcode</code> and <code>county</code> from your <code>address</code> table into a separate one.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T19:44:47.003",
"Id": "73446",
"Score": "0",
"body": "So are you basically saying (without going into the complex approach) to keep the structre as it is - aside from splitting out `city`, `postcode` and `county` from `address` - and separate the class into object and mapper?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T19:45:45.037",
"Id": "73447",
"Score": "0",
"body": "I was taught that a table name should reflect what a single record represents. So it's `Person` because it represents one person, where as `PersonDates` would reflect multiple dates – `dob` & `dod` – so it should be plural. It's worked for me so I've stuck with it.\n\nI do use foreign keys, but I've had problems deleting tables via phpMyAdmin once foreign keys are defined, so I tend to wait until I'm certain on my structure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:04:43.677",
"Id": "73448",
"Score": "0",
"body": "Yes, it is a solid approach. Split these fields on a database only level though. Splitting them on the model level would introduce a new `City` entity :). About the naming: its something personal really. MySql documentation uses plural too. Imho it really doesn't matter what you do, just stick to it - that's the real important thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:26:45.853",
"Id": "73450",
"Score": "0",
"body": "Thanks.\n\nSo with using mappers, would I still do `$person->save()` - where `Person` just calls the save method of `PersonMapper` or would I have do `PersonMapper::save($person)`?\n\nI did a quick search for 'PHP Mapper' and 'PHP ORM' but all I seem to get is links for software that uses this approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:37:13.353",
"Id": "73451",
"Score": "0",
"body": "I'd be `Repository::save($person)`. The mapper is not responsible for this. It is only responsible for for mapping `Database <-> Model`. The mapper can be part of of the repository (either fully integrated, slightly violating single responsibility, or as an extra class passed to the repository at construction time). As a rule of thumb: the model interacts with the repository only, the mapper is called by the repository only, the repository calls the database as only class."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:27:10.703",
"Id": "42618",
"ParentId": "42599",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:00:44.373",
"Id": "42599",
"Score": "2",
"Tags": [
"php",
"classes"
],
"Title": "Best structure for a Person in PHP classes (and databse)"
} | 42599 |
<p>I'm learning C for mainly for fun and to get a better understanding of how things work under the hood (most of my experience lies with high-level languages). I've been following quite a few books and working through the exercises. For extra practice, I've implemented a linked list using the knowledge I've learned - I thought it might be useful to get some feedback on it!</p>
<p>I plan to make this generic and work with any type once I learn how to do this :)</p>
<p>I desire any and all feedback. Especially feedback that pushes me in the right direction (except for 'give up'!)</p>
<p>llist.h:</p>
<pre><code>#ifndef __llist_
#define __llist_
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#define LLMSG_ELISTNULL "List cannot be NULL"
#define LLMSG_EHEADNULL "Head cannot be NULL - list corrupted"
#define LLMSG_ENODENULL "Node cannot be NULL"
#define LLMSG_ENEWNULL "New node cannot be NULL"
typedef struct _llist_node {
struct _llist_node *next;
int value;
} llist_node;
typedef struct _llist {
struct _llist_node *head;
} llist;
/*
constructors & destructor
*/
llist_node *llist_node_create(int value);
llist *llist_create(llist_node *head);
void llist_destroy(llist *list);
/*
insertion
*/
llist *llist_append(llist *list, llist_node *node);
llist *llist_prepend(llist *list, llist_node *node);
llist_node *llist_insert_after(llist_node *node, llist_node *new);
llist_node *llist_insert_before(llist *list, llist_node *node, llist_node *new);
/*
removal
*/
llist *llist_remove_head(llist *list);
llist_node *llist_remove_after(llist_node *node);
llist *llist_remove(llist *list, llist_node *node);
#endif
</code></pre>
<p>llist.c:</p>
<pre><code>#include "llist.h"
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
llist_node *llist_node_create(int value) {
llist_node *node = malloc(sizeof(llist_node));
if (! node) {
errno = ENOMEM;
return NULL;
}
node->value = value;
node->next = NULL;
return node;
}
llist *llist_create(llist_node *head) {
assert(head != NULL && LLMSG_ENODENULL);
llist *list = malloc(sizeof(llist));
if (list == NULL) {
errno = ENOMEM;
return NULL;
}
list->head = head;
return list;
}
void llist_destroy(llist *list) {
assert(list != NULL && LLMSG_ELISTNULL);
// do not proceed if list container corrupt
if (list->head != NULL) {
llist_node *head = list->head;
llist_node *next;
llist_node *next_next;
// free rest of list first
if (head->next != NULL) {
next = head->next;
while (next != NULL) {
next_next = next->next;
free(next);
next = next_next;
}
}
if (head != NULL) {
free(head);
}
}
free(list);
}
llist *llist_append(llist *list, llist_node *node) {
assert(list != NULL && LLMSG_ELISTNULL);
assert(node != NULL && LLMSG_EHEADNULL);
assert(list->head != NULL && LLMSG_EHEADNULL);
llist_node *next;
if (list->head->next == NULL) {
list->head->next = node;
}
else {
for (next = list->head->next; next != NULL; next = next->next) {
if (next->next == NULL) {
next->next = node;
break;
}
}
assert(next->next == node && "Failed to insert node to end of list");
}
return list;
}
llist *llist_prepend(llist *list, llist_node *node) {
assert(list != NULL && LLMSG_ELISTNULL);
assert(node != NULL && LLMSG_ENODENULL);
assert(list->head != NULL && LLMSG_EHEADNULL);
llist_node *head = list->head;
list->head = node;
node->next = head;
return list;
}
llist_node *llist_insert_after(llist_node *node, llist_node *new) {
assert(node != NULL && LLMSG_ENODENULL);
assert(new != NULL && LLMSG_ENEWNULL);
llist_node *next = node->next;
node->next = new;
new->next = next;
return new;
}
llist_node *llist_insert_before(llist *list, llist_node *node, llist_node *new) {
assert(list != NULL && LLMSG_ELISTNULL);
assert(node != NULL && LLMSG_ENODENULL);
assert(new != NULL && LLMSG_ENEWNULL);
llist_node *curr = list->head;
while (curr->next != NULL) {
if (node == curr->next) {
curr->next = new;
new->next = node;
break;
}
curr = curr->next;
}
return new;
}
llist *llist_remove_head(llist *list) {
assert(list != NULL && LLMSG_ELISTNULL);
llist_node *head = list->head;
if (list->head->next) {
list->head = list->head->next;
}
free(head);
return list;
}
llist_node *llist_remove_after(llist_node *node) {
assert(node != NULL && LLMSG_ENODENULL);
if (node->next != NULL) {
llist_node *delete = node->next;
node->next = node->next->next;
free(delete);
}
return node;
}
llist *llist_remove(llist *list, llist_node *node) {
assert(list != NULL && LLMSG_ELISTNULL);
assert(node != NULL && LLMSG_ENODENULL);
llist_node *curr = list->head;
while (curr->next != NULL) {
if (node == curr->next) {
curr = llist_remove_after(curr);
break;
}
curr = curr->next;
}
return list;
}
</code></pre>
<p>linked-list.c (test output for each operation):</p>
<pre><code>#include <stdio.h>
#include "llist.h"
int main() {
llist *list = llist_create(llist_node_create(1));
list = llist_append(list, llist_node_create(2));
list = llist_append(list, llist_node_create(3));
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
list = llist_prepend(list, llist_node_create(-1));
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
printf("4: %d\n", list->head->next->next->next->value);
llist_insert_after(list->head->next, llist_node_create(400));
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
printf("4: %d\n", list->head->next->next->next->value);
printf("5: %d\n", list->head->next->next->next->next->value);
llist_insert_before(list, list->head->next->next, llist_node_create(500));
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
printf("4: %d\n", list->head->next->next->next->value);
printf("5: %d\n", list->head->next->next->next->next->value);
printf("6: %d\n", list->head->next->next->next->next->next->value);
list = llist_remove_head(list);
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
printf("4: %d\n", list->head->next->next->next->value);
printf("5: %d\n", list->head->next->next->next->next->value);
list = llist_remove(list, list->head->next->next);
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
printf("4: %d\n", list->head->next->next->next->value);
list->head = llist_remove_after(list->head);
printf("1: %d\n", list->head->value);
printf("2: %d\n", list->head->next->value);
printf("3: %d\n", list->head->next->next->value);
llist_destroy(list);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p><strong>Making it type-generic</strong></p>\n\n<p>The key to making it generic is in the ll add function. This should take the size of the object you want to add, and a pointer to the data member:</p>\n\n<p><code>llist_node *llist_node_create(void * pData, uint size);</code></p>\n\n<p>And then the implementation becomes:</p>\n\n<pre><code>typedef struct llist_node { pNext, char data[1] };\nllist_node *llist_node_create(void * pData, uint dataSize)\n{\n // -1 so you don't waste a byte of memory when copying over\n llist_node * pNewNode = malloc(sizeof(llist_node -1) + dataSize);\n memcpy(&pNewNode->data, pData, dataSize);\n return pNewNode;\n}\n</code></pre>\n\n<p>This relies on whatever is calling the library knowing about the type/size of data object.</p>\n\n<p><strong>Encapsulation</strong></p>\n\n<p>Also, if you want to increase encapsulation, implement a <code>void * llist_GetDataElement(llist_node * llistEle);</code> function. This means you can hide the implementation details (i.e. the internal structure of your llist_node), and hence you could easily change it over to say, a fixed array, as opposed to malloc, based implementation etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:13:50.017",
"Id": "42624",
"ParentId": "42600",
"Score": "4"
}
},
{
"body": "<p>It looks good.</p>\n\n<hr>\n\n<pre><code>#ifndef __llist_\n</code></pre>\n\n<p>Avoid using leading underscores: <a href=\"https://stackoverflow.com/a/228797/49942\">they are reserved</a>.</p>\n\n<hr>\n\n<pre><code>#include <stdlib.h>\n#include <errno.h>\n#include <assert.h>\n</code></pre>\n\n<p>Code which includes your <code>llist.h</code> therefore includes <code><stdlib.h></code> etc., which makes compilation slower. Put as little as you can in your public header file; you could include those in your <code>llist.c</code> instead.</p>\n\n<hr>\n\n<pre><code>typedef struct _llist_node {\n struct _llist_node *next;\n int value;\n} llist_node;\n\ntypedef struct _llist {\n struct _llist_node *head;\n} llist;\n\n/* \n constructors & destructor\n*/\nllist_node *llist_node_create(int value);\nllist *llist_create(llist_node *head);\n</code></pre>\n\n<p>Continuing to minimize the contents of the header file, you can use an \"<a href=\"http://en.wikipedia.org/wiki/Opaque_pointer#C\" rel=\"nofollow noreferrer\">opaque pointer</a>\" (a.k.a. \"handle\" a.k.a. \"cheshire cat\") by declaring the following instead ...</p>\n\n<pre><code>struct llist_node;\n\nstruct llist;\n\n/* \n constructors & destructor\n*/\nstruct llist_node *llist_node_create(int value);\nstruct llist *llist_create(struct llist_node *head);\n</code></pre>\n\n<p>... and define the structs in your C file. After all, client code doesn't/shouldn't need to know what's inside your structs.</p>\n\n<p>To do that you would also need another function to get the value out of a node:</p>\n\n<pre><code>int llist_node_read_value(struct llist_node *node); // implemented as return node->value\n</code></pre>\n\n<p>Maybe an opaque pointer is 'overkill' in this simple example but it's a useful technique:</p>\n\n<ul>\n<li>Less in the header file makes it easier for clients to understand the public API</li>\n<li>Less in the header file makes it harder for clients to poke into private details (e.g. writing into your data structures</li>\n<li>May avoid recompiling client code when/if the layout/content of your struct changes (e.g. if your module is shipped as a static- or dynamic-linked library)</li>\n</ul>\n\n<hr>\n\n<pre><code>llist_node *llist_insert_after(llist_node *node, llist_node *new);\nllist_node *llist_insert_before(llist *list, llist_node *node, llist_node *new);\n</code></pre>\n\n<p>I understand why one needs a <code>llist *list</code> parameter and the other doesn't, but it looks odd.</p>\n\n<p>In llist_insert_after you don't check that node is on a list. When you add a created node to the list you assume that its <code>next</code> pointer is null.</p>\n\n<p>However your API allows user code to do:</p>\n\n<pre><code>llist_node *first = llist_node_create(1);\nllist *list = llist_create(first);\nllist_node *second = llist_node_create(2);\nllist_node *third = llist_node_create(3);\n// this works even though second isn't a member of a list\nllist_insert_after(second, third);\n// this works badly because second->next is not null\nllist_insert_before(list, first, second);\n</code></pre>\n\n<hr>\n\n<p>I don't understand why llist_append and llist_prepend return a pointer to llist instead of a pointer to llist_node.</p>\n\n<hr>\n\n<pre><code>void llist_destroy(llist *list) {\n assert(list != NULL && LLMSG_ELISTNULL);\n\n // do not proceed if list container corrupt\n if (list->head != NULL) {\n llist_node *head = list->head;\n llist_node *next;\n llist_node *next_next;\n\n // free rest of list first\n if (head->next != NULL) {\n next = head->next;\n while (next != NULL) {\n next_next = next->next;\n free(next);\n next = next_next;\n }\n }\n\n if (head != NULL) {\n free(head);\n }\n }\n\n free(list);\n}\n</code></pre>\n\n<p>It's better to avoid/delay declaring a local variable until (later) the moment when you can first assign a value to it; so, the following would be clearer:</p>\n\n<pre><code>void llist_destroy(llist *list) {\n assert(list != NULL && LLMSG_ELISTNULL);\n\n // do not proceed if list container corrupt\n if (list->head != NULL) {\n llist_node *head = list->head;\n\n // free rest of list first\n if (head->next != NULL) {\n llist_node *next = head->next;\n while (next != NULL) {\n llist_node *next_next = next->next;\n free(next);\n next = next_next;\n }\n }\n\n if (head != NULL) {\n free(head);\n }\n }\n\n free(list);\n}\n</code></pre>\n\n<hr>\n\n<p>Your list_remove methods silently do nothing (instead of loudly failing) if they fail to remove the requested node.</p>\n\n<p>Consider coding your <code>void llist_destroy(llist *list);</code> function as <code>void llist_destroy(llist **list_ptr);</code> instead, so that its last statement can be <code>*list_ptr = 0</code> to try to ensure that the user/caller can't try to use (dereference) the list memory after it has been freed.</p>\n\n<hr>\n\n<blockquote>\n <p>linked-list.c (test output for each operation):</p>\n</blockquote>\n\n<p>Your testing could be a bit more thorough, for example:</p>\n\n<ul>\n<li>Remove enough elements to completely empty the list and then verify that you can add more</li>\n<li>Destroy an empty list and destroy a non-empty list</li>\n<li>Append after one element in the list and prepend before one element in the list</li>\n<li>Decide whether you want to detect user errors (e.g. inserting a null pointer) and if so test that</li>\n</ul>\n\n<hr>\n\n<p>Your use of messages like LLMSG_ELISTNULL in assert functions was new to me (I hadn't seen that before).</p>\n\n<hr>\n\n<p>You don't have any methods to do anything useful with the list: for example, to search the list to see whether it contains a specific value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-02T22:59:08.043",
"Id": "137430",
"Score": "0",
"body": "I'm not sure that `llist_prepend()` and `llist_append()` require a return value at all. If the \"instance\" of `llist` being modified is provided, doesn't it not matter if a return to the list's node or the list itself is returned at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-02T23:07:31.230",
"Id": "137432",
"Score": "1",
"body": "Returning a pointer to the newly-created node lets the caller do things to that node (e.g. subsequently delete the node from the list)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-02T23:29:13.893",
"Id": "137437",
"Score": "0",
"body": "One more question. Where the program is checking for memory errors does it make sense to return `NULL`? Doesn't that put the impetus on the programmer to then deal with that error? Instead, shouldn't the program exist because none of the functions that follow adequately handle a Node or List with a `NULL` entry?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-03T00:23:45.310",
"Id": "137451",
"Score": "1",
"body": "It makes sense to check for errors, because when errors are detected 'as soon as possible' that's makes them easier to debug. When a library finds an error, returning an error value (e.g. NULL) is problematic if (and only if) the calling program doesn't test for that error value: and that's a reason why C++ supports throwing exceptions instead. I don't have time for a good, long answer. I suggest you post a question on Programmers.SE and/or ask about this in [the Chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T22:30:32.093",
"Id": "42627",
"ParentId": "42600",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:04:44.297",
"Id": "42600",
"Score": "5",
"Tags": [
"c",
"linked-list",
"memory-management",
"pointers"
],
"Title": "Linked list implementation in C"
} | 42600 |
<p>Here is a very basic Snake game in C, which I just want to make better. The game is working perfectly but it is very annoying because when playing it, it is always blinking. I hope that somebody could try it in their compiler to see how annoying it is. How can I improve this?</p>
<p>Here is a screen shot of the game:</p>
<p><img src="https://i.stack.imgur.com/2VXpb.png" alt="enter image description here"> </p>
<p>Of course it works, but I just need some advice about the design.</p>
<pre><code>#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#include<time.h>
#include<ctype.h>
#include <time.h>
#include <windows.h>
#include <process.h>
#include <unistd.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
int length;
int bend_no;
int len;
char key;
void record();
void load();
int life;
void Delay(long double);
void Move();
void Food();
int Score();
void Print();
void gotoxy(int x, int y);
void GotoXY(int x,int y);
void Bend();
void Boarder();
void Down();
void Left();
void Up();
void Right();
void ExitGame();
int Scoreonly();
struct coordinate{
int x;
int y;
int direction;
};
typedef struct coordinate coordinate;
coordinate head, bend[500],food,body[30];
int main()
{
char key;
Print();
system("cls");
load();
length=5;
head.x=25;
head.y=20;
head.direction=RIGHT;
Boarder();
Food(); //to generate food coordinates initially
life=3; //number of extra lives
bend[0]=head;
Move(); //initialing initial bend coordinate
return 0;
}
void Move()
{
int a,i;
do{
Food();
fflush(stdin);
len=0;
for(i=0;i<30;i++)
{
body[i].x=0;
body[i].y=0;
if(i==length)
break;
}
Delay(length);
Boarder();
if(head.direction==RIGHT)
Right();
else if(head.direction==LEFT)
Left();
else if(head.direction==DOWN)
Down();
else if(head.direction==UP)
Up();
ExitGame();
}while(!kbhit());
a=getch();
if(a==27)
{
system("cls");
exit(0);
}
key=getch();
if((key==RIGHT&&head.direction!=LEFT&&head.direction!=RIGHT)||(key==LEFT&&head.direction!=RIGHT&&head.direction!=LEFT)||(key==UP&&head.direction!=DOWN&&head.direction!=UP)||(key==DOWN&&head.direction!=UP&&head.direction!=DOWN))
{
bend_no++;
bend[bend_no]=head;
head.direction=key;
if(key==UP)
head.y--;
if(key==DOWN)
head.y++;
if(key==RIGHT)
head.x++;
if(key==LEFT)
head.x--;
Move();
}
else if(key==27)
{
system("cls");
exit(0);
}
else
{
printf("\a");
Move();
}
}
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void GotoXY(int x, int y)
{
HANDLE a;
COORD b;
fflush(stdout);
b.X = x;
b.Y = y;
a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(a,b);
}
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
void load(){
int row,col,r,c,q;
gotoxy(36,14);
printf("loading...");
gotoxy(30,15);
for(r=1;r<=20;r++){
sleep(200);//to display the character slowly
printf("%c",177);}
getch();
}
void Down()
{
int i;
for(i=0;i<=(head.y-bend[bend_no].y)&&len<length;i++)
{
GotoXY(head.x,head.y-i);
{
if(len==0)
printf("v");
else
printf("*");
}
body[len].x=head.x;
body[len].y=head.y-i;
len++;
}
Bend();
if(!kbhit())
head.y++;
}
void Delay(long double k)
{
Score();
long double i;
for(i=0;i<=(10000000);i++);
}
void ExitGame()
{
int i,check=0;
for(i=4;i<length;i++) //starts with 4 because it needs minimum 4 element to touch its own body
{
if(body[0].x==body[i].x&&body[0].y==body[i].y)
{
check++; //check's value increases as the coordinates of head is equal to any other body coordinate
}
if(i==length||check!=0)
break;
}
if(head.x<=10||head.x>=70||head.y<=10||head.y>=30||check!=0)
{
life--;
if(life>=0)
{
head.x=25;
head.y=20;
bend_no=0;
head.direction=RIGHT;
Move();
}
else
{
system("cls");
printf("All lives completed\nBetter Luck Next Time!!!\nPress any key to quit the game\n");
record();
exit(0);
}
}
}
void Food()
{
if(head.x==food.x&&head.y==food.y)
{
length++;
time_t a;
a=time(0);
srand(a);
food.x=rand()%70;
if(food.x<=10)
food.x+=11;
food.y=rand()%30;
if(food.y<=10)
food.y+=11;
}
else if(food.x==0)/*to create food for the first time coz global variable are initialized with 0*/
{
food.x=rand()%70;
if(food.x<=10)
food.x+=11;
food.y=rand()%30;
if(food.y<=10)
food.y+=11;
}
}
void Left()
{
int i;
for(i=0;i<=(bend[bend_no].x-head.x)&&len<length;i++)
{
GotoXY((head.x+i),head.y);
{
if(len==0)
printf("<");
else
printf("*");
}
body[len].x=head.x+i;
body[len].y=head.y;
len++;
}
Bend();
if(!kbhit())
head.x--;
}
void Right()
{
int i;
for(i=0;i<=(head.x-bend[bend_no].x)&&len<length;i++)
{
//GotoXY((head.x-i),head.y);
body[len].x=head.x-i;
body[len].y=head.y;
GotoXY(body[len].x,body[len].y);
{
if(len==0)
printf(">");
else
printf("*");
}
/*body[len].x=head.x-i;
body[len].y=head.y;*/
len++;
}
Bend();
if(!kbhit())
head.x++;
}
void Bend()
{
int i,j,diff;
for(i=bend_no;i>=0&&len<length;i--)
{
if(bend[i].x==bend[i-1].x)
{
diff=bend[i].y-bend[i-1].y;
if(diff<0)
for(j=1;j<=(-diff);j++)
{
body[len].x=bend[i].x;
body[len].y=bend[i].y+j;
GotoXY(body[len].x,body[len].y);
printf("*");
len++;
if(len==length)
break;
}
else if(diff>0)
for(j=1;j<=diff;j++)
{
/*GotoXY(bend[i].x,(bend[i].y-j));
printf("*");*/
body[len].x=bend[i].x;
body[len].y=bend[i].y-j;
GotoXY(body[len].x,body[len].y);
printf("*");
len++;
if(len==length)
break;
}
}
else if(bend[i].y==bend[i-1].y)
{
diff=bend[i].x-bend[i-1].x;
if(diff<0)
for(j=1;j<=(-diff)&&len<length;j++)
{
/*GotoXY((bend[i].x+j),bend[i].y);
printf("*");*/
body[len].x=bend[i].x+j;
body[len].y=bend[i].y;
GotoXY(body[len].x,body[len].y);
printf("*");
len++;
if(len==length)
break;
}
else if(diff>0)
for(j=1;j<=diff&&len<length;j++)
{
/*GotoXY((bend[i].x-j),bend[i].y);
printf("*");*/
body[len].x=bend[i].x-j;
body[len].y=bend[i].y;
GotoXY(body[len].x,body[len].y);
printf("*");
len++;
if(len==length)
break;
}
}
}
}
void Boarder()
{
system("cls");
int i;
GotoXY(food.x,food.y); /*displaying food*/
printf("F");
for(i=10;i<71;i++)
{
GotoXY(i,10);
printf("!");
GotoXY(i,30);
printf("!");
}
for(i=10;i<31;i++)
{
GotoXY(10,i);
printf("!");
GotoXY(70,i);
printf("!");
}
}
void Print()
{
//GotoXY(10,12);
printf("\tWelcome to the mini Snake game.(press any key to continue)\n");
getch();
system("cls");
printf("\tGame instructions:\n");
printf("\n-> Use arrow keys to move the snake.\n\n-> You will be provided foods at the several coordinates of the screen which you have to eat. Everytime you eat a food the length of the snake will be increased by 1 element and thus the score.\n\n-> Here you are provided with three lives. Your life will decrease as you hit the wall or snake's body.\n\n-> YOu can pause the game in its middle by pressing any key. To continue the paused game press any other key once again\n\n-> If you want to exit press esc. \n");
printf("\n\nPress any key to play game...");
if(getch()==27)
exit(0);
}
void record(){
char plname[20],nplname[20],cha,c;
int i,j,px;
FILE *info;
info=fopen("record.txt","a+");
getch();
system("cls");
printf("Enter your name\n");
scanf("%[^\n]",plname);
//************************
for(j=0;plname[j]!='\0';j++){ //to convert the first letter after space to capital
nplname[0]=toupper(plname[0]);
if(plname[j-1]==' '){
nplname[j]=toupper(plname[j]);
nplname[j-1]=plname[j-1];}
else nplname[j]=plname[j];
}
nplname[j]='\0';
//*****************************
//sdfprintf(info,"\t\t\tPlayers List\n");
fprintf(info,"Player Name :%s\n",nplname);
//for date and time
time_t mytime;
mytime = time(NULL);
fprintf(info,"Played Date:%s",ctime(&mytime));
//**************************
fprintf(info,"Score:%d\n",px=Scoreonly());//call score to display score
//fprintf(info,"\nLevel:%d\n",10);//call level to display level
for(i=0;i<=50;i++)
fprintf(info,"%c",'_');
fprintf(info,"\n");
fclose(info);
printf("wanna see past records press 'y'\n");
cha=getch();
system("cls");
if(cha=='y'){
info=fopen("record.txt","r");
do{
putchar(c=getc(info));
}while(c!=EOF);}
fclose(info);
}
int Score()
{
int score;
GotoXY(20,8);
score=length-5;
printf("SCORE : %d",(length-5));
score=length-5;
GotoXY(50,8);
printf("Life : %d",life);
return score;
}
int Scoreonly()
{
int score=Score();
system("cls");
return score;
}
void Up()
{
int i;
for(i=0;i<=(bend[bend_no].y-head.y)&&len<length;i++)
{
GotoXY(head.x,head.y+i);
{
if(len==0)
printf("^");
else
printf("*");
}
body[len].x=head.x;
body[len].y=head.y+i;
len++;
}
Bend();
if(!kbhit())
head.y--;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:38:31.137",
"Id": "74002",
"Score": "3",
"body": "Just use `gotoxy` instead of clearing the whole screen buffer with `system(\"cls\")` that is why it is flushing all over again when updating. I have done this before :D"
}
] | [
{
"body": "<h1>Things that could be improved:</h1>\n\n<h3>Portability:</h3>\n\n<ul>\n<li><p>Every time you add an <code>#import</code> to the top of your C file, you potentially create a dependency. For example: <code>#include <windows.h></code> creates a dependency that the program can only be compiled on a Windows system.</p>\n\n<blockquote>\n<pre><code>#include <stdio.h>\n#include <time.h>\n#include <stdlib.h>\n#include <conio.h>\n#include <time.h>\n#include <ctype.h>\n#include <time.h>\n#include <windows.h>\n#include <process.h>\n#include <unistd.h>\n</code></pre>\n</blockquote>\n\n<p>You should always try to create a program so that it is as portable as possible, and can be played on a variety of systems. Right now, your game can only be played on a few select systems.</p></li>\n</ul>\n\n<h3>Conventions/Standards:</h3>\n\n<ul>\n<li><p>You don't follow proper C naming conventions for method names.</p>\n\n<blockquote>\n<pre><code>void Delay(long double);\nvoid Move();\nvoid Food();\nint Score();\nvoid Print();\nvoid gotoxy(int x, int y);\nvoid GotoXY(int x,int y);\nvoid Bend();\nvoid Boarder();\nvoid Down();\nvoid Left();\nvoid Up();\nvoid Right();\nvoid ExitGame();\nint Scoreonly();\n</code></pre>\n</blockquote>\n\n<p>Either use <a href=\"https://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow noreferrer\">camelCase</a>, or <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a> with method names.</p></li>\n<li><p>You should have <em>unique</em> method names.</p>\n\n<blockquote>\n<pre><code>void gotoxy(int x, int y);\nvoid GotoXY(int x,int y);\n</code></pre>\n</blockquote>\n\n<p>Be more expressive with your function naming.</p></li>\n<li><p>You don't <code>typedef</code> a <code>struct</code> in the standard way, nor do you use proper naming conventions of <code>typedef struct</code>s.</p>\n\n<blockquote>\n<pre><code>struct coordinate{\n int x;\n int y;\n int direction;\n};\n\ntypedef struct coordinate coordinate;\n</code></pre>\n</blockquote>\n\n<p>You can combine these two together for the proper definition of a <code>typedef struct</code>. Also, you should always capitalize the first letter of the <code>typedef struct</code> name.</p>\n\n<pre><code>typedef struct\n{\n int x;\n int y;\n int direction;\n} Coordinate;\n</code></pre></li>\n<li><p>Don't use a <code>for</code> loop in the place of <code>sleep()</code>.</p>\n\n<blockquote>\n<pre><code>for(i=0;i<=(10000000);i++);\n</code></pre>\n</blockquote>\n\n<p>There are many problems with <a href=\"https://en.wikipedia.org/wiki/Busy_waiting\" rel=\"nofollow noreferrer\">busy waiting</a> instead of using <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>sleep()</code></a>. See <a href=\"https://codereview.stackexchange.com/q/42506/27623\">this question</a> for more information.</p></li>\n<li><p>If you don't take in any variables as parameters, you should declare them as <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>Define <code>i</code> inside of your <code>for</code> loop.<sup>(C99)</sup></p>\n\n<pre><code>for(int i = 4; i < length; i++)\n</code></pre></li>\n</ul>\n\n<h3>Styling:</h3>\n\n<ul>\n<li><p>You have <em>way</em> too much space in some areas of your program. </p>\n\n<blockquote>\n<pre><code>int main()\n{\n\n char key;\n\n Print();\n\n system(\"cls\");\n\n load();\n\n length=5;\n\n head.x=25;\n\n head.y=20;\n\n head.direction=RIGHT;\n\n Boarder();\n\n Food(); //to generate food coordinates initially\n\n life=3; //number of extra lives\n\n bend[0]=head;\n\n Move(); //initialing initial bend coordinate\n\n return 0;\n\n} \n</code></pre>\n</blockquote>\n\n<p>I'm all for using whitespace, but there are limits to everything. Cut back on it a bit, right now the amount of whitespace you are using makes this program unreadable.</p></li>\n</ul>\n\n<h3>Syntax:</h3>\n\n<ul>\n<li><p>You have some <code>#define</code>s that are related to each other.</p>\n\n<blockquote>\n<pre><code>#define UP 72\n#define DOWN 80\n#define LEFT 75\n#define RIGHT 77\n</code></pre>\n</blockquote>\n\n<p>These are all related to each other because they are all directions. Therefore, we can group them together in an <code>enum</code>.</p>\n\n<pre><code>typedef enum\n{\n UP = 72;\n DOWN = 80;\n LEFT = 75;\n RIGHT = 77;\n} Direction;\n</code></pre></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\" rel=\"nofollow noreferrer\"><code>puts()</code></a> instead of <code>printf()</code> when you are not formatting strings.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:09:58.530",
"Id": "42913",
"ParentId": "42602",
"Score": "17"
}
},
{
"body": "<p>The \"annoying blinking\" is probably caused by your calling <code>system(\"cls\");</code> at the top of your <code>Boarder()</code> function, which you call repeatedly from inside your <code>Move()</code> function. It would blink less if you didn't clear the screen every time your redraw the border, and/or if you didn't redraw the border for every move.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:36:07.310",
"Id": "42915",
"ParentId": "42602",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "42913",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T15:18:12.043",
"Id": "42602",
"Score": "15",
"Tags": [
"performance",
"c",
"game",
"snake-game"
],
"Title": "Snake game in C"
} | 42602 |
<p>Here is what I have. I have it outputting most of the sums just so I can check there values. I think the problem is with the value of the elements in the array storing the column sums. I would greatly appreciate any feedback. </p>
<pre><code>#include <iostream>
#include <cmath>
using namespace std;
void fillMatrix(int matrix[][4],const int SIZE);
int rowSum(int matrix[][4],const int SIZE,int row[]);
int columnSum(int matrix[][4], const int SIZE, int column[]);
bool isMagic(int matrix[][4], const int SIZE,int row[],int column[]);
int main()
{
const int SIZE=4;
int matrix[SIZE][SIZE];
int row[4],column[4];//arrays to be filled with row and column sums.
char response=0;
cout<<"This program determines whether or not a 4x4 square matrix is a magic square.\n";
do
{
fillMatrix(matrix,SIZE);
rowSum(matrix,SIZE,row);
columnSum(matrix,SIZE,row);
if(isMagic(matrix,SIZE,row,column))
cout<<"This is a magic square.\n\n";
else {
cout<<"This is not a magic square.\n\n";
}
cout<<"To end this program, enter q. To check another matrix, enter any other letter.\n";
cin>>response;
}while(response!='q'&&response!='Q');
return 0;
}
void fillMatrix(int matrix[][4],const int SIZE)
{
for(int i=0;i<4;i++)
{
cout<<"Enter four values for row "<<i+1<<".\n";
for(int j=0;j<4;j++)
{
cin>>matrix[i][j];
}
}
}
int rowSum(int matrix[][4],const int SIZE,int row[4])
{
int i=0;
int rowsum=0;
for(i=0;i<4;i++)
{
rowsum=0;
for(int j=0;j<4;j++)
{
rowsum+=matrix[i][j];
}
row[i]=rowsum;
cout<<row[i]<<endl;
}
return row[i];
}
int columnSum(int matrix[][4], const int SIZE, int column[4])
{
int j=0;
int columnsum=0;
for(j=0;j<4;j++)
{
columnsum=0;
for(int i=0;i<4;i++)
{
columnsum+=matrix[i][j];
}
column[j]=columnsum;
cout<<column[j]<<endl;
}
return column[j];
}
bool isMagic(int matrix[][4], const int SIZE,int row[4],int column[4])
{
int rightdiagonalsum=0, leftdiagonalsum=0, check;
for(int i=0;i<4;i++)
{
rightdiagonalsum+=matrix[i][i];
}
cout<<rightdiagonalsum<<endl;
for(int i=0;i<4;i++)
{
leftdiagonalsum+=matrix[i][3-i];
}
cout<<leftdiagonalsum<<endl;
for(int i=1;i<4;i++)
{
if (row[i]==row[i-1])
{
check=row[i];
}
else {
return false;
}
}
for(int j=0;j<4;j++)
{
if (column[j]!=check)
{
cout<<column[j]<<"*****";//For some reason, the value of column[j] is 0.
return false;
}
}
if (rightdiagonalsum!=check||leftdiagonalsum!=check)
{
return false;
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:22:46.800",
"Id": "73420",
"Score": "0",
"body": "You seem to lack the outermost level of indentation. If that is an artifact of pasting the code into Code Review, please be aware that the Stack Exchange text editor can indent a block of code if you click the \"{}\" button."
}
] | [
{
"body": "<p>The size of the matrix is hard-coded all over the place. You made a good attempt to define <code>const int SIZE = 4</code> in <code>main()</code>, and you pass <code>SIZE</code> to your functions. However, you still hard-code <code>int matrix[][4]</code>, <code>int row[4]</code>, and <code>int column[4]</code> in the function signatures. In addition, <code>fillMatrix()</code> says <code>\"Enter four values for row \"</code>.</p>\n\n<p>There are several possible remedies.</p>\n\n<ul>\n<li>The simplest is to <code>#define SIZE 4</code>, and don't bother passing the size around anymore. It's more of a C-style approach, but at least the size will be centrally defined.</li>\n<li>You could store the matrix in a <code>std::array<std::array<int>></code> <sup>(C++11)</sup>, a <code>std::vector<std::vector<int>></code>, or a <code>std::valarray<std::valarray<int>></code>. Then the helper functions could obtained the dimensions by calling <code>.size()</code>.</li>\n<li>You could flatten the matrix into a one-dimensional array, and pass the size.</li>\n<li>You could define a <code>Matrix</code> class.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T01:13:45.467",
"Id": "73472",
"Score": "1",
"body": "a matrix class? so useful, much c++, wow"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T17:19:05.580",
"Id": "42614",
"ParentId": "42607",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T16:24:26.663",
"Id": "42607",
"Score": "1",
"Tags": [
"c++",
"matrix"
],
"Title": "Test whether or not a 4x4 matrix is a magic square"
} | 42607 |
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p>
</blockquote>
<p>I wrote the following code with help of some Java 8, I'll explain the equivalent to Java 7 under the code. I'd like general comments. One note to give up ahead is that I did not write a program that gives the largest prime factor, but one that gives all prime factors.</p>
<pre><code>public class ProjectEuler {
private final static int WARMUP_COUNT = 0;
private final static int REAL_COUNT = 1;
private final List<Problem<?>> problems = new ArrayList<>();
private void init() {
problems.add(new Problem1());
problems.add(new Problem2());
problems.add(new Problem3(600851475143L));
process();
}
private void process() {
problems.stream().forEachOrdered(new ProblemConsumer());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new ProjectEuler().init();
}
private class ProblemConsumer implements Consumer<Problem<?>> {
@Override
public void accept(Problem<?> problem) {
for (int i = 0; i < WARMUP_COUNT; i++) {
problem.run();
}
System.gc();
long start = System.nanoTime();
for (int i = 0; i < REAL_COUNT; i++) {
problem.run();
}
double average = (System.nanoTime() - start) * 1.0d / REAL_COUNT;
String result = problem.getResult();
System.out.println(problem.getName() + ": " + result + " (" + String.format("%.5f", (average / 1_000_000.0)) + " ms" + ")");
}
}
}
</code></pre>
<hr />
<pre><code>public class Problem3 extends Problem<List<Long>> {
private final long number;
public Problem3(final long number) {
this.number = number;
}
@Override
public void run() {
long numberCopy = number;
result = new ArrayList<>();
while (numberCopy > 1) {
PrimeGenerator primeGenerator = new PrimeGenerator();
while (primeGenerator.hasNext()) {
long prime = primeGenerator.nextLong();
if (numberCopy % prime == 0) {
result.add(prime);
numberCopy /= prime;
break;
}
}
}
}
@Override
public String getName() {
return "Problem 3";
}
}
</code></pre>
<hr />
<pre><code>public class PrimeGenerator implements PrimitiveIterator.OfLong {
private final static LongNode HEAD_NODE = new LongNode(2);
private LongNode lastNode = HEAD_NODE;
private long current = 2;
@Override
public boolean hasNext() {
return true;
}
@Override
public long nextLong() {
if (lastNode.value == current) {
if (lastNode.next != null) {
long old = lastNode.value;
lastNode = lastNode.next;
current = lastNode.value;
return old;
}
return current++;
}
while (true) {
if (isPrime(current)) {
appendNode(current);
return current++;
}
current++;
}
}
private boolean isPrime(final long number) {
LongNode prime = HEAD_NODE;
while (prime != null && prime.value <= number) {
if (number % prime.value == 0) {
return false;
}
prime = prime.next;
}
return true;
}
private void appendNode(final long value) {
LongNode newNode = new LongNode(value);
couple(lastNode, newNode);
lastNode = newNode;
}
private void couple(final LongNode first, final LongNode second) {
first.next = second;
second.previous = first;
}
private static class LongNode {
public final long value;
public LongNode previous;
public LongNode next;
public LongNode(final long value) {
this.value = value;
}
}
public static LongStream infiniteStream() {
return StreamSupport.longStream(
Spliterators.spliteratorUnknownSize(new PrimeGenerator(), Spliterator.ORDERED | Spliterator.IMMUTABLE), false
);
}
}
</code></pre>
<p>Java 8 remarks:</p>
<ul>
<li>I've not used the <code>PrimeGenerator.infiniteStream()</code> in this answer, so no need to consider it.</li>
<li><code>ProjectEuler</code> class is just given for convenience.</li>
<li><code>PrimiteIterator.OfLong</code> is a primitive wrapper for Java 7 equivalent <code>Iterator<Long></code>.</li>
</ul>
<p>The idea I've used for this exercise was that I need a list of prime numbers. And everytime the original number modulo that prime was zero, I would add a factor to the list and divide the number by that prime.</p>
<p>Other remark on the speed, which I think is pretty interesting, I also ran code that sums up the first million prime numbers.</p>
<ul>
<li>When properly benchmarking, with 10000 warmups and 10000 real tests, the time was averaged 7.5ms.</li>
<li>However with just one real test, it is still running after a considerate amount of time, at least an hour I think.</li>
</ul>
| [] | [
{
"body": "<p>Actually, your iterator is two iterators - one for the known primes (from previous 'warmups'), and one for unknown primes. Your known prime iterator's choice of implementation looks a bit cumbersome - you could have used a simple list of <code>Long</code>, and iterate over it:</p>\n\n<pre><code>private final static List<Long> KNOWN_PRIMES = new LinkedList<Long>();\n\nprivate Iterator<Long> knownPrimeIterator = KNOWN_PRIMES.iterator();\nprivate long lastResult = 1;\n\npublic long nextLong() {\n if (knownPrimeIterator != null && knownPrimeIterator.hasNext()) {\n lastResult = knownPrimeIterator.next().toLong();\n } else {\n knownPrimeIterator = null;\n lastResult = findNextPrime(lastResult+1);\n KNOWN_PRIMES.add(new Long(lastResult));\n }\n return lastResult;\n}\n\nprivate long findNextPrime(long startFrom) {\n // whatever here...\n}\n</code></pre>\n\n<p>Regarding your benchmark, I believe that 'warming up' is a little like cheating... you are caching the results in your static array. If you wanted to have a high-performant solution, you could have pre-calculated the first 1,000,000 primes, saved them to a file, and read them at the beginning of the procedure... :P</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:57:30.190",
"Id": "42693",
"ParentId": "42609",
"Score": "6"
}
},
{
"body": "<p>Some general observations.</p>\n\n<ul>\n<li><p>I agree with Uri that your use of the custom Linked-List is cumbersome. It also leads you to have redundant code, like you have an unused 'previous' node... Uri is right to syggest a List for this, but I would recommend an ArrayList as it will be faster (because it will use half the memory as it has half the number of Objects).... actually, like most times, I would prefer the use of an array of <code>long[]</code> with a <code>size</code> parameter to track how large it is, and then resize as needed. That will use about 10% of the memory of the same data in the LinkedList, and about 20% of the data in your LinkNode system. Despite what many people believe, Java performance in many ways is related to the memory footprint. Smaller data is faster.</p></li>\n<li><p>Your class is not thread-safe. This is a problem for using with Java8. If your PrimeGenerator is linked to a parallel Lambda then you will be in trouble. in particular, the <code>private final static LongNode HEAD_NODE = new LongNode(2);</code> is going to mean that all threads will try to modify the same linked structure.</p></li>\n<li><p>I am aware that you have changed the problem from being 'find the largest' to 'find them all', but, you should consider a system where you start from the highest prime that could possibly be a factor (<code>Math.sqrt(value)</code>) and work backwards. This will save a lot of computation:</p>\n\n<pre><code>while (numberCopy > 1) {\n long root = (long)Math.sqrt(numberCopy);\n for (long prime : PrimesGenerator.descendingFrom(root)) {\n if (numberCopy % prime == 0) {\n numberCopy /= prime;\n factors.add(prime);\n }\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:29:52.063",
"Id": "42758",
"ParentId": "42609",
"Score": "6"
}
},
{
"body": "<p>A few comments:</p>\n\n<ul>\n<li>I agree that using a custom implementation of a LinkedList without a need to is a bad practice.</li>\n<li>Public mutable fields are bad.</li>\n<li>It is considered pedantic to add final to arguments.</li>\n<li>I don't like your method of generating primes. You check if a number is prime by iterating over all smaller primes. Two possible improvements would be to iterate only over primes in range [1, \\sqrt{x}], or to use a fancy primality test like Miller-Rabin. But a faster and easier approach would be to use <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Seive of Eratosthenes</a> to generate primes.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:51:33.307",
"Id": "42760",
"ParentId": "42609",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T16:51:29.207",
"Id": "42609",
"Score": "13",
"Tags": [
"java",
"project-euler",
"primes",
"java-8"
],
"Title": "Project Euler \"Largest prime factor\" (#3) in Java"
} | 42609 |
<p>I have articles on my website (built in PHP) and when an article is viewed the number of views is recorded back in the database. The SQL code snippet of my <code>load</code> method is:</p>
<pre><code>SELECT *
FROM article
WHERE id = :id;
UPDATE article
SET views = views + 1
WHERE id = :id;
</code></pre>
<p>This works fine, but I've only tested it locally with one user - me.</p>
<p>What happens if hundreds of people tried accessing the same article at once? I.e. would the <code>update</code> slow things down considerably? If so, is there a better way of doing this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T01:46:48.413",
"Id": "73476",
"Score": "1",
"body": "An update statement like you have written is about as good as you will get (using sql). Whether it effects performance will be dependent on if your database does row or table locking, and how heavily the site is being hit."
}
] | [
{
"body": "<p><strong>The performance with simple queries such as yours will depend more on what is going on in the database than what is going on in your code.</strong></p>\n\n<p>Here are a few things to consider if you are maintaining the DB yourself, or to bring up with the DBA if you are not:</p>\n\n<ol>\n<li><p>If the <code>id</code> field is an <strong>integer</strong>, and ideally a <strong>surrogate key</strong> (e.g. generated by an identity function instead of being a natural key using date/time, articlename, etc.), that will perform significantly better. <strong>Integers</strong> can be easily and swiftly ordered and generate relatively small indexes that can be searched quickly. A <strong>surrogate key</strong> improves performance for many reasons, one of which improved index performance by pushing data INSERTs to the leading edge of the index.</p></li>\n<li><p>If the article table has a <strong>clustered index</strong> on the id field, that's even better for your performance as it will reduce the cost of both the SELECT and the UPDATE in most cases. The clustered attribute means that the data is already ordered by your ID column, significantly improving search performance.</p></li>\n<li><p>If you don't have a lot of competing queries that try to lock bigger sets of data than a row at a time, that will also be good for the performance of these queries. You want to avoid <strong>contention</strong> for locking the same data as much as possible. For example, you don't want a big 100,000-row update that runs every 15 minutes competing with your single-row update.</p></li>\n</ol>\n\n<p>Which brings me to the one thing I would change about your query: locking. Unless you really need per-transaction integrity when serving articles to the readers (and in most cases, for a publishing system, you probably don't) you can <strong>hint</strong> to the database that you'd like a more permissive <strong>transaction isolation level</strong>. In layman's terms, you can volunteer to let the other guy win if you both need a lock.</p>\n\n<p>So if you are doing a SELECT at the same time an UPDATE is occurring to the same article, you can allow a READ UNCOMMITTED transaction isolation level on your query to avoid taking unnecessary locks. The syntax for doing this varies from one DBMS to another, but usually it's some variation on the theme of SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED. Some (MS SQL, for example) also have a shortened syntax such as WITH (NOLOCK).</p>\n\n<p>Finally, a couple of caveats to this advice since you didn't specify your DB system. Some DB systems don't fit this mold. For example, Oracle implements non-blocking SELECTs without requiring dirty reads, so there's no equivalent to NOLOCK there because it's a built-in assumption. MySQL, on the other hand, has InnoDB and MyISAM tables, and on the latter type you are not going to be able to use READ UNCOMMITTED due to the underlying architecture of the table. However, even though you will be taking a table lock the architecture is designed to efficiently allow many concurrent reads by sharing the lock to multiple readers.</p>\n\n<p>To sum up, your queries look fine but explore whether a NOLOCK-type option is available.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:57:23.287",
"Id": "44096",
"ParentId": "42617",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "44096",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T18:01:29.207",
"Id": "42617",
"Score": "5",
"Tags": [
"php",
"sql",
"concurrency"
],
"Title": "Updating number of article views - potential concurrent access issue?"
} | 42617 |
<p>I have this enum below:</p>
<pre><code>public enum TestEnum {
h1, h2, h3, h4;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
System.out.println(TestEnum.h1.name());
String ss = "h3";
try {
TestEnum.valueOf(ss); // but this validates with all the enum values
System.out.println("valid");
} catch (IllegalArgumentException e) {
System.out.println("invalid");
}
}
}
</code></pre>
<p>I need to check if the enum value represented by my string <code>ss</code> is one of my enum values <code>h1</code>, <code>h2</code> or <code>h4</code>. So if <code>h3</code> is being passed as a string, I would like to return false or throw <code>IllegalArgumentException</code>. I won't need to validate <code>ss</code> with <code>h3</code> in the enum.</p>
<p>I came up with the below code to do this with the enum, but I believe there is a more elegant solution.</p>
<pre><code>public enum TestEnum {
h1, h2, h3, h4;
public static boolean checkExcept(String el, TestEnum... except){
boolean results = false;
try{
results = !Arrays.asList(except).contains(TestEnum.valueOf(el));
}catch (Exception e){}
return results;
}
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
String ss = "h3";
if(TestEnum.checkExcept(ss,TestEnum.h1, TestEnum.h2, TestEnum.h3)){
System.out.println("valid");
}else{
System.out.println("invalid");
}
}
}
</code></pre>
<p>Is there any better way of solving this problem?</p>
| [] | [
{
"body": "<p>I would pass a <code>TestEnum</code> instead of a <code>String</code> to your method, forcing the exception handling to be outside the method. I don't see why you are using Strings at all actually (although I suspect that this is only a small part of your code, and that you have your reasons for needing this).</p>\n\n<p>I would do some refactoring and use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\"><code>EnumSet</code></a>, which could make your code something like this: (untested code, but I believe it should work)</p>\n\n<pre><code>public static void main(String[] args) {\n String enumName = \"h3\";\n EnumSet<TestEnum> except = EnumSet.of(TestEnum.h1, TestEnum.h2, TestEnum.h3);\n\n boolean valid;\n try {\n valid = !except.contains(TestEnum.valueOf(enumName));\n } catch (IllegalArgumentException e) { valid = false; }\n System.out.println(valid ? \"valid\" : \"invalid\");\n}\n</code></pre>\n\n<p>Note that I have gotten rid of your entire method here as I think that when you use EnumSet like this, you don't need the method. But of course you can put the relevant parts of the above code into a method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:00:29.050",
"Id": "73454",
"Score": "0",
"body": "What about if the String enumName is `h10`? It should return false as well? Correct? But it is throwing exception with your current code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:12:52.733",
"Id": "73458",
"Score": "0",
"body": "@user2809564 As if that's a big problem to solve.... ;) See edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-13T09:11:52.683",
"Id": "304378",
"Score": "0",
"body": "@ringbearer If you pass `enumName = \"h4\"` in this case it is a valid enum and will not throw, but `contains` will return `false`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-13T10:49:25.107",
"Id": "304396",
"Score": "0",
"body": "Right, i assumed before noting that OP wanted a filter."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:30:39.830",
"Id": "42621",
"ParentId": "42620",
"Score": "6"
}
},
{
"body": "<p>You can create an <code>isValid</code> or <code>checkValid</code> method inside the enum and override it in <code>h3</code> if it's not changing runtime.</p>\n\n<pre><code>public enum TestEnum {\n h1, \n h2, \n h3 {\n @Override\n public boolean isValid() {\n return false;\n }\n },\n h4;\n\n public boolean isValid() {\n return true;\n }\n}\n</code></pre>\n\n<p>It returns <code>true</code> for <code>h1</code>, <code>h2</code> and <code>h4</code>, <code>false</code> for <code>h3</code>.</p>\n\n<p>You could eliminate the <code>results</code> variable from checkExcept:</p>\n\n<pre><code>public static boolean checkExcept(String el, TestEnum... except) {\n try {\n return !Arrays.asList(except).contains(TestEnum.valueOf(el));\n } catch (Exception e) {\n return false;\n }\n}\n</code></pre>\n\n<p>Please note that <a href=\"https://stackoverflow.com/q/2416316/843804\">catching Exception is almost always a bad idea</a>. I'd catch a more specific exception here (<code>IllegalArgumentException</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:14:32.633",
"Id": "73459",
"Score": "0",
"body": "Overriding the isValid method is not a flexible solution for different validation requirements. I agree with catching IllegalArgumentException though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:58:30.210",
"Id": "42622",
"ParentId": "42620",
"Score": "2"
}
},
{
"body": "<p>Catching exception or its sub type is bad idea.\nThis should do it more proper way as mentioned code below.</p>\n\n<pre><code>public static boolean contains(String test) {\n\n for (EnumType type : EnumType.values()) {\n if (type.name().equals(test)) {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-09T14:33:42.460",
"Id": "150431",
"Score": "0",
"body": "This is generally a good option, but in this case it doesn't solve the same problem. The question asks for *I need to check if the enum value represented by my string `ss` is one of my enum values h1, h2 or h4. So if h3 is being passed as a string, I would like to return false or throw IllegalArgumentException.*"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-09T11:44:02.057",
"Id": "83638",
"ParentId": "42620",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42621",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T20:05:49.963",
"Id": "42620",
"Score": "4",
"Tags": [
"java",
"enum"
],
"Title": "Validating an input string against some enum fields"
} | 42620 |
<p>I am trying to convert over to MySQLi and wanted expert advice. Is the enclosed code 100% OOP. Also, how secure is the code against attacks? I know nothing is 100% secure, but how good/safe is it? How and what can I make better? This is just a generic query as I wanted to get a basic model setup.</p>
<pre><code><?php
define ('DB_HOST', 'localhost'); // Host name
define ('DB_USER', 'root'); // Mysql username
define ('DB_PASSWORD', 'password'); // Mysql password
define ('DB_NAME', 'database'); // Database name
// New Connection
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
require("dbcon.php"); // This is actually the code above in a separate file that I have included here for checking.
$query = "SELECT id, username, firstname FROM users WHERE firstname=?";
if ($stmt = $mysqli->prepare($query))
{
// Bind the variables
$firstname = $_POST[first_name];
// Bind parameters s - String, b - Boolean, i - Integer etc
$stmt->bind_param("s", $firstname);
// Execute it
$stmt->execute();
// Store it for num rows
$stmt->store_result();
$num_rows = $stmt->num_rows;
// Assign blank variables
$id = "";
$username = "";
$firstname = "";
// Bind the result and retrieve the data
$stmt->bind_result($id, $username, $firstname);
if(($num_rows) > 0)
{
while($stmt->fetch())
{
echo $id;
echo "<br />";
echo $username;
echo "<br />";
echo $password;
echo "<br />";
echo "Number of rows: ", $num_rows;
echo "<br />";
echo "<br />";
}
}
else
{
echo "No records";
}
// Close the statement
$stmt->close();
}
// Close connection
$mysqli->close();
?>
</code></pre>
| [] | [
{
"body": "<p>Your binding of parameters will help in preventing SQL injections.</p>\n\n<p>You need to sanitize your data first though.\nYou need to treat everything that comes from a user (passed from the client machine) as 'dirty' and not allow it into your system before it's been 'cleaned'. Your first step would be to clean it - converting all HTML tags and special characters into their HTML entities <code>htmlspecialchars()</code> <code>htmlentities()</code> (well as long as HTML isn't allowed). This will help prevent cross-sight scripting (XSS). Typically then you would move on to validating the data - making sure it's in a format you expect. Then if it's not you return it to the user with an error.\nThis is also assuming that you've checked the user has permission to run this function, if relevant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T00:17:01.090",
"Id": "73471",
"Score": "0",
"body": "ok, the validate and santize issue I was going to work on after I got this template started. Other than that, is it 100% oop, safe and secure enough to use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T11:47:21.597",
"Id": "73503",
"Score": "0",
"body": "It's pretty good. Obviously it's hard to give a proper review as this is only a small snippet of example code - obviously normally you wouldn't be echoing out the password etc., would have the connection details in a separate file (as you commented you do) and would hash (and salt) the password before putting into the db. OOP-wise I would load the user input into the relevant object - in your example this would likely be a User class - before using it on the page (e.g. to return it to the user if validation failed). So it would be `echo $user->getId()` for example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T22:25:56.473",
"Id": "42626",
"ParentId": "42623",
"Score": "1"
}
},
{
"body": "<p>Yes, it looks like you're exclusively using OO style.</p>\n\n<p>Your code will prevent SQL injection attacks by using MySQLi prepared statements as you do, but you're not doing anything to prevent a potential XSS attack through the output you're sending to the browser. To do this, escape characters that could be used in an XSS attack before sending them to the browser, for example</p>\n\n<pre><code>echo htmlentities($username);\n</code></pre>\n\n<p>It's unclear whether this is code you intend to use or if you're just illustrating concepts, but what you've posted exposes usernames to anybody who can access the script in a browser. You need do several things if you're actually going to run this code. The first that comes to mind is checking to see if the user is logged in under an account allowed to view usernames.</p>\n\n<p>Also I see a variable named $password although it's not part of the select. It's unclear why you have this variable, but you should never store passwords in a database without salting and hashing them - which makes it useless to display in the browser as you seem to want to do here. Here is an article on the topic: <a href=\"https://crackstation.net/hashing-security.htm\" rel=\"nofollow\">https://crackstation.net/hashing-security.htm</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T02:44:52.013",
"Id": "73607",
"Score": "0",
"body": "Thank you for your comment, and yes, I will use both htmlentities and the mysqli real escape. In hindsight, I should have added it earlier for other to see and perhaps use. The $password is actually a line of code that I copied accidentally and does not belong there. At least I know I am on the right and safe track. I am not sure if I should mark this as \"answered\", but cheers to all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T05:37:24.337",
"Id": "42641",
"ParentId": "42623",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-23T21:11:33.713",
"Id": "42623",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"security",
"mysqli"
],
"Title": "Does this generic query follow good OOP standards?"
} | 42623 |
<p>I am working on some multi-threaded code that requires a prime-number source.</p>
<p>The following code keeps an array of primes in memory, extending it as needed. It works in the 'int' domain, being careful to avoid overflows, and to keep the memory for storing the data relatively small.</p>
<p>it uses a state-based concurrency model... it keeps an immutable state that covers a range of primes (from 1..range). If a request is for some data that is outside that range, it will defer to a backup process which is single-threaded, where one thread extends the state. At any time, some other thread can query the state, and it is not blocked if the existing state covers its needs.</p>
<p>The idea is that only one thread is working at a time on calculating primes, and any pre-calculated primes are reused by other threads.</p>
<p>Additionally, during prime calculation, if one thread is calculating a really large extension, it regularly creates a new state, then 'breaks' out of the locked code, and allows any other waiting threads to use that new state if it is good enough.... The long-calculating thread will then start again on the next extension.</p>
<h2>PrimeReserveInt.java</h2>
<pre><code>import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* A thread-safe container that stores a list of prime numbers. The prime number
* list will be extended if needed to satisfy any request for primes up to
* MAX_PRIME_ALLOWED (Integer.MAX_VALUE). This is the 105097565th prime number
* (MAX_PRIME_NTH). Int primes require 4 bytes per number, or just less than
* 400MB to contain. Because of the way this code works, it occasionally needs
* to have two copies of the data in memory at a time, which leads to an
* occasional need for up to 1GB to do the work. Use -Xmx2g to get up these
* limits.
*
* Many sieve implementations would require an array of 2 Billion int values
* (8GB) to calculate this 100Millionth prime, so, in reality, this is a small
* implementation...
*
* @author rolf
*
*/
public final class PrimeReserveInt {
/**
* The largest prime this Reserve can contain. This also happens to be
* Integer.MAX_VALUE (which is prime).
*/
public static final int MAX_PRIME_ALLOWED = Integer.MAX_VALUE;
/**
* The largest nth' prime that can be managed (MAX_PRIME_ALLOWED is the
* MAX_PRIME_NTH prime number).
*/
public static final int MAX_PRIME_NTH = 105097565;
/**
* This is the most primes we will calculate in one locked operation.
*
* NEVER Violate the prime directive!
*/
private static final int PRIME_DIRECTIVE = 8 * 1024 * 1024;
/**
* As prime numbers are calculated, they will extend this far beyond the
* requested calc. This is a performance optimization so that when a user is
* incrementing through the primes, they do not have to do a full calc for
* each value....
*/
private static final int PRIME_STEP = 1024;
/**
* Internal state class. This class contains immutable values, and thus is
* thread-safe. The class model is that it creates various
*/
private static final class PrimeState {
private final int[] primes;
private final int limit;
// replaced is an indicator of whether this state is the currently
// active one.
private boolean replaced = false;
public PrimeState(int[] primes) {
if (primes.length == 0) {
throw new IllegalStateException("Cannot have empty prime state");
}
this.primes = primes;
this.limit = primes[primes.length - 1];
}
/**
* get a copy of all prime numbers less than or equal to the input range
*
* @param range
* the largest prime value to return.
* @return an ordered array of primes less than or equal to the range.
*/
public int[] getPrimesTo(final int range) {
if (range > limit) {
throw new IllegalArgumentException(
"This state only has values up to " + limit
+ " so cannot process range " + range);
}
// find the position of the prime after `range`
int pos = Arrays.binarySearch(primes, range);
if (pos < 0) {
pos = -pos - 1;
} else {
pos++;
}
return Arrays.copyOf(primes, pos);
}
/**
* get the nth prime number from this state.
*
* @param nth
* the prime number to retrieve
* @return the nth prime number.
*/
public int getNthPrime(final int nth) {
if (nth < 1 || nth > primes.length) {
throw new IllegalArgumentException("This state only has "
+ primes.length
+ " values, so cannot access nth prime " + nth);
}
return primes[nth - 1];
}
/**
* indicates whether this state includes the specified range
*
* @param range
* the value to check whether it is included.
* @return true if the range is within this state.
*/
public boolean coversRange(final int range) {
return range <= limit;
}
/**
* indicate whether this state contains the nth prime
*
* @param nth
* the prime to check for
* @return true if it is contained within this state.
*/
public boolean containsPrime(final int nth) {
return nth <= primes.length;
}
/**
* indicate how many primes are in this state
*
* @return the number of primes in this state.
*/
public int getPrimeCount() {
return primes.length;
}
/**
* the largest prime covered by this state.
*
* @return the largest in-state prime.
*/
public int getLargestPrime() {
return limit;
}
/**
* identify the 'nth' value for a prime number.
*
* @param prime
* the prime to get the nth for.
* @return the nth value of the prime (0 if the input is not prime).
*/
public int whichPrime(final int prime) {
int pos = Arrays.binarySearch(primes, prime);
return pos >= 0 ? (pos + 1) : 0;
}
/**
* get the largest prime less than or equal to the input.
*
* @param to
* the value to get the previous prime from.
* @return the largest prime <= to.
*/
public int getLargestPrimeTo(final int to) {
int pos = Arrays.binarySearch(primes, to);
if (pos >= 0) {
return primes[pos];
}
pos = (-pos - 1);
return primes[pos - 1];
}
private synchronized void waitReplaced() {
while (!replaced) {
try {
// wait up to a second....
this.wait(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private synchronized void replaced() {
replaced = true;
this.notifyAll();
}
}
/**
* Seed the initial state with the first 6 primes.
*/
private final AtomicReference<PrimeState> safestate = new AtomicReference<>(
new PrimeState(new int[] { 2, 3, 5, 7, 11, 13 }));
/**
* If a recalc is needed, this makes sure only one thread is recalcing at a
* time.
*/
private final AtomicBoolean lock = new AtomicBoolean();
/**
* Create a 'strategic reserve' of prime numbers.
*
* This class is fully thread-safe.
*
* If any thread has previously calculated primes that satisfy requests then
* querying those primes is a lock-free process, and O(1).
*
* If the primes you need to query have not been calculated, then only one
* thread calculates those primes, and other threads block until they are
* satisfied, at which point they are released and no longer block.
*/
public PrimeReserveInt() {
// useful to seed the system with the first batch of primes.
getPrimesTo(1000);
}
/**
* Get an array of all primes less-than-or-equals-to the input range.
*
* @param to
* the largest value to return in the results (or smaller if to
* is not prime)
* @return an array of primes less-than-or-equals-to to.
*/
public int[] getPrimesTo(final int to) {
return coverTo(to).getPrimesTo(to);
}
/**
* Get an array of all primes less-than-or-equals-to the input range.
*
* @param to
* the largest value to return in the results (or smaller if to
* is not prime)
* @return an array of primes less-than-or-equals-to to.
*/
public int[] getFirstNPrimes(final int n) {
final int nth = getNthPrime(n);
return coverTo(nth).getPrimesTo(nth);
}
/**
* get the value of the nth prime. The values are 1-based, i.e.
* getNthPrime(1) returns 2.
*
* @param nth
* the prime value to get.
* @return the prime value.
* @throws IllegalArgumentException
* if nth < 1 or the nth prime is larger than Long.MAX_VALUE
*/
public int getNthPrime(final int nth) {
if (nth < 1) {
throw new IllegalArgumentException("Cannot get the " + nth
+ " prime");
}
if (nth > MAX_PRIME_NTH) {
throw new IllegalArgumentException("The " + MAX_PRIME_NTH
+ "th prime is the largest int prime (" + MAX_PRIME_ALLOWED
+ "). Cannot get the " + nth + " prime.");
}
// zero-based nth
// final int zbnth = nth - 1;
PrimeState state = null;
while (!(state = safestate.get()).containsPrime(nth)) {
// guess something that will likely cover the nth prime.
// the following is the approximate number gap between primes.
double distribution = ((double) state.getLargestPrime())
/ state.getPrimeCount();
// need about this many more primes....
int extension = (int) ((nth - state.getPrimeCount()) * distribution);
// overcommit the primes in case there is a system extending things
// beyond.... one-at-a-time
final int current = state.getLargestPrime();
int to = current + extension;
if (to < current) {
// integer overflow.
to = MAX_PRIME_ALLOWED;
}
extendStateTo(state, to); // take it 1024 further just in case.
}
return state.getNthPrime(nth);
}
/**
* Which prime is the supplied value.
*
* @param prime
* the prime value to identify
* @return the position of the prime number, or 0 if the number is not
* prime.
*/
public int whichPrime(final int prime) {
if (prime <= 1 || prime > MAX_PRIME_ALLOWED) {
return 0;
}
return coverTo(prime).whichPrime(prime);
}
/**
* Get the largest prime that is less-than-or-equal to the input value.
*
* @param to
* the value to get the largest prime from.
* @return the largest prime available, or 0 if the input is less than 2.
*/
public int getLargestPrimeTo(int to) {
return to < 2 ? 0 : coverTo(to).getLargestPrimeTo(to);
}
private PrimeState coverTo(final int to) {
if (to <= 1) {
throw new IllegalArgumentException("Illegal range to " + to);
}
if (to > MAX_PRIME_ALLOWED) {
throw new IllegalArgumentException(
"Memory-limited to the largest prime " + MAX_PRIME_ALLOWED
+ " (which is the " + MAX_PRIME_NTH + "th prime)");
}
PrimeState state = null;
while (!(state = safestate.get()).coversRange(to)) {
// the current state is not good enough, extend it.
// over-commit the primes... in case there is a user that is looping
// through
// increasing values.
int realto = to + PRIME_STEP;
if (realto < state.getLargestPrime()) {
// overflow
realto = MAX_PRIME_ALLOWED;
}
extendStateTo(state, realto);
}
return state;
}
private void extendStateTo(final PrimeState estate, final int to) {
if (lock.compareAndSet(false, true)) {
// we are the thread with the lock...
try {
// OK, we are the only thread in here, and the state is not good
// enough...
// create a new state that will be good enough....
PrimeState nextstate = extendStateInternal(estate, to);
if (!safestate.compareAndSet(estate, nextstate)) {
throw new IllegalStateException(
"This can never happen, if it does, then shoot Monkey!");
}
estate.replaced();
} finally {
lock.compareAndSet(true, false);
}
} else {
estate.waitReplaced();
}
}
private PrimeState extendStateInternal(final PrimeState estate, final int to) {
// This method will only be called from a locked context...
// to limit the amount of memory we occupy, we will only process
// primes in a smallish sieve..... (limit to 10million or so entries)
// the way this works is that it creates a sieve that is a 'window' on
// a virtual full-size sieve
// this allows us to work with numbers in the long domain, while staying
// in the int domain.
final int offset = estate.getLargestPrime() + 1;
int longsievesize = (to - offset) + 1;
final int sievesize = longsievesize > PRIME_DIRECTIVE ? (int) PRIME_DIRECTIVE
: (int) longsievesize;
final int tolimit = offset - 1 + sievesize; // need to use tolimit as <=
// hence the -1 in case
// tolimit is
// Intger.MAX_VALUE
boolean[] sieve = new boolean[sievesize];
final int maxp = (int) Math.sqrt(to);
// For the sieve, eliminate all previously calculated primes.
for (int p : estate.primes) {
// optimize -- break at sqrt(to).
if (p > maxp) {
break;
}
// optimize -- start at square value.
int check = p * p;
if (check > 0 && check < offset) {
// the prime square is less than our sieve window. Extend it in
// to the window.
check = p + (((offset - 1) / p) * p);
}
while (check > 0 && check <= tolimit) {
int pos = (int) (check - offset);
// if (to == MAX_PRIME_ALLOWED) {
// System.out.println("In end-range with prime " + p +
// " and check " + check);
// }
sieve[pos] = true;
check += p;
}
}
// now apply all the newly found primes....
int cnt = 0;
for (int i = 0; i < sievesize; i++) {
if (!sieve[i]) {
// found a prime....
cnt++;
int p = offset + i;
// optimize -- break at sqrt(to).
if (p > maxp) {
continue;
}
// optimize -- start at square value.
int check = p * p;
if (check < offset) {
check = p + (((offset - 1) / p) * p);
}
while (check > 0 && check <= tolimit) {
int pos = (int) (check - offset);
// if (to == MAX_PRIME_ALLOWED) {
// System.out.println("In end-range with prime " + p +
// " and check " + check);
// }
sieve[pos] = true;
check += p;
}
}
}
int pos = estate.primes.length;
int[] primes = Arrays.copyOf(estate.primes, pos + cnt);
for (int i = 0; i < sieve.length; i++) {
if (!sieve[i]) {
primes[pos++] = offset + i;
}
}
return new PrimeState(primes);
}
}
</code></pre>
<h2>PrimeTester.java</h2>
<p>(used to test the generator)</p>
<pre><code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class PrimeTester {
// These values extracted from: http://www.primos.mat.br/dados/2T_part11.7z
private static final int[] largeprimes = {
2147459851, 2147459887, 2147459917, 2147459959, 2147459969, 2147459981, 2147459987, 2147459999, 2147460013, 2147460017,
2147460019, 2147460041, 2147460089, 2147460137, 2147460151, 2147460173, 2147460187, 2147460197, 2147460223, 2147460233,
2147460253, 2147460269, 2147460277, 2147460299, 2147460373, 2147460379, 2147460421, 2147460431, 2147460437, 2147460449,
2147460457, 2147460461, 2147460467, 2147460547, 2147460569, 2147460589, 2147460611, 2147460629, 2147460631, 2147460641
};
--TESTER NOTE .... there are other numbers I trimmed out to get this below 30K
private static final void tests(final PrimeReserveInt pr) {
// compare the first million primes with an external reference...
checkMillion(pr);
checkNthPrime(pr, 29, 109);
checkNthPrime(pr, 1229, 9973);
checkNthPrime(pr, 50000, 611953);
checkNthPrime(pr, 100000000, 2038074743);
checkNthPrime(pr, PrimeReserveInt.MAX_PRIME_NTH, PrimeReserveInt.MAX_PRIME_ALLOWED);
int pos = 105096451; // this is verified as: pr.whichPrime(largeprimes[0]);
for (int lp : largeprimes) {
checkNthPrime(pr, pos++, lp);
}
checkPrimeNth(pr, PrimeReserveInt.MAX_PRIME_ALLOWED, PrimeReserveInt.MAX_PRIME_NTH);
checkPrimeNth(pr, -1, 0);
checkPrimeNth(pr, 2147459851, 105096451);
checkPrimeBefore(pr, 2147483646, 2147483629);
checkPrimeBefore(pr, 2147483647, 2147483647);
checkPrimeBefore(pr, 1, 0);
}
public static void main(String[] args) throws InterruptedException {
int cpus = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(cpus);
final PrimeReserveInt pr = new PrimeReserveInt();
for (int i = cpus; i > 0; i--) {
final Runnable torun = new Runnable() {
@Override
public void run() {
tests(pr);
}
};
pool.execute(torun);
}
pool.shutdown();
while (!pool.isTerminated()) {
System.out.println("Waiting for executorservice...");
pool.awaitTermination(10, TimeUnit.SECONDS);
}
System.out.println("Service complete");
}
private static void checkPrimeBefore(PrimeReserveInt pr, int target,
int expectprime) {
int actual = pr.getLargestPrimeTo(target);
System.out.printf("Prime (which) %d US %d REF %d %s\n", target, actual, expectprime, expectprime == actual ? "OK" : "FAIL!!!");
}
private static void checkPrimeNth(PrimeReserveInt pr, int prime,
int expectnth) {
int actual = pr.whichPrime(prime);
System.out.printf("Prime (which) %d US %d REF %d %s\n", prime, actual, expectnth, expectnth == actual ? "OK" : "FAIL!!!");
}
private static final void checkNthPrime(PrimeReserveInt pr, int nth, int expectprime) {
int actual = pr.getNthPrime(nth);
System.out.printf("Prime (nth) %d US %d REF %d %s\n", nth, actual, expectprime, expectprime == actual ? "OK" : "FAIL!!!");
}
private static void checkMillion(PrimeReserveInt pr) {
// http://primes.utm.edu/lists/small/millions/primes1.zip
PrimeReader reader = new PrimeReader("primes1.txt");
int[] reference = reader.readFile();
int[] actual = pr.getPrimesTo(pr.getNthPrime(1000000));
int ri = 0;
int ai = 0;
while (ri < reference.length && ai < actual.length) {
while (ai < actual.length && ri < reference.length && actual[ai] < reference[ri]) {
System.out.println("Extra value " + ai + " " + actual[ai]);
ai++;
}
while (ai < actual.length && ri < reference.length && actual[ai] > reference[ri]) {
System.out.println("Missing value before " + ai + " (" + ri + " in reference) " + reference[ri]);
ri++;
}
ri++;
ai++;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T06:52:36.747",
"Id": "73490",
"Score": "1",
"body": "Regarding your comment in the code: A semi-decent sieve implementation uses bitsets and only requires 128MB memory :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T11:28:11.320",
"Id": "73502",
"Score": "0",
"body": "@ChrisWue Interesting .... I feel a follow-on is about to happen."
}
] | [
{
"body": "<p>Think I've found one concurrency issue :</p>\n\n<p>in </p>\n\n<pre><code>private void extendStateTo(final PrimeState estate, final int to) {\n if (lock.compareAndSet(false, true)) {\n // we are the thread with the lock...\n try {\n // OK, we are the only thread in here, and the state is not good\n // enough...\n // create a new state that will be good enough....\n PrimeState nextstate = extendStateInternal(estate, to);\n if (!safestate.compareAndSet(estate, nextstate)) {\n throw new IllegalStateException(\n \"This can never happen, if it does, then shoot Monkey!\");\n }\n estate.replaced();\n } finally {\n lock.compareAndSet(true, false);\n }\n } else {\n estate.waitReplaced();\n }\n\n}\n</code></pre>\n\n<p>It is possible to start waiting for an ongoing replacement, when it has already signaled it is done.</p>\n\n<p>Suppose thread T1 is doing the replacement and thread T2 arrives in this method. This scheduling is possible :</p>\n\n<ul>\n<li>T2 : <code>lock.compareAndSet()</code> returns false</li>\n<li>T1 : <code>estate.replaced()</code> executed.</li>\n<li>T2 : <code>estate.waitReplaced()</code> : starts waiting, but the signal has been missed.</li>\n</ul>\n\n<p>T2 is now blocked until another thread triggers a replacement and it finishes. This may even never occur.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T11:26:46.333",
"Id": "73501",
"Score": "0",
"body": "You are right... It is not quite as bad as 'never occur' because the `estate.waitReplaced()` has a 1 second timeout, at which point that thread will re-establish the 'current' estate, but it is still not good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:19:39.147",
"Id": "73535",
"Score": "0",
"body": "True, the timeout somewhat mitigates the problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T09:56:00.700",
"Id": "42646",
"ParentId": "42636",
"Score": "11"
}
},
{
"body": "<p>A few generic notes:</p>\n\n<ol>\n<li><p><code>PrimeReserveInt</code>: I think it could be smaller with <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">separated responsibilities</a>. I would put the prime generation (and related) logic to a separate class and put the (prime)state reference and thread handling to another one. (What would you extract out if you wanted to change prime generation to another algorithm?)</p></li>\n<li><p>I don't see any reason to use <code>AtomicBoolean</code> instead of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html\" rel=\"nofollow\"><code>ReentrantLock</code></a> for locking. It supports <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html#tryLock%28%29\" rel=\"nofollow\"><code>tryLock</code></a>. (If there is a reason you should document it somehow.)</p></li>\n<li><p>You could use a <code>CountDownLatch</code> instead of the <code>wait</code>/<code>notify</code>.</p>\n\n<pre><code>private final CountDownLatch replaced = new CountDownLatch(1);\n\nsynchronized void waitReplaced() {\n try {\n replaced.await();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n}\n\nsynchronized void replaced() {\n replaced.countDown();\n}\n</code></pre>\n\n<p>See: <em>Effective Java, 2nd edition</em>, <em>Item 69: Prefer concurrency utilities to wait and notify</em></p></li>\n<li><p><code>containsPrime</code> could be <code>containsNthPrime</code> (for consistency with <code>getNthPrime</code>).</p></li>\n<li><p>For this:</p>\n\n<pre><code>if (to <= 1) {\n throw new IllegalArgumentException(\"Illegal range to \" + to);\n}\nif (to > MAX_PRIME_ALLOWED) {\n throw new IllegalArgumentException(\"Memory-limited to the largest prime \" + MAX_PRIME_ALLOWED\n + \" (which is the \" + MAX_PRIME_NTH + \"th prime)\");\n}\n</code></pre>\n\n<p>Validation would be readable with Guava's <a href=\"https://code.google.com/p/guava-libraries/wiki/PreconditionsExplained\" rel=\"nofollow\"><code>Preconditions</code></a>:</p>\n\n<pre><code>checkArgument(to > 1, \"Illegal range to %s\", to);\ncheckArgument(to <= MAX_PRIME_ALLOWED, \n \"Memory-limited to the largest prime %s (which is the %sth prime)\",\n MAX_PRIME_ALLOWED, MAX_PRIME_NTH);\n</code></pre>\n\n<p>(It could also save you a few unnecessary string concatenation.)</p></li>\n<li><p>In <code>System.out.printf</code> use <code>%n</code> instead of <code>\\n</code>. The former outputs the correct platform-specific line separator.</p></li>\n<li><p>It's not unambiguous who is this comment for:</p>\n\n<pre><code> * NEVER Violate the prime directive!\n</code></pre>\n\n<p>The client or the developer of <code>PrimeReserveInt</code>? It's on a private field but sounds like a warning to clients of the class. As a client, what should I do?</p></li>\n<li><p>This comment should be on the class declaration instead of the constructor:</p>\n\n<pre><code>/**\n * ...\n * This class is fully thread-safe.\n * ...\n */\npublic PrimeReserveInt() {\n ...\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:53:02.723",
"Id": "73676",
"Score": "1",
"body": "Never violate the [Prime Directive](http://en.wikipedia.org/wiki/Prime_Directive) ... I know, it was a weak joke."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-21T12:56:49.823",
"Id": "141604",
"Score": "0",
"body": "Where are 5 and 7?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-21T14:15:30.117",
"Id": "141614",
"Score": "0",
"body": "@Pimgd: I guess you have found this issue: https://meta.stackexchange.com/questions/99651/list-bullet-missing-with-code-block-as-the-first-paragraph-of-a-list-chrome-12 I've updated the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T22:38:33.463",
"Id": "42705",
"ParentId": "42636",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "42705",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T02:28:13.693",
"Id": "42636",
"Score": "18",
"Tags": [
"java",
"thread-safety",
"primes"
],
"Title": "Thread-safe prime number source"
} | 42636 |
<p>I have a website which has reviews about games. Right now, to list the advantages (+) and disadvantages (-) of that game, there's a textarea in the admin panel with a WYSIWYG editor with only element. So my users list their (+) with list elements :</p>
<pre><code><ul>
<li>Game is too slow</li>
<li>Game is very hard</li>
</ul>
</code></pre>
<p>I want to update it and I was wondering if it wouldn't be a better way to have input fields to add their (+) and (-) about the game and each time they want to add one, they click on a button which adds an input field. Then, when the form is submitted, I could encode the datas with JSON like :</p>
<pre><code>[
['Game is too slow'],
['Game is very hard']
]
</code></pre>
<p>Would be like:</p>
<pre><code><input name="advantages[]" /> <a href="#" data-add>+</a>
<script>
$('[data-add]').click(function(){
$(this).before('<br /><input name="advantages[]" />')
});
</script>
</code></pre>
<p>and then:</p>
<pre><code>// encode
$list = json_encode($_POST['advantages']);
//decode
echo '<ul>';
foreach($list as $item) {
echo '<li>'.$item.'</li>';
}
echo '</ul>';
</code></pre>
<p>And when I want to show the datas, I could decode them and display them as a list, which would be like the first option. My point would be to get rid of the WYSIWYG and maybe have a more flexible system.</p>
<p>What do you think?</p>
| [] | [
{
"body": "<p>First of all, there's a problem with the HTML approach you have:</p>\n\n<ul>\n<li>That's risky (XSS most of the time)</li>\n<li>Do you expect them to be web developers? I can be a gamer/reviewer with zero HTML knowledge.</li>\n<li>We're writing a review, we should only write reviews, not HTML. Leave HTML to the developers.</li>\n</ul>\n\n<hr>\n\n<p>Now, as you said, you can do JSON, and your other approach seems to be right:</p>\n\n<p>Form</p>\n\n<pre><code><form>\n <h3>Advantages</h3>\n <button>Add</button> // get nextAll advantages, find the last and append after\n <input type=\"text\" name=\"advantages[]\" />\n <input type=\"text\" name=\"advantages[]\" />\n <input type=\"text\" name=\"advantages[]\" />\n\n <h3>Disadvantages</h3>\n <button>Add</button> // get nextAll disadvantages, find the last and append after\n <input type=\"text\" name=\"disadvantages[]\" />\n <input type=\"text\" name=\"disadvantages[]\" />\n <input type=\"text\" name=\"disadvantages[]\" />\n</form>\n</code></pre>\n\n<p>Data structure to server</p>\n\n<pre><code>{\n advantages : ['foo','bar','baz'],\n disadvantages : ['foo','bar','baz']\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T03:22:17.337",
"Id": "73479",
"Score": "0",
"body": "In fact, I'm just updating a code which I didn't write so I know that it was not the good approach and that's why I want to change. Thank you for your answer, I didn't even think about XSS. I think I'll do it with JSON then ;)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T03:13:54.490",
"Id": "42638",
"ParentId": "42637",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42638",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T02:38:25.370",
"Id": "42637",
"Score": "3",
"Tags": [
"php",
"mysql",
"json"
],
"Title": "Listing with JSON or plain HTML"
} | 42637 |
<p>In an effort to complete <a href="https://codereview.meta.stackexchange.com/a/1472/23788">this month's code challenge</a>, I've started off with the basics. Below I have for review, a class that I can call to create the square/button a user would click to mark a spot on a Tic Tac Toe board. I haven't done any game logic, so I could very easily be forgetting something my buttons need to have.</p>
<ul>
<li>Would this package stand up to any future additions?</li>
<li>How is my objected orientation here?</li>
<li>Is there anything I can do to compact it?</li>
<li>Am I following common practices?</li>
</ul>
<p></p>
<pre><code>package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class SquareSpace extends MovieClip
{
public static const SQUARE_LENGTH:int = 30;
public static const PLAYER_A_OWNED_SQUARE:int = 0;
public static const PLAYER_B_OWNED_SQUARE:int = 1;
public static const NEUTRAL_SQUARE:int = 2;
public static const AVAILABLE_SQUARE:int = 3;
public static const STATE_COLORS:Array = [0xFF3333,0x3333FF,0xDDDDDD,0x33FF33];
private var _state:int = AVAILABLE_SQUARE;
private var _square:MovieClip;
public function SquareSpace(boxX:int, boxY:int)
{
_square = formSquare();
_square.x = boxX;
_square.y = boxY;
_square.buttonMode = true;
}
public function addSquare():MovieClip
{
_square.addEventListener(MouseEvent.CLICK, sendClick);
return _square;
}
private function sendClick(event:MouseEvent):void
{
dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}
public function changeSquareState(sqrState:int):void
{
if (sqrState >= PLAYER_A_OWNED_SQUARE && sqrState <= AVAILABLE_SQUARE) {
_state = sqrState;
_square.graphics.beginFill(STATE_COLORS[sqrState]);
_square.graphics.drawRect(0,0,SQUARE_LENGTH,SQUARE_LENGTH);
_square.graphics.endFill();
} else {
throw new ArgumentError('State not acceptable.');
}
}
public function getState():int
{
return _state;
}
private function formSquare():MovieClip
{
var mvclp:MovieClip = new MovieClip();
mvclp.graphics.beginFill(STATE_COLORS[NEUTRAL_SQUARE]);
mvclp.graphics.drawRect(0,0,SQUARE_LENGTH,SQUARE_LENGTH);
mvclp.graphics.endFill();
return mvclp;
}
}
}
</code></pre>
<p>Here is some calling code. I dispatch that click event (<code>sendClick()</code>) so my actual SquareSpace variable can handle clicks, rather than having the event listeners for the movieclip square outside of the class.</p>
<p></p>
<pre><code>private function setUpBlankSubBoard (xOffset:int, yOffset:int, topBoard:int):void
{
for (var boxIndX:int = 1; boxIndX <= BOARD_LENGTH; boxIndX++) {
for (var boxIndY:int = 1; boxIndY <= BOARD_LENGTH; boxIndY++) {
var newSqr:SquareSpace = new SquareSpace(
xOffset + (SquareSpace.SQUARE_LENGTH * 1.2) * boxIndX,
yOffset + (SquareSpace.SQUARE_LENGTH * 1.2) * boxIndY);
newSqr.addEventListener (MouseEvent.CLICK, squareChosen); // Called an unrelated function
addChild (newSqr.addSquare());
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Overall this is looking pretty good. I do have a few questions and suggestions based on what I see.</p>\n<ol>\n<li><p>Constructor<br />\nYour class extends MovieClip therefore it IS a Movieclip. What is the purpose of the inner <code>_square</code> class variable? Is SquareSpace meant to be purely a logic controller class with <code>_square</code> being the visual representation of the square? If so there is no need for SquareSpace to extend MovieClip. I would look at <code>EventDispatcher</code> or just plain <code>Object</code>.</p>\n</li>\n<li><p><code>addSquare</code>/<code>sendClick</code><br />\nI'm not sure I'm understanding the purpose of these methods. Can you explain your thought behind them?</p>\n</li>\n<li><p><code>changeSquareState</code><br />\nFor state control/detection you generally want to use a switch statement. That way adding more states in the future is much easier.</p>\n</li>\n<li><p>The State Constants<br />\nThis is more of a cosmetic comment but I usually prepend any constants with the word <code>STATE_</code> so that you/other developers can easily tell that those are values intended to be used for state control and passed into <code>changeSquareState</code>.</p>\n</li>\n<li><p>Argument Error<br />\nA really minor comment but I like to include the state which is not acceptable in the error statement. Makes debugging in the future easier. Not a big deal though.</p>\n</li>\n<li><p>Future Design<br />\nAs you build out this game do you plan on using the Flash timeline to position and configure your assets or are you going pure AS3?</p>\n</li>\n<li><p>Package<br />\nGenerally you want to organize each of your classes into a package. If you're not using a proper IDE like FlashBuilder, FlashDevelop, or FDT this will be a bit of a pain but it's good practice none the less. Packages generally look like reversed domain names so for example your SquareSpace class might be in the following package <code>com.alex.ultimatetictactoe.square</code></p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:58:02.793",
"Id": "73622",
"Score": "0",
"body": "Thanks for #1: I switched to `EventDispatcher` #2: I've edited my question to include some calling code. Hopefully that might help! #3: Changed! #4: Good idea, renamed my consts! #5: Got it #6 It's all in AS3, nothing on the timeline! #7: I didn't think this project would last, so I didn't bother structure my directories when I started! But now that it looks fairly good, I've added some packages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:24:01.743",
"Id": "73712",
"Score": "1",
"body": "#2 That makes sense. I usually name my event handlers using the convention on{item}{eventType} so I would rename `sendClick` to `onSquareClick`. That way I know it's an event handler at first glance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-25T03:57:44.427",
"Id": "42728",
"ParentId": "42642",
"Score": "8"
}
},
{
"body": "<p>Besides what mbaker3 wrote, I just have one thing to add (for now at least), I consider it quite important though:</p>\n\n<pre><code> public function addSquare():MovieClip \n {\n _square.addEventListener(MouseEvent.CLICK, sendClick);\n return _square;\n }\n</code></pre>\n\n<ol>\n<li>This method doesn't add the actual square to anything and therefore it's name is misleading</li>\n<li>This method adds an event listener each time it is called, so calling it twice would add two event listeners (If I remember my ActionScript correctly)</li>\n</ol>\n\n<p>I strongly suggest <strong>adding the event listener in the constructor instead,</strong> and only returning <code>_square</code> in the method, and <strong>renaming</strong> the method to <code>getSquare()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:00:21.767",
"Id": "43550",
"ParentId": "42642",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "42728",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T05:41:46.110",
"Id": "42642",
"Score": "15",
"Tags": [
"object-oriented",
"game",
"actionscript-3",
"community-challenge"
],
"Title": "UltimateTicTacToe - ActionScript Style!"
} | 42642 |
<p>I'm new to this PDO PHP and I have coded this spaghetti style. I hope you can give me idea how to improve using prepared statements. I'm not a lazy person, but I really need your help to improve my coding style.</p>
<pre><code> try {
$select = "SELECT users.id, users.users_id, username, firstname, lastname, password, position";
$from = " FROM users
INNER JOIN users_role
ON users.id=users_role.users_id
INNER JOIN role
ON users_role.users_role=role.id";
$where = " WHERE";
$placeholders = array();
if ($category !=''){
if ($category == 'admin'){
$where .= " position='admin'";
if ($character_match !=''){
$where .= " AND ";
}
}
else if($category == 'instructor'){
$where .= " position='Instructor'";
if ($character_match !=''){
$where .= " AND ";
}
}
else if ($category=='student'){
$where .= " position='student'";
if ($character_match !=''){
$where .= " AND ";
}
}
elseif ($category == 'Unverified'){
$where .= " position='Unverified'";
}
else if ($category == 'view_all') {
$where = "";
if ($character_match != ''){
$where = " WHERE ";
}
}
if($character_match !=''){
$where .= "(username LIKE '" . $character_match . "%'"
. " OR firstname LIKE '" . $character_match . "%'"
. " OR lastname LIKE '" . $character_match . "%')";
$placeholders[] = $character_match;
}
$where .= " ORDER BY position ASC";
$sql = $select . $from . $where;
$q = $this->db->prepare($sql);
$q->execute($placeholders);
}
}
catch(PDOException $e){
$e->getMessage();
}
$rows = array();
while($row = $q->fetch(PDO:: FETCH_ASSOC)){
$rows[] = $row;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T08:34:32.567",
"Id": "73492",
"Score": "0",
"body": "That's not spaghetti style. Spaghetti style is when you intermingle this code in the middle an html page while rendering a table from the results :)"
}
] | [
{
"body": "<p>First, a few minor remarks:</p>\n\n<ul>\n<li><p>Your spacing and indentation is inconsistent, e.g. <code>$category=='student'</code> vs. <code>$category == 'instructor'</code>, <code>else if</code> vs. <code>elseif</code>. If you have decided on a coding style, follow it through. It doesn't matter that much what you do as long as you do it consistently.</p></li>\n<li><p>Your code snippet does not seem to be wrapped inside a function. Do this even when the code is only used in one place, as it lends a self-documenting quality to the code, and makes the scope of some variables clearer.</p></li>\n</ul>\n\n<p>Now on to your code. Assuming that <code>$character_match</code> is external data and has not been sanitized, you are suffering from an SQL injection vulnerability. Consider what happens with <code>%'; DROP TABLE students; --</code> or <a href=\"https://xkcd.com/327/\" rel=\"nofollow\">similar fun</a>. Use the <a href=\"http://php.net/manual/en/pdo.quote.php\" rel=\"nofollow\"><code>quote</code> method</a> on your PDO object to avoid this.\nYour current use of placeholders makes exactly zero sense, as far as I can see. (I.e. I am not seeing any placeholders, but an argument to <code>execute</code>)</p>\n\n<p><code>if ($category == 'Unverified' && $character_match != '')</code>, then you will generate invalid SQL.</p>\n\n<p>You do not handle the case that <code>$category</code> is none of the given strings.</p>\n\n<p>Your cases for <code>admin</code>, <code>instructor</code>, and <code>student</code> are exactly the same, except that the capitalization of <code>instructor</code> changes. If possible clean up your DB to be consistent in this respect. In the meanwhile, you could use an array:</p>\n\n<pre><code># careful: the values have to be safe for SQL without further escaping\n$position = array(\n 'admin' => 'admin',\n 'instructor' => 'Instructor',\n 'student' => 'student');\n\nif (array_key_exists($category, $position)) {\n $where .= \" position='\" . $position[$category] . \"'\";\n ...\n}\n</code></pre>\n\n<p>This means you only have to handle the two special cases <code>Unverified</code> and <code>view_all</code> differently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T09:35:47.683",
"Id": "42645",
"ParentId": "42644",
"Score": "1"
}
},
{
"body": "<p>There's different things about your code, the most important one is to start using PDO tools to facilitate our work. Use named parameters, and dissociate your query construct from setting correct values:</p>\n\n<ol>\n<li><p>if the only thing you're going to catch is echo the error message, there's absolutely no reason to do it. setting <code>$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);</code> will react in the exact same way.</p></li>\n<li><p>for the <code>LIKE</code> portion of the code: named parameters must contain a full litteral string (or integer, or whatever) but you have to put wildcards <code>%</code> IN the string for the <code>LIKE</code> to work. exemple: <code>$values[':character_match'] = '%value%'</code></p></li>\n</ol>\n\n<hr>\n\n<pre><code>$sql = 'SELECT users.id, users.users_id, username, firstname, lastname, password, position\n FROM users\n INNER JOIN users_role ON users.id=users_role.users_id\n INNER JOIN role ON users_role.users_role=role.id ';\nif ($category != 'view_all') {\n $sql .= 'WHERE position=:position ';\n}\nif ($character_match != '') {\n $sql .= ($category == 'view_all' ? ' WHERE ' : ' AND ');\n $sql .= '(username LIKE :character_match OR firstname LIKE :character_match OR lastname LIKE :character_match)';\n $values[':character_match'] = $character_match;\n}\n$sql .= ' ORDER BY position';\n\nswitch ($category) {\n case 'admin':\n $values[':position'] = 'admin';\n break;\n case 'instructor':\n $values[':position'] = 'Instructor';\n break;\n case 'student':\n $values[':position'] = 'student';\n break;\n case 'Unverified':\n $values[':position'] = 'Unverified';\n break;\n}\n\n$q = $this->db->prepare($sql);\n$q->execute($placeholders);\n\n$rows = array();\nwhile ($row = $q->fetch(PDO:: FETCH_ASSOC)) {\n $rows[] = $row;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:18:47.897",
"Id": "42688",
"ParentId": "42644",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T07:08:59.297",
"Id": "42644",
"Score": "4",
"Tags": [
"php",
"beginner",
"mysql",
"pdo"
],
"Title": "MySQL PDO query to search by name and role"
} | 42644 |
<p>I would like to improve the interfaces of some polymorphic classes going from positional to named parameters and I came up with the fluent interface.</p>
<p>The following is the most clean, compact and compilable (-std=c++11 required) example that I have been able to come up with:</p>
<pre><code>#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
struct Figure {
string _name;
Figure * name(const string & str) { _name=str; return this; }
virtual double area() const=0;
};
struct Circle: Figure {
double _radius;
Circle * radius(double r) { _radius=r; return this;}
double area() const override {return M_PI*_radius*_radius;}
};
struct Square: Figure {
double _side;
Square * side(double s) { _side=s; return this;}
double area() const override {return _side*_side;}
};
struct Scene {
vector<Figure*> v;
~Scene() { for (auto & f : v) delete f; }
Scene & add(Figure * f) {v.push_back(f); return *this;}
double total_area() const {
double total=0;
for (auto f : v) total += f->area();
return total;
}
};
int main() {
Scene scene;
scene.add((new Circle)->radius(1.)->name("c1"))
.add((new Square)-> side(1.)->name("s1"));
cout << "Total area: " << scene.total_area() << endl;
return 0;
}
</code></pre>
<p>I have a couple of issues with this:</p>
<ol>
<li>That is an ugly place to have a <code>new</code> operator, could it be avoided somehow?</li>
<li>After having called the method <code>name("name")</code> the type is lost so there is still an ordering to respect: <code>add((new Square)->name("s1")->side(1.))</code> will not compile. You should imagine to have many levels of inheritance and lots of parameters to be setted!</li>
</ol>
<p>How would you address these issues and improve the code? C++1y is allowed and preferred to Boost?</p>
<hr>
<p>For <em>further improvements</em> see the related question: <a href="https://codereview.stackexchange.com/questions/42748/variadic-templates-and-pointers-to-member-functions-to-achieve-a-named-parameter">Variadic templates and pointers to member functions to achieve a named-parameters interface in C++</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:15:58.053",
"Id": "73496",
"Score": "0",
"body": "as a quick aside: you can solve the type problem with a template, e.g. `template <T> struct Figure { T name(...) ...}`, then `struct Square: Figure<Square*>`. Not sure if that's the exact syntax, but the general idea should work."
}
] | [
{
"body": "<blockquote>\n <p>After having called the method name(\"name\") the type is lost so there is still an ordering to be respected: add((new Square)->name(\"s1\")->side(1.)) will not compile. </p>\n</blockquote>\n\n<p>You could do that using a template as follows:</p>\n\n<pre><code>template<typename TSelf>\nstruct Figure {\n string _name;\n TSelf* name(const string & str)\n {\n _name=str;\n return (TSelf*)this; // could be a dynamic or static cast\n }\n virtual double area() const=0;\n};\n\nstruct Circle: Figure<Circle> {\n ... etc ...\n};\n</code></pre>\n\n<p>An alternative would be a method in the subclass, which hides the method in the superclass:</p>\n\n<pre><code>struct Circle: Figure {\n Circle* name(const string & str) { Figure::name(str); return this; }\n ... etc ...\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:30:37.750",
"Id": "73497",
"Score": "0",
"body": "Static polymorphism would require me a lot of refactoring, but your second alternative is cool: it allows me to stress all the parameters that are important to an object, just looking at its header! Thank you, +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:22:19.997",
"Id": "42648",
"ParentId": "42647",
"Score": "7"
}
},
{
"body": "<blockquote>\n <p>That is an ugly place to have a new operator, could it be avoided somehow?</p>\n</blockquote>\n\n<p>The accepted answer to <a href=\"https://stackoverflow.com/a/20848444/49942\">About the usage of new and delete, and Stroustrup's advice</a> suggests you use <a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared\" rel=\"nofollow noreferrer\"><code>std::make_shared</code></a> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:49:47.623",
"Id": "42661",
"ParentId": "42647",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>I have a couple of issues with this:</p>\n \n <ol>\n <li>That is an ugly place to have a new operator, could it be avoided somehow?</li>\n <li>After having called the method name(\"name\") the type is lost so there is still an ordering to respect: add((new Square)->name(\"s1\")->side(1.)) will not compile.</li>\n </ol>\n \n <p>You should imagine to have many levels of inheritance and lots of parameters to be setted!</p>\n</blockquote>\n\n<p><code>1.</code> Yes. You can use a solution based on passing a std::shared_ptr or std::unique_ptr (unique_ptr should be prefered if you are passing ownership, like in your example).</p>\n\n<p><strong>Second edit</strong>:</p>\n\n<p>Alternately, you could try implementing this:</p>\n\n<pre><code>std::vector<std::unique_ptr<Figure>> v;\n\ntemplate<typename T, typename ...Args>\nShape& add(Arg... args)\n{\n // I think this is correct;\n // but don't have compiler nearby\n v.emplace_back(std::unique_ptr<Figure>{new T{std::forward<Args>(args)...}});\n}\n</code></pre>\n\n<p>client code:</p>\n\n<pre><code>Shape s;\ns.add<Circle>(\"c1\", 10); // assumes constructor shown at point below (2)\n</code></pre>\n\n<p><strong>End second edit</strong>.</p>\n\n<p><code>2.</code> You are writing client code assuming that your Figure class hierarchy supports polymorphic behavior (i.e. <code>(new Circle)->name(\"c1\")->radius(1.)</code> assumes that the return type of <code>name()</code> will support a <code>radius</code> function).</p>\n\n<p>This implies you should write the <code>Figure</code> base class to support invalid operations on compilation:</p>\n\n<pre><code>struct Figure {\n string _name;\n Figure * name(const string & str) { _name=str; return this; }\n virtual double area() const=0;\n virtual Figure * radius(double r) { throw std::logic_error(\"invalid op.\"); }\n virtual Figure * side(double s) { throw std::logic_error(\"invalid op.\"); }\n // any other operations here\n};\n</code></pre>\n\n<p><strong>Edit</strong>: The correct solution (since we are all creative people, \"correct\" is actually debatable) would be to avoid call chains for constructing your objects completely:</p>\n\n<p>old code:</p>\n\n<pre><code>Scene scene;\nscene.add((new Circle)->radius(1.)->name(\"c1\"))\n .add((new Square)-> side(1.)->name(\"s1\"));\n</code></pre>\n\n<p>new code:</p>\n\n<pre><code>struct Circle: Figure {\n double _radius;\n Circle(std::string name, double radius = 0.)\n : Figure{std::move(name)}, _radius{radius} {}\n // ... \n};\n\nstruct Square: Figure {\n double _side;\n Square(std::string name, double side = 0.)\n : Figure{std::move(name)}, _side{side} {}\n // ... \n};\n\nScene scene;\nscene.add(new Circle{\"c1\", 1.});\nscene.add(new Square{\"s1\", 1.});\n</code></pre>\n\n<p><strong>End edit</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:44:40.617",
"Id": "73522",
"Score": "0",
"body": "Your edit is exactly what I have now and what I want to improve since those cctors contains way to many parameters! By the way, why you are using std::move instead of the good old const reference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:53:28.040",
"Id": "73527",
"Score": "0",
"body": "@DarioP, It is a design principle that states you should pass completely constructed objects into your constructors. If the object has it's own copy of the value (i.e. Figure::_name is not a const reference) I prefer to create the value in the constructor. This has the advantage of enabling all std::string constructors optimally, or close (consider: `Circle c{std::string{b, e}};` where b and e are iterators: to implement optimally with `const&`, you would need a new constructor (`Circle(std::string&&)`). Passing std::string by value enables use of `std::string(std::string&&)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:54:40.703",
"Id": "73528",
"Score": "0",
"body": "In the end I guess it's a matter of style/consistence and coding conventions for your project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:03:26.040",
"Id": "73565",
"Score": "0",
"body": "@DarioP, to reduce the number of parameters, consider passing in a collection of values (`Circle c{\"c1\", defaults};` where defaults looks like `struct X { const double default_radius = 1; const double default_width = .5; /* etc. */} const defaults;`. Then, it's a single parameter :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:37:17.967",
"Id": "73671",
"Score": "0",
"body": "I believe that your `new T{std::forward<Args>(args)}` lacks an ellipsis after `arg` :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:18:29.897",
"Id": "73679",
"Score": "0",
"body": "@Morwenn, Thanks, I have edited the code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:23:01.460",
"Id": "42666",
"ParentId": "42647",
"Score": "7"
}
},
{
"body": "<p>Another thing to consider in your current design:</p>\n\n<pre><code>~Scene() { for (auto & f : v) delete f; }\n</code></pre>\n\n<p>You are calling the destructor of the base here, not the derived classes' destructors. Remember to make a virtual destructor in your class to solve this problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:47:29.343",
"Id": "73524",
"Score": "0",
"body": "Of course, I just did't want to overload the example making the question less clear, so please stick to the questions!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:52:29.240",
"Id": "73526",
"Score": "0",
"body": "Cheers. You just emphasized that your example was working and compilable, so i thought i would chip in.. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:02:38.963",
"Id": "73529",
"Score": "5",
"body": "@DarioP - as per the [help/on-topic] people can review any aspect of your code... 'please stick to the questions!' is a request, not a demand. Shaggi, welcome to code-review, you just passed the first-answer review ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:15:25.837",
"Id": "73534",
"Score": "0",
"body": "In the framework of the example what's the point of the virtual destructor? It does absolutely nothing, however I accept the help center policy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:22:58.280",
"Id": "73536",
"Score": "0",
"body": "@rolfl why thanks! i guess i'm used to stackoverflow's mentality\n-dariop sorry for going 'offtopic', that wasn't my intention. however to answer your question (in your comment), since you are deleting a derived class through a base class pointer without a virtual destructor, you're actually invoking undefined behaviour afaik."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:47:25.143",
"Id": "73540",
"Score": "0",
"body": "@Shaggi I'm just using the destructor of the base class, which is totally fine in this case. The example compiles just fine on gcc and does not have any leak, but the most important aspect is it does what it was written for: illustrate the weak points I have in my interface design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:06:14.493",
"Id": "73545",
"Score": "1",
"body": "But it _is not_ totally fine. Yes it works, but you're still invoking undefined behaviour (which may or may not immediately show itself)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:19:08.290",
"Id": "73546",
"Score": "0",
"body": "By running this program I will have my hdd formatted, but not now, in ten years! Ok, I can live with this fantasy. Nobody is saying is not correct, but it is simply not the point. That's all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:40:04.090",
"Id": "73602",
"Score": "0",
"body": "Nice answer! Keep up the good work!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T18:37:35.220",
"Id": "74478",
"Score": "0",
"body": "Since this has become the most upvoted answer, I'm accepting this as a protest against a community behaviour that I find totally crazy. Keep up the good work!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:36:14.803",
"Id": "42668",
"ParentId": "42647",
"Score": "9"
}
},
{
"body": "<p>I disagree with the fundamental motivation here. Fluent interfaces are fine for builder objects, but constructing a half-baked class and initializing its fields with chained setters just feels wrong. The constructor should be enough to initialize the object.</p>\n\n<p>As for the pointer, consider using value semantics polymorphic objects through type erasure, as demonstrated by Sean Parent here:</p>\n\n<p><a href=\"http://www.youtube.com/watch?v=_BpMYeUFXv8\" rel=\"noreferrer\">http://www.youtube.com/watch?v=_BpMYeUFXv8</a></p>\n\n<p>The slides can be found here:</p>\n\n<p><a href=\"https://github.com/boostcon/cppnow_presentations_2012\" rel=\"noreferrer\">https://github.com/boostcon/cppnow_presentations_2012</a></p>\n\n<p><strong>Edit:</strong> Since that presentation is quite long, a short summary: the idea is to have types that act polymorphic but have value semantics. In a way they act like custom smart pointers, but they completely hide their pointer nature. <code>std::function<></code> is an example of such a type.</p>\n\n<p>Here's a very simple example of what that might look like.</p>\n\n<pre><code>class Figure {\nprivate:\n class Interface {\n public:\n virtual ~Interface() {}\n virtual Interface* copy() const = 0;\n virtual std::string name() const = 0;\n virtual double area() const = 0;\n };\n template <typename T>\n class Implementation : public Interface {\n T t;\n public:\n Implementation(const T& t) : t(t) {}\n Implementation(T&& t) : t(std::move(t)) {}\n Interface* copy() const override { return new Implementation(*this); }\n std::string name() const override { return t.name(); }\n double area() const override { return t.area(); }\n };\n std::unique_ptr<Interface> value;\n\npublic:\n template <typename T>\n Figure(T&& t) : value(new Implementation(std::forward<T>(t))) {}\n\n Figure(const Figure& o) : value(o.value->copy()) {}\n Figure& operator =(const Figure& o) { value.reset(o.value->copy()); }\n ~Figure() = default;\n\n double area() const { return value->area(); }\n};\n\nclass Circle { // no inheritance\n std::string myname;\n double myradius;\n\npublic:\n Circle(const std::string& name, double radius)\n : myname(name), myradius(radius) {}\n std::string name() const { return myname; }\n double area() const { return myradius * myradius * M_PI; }\n};\n\nclass Scene {\n std::vector<Figure> v; // no pointers\n\n template <typename T>\n Scene& add(T&& f) { v.push_back(std::forward<T>(f)); return *this; }\n double total_area() const {\n return boost::range::accumulate(\n v | boost::adapters::transformed(\n [](const Figure& f) { return f.area(); }));\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:36:43.747",
"Id": "73538",
"Score": "1",
"body": "I agree with you: even default constructors should always return fully constructed objects, eventually with a set of default parameters. That's fine, I never thought about doing differently. Is there a code snippet that illustrate the concept explained in about a couple of hours presentation?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:16:16.000",
"Id": "42675",
"ParentId": "42647",
"Score": "6"
}
},
{
"body": "<p>What you've written isn't really a \"named parameter\" API; it's more of a \"getter/setter\" API. Here's what it would look like in idiomatic C++11 — basically, changing all your <code>new/delete</code> heap traffic into plain old objects and using <code>setName()</code> for your mutator instead of just <code>name()</code>.</p>\n\n<pre><code>#include <iostream>\n#include <cmath>\n#include <vector>\n#include <string>\n\nstruct Figure {\n std::string m_name;\n Figure& setName(const std::string& str) { m_name = str; return *this; }\n virtual double getArea() const = 0;\n};\n\nstruct Circle : public Figure {\n double m_radius;\n Circle& setRadius(double r) { m_radius = r; return *this; }\n Circle& setName(const std::string& str) { Figure::setName(str); return *this; }\n double getArea() const { return M_PI * m_radius * m_radius; }\n};\n\nstruct Square : public Figure {\n double m_side;\n Square& setSide(double s) { m_side = s; return *this; }\n Square& setName(const std::string& str) { Figure::setName(str); return *this; }\n double getArea() const { return m_side * m_side; }\n};\n\nstruct Scene {\n // Unfortunately, the naive implementation of polymorphism\n // requires heap traffic. We can fix this, but for now let's\n // leave it using the heap.\n //\n std::vector<std::unique_ptr<Figure>> v;\n\n // Move an arbitrary Figure into the scene.\n template<typename FigureSubclass>\n Scene& add(FigureSubclass &&f) {\n using FSC = typename std::remove_reference<FigureSubclass>::type;\n std::unique_ptr<Figure> newFig(new FSC(std::forward<FigureSubclass>(f)));\n v.emplace_back(std::move(newFig));\n return *this;\n }\n\n double getTotalArea() const {\n double total=0;\n for (const auto& f : v) total += f->getArea();\n return total;\n }\n};\n\nint main() {\n Scene scene;\n scene.add(Circle().setRadius(1).setName(\"c1\"))\n .add(Square().setSide(1).setName(\"s1\"));\n std::cout << \"Total area: \" << scene.getTotalArea() << std::endl;\n return 0;\n}\n</code></pre>\n\n<p>For \"non-naive\" implementations of polymorphism (and/or heterogeneous containers), see <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil\" rel=\"nofollow noreferrer\">Sean Parent's talk at GoingNative</a> or other StackExchange questions such as <a href=\"https://stackoverflow.com/questions/18856824/ad-hoc-polymorphism-and-heterogeneous-containers-with-value-semantics\">Ad hoc polymorphism and heterogeneous containers with value semantics</a> (a great grab-bag of keywords for your further Google-searching, btw).</p>\n\n<p>On the <em>other</em> other hand, when I hear \"named parameters\", I think of an API that's more like</p>\n\n<pre><code>Scene.add(Circle(\"radius\", 1.0))\n .add(Square(\"side\", 1.0));\n</code></pre>\n\n<p>which is a whole new bag of problems, but doesn't have anything to do with polymorphism/heterogeneity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:29:23.863",
"Id": "73638",
"Score": "0",
"body": "I do not see the point of having `set` in front of every methods, but all the rest looks very nice! I also appreciate a lot the fact of using `.` instead of `->`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:39:57.673",
"Id": "42714",
"ParentId": "42647",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42668",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T10:02:14.197",
"Id": "42647",
"Score": "10",
"Tags": [
"c++",
"c++11",
"inheritance",
"polymorphism",
"fluent-interface"
],
"Title": "Fluent interface and polymorphism for building a scene with shapes"
} | 42647 |
<p>I have implemented customized encoding mechanism for javaUTF16. Does this implementation support all the characters? </p>
<pre><code>public class Encoding {
public static void main(String[] args) {
byte [] arr = new byte[1000];
String str = "abcde" ; //even this encoding works supplementary characters
Encode(arr,0,str);
System.out.println(Decode(arr,str.length()));
}
public static byte[] Encode(byte[] ByteArray , int offset ,String str) {
char[] ch = str.toCharArray();
for(char c : ch) {
ByteArray[offset++] = (byte) (c >>> 8);
ByteArray[offset++] = (byte) (c & 0xff);
}
return ByteArray;
}
public static String Decode(byte[] ByteArray ,int len) {
char [] res = new char[len*2];
int i = 0;
int offset = 0;
while(i < len) {
res[i] = (char) ((ByteArray[offset++] << 8) | (ByteArray[offset++] & 0xff));
i++;
}
return new String(res);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T12:45:46.603",
"Id": "73664",
"Score": "0",
"body": "I would like to be sure you already read http://utf8everywhere.org/"
}
] | [
{
"body": "<h2>Style</h2>\n\n<p>Method names in Java <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">start with a lower-case letter</a>.</p>\n\n<ul>\n<li><code>Encode(...)</code> -> <code>encode(...)</code></li>\n<li><code>Decode(...)</code> -> <code>decode(...)</code></li>\n</ul>\n\n<p>Variable names in java start with a lower-case letter too:</p>\n\n<ul>\n<li><code>ByteArray</code> -> <code>byteArray</code></li>\n</ul>\n\n<h2>Error Handling</h2>\n\n<p>Your encode method assumes there is enough space in the array....</p>\n\n<p>You should have something like:</p>\n\n<pre><code>if (offset < 0 || offset + (ch.length) > byteArray.length) {\n throw new IllegalArgumentException(\"Not enough space in array....\");\n}\n</code></pre>\n\n<h2>Functionality</h2>\n\n<p>The code looks functional, but there is one item that is non standard....</p>\n\n<p>If you are passing in an array to a method for it to be populated, you should not also return it as the return value.... the method <code>encode(...)</code> should be a <code>void</code> method.</p>\n\n<h2>About Surrogates, etc.</h2>\n\n<p>It is right that you are concerned about Surrogates and other esoteric encoding issues.</p>\n\n<p>On the other hand, your code does a simple transformation that is 100% reversible. It simply converts a char system to a byte system, and back again. This transformation does not need to be concerned about items like surrogates.</p>\n\n<p>Because the input to the encode function is always a String, the output will also decode back in to a valid string too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:04:08.843",
"Id": "73504",
"Score": "0",
"body": "Thanks for the reply :)\nBut my major concern is, how this code handles Surrogate or complimentary characters? Even though i'm not checking for surrogates , it still encodes all the supplementary characters .. Does it fail in any scenario ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:07:33.217",
"Id": "73505",
"Score": "0",
"body": "@srikanth It happens to handle surrogates correctly because Java's `char` is just a 16-bit code unit, not an Unicode code point. I.e. Java has already implicitly taken care of that, and you only have to translate each code unit into their corresponding bytes. Another way to interpret this is that Java's strings are actually more like UCS-2 which can be used as UTF-16, just like a byte sequence can be used as UTF-8"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:12:42.667",
"Id": "73506",
"Score": "0",
"body": "@amon : okay . Why java implementation of UTF16 considers Surrogate checks ? If you look this method UnicodeEncoder.encodeLoop(buffer,buffer) they are checking for surrogates. Could you please explain me why are inserting checks for surrogates?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:20:21.743",
"Id": "73508",
"Score": "0",
"body": "@srikanth That's just a few sanity checks (i.e. making sure that the whole code point can be directly encoded, instead of terminating with a half-encoded character in the output buffer). Note that in case of surrogate pairs, the whole character (two pairs) is first parsed to an `int` (which can hold arbitrary codepoints), and then translated back to a byte representation of the surrogates. Think: `int` is the new `char`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:22:57.017",
"Id": "73509",
"Score": "0",
"body": "@srikanth ... what Amon says. Also, a fair number of checks [to make sure there is space in the target area](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/nio/cs/UnicodeEncoder.java#70)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:26:29.503",
"Id": "73510",
"Score": "0",
"body": "@amon: Thanks a lot :) Can i directly bench mark the performance of Customized utf-16 vs Java's Utf-16 ? Do i need to consider any other external factors? As i already tried this , performance of this method is 3*x times faster then java utf16 method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:29:40.667",
"Id": "73511",
"Score": "0",
"body": "@srikanth your method assumes the input String is valid. The java one ensures it is valid, and also the output is valid. Yours will fail with the input string `encode(new byte[100], 0, \"\\u0000 is null byte\");` (well, it won't fail, but the output 'file' is not a valid unicode document)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:43:14.210",
"Id": "73512",
"Score": "0",
"body": ":) okay. I've implemented a cutomised UTF8 too. Would you mind to help me in that too?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T11:40:57.710",
"Id": "42650",
"ParentId": "42649",
"Score": "11"
}
},
{
"body": "<h3>Question of Completeness</h3>\n\n<p>Yes, your code covers all Unicode characters, including the <a href=\"http://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B10000_to_U.2B10FFFF\">supplementary characters U+10000 to U+10FFFF</a>, because you \"inherit\" that functionality from the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#unicode\">way such characters would be stored in Java's <code>String</code> class</a>:</p>\n\n<blockquote>\n <h3>Unicode Character Representations</h3>\n \n <p>The <code>char</code> data type (and therefore the value that a <code>Character</code> object\n encapsulates) are based on the original Unicode specification, which\n defined characters as fixed-width 16-bit entities. The Unicode\n Standard has since been changed to allow for characters whose\n representation requires more than 16 bits. The range of legal code\n points is now U+0000 to U+10FFFF, known as Unicode scalar value.\n (Refer to the <a href=\"http://www.unicode.org/reports/tr27/#notation\"><em>definition</em></a> of the U+<em>n</em> notation in the Unicode Standard.)</p>\n \n <p>The set of characters from U+0000 to U+FFFF is sometimes referred to\n as the <em>Basic Multilingual Plane (BMP)</em>. Characters whose code points\n are greater than U+FFFF are called <em>supplementary characters</em>. The Java\n platform uses the UTF-16 representation in <code>char</code> arrays and in the\n <code>String</code> and <code>StringBuffer</code> classes. In this representation, supplementary\n characters are represented as a pair of <code>char</code> values, the first from\n the <em>high-surrogates</em> range, (\\uD800-\\uDBFF), the second from the\n <em>low-surrogates</em> range (\\uDC00-\\uDFFF).</p>\n \n <p>A <code>char</code> value, therefore, represents Basic Multilingual Plane (BMP)\n code points, including the surrogate code points, or code units of the\n UTF-16 encoding. An int value represents all Unicode code points,\n including supplementary code points. […]</p>\n</blockquote>\n\n<h3>Reinventing the Wheel</h3>\n\n<p>Since you did not tag your question as <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a>, I'm obligated to mention that you could accomplish the task more simply using the built-in support for charsets.</p>\n\n<pre><code>private static final Charset UTF_16 = Charset.forName(\"UTF-16BE\");\n\npublic static byte[] Encode(byte[] ByteArray , int offset ,String str) {\n byte[] bytes = str.getBytes(UTF_16);\n System.arraycopy(bytes, 0, ByteArray, offset, bytes.length);\n return ByteArray;\n}\n\npublic static String Decode(byte[] ByteArray ,int len) {\n return new String(ByteArray, 0, 2 * len, UTF_16);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:12:32.543",
"Id": "42658",
"ParentId": "42649",
"Score": "17"
}
},
{
"body": "<p>Proceeding with a \"regular\" code review…</p>\n\n<p>In <code>Encode()</code>, <code>(byte)(c & 0xff)</code> could just be <code>(byte)c</code>.</p>\n\n<p>Your doubts about the completeness of your code could be alleviated with a more effective unit test. For example, you could try encoding (<a href=\"http://www.utf8-chartable.de/unicode-utf8-table.pl?start=128512\">U+1F600: the GRINNING FACE emoticon</a>).</p>\n\n<pre><code>public static void main(String[] args) {\n // U+1F600: the GRINNING FACE emoticon\n String orig = new String(Character.toChars(0x1f600));\n // Buffer size should not be hard-coded to 1000\n byte[] bytes = new byte[2 * orig.length()];\n\n System.out.println(orig);\n\n Encode(bytes, 0, orig);\n for (byte b : bytes) {\n System.out.printf(\"%02x \", b);\n }\n System.out.println();\n\n String recovered = Decode(bytes, orig.length());\n System.out.println(recovered);\n\n if (!orig.equals(recovered)) {\n System.out.println(\"Round trip conversion failed\");\n }\n}\n</code></pre>\n\n<p>The <code>len</code> parameter to <code>Decode(byte[] ByteArray, int len)</code> is deceptive. The method signature suggests that it would decode <code>len</code> bytes from <code>ByteArray</code>, but it actually decodes <code>ByteArray</code> until it obtains <code>len</code> characters. You could provide better usage hints by reversing the parameters, giving a better parameter name, and providing JavaDoc:</p>\n\n<pre><code>/**\n * Decodes the specified number of <tt>char</tt>s from\n * <tt>buf</tt>, a buffer containing text encoded in UTF-16BE.\n * (One <tt>char</tt> is one character in the Unicode Basic\n * Multilingual Plane. A Unicode supplementary character is\n * stored as two <tt>char</tt>s using a surrogate pair.)\n */\npublic static String Decode(int numChars, byte[] buf) {\n …\n}\n</code></pre>\n\n<p>Alternatively, change the semantics to meet my expectations.</p>\n\n<pre><code>/**\n * Decodes the first <tt>numBytes</tt> from <tt>buf</tt>,\n * a buffer containing text encoded in UTF-16BE. <tt>numBytes</tt>\n * must be an even number.\n */\npublic static String Decode(byte[] buf, int numBytes) {\n …\n}\n</code></pre>\n\n<p>In <code>Encode()</code>, it would be more logical to reorder the parameters with <code>String str</code> first. That would be consistent with other parts of the Java API, such as <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)\"><code>System.arraycopy()</code></a>, which put the source parameter before the destination.</p>\n\n<p>Your <code>Encode()</code> lets the caller specify an offset, but not a length. Your <code>Decode()</code> lets the caller specify a length, but not an offset. Some design consistency would be appreciated. (The simplest approach would be to allow neither offsets nor lengths to be specified.)</p>\n\n<p>As @rolfl points out, you violate naming conventions by using Capitalized names for Functions and Variables. In addition ,I'll note that your indentation is haphazard and you have odd spacing around your commas ,which is slightly annoying.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:57:13.520",
"Id": "73554",
"Score": "0",
"body": "You are right, no idea why I did not see that it is an char[]. :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:06:35.740",
"Id": "73557",
"Score": "2",
"body": "@ThorstenS. No worries. Welcome to Code Review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T12:31:43.103",
"Id": "73871",
"Score": "0",
"body": "I have implemented UTF-8 too .. Please have a look on this \n\nhttp://codereview.stackexchange.com/questions/42863/customised-java-utf-8"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:06:39.567",
"Id": "42664",
"ParentId": "42649",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T11:25:14.353",
"Id": "42649",
"Score": "11",
"Tags": [
"java",
"strings",
"unicode"
],
"Title": "Customised Java UTF-16"
} | 42649 |
<p>The word processor I've had in mind would be similar to Microsoft Word and OpenOffice. I am trying to keep my logic separated from the user Interface and that separated from the controller, basically using the MVC (Model View Controller).</p>
<p>Other things I would like reviewed would be code layout: should I try to abstract the code more? Am I using the correct writing surface (<code>JTextArea</code>) so that I can later implement a font style, size change on run time? Also, should I be doing something about thread safety (I understand that <code>JFrame</code>s are not thread safe, and I am going to be honest and say that I don't fully understand what this really means, but I am sure it has to do with a single thread running for the user input, graphics and business logic).</p>
<p><strong>Controller:</strong></p>
<pre><code>import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class ProcessEvents {
private WordFrame frame = new WordFrame();
private DataStuff data = new DataStuff();
private DialogBoxes dialogs = new DialogBoxes();
private boolean fileSaved;
String fileName = "";
int fontSize = 0;
public ProcessEvents(WordFrame frame, DataStuff data){
this.frame = frame;
this.data = data;
this.frame.addListener(new wordProcessListener());
}
class wordProcessListener implements ActionListener{
@SuppressWarnings("static-access")
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(frame.openMenuItem)){
frame.fileChooser.showOpenDialog(frame);
File f = frame.fileChooser.getSelectedFile();
System.out.println("Command Executed: open");
data.loadFile(f.getAbsoluteFile());
if(data.showText() != null){
System.out.println(data.showText());
frame.textArea.append(data.showText().toString());
}
}
if(e.getSource().equals(frame.FontMenuItem)){
System.out.println("font");
}
if(e.getSource().equals(frame.exitMenuItem)){
dialogs.getConfirmDialog("exitWithoutSave");
}
if(e.getSource().equals(frame.saveMenuItem)){
frame.fileChooser.showSaveDialog(null);
File f = frame.fileChooser.getSelectedFile();
String text = frame.textArea.getText();
data.saveFile(f.getAbsolutePath()+".txt", text);
System.out.println(f.getName());
fileSaved = true;
}
}
}
}
</code></pre>
<p><strong>Model:</strong></p>
<pre><code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataStuff {
private File file;
String text;
String name;
private File saveFile;
int counter = 0;
FileInputStream fis = null;
FileOutputStream fout = null;
StringBuilder sb = new StringBuilder(4096);
int count = 0;
public void loadFile(File fileName){
this.file = fileName;
try{
fis = new FileInputStream(file);
while ((counter = fis.read()) != -1) {
System.out.print((char) counter);
sb.append((char) counter);
}
}
catch(IOException ex){
System.out.println("file couldn't be opened, or was incorrect or you clicked cancel");
}
finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public StringBuilder showText(){
return sb;
}
public void saveFile(String name, String text) {
this.name = name;
try{
fout = new FileOutputStream(name);
fout.write(text.getBytes());
System.out.println("file saving worked");
}
catch(IOException e){
System.out.println("File failed to save or something went horribly wrong");
}
}
}
</code></pre>
<p><strong>View:</strong></p>
<pre><code>import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class WordFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JMenuBar menubar;
private JMenu fileMenu, editMenu, viewMenu;
JMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, FontMenuItem;
JTextArea textArea = new JTextArea(1000,900);
private int width = 1280, height = 980;
private JScrollPane scrollbar = new JScrollPane(textArea);
JFileChooser fileChooser = new JFileChooser();
private int textHeight = 12;
private Font yeah = new Font(Font.SANS_SERIF, 2, textHeight);
public WordFrame(){
setUI();
addMenuBar();
textArea.setFont(yeah);
}
public void setUI(){
this.setTitle("Word Processor");
this.setIconImage(new ImageIcon(this.getClass().getResource("Bridge.jpg")).getImage());
this.setSize(width, height);
this.setLocation(0,0);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(scrollbar);
}
public void addMenuBar(){
menubar = new JMenuBar();
fileMenu = new JMenu(" File ");
editMenu = new JMenu("Edit ");
viewMenu = new JMenu("View ");
newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
fileMenu.addSeparator();
fileMenu.setMnemonic('f');
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
saveMenuItem = new JMenuItem("Save");
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
FontMenuItem = new JMenuItem("Font");
editMenu.add(FontMenuItem);
menubar.add(fileMenu);
menubar.add(editMenu);
menubar.add(viewMenu);
this.setJMenuBar(menubar);
}
public void setFontSize(int i){
this.textHeight = i;
}
public void addListener(ActionListener listener){
openMenuItem.addActionListener(listener);
exitMenuItem.addActionListener(listener);
saveMenuItem.addActionListener(listener);
}
}
</code></pre>
<p><strong><code>Main</code> class:</strong></p>
<pre><code>public class Main {
/*
* @Version: 0.002
* not much in terms of commenting but a lot of this stuff is very obvious
*/
public Main(){
WordFrame mainFrame = new WordFrame();
DataStuff data = new DataStuff();
@SuppressWarnings("unused")
ProcessEvents process = new ProcessEvents(mainFrame, data );
mainFrame.setVisible(true);
}
public static void main(String args[]){
@SuppressWarnings("unused")
Main m = new Main();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:13:29.800",
"Id": "73507",
"Score": "3",
"body": "You shouldn't extends JFrame: http://stackoverflow.com/questions/1143923/why-shouldnt-you-extend-jframe-and-other-components"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:45:27.823",
"Id": "73523",
"Score": "0",
"body": "Thanks Landei, i have adjusted my code to remove that, WordFrame no longer extends JFrame but instantiates it."
}
] | [
{
"body": "<p>At face value the code looks OK. I want to focus on one area, though: File Management</p>\n\n<p>You use <code>FileInputStream</code> and <code>FileOutputStream</code> to read and write your files.</p>\n\n<p>Input/Output streams are designed for byte data. You do not have bytes, you have characters.</p>\n\n<p>But, you are trying to shoe-horn these characters in to single byte values, and this will cause all sorts of problems for non-ascii characters.... This code here:</p>\n\n<blockquote>\n<pre><code> fis = new FileInputStream(file);\n while ((counter = fis.read()) != -1) {\n System.out.print((char) counter);\n sb.append((char) counter);\n }\n</code></pre>\n</blockquote>\n\n<p>is the problem. <code>fis.read()</code> reads just a single byte, and then you shoe-horn that in to a char... which it may not be.</p>\n\n<p><strong>ALSO</strong> ... doing it that way is probably the slowest possible way to read a file ... ;-)</p>\n\n<p>Readers/Writers are designed for characters, and they do all the smarts of character encoding for you.</p>\n\n<p>By default, Readers/Writers will use the platform encoding for your files. I recommend that you force them to use the UTF-8 encoding so that you have consistency from one platform to the next.</p>\n\n<p>Additionally, you can save a fair amount of error handling if you use the Java7 try-with-resources structures.</p>\n\n<p>The write code will be something like:</p>\n\n<pre><code>public void saveFile(String name, String text) {\n this.name = name;\n\n try (Writer writer = new BufferedWriter(new OutputStreamWriter(\n new FileOutputStream(name), StandardCharsets.UTF_8))) {\n\n writer.write(text); \n writer.flush();\n System.out.println(\"file saving worked\"); \n } catch(IOException e){\n // do at least a little more than just print a useless message\n e.printStackTrace();\n System.out.println(\"File failed to save or something went horribly wrong\");\n } \n} \n</code></pre>\n\n<p>and the read code will look something like:</p>\n\n<pre><code>public void loadFile(File fileName){\n // this.file = fileName;\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(\n new FileInputStream(fileName), StandardCharsets.UTF_8))) {\n\n char[] buffer = new char[8192]; // decent size buffer.\n sb.setLength(0);\n int len = 0;\n while ((len = reader.read(buffer)) >= 0) {\n sb.append(buffer, 0, len);\n }\n\n } catch(IOException ex){\n // do at least a little more than just print a useless message\n ex.printStackTrace();\n System.out.println(\"file couldn't be opened, or was incorrect or you clicked cancel\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:47:58.960",
"Id": "73525",
"Score": "0",
"body": "Thanks rolfl i will be adjusting my code to reflect your recommendations. I am still reading your answer over just so i can compare the difference and understand the effects it will have, performance etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T13:02:17.983",
"Id": "42653",
"ParentId": "42651",
"Score": "8"
}
},
{
"body": "<p>I see you have a lot of different kinds of data defined as members of a single class:</p>\n\n<pre><code>private JMenuBar menubar;\nprivate JMenu fileMenu, editMenu, viewMenu;\nJMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, FontMenuItem;\nJTextArea textArea = new JTextArea(1000,900);\nprivate int width = 1280, height = 980;\nprivate JScrollPane scrollbar = new JScrollPane(textArea);\nJFileChooser fileChooser = new JFileChooser();\nprivate int textHeight = 12;\nprivate Font yeah = new Font(Font.SANS_SERIF, 2, textHeight);\n</code></pre>\n\n<blockquote>\n <p>I think I am asking a lot as is but I am predicting my code will bloat a lot more than it is.</p>\n</blockquote>\n\n<p>I suggest that you define more classes, which don't depend on being run as members of a JFrame.</p>\n\n<p>For example, you might have a <code>Document</code> class which encapsulates the contents (data) of the document. Methods of the <code>Document</code> class could let you edit the document, for example:</p>\n\n<ul>\n<li>Inject key-strokes (alpha-numeric keys, cursor keys)</li>\n<li>Select regions of (a.k.a. ranges in) the document (a letter, a word, a paragraph)</li>\n<li>Change properties of the selected range (font, bold, etc.)</li>\n</ul>\n\n<p>A reason for making this Document independent of (decoupled from) JFrame is so that you can use it in two places:</p>\n\n<ul>\n<li>Inside JFrame (driven by an interactive user)</li>\n<li>Outside JFrame (driven by an automated test suite)</li>\n</ul>\n\n<p>For example you might want an automated/regression test which:</p>\n\n<ul>\n<li>Creates a new document</li>\n<li>Inserts \"aa\"</li>\n<li>Positions the cursor between the two letters</li>\n<li>Inserts carriage return to break it into two paragraphs</li>\n<li>Asserts that the resulting document contains two paragraphs, each consisting of \"a\"</li>\n</ul>\n\n<p>Apart from the <code>Document</code> class, you might want another class which encapsulates the toolbar settings. For example when you insert \"aa\" into a document, the document might want to know which font you're using. One way to do that could be to pass Font information as a parameter to the <code>Document.insertText</code> method ... but that might mean adding a lot of extra parameters to a lot of extra functions ... a simpler way might be to pass an <code>EditorSettings</code> class (which contains all the properties like font, margins, grammar/dictionary, etc.) to the Document constructor, so that instead of needing to tell the Document (by pushing a parameter) what the settings are each time, the <code>Document</code> can discover the settings whenever it needs to (by reading the properties of the <code>EditorSettings</code> class).</p>\n\n<p>Apart from Document's using <code>EditorSettings</code>, your <code>JMenuBar</code> would be the other object that accesses your <code>EditorSettings</code>: to display existing settings and to let the user change existing settings.</p>\n\n<p>Another independent class is the rendered view of the document. For example, if the document is HTML, then the \"rendered view\" must calculate where to place each word (measuring the size of words in a given font, splitting paragraphs into multiple lines, etc.). The rendered view might take, as input, the document and the window size.</p>\n\n<p>In summary, perhaps your WordFrame should include the following data members:</p>\n\n<ul>\n<li>A <code>Document</code> instance</li>\n<li>A <code>EditorSettings</code> instance</li>\n<li>A <code>RenderedView</code> instance</li>\n<li>Various Swing components, e.g. toolbar etc.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:43:28.800",
"Id": "73521",
"Score": "0",
"body": "Hi Chris, that is an interesting answer. Interesting in the fact that it's going to take me some time to dissect my code and to understand how a class like Document should be defined. Would Document itself be a subclass of JTextArea since it would be adding functionality or would i be extracting the data from the JTextArea to the class Document. At the moment the Document class (to me) would look like it would need to be available to the Controller class and that WordFrame class would need to be available to the Document class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:13:26.833",
"Id": "73629",
"Score": "1",
"body": "I think that `Document` is the \"Model\" in an MVC pattern. It knows nothing about the UI. It contains the document's text and styling information. It supports methods like \"insertWord\", \"deleteRange\", etc. `RenderedView` also know nothing about Swing. Its contents are a list of words to be rendered, with the font and (X,Y) coordinates associated with each word. Your program: a) paints word from `RenderedView` onto its Swing control b) calls methods of `Document` when the user types-in text. When `Document`s content changes it notifies `RenderedView`, which recalculates itself and then repaints."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T13:46:53.780",
"Id": "42655",
"ParentId": "42651",
"Score": "6"
}
},
{
"body": "<p>Some general note about your program.</p>\n\n<p><strong>Comments</strong></p>\n\n<pre><code> /**\n * \n */\n private static final long serialVersionUID = 1L;\n</code></pre>\n\n<p>Never leave an empty comment. Comment are already something I'm not a fan of, but an empty one is useless. </p>\n\n<pre><code> /*\n * @Version: 0.002\n * not much in terms of commenting but a lot of this stuff is very obvious\n */\n</code></pre>\n\n<p>You don't have to say that there isn't much to say. When I read a comment, I want to have useful information about the code, not that I won't find anything of value. I would suggest that if you have nothing to say then just say nothing. </p>\n\n<p><strong>Naming convention</strong></p>\n\n<pre><code>JMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, FontMenuItem;\n</code></pre>\n\n<p>One of your variable don't respect the naming convention. \nPay close attention to that, when you don't respect convention your code is less readable.</p>\n\n<pre><code>private JMenuBar menubar;\n</code></pre>\n\n<p>Camel-case is not respected here.</p>\n\n<pre><code>private Font yeah = new Font(Font.SANS_SERIF, 2, textHeight);\n</code></pre>\n\n<p>Is <code>yeah</code> the name of the font ? If not, than I don't find <code>yeah</code> a good name. Something like <code>defaultFont</code> or the name of the font you'll use would be better.</p>\n\n<p><strong>Constant</strong></p>\n\n<pre><code>private int width = 1280, height = 980;\n</code></pre>\n\n<p>I didn't find a place in the code where you change the width and height. Those should probably be a constant with proper definition and naming.</p>\n\n<p><strong>Suppress warnings</strong> </p>\n\n<pre><code>public static void main(String args[]){\n @SuppressWarnings(\"unused\")\n Main m = new Main();\n}\n</code></pre>\n\n<p>Suppress warnings is something that I take particular attention. Why have you suppress the warning ? Warning should ring a bell and raise the question : Am I doing something wrong ? In your case, the warning is probably unused variable. But is it really an unused variable ? No, the action to start the application is in the constructor. Is it a good design, I'm wondering myself. I don't find it clear when an application start in a constructor. IMHO, constructor should initialize a class, not really much. If I were you I would probably have a method to actually start the application. </p>\n\n<p>But in general warning should pop the question, am I doing something wrong? A suppress warning should be the last option to that though process. In many case, it's acceptable to have a <code>@SupressWarning</code> but sometimes it's just an easy solution that could lead to maintenance problem later on. (Bad design decision etc..)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:38:16.497",
"Id": "73520",
"Score": "1",
"body": "Hi Marc, i have taken on board your comments and have amended my code to reflect proper naming conventions as well as changed private int width = 1280, height = 980; to static final int WIDTH = 1280, HEIGHT = 980;"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:29:49.637",
"Id": "42667",
"ParentId": "42651",
"Score": "12"
}
},
{
"body": "<p>I get the feeling that you are awkwardly confusing nouns and verbs, and, judging by the warnings, the compiler agrees with me.</p>\n\n<hr>\n\n<p>Let's start with <code>ProcessEvents</code>. Classes should be named as nouns; <code>ProcessEvents</code> is a verb phrase. <code>EventProcessor</code> would be more appropriate. <code>WordProcessorActionListener</code> would be more Javalicious.</p>\n\n<p>Another symptom of the confusion is that the <code>wordProcessorListener</code> inner class is actually the noun I was expecting (why the <code>lowerCaseNaming</code> for a class, by the way?), and the <code>ProcessEvents</code> constructor just attaches it to the frame. The outline should be:</p>\n\n<pre><code>public class WordProcessorActionListener implements ActionListener {\n private WordFrame frame;\n private DataStuff data;\n\n public WordProcessorEventListener(WordFrame frame, DataStuff data) {\n this.frame = frame;\n this.data = data;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n …\n }\n}\n</code></pre>\n\n<p>The event handler, which acts as a controller, has no business keeping <code>fileName</code>, <code>fontSize</code>, or any of the other state — all of that belongs in the model.</p>\n\n<hr>\n\n<p><code>Main</code> could use an analogous cleanup. In accordance with the advice that classes should be named as nouns, I'd also rename it to <code>WordProcessorLauncher</code>.</p>\n\n<pre><code>public class WordProcessorLauncher {\n private WordFrame mainFrame;\n\n public WordProcessorLauncher() {\n this.mainFrame = new WordFrame();\n DataStuff data = new DataStuff();\n WordProcessorActionListener listener = new WordProcessorActionListener(this.mainFrame, data);\n this.mainFrame.addListener(listener);\n }\n\n public void launch() {\n this.mainFrame.setVisible(true);\n }\n\n public static void main(String[] args) {\n (new WordProcessorLauncher()).launch();\n }\n}\n</code></pre>\n\n<p>Keep your classes as nouns and methods as verbs, and <em>voilà</em> — there's no more need for <code>@SuppressWarning(\"unused\")</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:12:34.073",
"Id": "73688",
"Score": "0",
"body": "thanks for that, i was not aware until you used it, that you could create an anonymous instance of a class. Just read up on it on the Oracle java tutorial site"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:34:57.457",
"Id": "42713",
"ParentId": "42651",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42653",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T11:42:57.807",
"Id": "42651",
"Score": "8",
"Tags": [
"java",
"object-oriented",
"mvc"
],
"Title": "Making a word processor"
} | 42651 |
<p>I've been trying to learn how to use the TPL for quite some time now.
Basically I'm trying to fire off a group of Tasks, wait for them to complete and then fire off another group of tasks, waiting for them to complete before firing off the tasks that update form elements on the UI Thread.</p>
<p>Here's what I got. I think I'm probably overcomplicating it however it does seem to work as I want it too.
Please could I have some advice on how I could simplify this based on what I want to achieve?</p>
<pre><code>private async Task PrepareData()
{
Task[] FirstTasks = new Task[] { TaskOne(), TaskTwo() }; // Do First group of Tasks
await Task.WhenAll(FirstTasks); // Wait for First group of Tasks
Task[] SecondTasks = new Task[] { TaskThree(), TaskFour() }; // Do Second group of Tasks
await Task.WhenAll(SecondTasks).ContinueWith(c => // Wait for Second group of Tasks
{
GuiTaskOne();
GuiTaskTwo();
}, TaskScheduler.FromCurrentSynchronizationContext()); // Then update the form on the UI Thread
}
private async Task TaskOne()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task TaskTwo()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task TaskThree()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task TaskFour()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task GuiTaskOne()
{
someControl.Text = await Task.Run(() => DoSomething());
}
private async Task GuiTaskTwo()
{
someControl.Text = await Task.Run(() => DoSomething());
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T13:47:33.160",
"Id": "73514",
"Score": "0",
"body": "I presume `DoSomething()` is just a method that runs something like `Thread.Sleep(1000);`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:03:26.183",
"Id": "73518",
"Score": "0",
"body": "It could be. I'm using the above code in a real world scenario. The FirstTasks Task array does a couple of Active Directory lookups where the the SecondTasks Task Array uses the information gathered from AD to populate SQL databases. The GUI tasks report progress/information. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:14:25.297",
"Id": "73519",
"Score": "2",
"body": "I think you'd get a better review and more useful comments if you posted your *actual* code - at least the names for `TaskThree` and `GuiTaskOne` (and the others).. right now it looks like all tasks call the same `DoSomething` method. I *know* in reality it's probably not the case, but since reviewers can comment on *any aspect of your code*, it'd be nice if your code wasn't too narrowed down on the `async/await` mechanics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-01T13:55:54.990",
"Id": "220647",
"Score": "0",
"body": "Have a search on TPL Dataflow"
}
] | [
{
"body": "<p>Since <code>await</code> is effectively a continuation anyway, you could simplify your function to:</p>\n\n<pre><code>private async Task PrepareData()\n{\n Task[] FirstTasks = new Task[] { TaskOne(), TaskTwo() }; // Do First group of Tasks\n await Task.WhenAll(FirstTasks); // Wait for First group of Tasks\n\n Task[] SecondTasks = new Task[] { TaskThree(), TaskFour() }; // Do Second group of Tasks\n await Task.WhenAll(SecondTasks); // Wait for Second group of Tasks \n\n GuiTaskOne();\n GuiTaskTwo();\n}\n</code></pre>\n\n<p>I also suspect you meant to await the GUI tasks too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:04:55.213",
"Id": "42769",
"ParentId": "42652",
"Score": "8"
}
},
{
"body": "<p>You can simplify Gaz's code even more by using the fact that <code>WhenAll()</code> is a <code>params</code> method:</p>\n\n<pre><code>private async Task PrepareData()\n{\n await Task.WhenAll(TaskOne(), TaskTwo());\n\n await Task.WhenAll(TaskThree(), TaskFour());\n\n GuiTaskOne();\n GuiTaskTwo();\n}\n</code></pre>\n\n<p>Also, depending on what the <code>Task</code> methods actually do, there might be a better way than having them set a field, but that's hard to tell from the example code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:22:16.553",
"Id": "44791",
"ParentId": "42652",
"Score": "8"
}
},
{
"body": "<pre><code>await Task.WhenAll(Task.Delay(TimeSpan.FromSeconds(5)), Task.Delay(TimeSpan.FromSeconds(5)), Task.Delay(TimeSpan.FromSeconds(5)))\n .ContinueWith(_ => Task.WhenAll(Task.Delay(TimeSpan.FromSeconds(5)), Task.Delay(TimeSpan.FromSeconds(5)), Task.Delay(TimeSpan.FromSeconds(5))))\n .Unwrap();\n</code></pre>\n\n<p>Note that it is important to call <code>Unwrap</code> when your action returns <code>Task<Task></code> rather than <code>Task<TResult></code>.</p>\n\n<p>The above statement should take 10 seconds. Without <code>Unwrap</code>, it would take 5 seconds because it will not 'await' for the second group to complete.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T02:37:30.817",
"Id": "73886",
"ParentId": "42652",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "44791",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T12:19:44.643",
"Id": "42652",
"Score": "6",
"Tags": [
"c#",
"multithreading",
"winforms"
],
"Title": "Chaining Tasks with async/await"
} | 42652 |
<p>How would you DRY up this RSpec code?</p>
<pre><code>require "spec_helper"
describe InvoiceMailer do
let(:user) { create(:user) }
let(:student) { create(:student, user: user) }
let(:body) { "And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on this earth." }
subject(:mail) { InvoiceMailer.issue(student, body) }
describe "issue" do
subject(:mail) { InvoiceMailer.issue(student, body) }
it "renders the subject" do
expect(mail.subject).to eq "New Invoice!"
end
it "renders the receiver email" do
expect(mail.to).to eq [student.user.email]
end
it "renders the sender email" do
expect(mail.from).to eq ["info@test.com"]
end
end
describe "rescind" do
subject(:mail) { InvoiceMailer.rescind(student, body) }
it "renders the subject" do
expect(mail.subject).to eq "Invoice Rescinded!"
end
it "renders the receiver email" do
expect(mail.to).to eq [student.user.email]
end
it "renders the sender email" do
expect(mail.from).to eq ["info@test.com"]
end
end
end
</code></pre>
| [] | [
{
"body": "<p>You can use the <code>its</code> syntax:</p>\n\n<pre><code>require \"spec_helper\"\n\ndescribe InvoiceMailer do\n let(:user) { create(:user) }\n let(:student) { create(:student, user: user) }\n let(:body) { \"And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on this earth.\" }\n\n describe \"issue\" do\n subject { InvoiceMailer.issue(student, body) }\n\n its(:subject) { should eq \"New Invoice!\" }\n\n its(:to) { should eq [student.user.email] }\n\n its(:from) { should eq [\"info@test.com\"] }\n end\n\n describe \"rescind\" do\n subject { InvoiceMailer.rescind(student, body) }\n\n its(:subject) { should eq \"Invoice Rescinded!\" }\n\n its(:to) { should eq [student.user.email] }\n\n its(:from) { should eq [\"info@test.com\"] }\n end\n\nend\n</code></pre>\n\n<p>You can further DRY it up using <a href=\"https://www.relishapp.com/rspec/rspec-core/v/2-0/docs/example-groups/shared-example-group\" rel=\"nofollow\">example groups</a></p>\n\n<pre><code>describe InvoiceMailer do\n let(:user) { create(:user) }\n let(:student) { create(:student, user: user) }\n let(:body) { \"And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on this earth.\" }\n\n shared_examples_for \"outgoing mail\" do |method, mail_subject|\n subject { InvoiceMailer.send(method, student, body) }\n\n its(:subject) { should eq mail_subject }\n\n its(:to) { should eq [student.user.email] }\n\n its(:from) { should eq [\"info@test.com\"] }\n end\n\n describe \"issue\" do\n it_should_behave_like \"outgoing mail\", :issue, 'New Invoice!'\n end\n\n describe \"rescind\" do\n it_should_behave_like \"outgoing mail\", :rescind, 'Invoice Rescinded!'\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T02:34:07.137",
"Id": "73605",
"Score": "0",
"body": "Thanks for this answer! I don't usually like `its` but in this case it's very readable. \n\nI feel like there is still a lot of duplication between the the `issue` and `rescind` describe blocks though. The only differences between the two are the methods on `InvoiceMailer` and the subject. Any thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:15:17.557",
"Id": "73630",
"Score": "0",
"body": "Added an option with example groups"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:49:25.600",
"Id": "73659",
"Score": "0",
"body": "Oh! That's exactly what I was looking for!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:16:10.117",
"Id": "42679",
"ParentId": "42656",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42679",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T13:59:29.417",
"Id": "42656",
"Score": "3",
"Tags": [
"ruby",
"email",
"rspec"
],
"Title": "RSpec tests for an invoice mailer"
} | 42656 |
<p>This is small piece of bigger puzzle, but usable by its own.
It an attempt to have a nonblocking queue with "unlimited" (besides memory size) buffer length.</p>
<p>Got unit-tests 100% statement coverage, it looks that it's ok, but I'm very new to Go and concurrency so I might miss something.</p>
<pre><code>import "sync"
// Message and MessageQueuer are interfaces, defined in other file
type msgQueue struct {
input, output chan Message
buffer []Message
head, tail, count int
immediateClose bool
done sync.WaitGroup
}
func NewQueue() MessageQueuer {
mq := &msgQueue{
input: make(chan Message),
output: make(chan Message),
buffer: make([]Message, 16),
}
mq.done.Add(1)
go mq.magicBuffer()
return mq
}
func (mq *msgQueue) In() chan<- Message {
return mq.input
}
func (mq *msgQueue) Out() <-chan Message {
return mq.output
}
func (mq *msgQueue) Len() int {
return mq.count
}
func (mq *msgQueue) Close() {
close(mq.input)
}
func (mq *msgQueue) CloseAndWait() {
close(mq.input)
mq.done.Wait()
}
func (mq *msgQueue) ClearAndClose() {
mq.immediateClose = true
mq.count = 0
close(mq.input)
}
func (mq *msgQueue) enqueue(msg Message) {
if mq.head == mq.tail && mq.count > 0 {
buffer := make([]Message, len(mq.buffer)*2)
copy(buffer, mq.buffer[mq.head:])
copy(buffer[len(mq.buffer)-mq.head:], mq.buffer[:mq.head])
mq.head = 0
mq.tail = len(mq.buffer)
mq.buffer = buffer
}
mq.buffer[mq.tail] = msg
mq.tail = (mq.tail + 1) % len(mq.buffer)
mq.count++
}
func (mq *msgQueue) dequeue() Message {
msg := mq.buffer[mq.head]
mq.head = (mq.head + 1) % len(mq.buffer)
mq.count--
return msg
}
func (mq *msgQueue) shutdown() {
defer mq.done.Done()
if mq.immediateClose {
mq.buffer = nil
}
for mq.count > 0 {
mq.output <- mq.dequeue()
}
close(mq.output)
}
func (mq *msgQueue) magicBuffer() {
for {
if mq.count == 0 {
msg, open := <-mq.input
if open && !mq.immediateClose {
mq.enqueue(msg)
} else {
mq.shutdown()
return
}
} else {
select {
case msg, open := <-mq.input:
if open && !mq.immediateClose {
mq.enqueue(msg)
} else {
mq.shutdown()
return
}
case mq.output <- mq.buffer[mq.head]:
// dequeue
mq.head = (mq.head + 1) % len(mq.buffer)
mq.count--
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-11T16:58:35.243",
"Id": "387994",
"Score": "0",
"body": "I wonder why did you choose do it with channels. You can do much better with mutexes."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T14:44:10.397",
"Id": "42660",
"Score": "4",
"Tags": [
"asynchronous",
"queue",
"go"
],
"Title": "Queue with \"unlimited\" buffer in Go"
} | 42660 |
<p>The architecture is showing a call to an external Web Service which is called by me. Then I will expose the data using WCF to be callable from another WCF client. But I really don't like how it's done. Interfaces, contracts, implementation in the BLO and implementations on the DAL.</p>
<p>7 time copy & paste of method which just call another identical method.</p>
<p>P.S: I've changed the name of the methods between the image and the code.. In the code I've called the main duplicate method <code>GetExampleData</code> / <code>GetExampleDataInfo</code>.</p>
<p><img src="https://i.stack.imgur.com/Vgh4U.jpg" alt="enter image description here"></p>
<pre><code>namespace .Risk.WCF.Services
{
public static class LeagueServerSingletonContainer
{
private static volatile IWindsorContainer serverInstance;
private static readonly object serverSyncRoot = new Object();
public static IWindsorContainer ServerContainer
{
get
{
if (serverInstance == null)
{
lock (serverSyncRoot)
{
if (serverInstance == null) // double-check
{
IWindsorContainer serverContainer = SingletonContainerFactory.ConfigureContainer(
"LeagueServerWindsor.config")
.Install(new LeagueWcfClientsWindsorInstaller());
serverInstance = serverContainer;
}
}
}
return serverInstance;
}
}
}
}
namespace .Example.WCF.Services
{
public class ExampleService : IWCFService, IExampleService
{
public ExampleApiResponse<ExampleDataResponse> GetExampleData(int targetId, DateTime? dateFrom,
DateTime? dateTo)
{
var apiSessionKey = InitSessionKeyInformation();
return ExampleSingleton.Example()
.GetExampleDataInfo(apiSessionKey, targetId, dateFrom, dateTo);
}
}
}
namespace .Example.WCF.Services.Contracts
{
public static class ExampleServerContainer
{
private static volatile IWindsorContainer serverInstance;
private static readonly object serverSyncRoot = new Object();
public static IWindsorContainer ServerContainer
{
get
{
if (serverInstance == null)
{
lock (serverSyncRoot)
{
if (serverInstance == null) // double-check
{
IWindsorContainer serverContainer =
new WindsorContainer().Install(new ExampleWcfClientsWindsorInstaller());
serverInstance = serverContainer;
}
}
}
return serverInstance;
}
}
}
}
namespace .Example.WCF.Services.Contracts
{
public class ExampleWcfClientsWindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Install
(
new WcfClientInstaller<IExampleService>(
"ExampleServiceEndpoint",
Config.ExampleService.ExampleServiceConnectionPoolCapacity,
(int) Config.ExampleService.ExampleServiceAcquireChannelTimeout.TotalMilliseconds,
"ExampleServiceWcfClient")
);
}
}
}
namespace .Example.WCF.Services.Contracts
{
[ServiceContract]
public interface IExampleService
{
[OperationContract]
[FaultContract(typeof (TrackedFault))]
ExampleApiResponse<ExampleDataResponse> GetExampleData(int targetId, DateTime? dateFrom,
DateTime? dateTo);
}
}
namespace .Example.BLL
{
public class ExampleBLO : IExampleBLO
{
private static readonly Object _apiTokenLockObj = new object();
private readonly ILog log = LogManager.GetLogger(typeof (ExampleBLO));
private string ExampleApiSessionToken;
private Timer ExampleKeepAliveTimer;
public ExampleApiResponse<ExampleDataResponse> GetExampleDataInfo(int targetId, DateTime? dateFrom,
DateTime? dateTo)
{
return ExampleDAOSingleton.Example()
.GetExampleDataInfo(ExampleApiSessionToken, targetId, dateFrom, dateTo, _apiSessionKey.ApiUrlv2);
}
private void ClearApiToken()
{
log.Info("Clearing APIToken.");
ExampleKeepAliveTimer.Stop();
lock (_apiTokenLockObj)
{
ExampleApiSessionToken = null;
}
}
}
}
namespace .Example.BLL
{
public class ExampleSingleton
{
private static volatile IExampleBLO _ExampleBLO;
private static readonly object _ExampleBLOSyncRoot = new Object();
/// <summary>
/// Restituisce l'istanza statica dell'oggetto per l'accesso ai dati alle terze parti
/// </summary>
public static IExampleBLO Example()
{
if (_ExampleBLO == null)
{
lock (_ExampleBLOSyncRoot)
{
if (_ExampleBLO == null) // double-check
_ExampleBLO = new ExampleBLO();
}
}
return _ExampleBLO;
}
}
}
namespace .Example.BLL.Interfaces
{
public interface IExampleBLO
{
ExampleApiResponse<ExampleDataResponse> GetExampleDataInfo(int targetId, DateTime? dateFrom,
DateTime? dateTo);
}
}
namespace .Example.DAL
{
internal class ExampleDAO : AbstractDAO, IExampleDAO
{
private readonly ILog log = LogManager.GetLogger(typeof (ExampleDAO));
public ExampleApiResponse<ExampleDataResponse> GetExampleDataInfo(string authenticationToken,
int targetId, DateTime? dateFrom, DateTime? dateTo, string apiUrlv2)
{
string url;
if (dateFrom == null && dateTo == null)
{
url =
HttpUtility.UrlPathEncode(
string.Format(
@"{0}?method=information::get_earnings_market&token={1}&target_id={2}&extended=true",
apiUrlv2, authenticationToken, targetId));
}
else
{
url =
HttpUtility.UrlPathEncode(
string.Format(
@"{0}?method=information::get_earnings_market&token={1}&target_id={2}&datefrom={3}&dateto={4}&extended=true",
apiUrlv2, authenticationToken, targetId, dateFrom.Value.ToString("yyyy-MM-dd HH:mm:ss"),
dateTo.Value.ToString("yyyy-MM-dd HH:mm:ss")));
}
ExampleApiResponse<ExampleDataResponse> response = CallApiMethod<ExampleDataResponse>(url);
return response;
}
private ExampleApiResponse<T> CallApiMethod<T>(string url) where T : ExampleBaseResponse
{
log.DebugFormat("Contacting API with request url : {0}", url);
ExampleApiResponse<T> response = null;
var serializer = new XmlSerializer(typeof (ExampleApiResponse<T>));
try
{
using (var client = new WebClient())
{
using (Stream stream = client.OpenRead(url))
{
client.Encoding = Encoding.UTF8;
if (stream != null)
{
response = (ExampleApiResponse<T>) serializer.Deserialize(stream);
}
if (response != null && response.Response.ParseResult() != Results.Success)
{
log.WarnFormat("Error in API response. Request url: {0}", url);
}
}
}
}
catch (Exception)
{
log.WarnFormat("Error in API call with request url: {0}", url);
throw;
}
return response;
}
}
}
namespace .Example.DAL
{
public class ExampleDAOSingleton
{
private static volatile IExampleDAO _ExampleDAO;
private static readonly object _ExampleDAOSyncRoot = new Object();
/// <summary>
/// Restituisce l'istanza statica dell'oggetto per l'accesso ai dati alle terze parti
/// </summary>
public static IExampleDAO Example()
{
if (_ExampleDAO == null)
{
lock (_ExampleDAOSyncRoot)
{
if (_ExampleDAO == null) // double-check
_ExampleDAO = new ExampleDAO();
}
}
return _ExampleDAO;
}
}
}
namespace .Example.DAL.Interfaces
{
public interface IExampleDAO
{
ExampleApiResponse<ExampleDataResponse> GetExampleDataInfo(string authenticationToken, int targetId,
DateTime? dateFrom, DateTime? dateTo, string apiUrlv2);
}
}
</code></pre>
| [] | [
{
"body": "<p>You've turned your IoC container into a <a href=\"http://en.wikipedia.org/wiki/Service_locator_pattern\">Service Locator</a> (happens when you pass the IoC container around as a dependency)!</p>\n\n<pre><code>public void Install(IWindsorContainer container, IConfigurationStore store)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^ here!\n</code></pre>\n\n<blockquote>\n <p><strong>Advantages</strong></p>\n \n <ul>\n <li>The \"service locator\" can act as a simple run-time linker. This allows code to be added at run-time without re-compiling the application, and in some cases without having to even restart it.</li>\n <li>Applications can optimize themselves at run-time by selectively adding and removing items from the service locator. For example, an application can detect that it has a better library for reading JPG images available than the default one, and alter the registry accordingly.</li>\n <li>Large sections of a library or application can be completely separated. The only link between them becomes the registry.</li>\n </ul>\n</blockquote>\n\n<p>But this comes at a price:</p>\n\n<blockquote>\n <p><strong>Disadvantages</strong></p>\n \n <ul>\n <li>Things placed in the registry are effectively black boxes with regards to the rest of the system. This makes it harder to detect and recover from their errors, and may make the system as a whole less reliable.</li>\n <li>The registry must be unique, which can make it a bottleneck for concurrent applications.</li>\n <li>The registry can be a serious security vulnerability, because it allows outsiders to inject code right into an application.</li>\n <li>The registry hides the class' dependencies, causing run-time errors instead of compile-time errors when dependencies are missing.</li>\n <li>The registry makes the code more difficult to maintain (opposed to using Dependency injection), because it becomes unclear when you would be introducing a breaking change</li>\n <li>The registry makes code harder to test, since all tests need to interact with the same global service locator class to set the fake dependencies of a class under test.</li>\n </ul>\n</blockquote>\n\n<p><sub>(<a href=\"http://en.wikipedia.org/wiki/Service_locator_pattern\">http://en.wikipedia.org/wiki/Service_locator_pattern</a>)</sub></p>\n\n<p>By doing this, you've introduced <strong>tight coupling</strong> between <code>ExampleService</code> and <code>ExampleSingleton</code>, which has become <em>ambient context</em> - which is a DI/IoC anti-pattern that you should strive to eliminate.</p>\n\n<p>The solution is to <em>inject the dependencies</em> through the class' constructor, ideally as an interface (/abstraction - an <code>abstract</code> class works just as well).</p>\n\n<p>Your architecture relies heavily on <code>static</code> classes and the <em>Singleton</em> [anti-]pattern, which is making your solution essentially untestable, as far as I can tell.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:57:22.173",
"Id": "73542",
"Score": "0",
"body": "Thanks a lot. I think there is no real need to use Singleton or Service Locator here. How should I refactor it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:00:08.247",
"Id": "73543",
"Score": "1",
"body": "@Sam: I'd suggest only passing the things you need. You may also want to look into tutorials for your container, because it does support composition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:02:17.177",
"Id": "73544",
"Score": "0",
"body": "@Sam Get rid of `static` stuff, inject dependencies into the classes' constructor, let the IoC container determine the *lifestyle* of dependencies (if you only need 1 instance of something, configure your container to always provide the same instance)... and read [Mark Seemann's book](http://www.manning.com/seemann/) ;) (don't have time to provide an answer with an alternative approach right now, might do it later)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:55:20.873",
"Id": "42670",
"ParentId": "42663",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:06:04.080",
"Id": "42663",
"Score": "3",
"Tags": [
"c#",
"web-services",
"wcf"
],
"Title": "Call to external web service"
} | 42663 |
<p>I'm writing wrapper functions for some of the functions in <code><algorithm></code>.
While the following works perfectly, I'm not sure if this is the best way to approach it:</p>
<pre><code>template<class ContainerType, class Predicate>
ContainerType filter(
const ContainerType& container,
Predicate predicate
) {
ContainerType filteredContainer;
std::remove_copy_if(
container.begin(),
container.end(),
std::back_inserter(filteredContainer),
predicate
);
return filteredContainer;
</code></pre>
<p>Would you change something about the wrapper? I'm especially worried about the template parameters, e.g. you'll have to read the entire function in order to know what types are valid for <code>predicate</code> etc.</p>
| [] | [
{
"body": "<p>The use of template parameters here is just fine. You can call the second one <code>UnaryPredicate</code> if that makes you happier, but in the end, C++ currently lacks the ability to specify further requirements on template arguments. (That's what concepts are for.)</p>\n\n<p>So you really need to specify the detailed requirements in prose in the documentation, e.g.</p>\n\n<blockquote>\n <p><code>ContainerType</code> must fulfill the <code>Container</code> requirement, and its <code>value_type</code> must be <code>Copyable</code>. <code>Predicate</code> must be an <code>UnaryPredicate</code> taking <code>value_type</code> as its argument.</p>\n</blockquote>\n\n<p>What you could possibly improve is making this more efficient in C++11 when the argument is a temporary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:06:19.180",
"Id": "73530",
"Score": "0",
"body": "\"making this more efficient in C++11\" - you mean by adding a overload taking a rvalue reference, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:09:42.093",
"Id": "73532",
"Score": "1",
"body": "That's one way. Another would be trying advanced template trickery to do it all in one function. Not sure I would want to do that, but it's an option."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:03:55.487",
"Id": "42672",
"ParentId": "42671",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42672",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T15:56:37.477",
"Id": "42671",
"Score": "3",
"Tags": [
"c++",
"template"
],
"Title": "Could this template function be improved?"
} | 42671 |
<p>I have these two carousels that randomly pick up pictures. <strong><a href="http://jsfiddle.net/stonecold111/YrPc7/18/" rel="nofollow">[fiddle]</a></strong> Each of them picks up pictures and links from their own different inner array. It works fine as it is, but I was just wondering if there's any part that I can encapsulate/shorten. The only thing I can come up with that doesn't return any error is them sharing the same <code>$(document).ready(function(){</code> <strong><a href="http://jsfiddle.net/stonecold111/YrPc7/19/" rel="nofollow">[fiddle]</a></strong>.</p>
<pre><code>$('#carousel1').jsCarousel({ onthumbnailclick: function(src) { load(src); }, autoscroll: true, circular: true, masked: false, itemstodisplay: 3, orientation: 'h' });
$('#carouselu').jsCarousel({ onthumbnailclick: function(src) { load(src); }, autoscroll: true, circular: true, masked: false, itemstodisplay: 3, orientation: 'h' });
var theImages = [
['img1','url_1'],
['img2','url_2'],
['img3','url_3'],
['img4','url_4'],
['img5','url_5'], ];
var shuffled = [];
while (theImages.length) {
shuffled.push(theImages.splice(Math.random() * theImages.length, 1)[0]);
}
$(document).ready(function(){
var imgPath = "/pic/";
var urlPath = "/url/";
$("#carousel1 .1").each(function(index){
$(this).prepend('<a href="'+imgPath+shuffled[index][1]+'"><img src="'+urlPath+shuffled[index][0]+'"></a>');
});
});
/* Second rotator */
var theImagesabc = [
['imga','url_a'],
['imgb','url_b'],
['imgc','url_c'],
['imgd','url_d'],
['imge','url_f'] ];
var shuffledabc = [];
while (theImagesabc.length) {
shuffledabc.push(theImagesabc.splice(Math.random() * theImagesabc.length, 1)[0]);
}
$(document).ready(function(){
var imgPath = "/pic/";
var urlPath = "/url/";
$("#carouselu .u").each(function(index){
$(this).prepend('<a href="'+imgPath+shuffledabc[index][1]+'"><img src="'+urlPath+shuffledabc[index][0]+'"></a>');
});
});
</code></pre>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>You can use <code>$('#carousel1, #carousel2').jsCarousel(...);</code> or even better<br></p>\n\n<pre><code>$('.carouselSelector').jsCarousel(...);\n</code></pre></li>\n<li>The name <code>theImagesabc</code> is terrible, just terrible</li>\n<li>Shuffling each array in it's own <code>for</code> loop is not <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>.</li>\n<li>Prepending each carousel is not DRY either</li>\n<li><p>You could rewrite <code>(document).ready()</code>:</p>\n\n<pre><code>$(document).ready(function(){\n\n var imgPath = \"/pic/\"; \n var urlPath = \"/url/\";\n\n setUpCarousel( '#carousel1 .1', imgPath , urlPath , theImages );\n setUpCarousel( '#carouselu .u', imgPath , urlPath , theImagesabc );\n\n function setUpCarousel( selectorString, imgPath , urlPath , images )\n {\n var shuffledImages= [];\n //Shuffle images into shuffledImages\n while (images.length) {\n shuffledImages.push(images.splice(Math.random() * images.length, 1)[0]);\n }\n //Build the carousel\n $( selectorString ).each(function(index){ \n $(this).prepend('<a href=\"'+urlPath+shuffledImages[index][1]+'\"><img src=\"'+imgPath+shuffledImages[index][0]+'\"></a>');\n }); \n } \n\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:37:27.423",
"Id": "42680",
"ParentId": "42676",
"Score": "2"
}
},
{
"body": "<p>Beyond the repetition in the JS, you've got some repetition across the HTML and JS; I'd avoid having both the array and the empty divs. If you have more divs than you have images in the array, weird stuff starts happening. There's no reason to manually have to manage both of those \"lists\" when you can just add divs as necessary.</p>\n\n<p>Here's how I might write it, to include that while avoiding the repetition</p>\n\n<pre><code>function randomizeCarousel(selector, images) {\n var i, l, carousel = $(selector);\n\n function shuffle(images) {\n var i, shuffled = [];\n while(images.length) {\n i = Math.floor(Math.random() * images.length);\n shuffled = shuffled.concat(images.splice(i, 1));\n }\n return shuffled;\n }\n\n function addImage(src, href) {\n var container = $(\"<div>\"),\n link = $(\"<a></a>\").attr(\"href\", href).appendTo(container),\n img = $(\"<img/>\").attr(\"src\", src).appendTo(link);\n carousel.append(container);\n }\n\n images = shuffle(images.slice(0));\n for(i = 0, l = images.length; i < l; i++) {\n addImage(\"/pic/\" + images[i][0], \"/url/\" + images[i][1]);\n }\n\n carousel.jsCarousel({\n onthumbnailclick: function(src) { load(src); },\n autoscroll: true,\n circular: true,\n masked: false,\n itemstodisplay: 3,\n orientation: 'h'\n });\n}\n\n$(function () {\n randomizeCarousel(\"#carousel1\", [...]); // add your 1st array here\n randomizeCarousel(\"#carousel2\", [...]); // add your 2nd array here\n // ... etc.\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T12:05:44.097",
"Id": "73869",
"Score": "0",
"body": "if the carousels have their own image paths and links to different subdomains, instead of using actual paths \"/pic/\" and \"/url/\" in `addImage(\"/pic/\" + images[i][0], \"/url/\" + images[i][1]);` , is it possible to use a domain as a variable and then change its value for each carousel's ID?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T21:04:52.867",
"Id": "73944",
"Score": "0",
"body": "@user35295 Then it'd be easier to simply have the full URLs in the array to begin with. Or you can have a function alter the arrays, before you pass them on to the carousel-builder-function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:55:12.740",
"Id": "42684",
"ParentId": "42676",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42684",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:25:04.953",
"Id": "42676",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"array"
],
"Title": "Same function but use different array data"
} | 42676 |
<p>I have implemented a basic <code>object</code> class in C++, and I want to make sure that I have implemented everything <em>efficiently and safely</em>, as I made a few mistakes while making it, which I corrected, but I could have left a few more mistakes behind:</p>
<pre><code>class object
{
private:
class dummy
{
public:
dummy()
{
}
virtual ~dummy()
{
}
virtual const std::type_info &type() = 0;
virtual dummy *duplicate() const = 0;
virtual bool eq(object &) = 0;
};
template < typename _Ty > class data : public dummy
{
public:
data()
{
}
data(const _Ty &_Value)
: __data(_Value)
{
}
~data()
{
}
const std::type_info &type()
{
return typeid(_Ty);
}
data *duplicate() const
{
return new data<_Ty>(__data);
}
bool eq(object &_Obj)
{
return _Obj.cast<_Ty>() == __data;
}
_Ty __data;
};
dummy *d;
public:
object()
{
}
template < typename _Ty > object(const _Ty &_Value)
: d(new data<_Ty>(_Value))
{
}
object(const object &_Obj)
: d(_Obj.d->duplicate())
{
}
~object()
{
if (!empty())
{
delete d;
}
}
const std::type_info &type()
{
return (empty() ? typeid(void) : d->type());
}
object &operator=(object &_Rhs)
{
d = _Rhs.d->duplicate();
return *this;
}
object &swap(object &_Rhs)
{
std::swap(*this, _Rhs);
return *this;
}
template < typename _Ty > object &operator=(const _Ty &_Value)
{
d = new data<_Ty>(_Value);
return *this;
}
template < typename _Ty > _Ty cast()
{
if (type() == typeid(_Ty))
{
return static_cast<data<_Ty> *>(d)->__data;
}
throw std::exception("Invalid cast type");
}
bool operator==(object &_Rhs)
{
return (type() == _Rhs.d->type() ? d->eq(_Rhs) : false);
}
template < typename _Ty > bool operator==(_Ty _Value)
{
return (type() == typeid(_Ty) ? cast<_Ty>() == _Value : false);
}
bool operator!=(object &_Rhs)
{
return !(*this == _Rhs);
}
template < typename _Ty > bool operator!=(const _Ty &_Value)
{
return !(*this == _Value);
}
bool empty()
{
return !d;
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:20:29.407",
"Id": "73585",
"Score": "0",
"body": "1) Replace `{ }` with `= default;` 2) Get rid of names starting with underscore(s)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:51:12.147",
"Id": "73589",
"Score": "4",
"body": "You should stop using reserved identifiers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:07:10.407",
"Id": "73594",
"Score": "0",
"body": "Your default constructor `object(){}` will *default-initialize* the data member `dummy *d;`. Default-initialization for fundamental types means **no initialization is performed**. Subsequent calls of `empty()` might return `false`. Use value-initialization `object() : d() {}` or explicit initialization `object() : d(nullptr) {}`. Also, you don't need to check `if(!empty())` before `delete d;`; deleting a nullptr value is safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:18:41.757",
"Id": "73595",
"Score": "0",
"body": "`std::swap(*this, _Rhs);` won't do any magic. It will make a three copies (one copy-construction of a \"temporary\", and two copy-assignments). That's exactly what you want to *avoid* when supplying a custom `swap` function. Also, you should consider making it a non-member friend function, see http://stackoverflow.com/a/5695855/420683"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:13:08.220",
"Id": "73628",
"Score": "3",
"body": "Why!!!!!!!!!!!!"
}
] | [
{
"body": "<ul>\n<li><p>As per common naming convention, the class names should start with a capital letter.</p></li>\n<li><p>It may be more readable to put the <code>template</code> line above the <code>class</code> line:</p>\n\n<pre><code>template < typename _Ty >\nclass data : public dummy\n{\n}\n</code></pre></li>\n<li><p>Your <code>bool</code> functions should be <code>const</code>. Any member function that doesn't modify data members should be <code>const</code>. Such functions also include accessors (\"getters\") and the <code>bool</code> operators (<code>operator==</code>, <code>operator!=</code>, <code>operator<</code>, and <code>operator></code>).</p>\n\n<p>For instance, with <code>empty()</code>:</p>\n\n<pre><code>bool empty() const\n{\n // ...\n}\n</code></pre>\n\n<p>and <code>operator==</code>:</p>\n\n<pre><code>bool operator==(object &_Rhs) const\n{\n // ...\n}\n</code></pre>\n\n<p>Also, the above parameter should be <code>const&</code> since <code>_Rhs</code> is not being modified.</p></li>\n<li><p>If you're not defining your own constructor and/or destructor, you don't need to make them yourself. The compiler will make them for you.</p>\n\n<p>However, if you're using C++11, you can have an <a href=\"http://en.wikipedia.org/wiki/C++0x#Explicitly_defaulted_and_deleted_special_member_functions\" rel=\"nofollow\">explicitly defaulted constructor and destructor</a>:</p>\n\n<pre><code>data() = default;\n~data() = default;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:28:09.440",
"Id": "73601",
"Score": "2",
"body": "A default constructor will be created for you if no other constructor exists. I think it's always clearer to use `default` for this reason - it shows *intent* to have a default constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:43:21.507",
"Id": "73603",
"Score": "0",
"body": "@Yuushi: Oh, you mean like `data() = default;`? If I'm correct, it's for C++11."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:02:57.570",
"Id": "73667",
"Score": "0",
"body": "\"As per common naming convention, the class names should start with a capital letter.\" Like the standard library?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:19:03.533",
"Id": "73774",
"Score": "0",
"body": "@SebastianRedl Stroustrup suggests that you capitalize user-defined names in TC++PLv4p156. He then continues, \"Note that the language and the standard library use lowercase for types; this can be seen as a hint that they are part of the standard.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:50:07.887",
"Id": "74702",
"Score": "0",
"body": "@Jamal - the only point I disagree with in your answer is this: \"As per common naming convention, the class names should start with a capital letter\". In all C++ projects I've worked in, the naming convention was never based on Stroustrup's suggestion; instead, it was either MFC/hungarian convention (yuk!), or `lower_case_with_underscores` because of uniformity of client code and readability (or similar arguments), or a custom convention (e.g. `int mylib_ApiName(const int in_value, int &out_value);` or similar)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:08:46.547",
"Id": "42686",
"ParentId": "42681",
"Score": "7"
}
},
{
"body": "<pre><code>object &operator=(object &_Rhs)\n{\n d = _Rhs.d->duplicate();\n return *this;\n}\n</code></pre>\n\n<p>I think you're leaking your previous <code>d</code> object.</p>\n\n<p>It's also conventional to verify whether <code>_Rhs</code> and <code>this</code> are the same (and to do nothing if they are), otherwise it will misbehave if you assign an object to itself (like <code>foo = foo;</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:26:24.387",
"Id": "73600",
"Score": "2",
"body": "Or to use copy-and-swap instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:27:33.740",
"Id": "42689",
"ParentId": "42681",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "42689",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:37:53.770",
"Id": "42681",
"Score": "6",
"Tags": [
"c++",
"reinventing-the-wheel",
"object"
],
"Title": "Basic C++ object class"
} | 42681 |
<p>The following PHP code does exactly what I need it to do but, as a complete PHP novice, I am wondering: what can be improved here?</p>
<pre><code>$theurl='./section-1.html';
function getbody1($filename) {
$file = file_get_contents($filename);
$bodypattern = ".*";
$bodyendpattern = ".*";
$thecontainer = "id=\"container\"";
$thecleanup = "";
$noheader = preg_replace("/".$bodypattern."/", "", $file);
$noheader = preg_replace("~".$bodyendpattern."~", "", $noheader);
$noheader = preg_replace("|".$thecontainer."|", "", $noheader);
$noheader = preg_replace("#".$thecleanup."#", "", $noheader);
return $noheader;
}
echo getbody1("$theurl");
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:34:34.710",
"Id": "73569",
"Score": "1",
"body": "Can you please add a little description of what it is that your code does, and what you are using it for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:45:10.530",
"Id": "73571",
"Score": "1",
"body": "I have 5 pages created by an html generator. I want to strip out everything before and after the body tag so I am left with just the content of the body section. I will then use php include (I assume??) to pull each of these stripped down pages into a single page as articles in an html5 page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T20:04:36.760",
"Id": "73577",
"Score": "0",
"body": "Thank you, that's the kind of information that will help reviewers. If you put such information into your question you can expect more up-votes. It's all about making it easier for reviewers to review your code :)"
}
] | [
{
"body": "<pre><code>$theurl='./section-1.html';\nfunction getbody1($filename) {\n $file = file_get_contents($filename);\n //$bodypattern = \".*<body>\";\n //$bodyendpattern = \"</body>.*\";\n //$thecontainer = \"id=\\'container\\'\";\n //$thecleanup = \"<div >\";\n $noheader = preg_replace(\"/\".\".*<body>\".\"/\", \"\", $file);\n $noheader = preg_replace(\"~\".\"</body>.*\".\"~\", \"\", $noheader);\n $noheader = preg_replace(\"|\".\"id=\\'container\\'\".\"|\", \"\", $noheader);\n $noheader = preg_replace(\"#\".\"<div >\".\"#\", \"<div>\", $noheader);\n return $noheader;\n}\necho getbody1(\"$theurl\");\n</code></pre>\n\n<p>This might work, I just commented out the veriables you were not using and put them directly into the code.</p>\n\n<p>Also there was an error in</p>\n\n<pre><code>$thecontainer = \"id=\\\"container\\\"\";\n</code></pre>\n\n<p>The second \" will end the string, you need to use ' to have a string inside a string.</p>\n\n<p>But honestly, I wouldn't do this, the amount of processing time/power you might save wont compare to the amount of readability you lose. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:00:03.757",
"Id": "73564",
"Score": "0",
"body": "Ah, it seems when I copied the code it missed out some of the content in the variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:29:10.780",
"Id": "73567",
"Score": "0",
"body": "OK, so you can see I am a complete novice. My intent is to scrape several of my own domain's pages and use php include to bring them into a single page. The original pages are created by an html generator and I want to remove everything before and including the body tag and everything after and including the ending body tag. Is there a better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:39:07.110",
"Id": "73570",
"Score": "0",
"body": "I was trying this myself, depending on how many pages you have, this might be the smartest way. And when I did it I too used the technique you are using. With the file get and the replace. Although I was trying to scrape google plus pages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:30:04.320",
"Id": "73682",
"Score": "0",
"body": "@Daniel: If you every want to try that again, have a look at my answer, too. regex + markup is _not_ the smartest way... far from it actually"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:35:11.033",
"Id": "73781",
"Score": "0",
"body": "Thanks, I will, I didn't know that about regex."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:51:11.087",
"Id": "42692",
"ParentId": "42691",
"Score": "0"
}
},
{
"body": "<p>You can pass an array of patterns / replacements to <code>preg_replace</code>. So you could do:</p>\n\n<pre><code>$noheader = preg_replace(array(\"/\" . $bodypattern . \"/\", \"~\" . $bodyendpattern . \"~\", \"|\" . $thecontainer . \"|\", \"#\" . $thecleanup . \"#\"), \"\", $file);\n</code></pre>\n\n<p>I haven't done much with <code>preg_replace</code> but it seems like you are removing all characters in your first replacement - <code>/.*/</code>?!</p>\n\n<p>Also you don't need to quote your paramater:</p>\n\n<pre><code>echo getbody1(\"$theurl\");\n</code></pre>\n\n<p>Just pass it like <code>getbody1($theurl)</code>. You would only quote it if you wanted to do variable interpolation.. e.g. something like:</p>\n\n<pre><code>echo \"There are $numBooks books available on that subject\". \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:33:23.227",
"Id": "73683",
"Score": "0",
"body": "On the variable interpolation remark: given that `echo` is a language construct, that just pushes everything to the `stdout` stream, the best approach there would be `echo 'There are ', $numBooks, ' books available on that subject';`. Comma separated avoids unnecessary string concatenation or creation (which causes overhead as it allocates memory, only to free it after echoing the new string), and leaves the variables' types unchanged (`$i = 1; \"$i\"; <-- `$i` was int, now is string)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:31:41.350",
"Id": "42694",
"ParentId": "42691",
"Score": "1"
}
},
{
"body": "<p>First things first, you are <strong><em>not</em></strong> using the right tool for the job. Regular expressions can't reliably parse markup. Full stop. But more on that later, let's first take a look at your patterns, as this may help you in the future:</p>\n\n<pre><code>$bodypattern = \".*\";//for example\n//later\npreg_replace('/'.$bodypattern.'/',...);\n</code></pre>\n\n<p>Now, whenever you quote a string into a regex pattern, you have to stop and think: <em>what if the string happens to contain special chars?</em>. I mean: half of the characters can mean a variety of things depending on the context. Thankfully, there's a handy function called <a href=\"http://www.php.net/preg_quote\" rel=\"nofollow noreferrer\"><code>preg_quote</code></a> to help you with that. The safe option here would be:</p>\n\n<pre><code>preg_replace('/'.preg_quote($bodypattern, '/').'/', ...);\n</code></pre>\n\n<p>Now, you seem to be under the impression that a dot matches anything. And it does, <strong><em>except</em></strong> line-feeds. If I were to apply <code>preg_match('/.+/', $thisAnswer, $matches);</code> to this answer, the pattern would only match the text until a <code>\\n</code> is encountered.<Br>\nYou need a <a href=\"http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">PCRE modifier</a>: <code>s</code>:</p>\n\n<pre><code>preg_match('/.+/s', $thisAnswer, $match);\n</code></pre>\n\n<p>That's more like it. However, this is just as an aside, because what you <em>really</em> should be looking into are ways to actually treat markup as markup: a DOM needs to be <em>parsed</em>, if you want to get the most out of it. Here's my actual (and as-originally-posted) answer:</p>\n\n<p>Ouch, The first thing I noticed is that you're processing <em>markup</em>, and have chosen to do so using regular expressions. <a href=\"https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454\">That's a bad idea</a> from the off.<br>\nIt's especially bad considering you have a tool at your disposal that is specifically built <a href=\"http://www.php.net/DOMDocument\" rel=\"nofollow noreferrer\">to parse markup, the <code>DOMDocument</code> object</a>.</p>\n\n<p>Basically, what you're trying to do can be written as simple as this:</p>\n\n<pre><code>$DOM = new DOMDocument;//create DOM\n$DOM->loadHTMLFile($theUrl);//parse HTML\n$container = $DOM->getElementById('container');//get the id=container element\nif ($container)\n{//make sure it was found\n $container->removeAttribute('id');//remove the id attribute\n}\n$body = $contents = $dom->getElementsByTagName('body')->item(0);//get body\n//remove attributes\nwhile ($body->hasAttributes())\n{//while tag has attributes\n //remove attribute\n $body->removeAttribute($body->attributes->item(0)->nodeName);\n}\n//Get the body as string, use saveXML\n//as saveHTML adds DOCTYPE, html, head and title tag again\n$body = substr($DOM->saveXML($body), 6, -7);\n</code></pre>\n\n<p>The reason why you need to remove the attributes for the body tag, is because <code>DOMDocument::saveXML</code> will return the markup string <em>with</em> the outer <code><body></code> and <code></body></code> tags. Their length is a given, but only if the opening <code><body></code> tag hasn't got any attributes. Thankfully, we can remove them quite easily, and slice them off with <code>substr</code>.<br></p>\n\n<p>If you want, you could easily use:</p>\n\n<pre><code>$body = str_replace(\n array('<body>', '</body>'),\n '',\n $DOM->saveXML($body)\n);\n</code></pre>\n\n<p>Perhaps this is a bit easier to understand. Anyway: read the <code>DOMDocument</code> docs, there's a lot you can do there. Just click on the methods I used, and click the objects they return, too, so you know what instances you're working with.</p>\n\n<p>Now wrap all this in a function, and we can add some checks to avoid exceptions or errors from showing up:</p>\n\n<pre><code>function getBody($file, DOMDocument $dom = null)\n{//optionally pass existing DOMDocument instance\n //to avoid creating a new one each time we call this function\n if (!file_exists($file))\n {//check if the file exists, if not:\n throw new InvalidArgumentException($file. ' does not exist!');\n }\n $dom = $dom instanceof DOMDocument ? $dom : new DOMDocument;\n $dom->loadHTMLFile($file);\n $container = $dom->getElementById('container');\n if ($container)\n $container->removeAttribute('id');\n $body = $dom->getElementsByTagName('body')->item(0);\n while($body->hasAttributes())\n {\n $body->removeAttribute(\n $body->attributes->item(0)->nodeName\n );\n }\n $body = substr($dom->saveXML($body), 6, -7);\n //optionally remove trailing whitespace:\n return trim($body);\n}\n</code></pre>\n\n<p>Call this function either like this:</p>\n\n<pre><code>$body1 = getBody('path/to/file1.html');\n</code></pre>\n\n<p>or, since you're going to process more than 1 file, and we can avoid creating a new <code>DOMDocument</code> instance for every function call:</p>\n\n<pre><code>$dom = new DOMDocument;\n$files = array('file1.html', 'file2.html');\n$bodyStrings = array();\nforeach ($files as $file)\n $bodyStrings[] = getBody($file, $dom);\n</code></pre>\n\n<p>That's it.</p>\n\n<hr>\n\n<p>As a guide-to-the-DOMDocument-docs:</p>\n\n<p>Every class extends from <a href=\"http://www.php.net/manual/en/class.domnode.php\" rel=\"nofollow noreferrer\">the <code>DOMNode</code> class</a>, except for the <code>DOMNodeList</code> class, which is a <code>Traversable</code> containing only <code>DOMNode</code> instances, accessible through the <code>item</code> method. Anyway, check the <code>DOMNode</code> methods and properties. Learn that class by heart, as almost every object you work with inherits its properties and methods.<br>\nThe other class to check is <a href=\"http://www.php.net/manual/en/class.domelement.php\" rel=\"nofollow noreferrer\">the <code>DOMElement</code> class</a>. Instances of this class represent a node (a tag if you will). It has some methods that I've used here (like <code>removeAttribute</code>).<Br>\nFinally, everything, of course starts with <a href=\"http://www.php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\">the <code>DOMDocument</code> class</a>. I had already linked to the docs, but an extra link never hurt anyone.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:48:52.537",
"Id": "73685",
"Score": "0",
"body": "Err.....wow. Give me a while to digest this!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:00:47.073",
"Id": "73686",
"Score": "0",
"body": "@PBB: No problem. Just added a couple of links to the important bits of the `DOMDocument` docs. That might help you digest my verbose CR, if it sometimes seem harsh, [there's a reason for that](http://meta.codereview.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag). If I say something is bad, I try to back my claim up, and offer an alternative _and_ explain how and why I chose that alternative. Hope my answer, and this comment, make sense and are helpful. Just keep in mind that my main goal is to _help_, not to be a _\"Debby-downer\"_ :-P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:12:16.710",
"Id": "73687",
"Score": "0",
"body": "Elias, Worry not. You are clearly a good teacher and everything you have stated is very much appreciated. So far I am getting most of it and my initial tests show this really works very well. My next step is to try the code for the multiple files!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:34:45.903",
"Id": "73692",
"Score": "0",
"body": "@PBB: If there is something you're not 100% about, or if there are some hickups, let me know. I wrote the code in this answer off the top of my head, without any testing, so it might contain some bugs, still. I'm off for now, so it may take some time before I can respond to any questions, but don't worry: I will follow up"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:12:36.580",
"Id": "73703",
"Score": "0",
"body": "Elias,\n\nNo, I'm all OK here. I have learnt a great deal and have a better webpage as a result of your code. Very much appreciated!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:28:22.247",
"Id": "73776",
"Score": "0",
"body": "Elias,\nIs there any reason why this would strip out an ending </iframe> tag? I even placed an iframe inside a div but it still manages to eat </iframe> but leave all the rest of the html intact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T07:16:28.733",
"Id": "73836",
"Score": "0",
"body": "@PBB: I'm not sure, but it could be that iframes, which contain an entire DOM, too, are parsed, too, which means they contain a body tag, too. you could try (first) to call `$dom->saveXML($body, LIBXML_NOEMPTYTAG)`. If that doesn't work, you're going to have to remove the iframe tags, _then_ get the body tag, and add the iframes just before calling `saveXML`"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:56:22.820",
"Id": "42761",
"ParentId": "42691",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42761",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:42:14.797",
"Id": "42691",
"Score": "3",
"Tags": [
"php",
"beginner"
],
"Title": "Get contents from file"
} | 42691 |
<p>I've implemented Excel's <a href="http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx" rel="noreferrer">SUMIFS function</a> in <a href="http://pandas.pydata.org" rel="noreferrer">Pandas</a> using the following code. Is there a better — more Pythonic — implementation?</p>
<pre><code>from pandas import Series, DataFrame
import pandas as pd
df = pd.read_csv('data.csv')
# pandas equivalent of Excel's SUMIFS function
df.groupby('PROJECT').sum().ix['A001']
</code></pre>
<p>One concern I have with this implementation is that I'm not explicitly specifying the column to be summed.</p>
<h2>Data File</h2>
<p>Here's an example CSV data file (<code>data.csv</code>), although I'm displaying | instead of commas to improve the visual appearance.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>DATE | EMPLOYEE | PROJECT | HOURS
02/01/14 | Smith, John | A001 | 4.0
02/01/14 | Smith, John | B002 | 4.0
02/01/14 | Doe, Jane | A001 | 3.0
02/01/14 | Doe, Jane | C003 | 5.0
02/02/14 | Smith, John | B002 | 2.0
02/02/14 | Smith, John | C003 | 6.0
02/02/14 | Doe, Jane | A001 | 8.0
</code></pre>
</blockquote>
<h2>Equivalent Excel SUMIFS Function</h2>
<p>If I were to open <code>data.csv</code> in Excel and wanted to determine how many hours were worked on project A001, I would use the SUMIFS formula as follows:</p>
<pre class="lang-python prettyprint-override"><code>=SUMIFS($D2:$D8, $C2:$C8, "A001")
</code></pre>
<p>Where the <a href="http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx" rel="noreferrer">SUMIFS function</a> syntax is:</p>
<pre class="lang-python prettyprint-override"><code>=SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2,
criteria2], …)
</code></pre>
| [] | [
{
"body": "<p>The usual approach -- if you want all the projects -- would be</p>\n\n<pre><code>>>> df.groupby(\"PROJECT\")[\"HOURS\"].sum()\nPROJECT\nA001 15\nB002 6\nC003 11\nName: HOURS, dtype: float64\n</code></pre>\n\n<p>This only applies the <code>sum</code> on the desired column, as this constructs an intermediate <code>SeriesGroupBy</code> object:</p>\n\n<pre><code>>>> df.groupby(\"PROJECT\")[\"HOURS\"]\n<pandas.core.groupby.SeriesGroupBy object at 0xa94f8cc>\n</code></pre>\n\n<p>If you're only interested in the total hours of a particular project, then I suppose you could do</p>\n\n<pre><code>>>> df.loc[df.PROJECT == \"A001\", \"HOURS\"].sum()\n15.0\n</code></pre>\n\n<p>or if you dislike the repetition of <code>df</code>:</p>\n\n<pre><code>>>> df.query(\"PROJECT == 'A001'\")[\"HOURS\"].sum()\n15.0\n</code></pre>\n\n<p>but I find that I almost always want to be able to access more than one sum, so these are pretty rare patterns in my code.</p>\n\n<p>Aside: <code>.ix</code> has fallen out of favour as it has some confusing behaviour. These days it's recommended to use <code>.loc</code> or <code>.iloc</code> to be explicit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T03:01:07.397",
"Id": "42725",
"ParentId": "42695",
"Score": "5"
}
},
{
"body": "<p>If you want to do simple sum aggregation together with <code>SUMIF</code>, or multiple <code>SUMIFS</code> with different criteria simultaneously, I would suggest the following approach:</p>\n\n<pre><code>(\n df\n .assign(HOURS_A001 = lambda df: df.apply(lambda x: x.HOURS if x.PROJECT == \"A001\" else 0, axis=1))\n .agg({'HOURS': 'sum', 'HOURS_A001': 'sum'})\n)\n</code></pre>\n\n<p>or without per-row apply (this version is much faster):</p>\n\n<pre><code>(\n df\n .assign(HOURS_A001 = lambda df: df.HOURS * np.where(df.PROJECT == \"A001\", 1, 0))\n .agg({'HOURS': 'sum', 'HOURS_A001': 'sum'})\n)\n</code></pre>\n\n<p>So basically apply criteria and create a new row, then sum values in this row.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2016-12-29T08:45:18.300",
"Id": "151131",
"ParentId": "42695",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T19:40:14.960",
"Id": "42695",
"Score": "6",
"Tags": [
"python",
"excel",
"pandas"
],
"Title": "Excel's SUMIFS implemented using PANDAS, the Python Data Analysis Library"
} | 42695 |
<pre><code>function transform(tree,fn){
var root = tree,
node = tree,
child,
parent,
is_node,
dir;
root.dir = 0;
while(true) {
is_node = typeof(node)==="object";
dir = is_node ? node.dir : 2;
if (dir < 2)
child = node[dir],
node.dir++,
child.parent = parent = node,
child.dir = 0,
node = child;
else if ((changed = fn(node))!==undefined)
changed.parent = parent,
changed.dir = 0,
node = changed;
else
if (!parent)
return node;
else
parent[parent.dir-1] = node,
node = parent,
parent = node.parent;
};
};
// TEST
var tree = [[1,2],[[3,4],[5,6]]];
console.log(
JSON.stringify(transform(tree,function(a){
if (a[0]===1) return [3,[5,5]];
if (a[0]===5) return 77;
})) === "[[3,77],[[3,4],77]]");
</code></pre>
<p>I need to make this function as fast as possible, no matter what. I'm aware this is far from the optimal implementation. How could I improve it? Asm.js, maybe?</p>
| [] | [
{
"body": "<p>Ok, I've decided to write something after all, however not about the performance, but about the coding style. </p>\n\n<p>First off you should give more information what your function actually does. It took me a lot of time to understand that it you are working with binary trees here. </p>\n\n<p>I don't like your use of the comma operator. All code conventions I know discourage its use like this.</p>\n\n<p>Normally I'm fine with declaring all the variables at the start of the function instead of when they are used. However in this case, the declaration makes it look like all of the \nvariables are used \"globally\" within the function, although most of them are just temporal use. This makes reading the code very difficult.</p>\n\n<p>Additionally some of your variables (mainly <code>parent</code> and <code>dir</code>) seem to just duplicate the properties of the same name of the current <code>node</code>. This makes tracking the use of the variables and it's matching property very confusing IMHO.</p>\n\n<p>Actually lets go through the variables one by one:</p>\n\n<ul>\n<li><strong><code>root</code></strong>: With exception of setting the first <code>dir</code> property unused, and thus completely unnecessary. </li>\n<li><p><strong><code>node</code></strong>: Should be called <code>currentNode</code>.</p></li>\n<li><p><strong><code>child</code></strong>: One of the variables that seem to be \"global\", however is just used temporally in the <code>dir < 2</code> block. It should be declared there.</p></li>\n<li><p><strong><code>parent</code></strong>: I admit I haven't quite undesrtood the point of this (and the corresponding <code>parent</code> property), but I'm quite sure you are just duplicating the value of <code>node.parent</code>. I think it should be possible to get rid of it all together.</p></li>\n<li><p><strong><code>is_node</code></strong>: Like <code>child</code> just a temporary variable, so it's shouldn't be declared at the beginning of the function. Also it's named very badly. You are not using it when checking if a node \"is a node\", but if a node is an array (or has children, or if's not a leaf). So it should be called <code>is_array</code>, <code>has_children</code> or (if logically switched) <code>is_leaf</code>. However at the end, you don't need it at all IMHO. Instead just merge the two lines you are using it in.</p></li>\n<li><p><strong><code>dir</code></strong>: Sorry, but it's the worst of them all: </p>\n\n<ul>\n<li>Again just a temporary variable, that shouldn't be declared at the start of the function. </li>\n<li>It also just duplicates the value of <code>node.dir</code>. </li>\n<li>Very badly named. \"dir\" normally stands for \"direction\", which doesn't apply here. It's the \"current index\". </li>\n<li>Worst of all: The use of the \"magic\" (and yet completely meaningless) number <code>2</code>.</li>\n<li>Conclusion: Get rid of it. It's completely unnecessary. </li>\n</ul></li>\n</ul>\n\n<p>Instead of:</p>\n\n<pre><code>is_node = typeof(node)===\"object\";\ndir = is_node ? node.dir : 2;\nif (dir < 2)\n child = node[dir],\n</code></pre>\n\n<p>use</p>\n\n<pre><code>if (typeof(node)===\"object\")\n child = node[node.dir],\n</code></pre>\n\n<hr>\n\n<p>There is much more, but I don't have the time right now. Maybe I'll come back.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:57:41.710",
"Id": "73698",
"Score": "0",
"body": "Many of those were put on purpose and have a justification. Root is necessary to remember the first node, in order to stop computation. Parent and dir are duplicating boxed values because this provides huge performance boosts in JavaScript. About declaring temporary variables in the beginning of the function, this allows for the comma based style. The comma based style itself is much better because this way **everything is an expression**. This allows for much easier compiling back and fort of the code to other functional languages. The problem here is that \"var\" can't be used inside an (...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:01:58.220",
"Id": "73699",
"Score": "0",
"body": "expression, so the \"var\" declaration needs an statement. Including it on top of the function allows every function in the language to follow the same form: `function(<binds>){var <variables>; return <expression>}`. This is not the case because the function is particularly imperative and hand-optimized, but this keeps it in the same style of the rest of the code where compilers are used a lot. And yes, \"dir\" means directios: \"0\" = pointing left, \"1\" = pointing right, \"2\" = pointing up (or: go to parent). Magic numbers are necessary for performance reason plus lack of \"ENUM\" on JS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:04:05.670",
"Id": "73702",
"Score": "0",
"body": "The only thing I really agree is with the bad naming of \"is_node\". Indeed, \"is_array\" would be much better. The code itself is MUCH cleaner in the recursive version (it is a one liner!), but this is supposed to be fast version of it (recursion was up to 10x slower on my benchmarks because of stack explosion), so most of the things you complained about are necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:14:34.463",
"Id": "73705",
"Score": "0",
"body": "I assumed that these choices were made for perceived performance optimizations, however I don't believe they are actually justified (especially the comma operator), and I believe you should do some concrete performance tests for each \"optimization\", especially since IMHO they are probably strongly depended of the run-time engine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:16:01.313",
"Id": "73707",
"Score": "0",
"body": "But then lets talk about performance. First up: Why? JavaScript is rarely used in scenarios where such low level optimization is required. And to be honest, if you actually need such optimized performance (which you should prove BTW - and you still haven't said what you actually doing here), then you shouldn't be using JavaScript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:36:38.623",
"Id": "73714",
"Score": "0",
"body": "The actual application here is an structural editor for a functional language (Lambda Calculus enriched with numbers and lists) that runs on the browser. While a fast transformer is interesting for the interpreter/inliner/compiler/everything. The current slowdown happens when you are editing a deep AST (source code). My currently algorithm (recursive) is taking a long time (milliseconds) to apply some necessary transformations when you edit a node (eg: linking vars to their origin), due to stack explosion. That mini-lag is visible and worsens the user experience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:41:25.387",
"Id": "73715",
"Score": "0",
"body": "Another application of that editor is compiling the language and running it, so you can do interactive programming. So, sending the source to a server to compile it in a faster language and sending the result back would never be satisfactory, when the idea is that of \"compile - see result\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:44:56.440",
"Id": "73716",
"Score": "0",
"body": "About performance tests, I've done (not for this case) but in absolutely 100% of the algorithms, caching boxed variables provide huge performance boosts, sometimes even doubling it. So I've made that an automatic for performance intensive algorithms. Do the tests yourself if you want and you'll see what I'm talking about. And the comma is not about performance, but about keeping everything as an expression. This makes it much easier for compilers and parsers from FP-Languages <-> JavaScript. I also particularly believe it is much cleaner this way so I learned to love it."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:08:08.180",
"Id": "42747",
"ParentId": "42700",
"Score": "-1"
}
},
{
"body": "<p>Hmmm,</p>\n\n<p>I don't think your code works,</p>\n\n<pre><code>var tree = [[1,2,[1,2,[5]]],[[3,4],[5,6]],[1,2,[1,2,[5]]],[[3,4],[5,6]]];\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>[[3, 77], [[3, 4], 77], [1, 2, [1, 2, [5]]], [[3, 4], [5, 6]]]\n</code></pre>\n\n<p>I would have expected that you want that last [5,6] to be 77 in your fiddle.</p>\n\n<p>Furthermore, as RoToRa mentioned</p>\n\n<ul>\n<li>It is not clear in your code what you want to achieve</li>\n<li>Comma separated statements to avoid curly braces are evil, python much?</li>\n<li>Going through a tree pretty much asks for a recursive solution because you need to keep track of where you are</li>\n</ul>\n\n<p>This function seems to do what you want thru recursion:</p>\n\n<pre><code>function transform( node, f )\n{\n node = f(node) || node; \n var index = node.length;\n if( index )\n {\n while( index-- )\n {\n node[index] = transform( node[index] , f );\n }\n } \n return node;\n}\n</code></pre>\n\n<p>Or, if you drop those curlies which you seem to like:</p>\n\n<pre><code>function transform( node, f )\n{\n node = f(node) || node; \n var index = node.length;\n if( index )\n while( index-- )\n node[index] = transform( node[index] , f );\n return node;\n}\n</code></pre>\n\n<p>I originally wanted to use <code>[].map</code> which would be cleaner, however you insisted speed.</p>\n\n<p>Update: I checked jsperf for the fastest loop and it turns out there is a new loop variant that blows the other approaches out of the water: <a href=\"http://jsperf.com/loops/142\" rel=\"nofollow\">http://jsperf.com/loops/142</a></p>\n\n<p>Using this approach the code would look like this:</p>\n\n<pre><code>function transform( node, f )\n{\n node = f(node) || node; \n if( node.length )\n for (var i = 0, child; child = node[i]; i++)\n node[i] = transform( child , f );\n return node;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:03:06.560",
"Id": "73700",
"Score": "0",
"body": "Great implementations. They allow you see with one look what they do!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:15:48.597",
"Id": "73706",
"Score": "0",
"body": "Sorry, but this is basically what I had before rewriting it. The reason I attempted to write a non-recursive algorithm is exactly because I was having massive slowdowns due to stack explosions. The interactive algorithm is self-restricted in space and thus the only real option if you really want speed. Also, commas are not evil. **They keep everything as an expression** and thus make the whole code much more friendlier for compilers targeting JavaScript, while being much cleaner and more powerful than the statement-based style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:18:33.143",
"Id": "73709",
"Score": "0",
"body": "@Dokkat But your code, it does not work per my first comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:20:42.080",
"Id": "73710",
"Score": "0",
"body": "Also, I should have expressed myself better on the OP, so I'm sorry for that. It is meant for binary trees only, so obviously it breaks for other kinds of trees. Also, you provided a top-down transformer, which is not equivalent to a bottom-up transformer. Also, considering I expressed myself badly and you do provide an actually good answer for a similar problem, I'll be upvoting and accepting this answer in case nobody answers the actual problem. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:23:12.910",
"Id": "73711",
"Score": "0",
"body": "@Dokkat Thanks, I am curious, why must it be bottom-up? Do you think it will be faster or are there other reasons ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:27:49.323",
"Id": "73713",
"Score": "0",
"body": "@konijn because working bottom-up is necessary to find redexes in a tree-reduction algorithm. That is, suppose you are reducing, `(+ (+ 1 2) 3)`. The first redex is obviously `(+ 1 2)` - the deeper. Reducing it results in `(+ 3 3)` which is another redex, which becomes `6`. Going top-down would not work, I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:55:50.817",
"Id": "73761",
"Score": "0",
"body": "@Last comment before CR bugs me to start a chat; it would be great if you could update your question or your fiddle with a more realistic data set."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:58:35.177",
"Id": "42768",
"ParentId": "42700",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:22:43.230",
"Id": "42700",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"tree"
],
"Title": "JavaScript bottom-up tree transformer aimed for performance"
} | 42700 |
<p>Interested in a review of this code, in particular the (hopefully monadic) bind. I actually put this to good use. It was a nice complement to Guava's Optional, and shorter than:</p>
<blockquote>
<p>Optional.fromNullable(x).or(y);</p>
</blockquote>
<p>And I threw in a <code>bind</code> method, which I think lifts it up into monad space.</p>
<p>One question I wasn't sure of the the semantics of multiple calls. Should I carry along the original default value, or does each new value become the default? So in psuedo code, should</p>
<blockquote>
<p>Either.with("A").or("B").or(null)</p>
</blockquote>
<p>result in "A" (the original default) or "B"? I thought "B" made more sense.</p>
<p>I'm interested in if I got the monad signature & semantics right.</p>
<pre><code>public class Either<A> {
private final A value;
/**
* constructor sets the default & value the same
* @param defaultValue
*/
Either(A value) {
if (value == null) {
throw new IllegalArgumentException("Either cannot be null");
}
this.value = value;
}
/**
* constructor sets the default & value the same
* @param defaultValue
*/
Either(A defaultValue, A value) {
this.value = (value == null) ? defaultValue : value;
}
/**
* the unit method lifts the value into the monadic space
*
* @param value
* @return an either with the value as default
*/
public static <A> Either<A> with(A value) {
return new Either<A>(value);
}
/**
* create a new either using the previous default
*
* @param value
* @return
*/
public Either<A> or(A value) {
return new Either<A>(this.value, value);
}
/**
* @return the value, or the default
*/
public A get() {
return value;
}
/**
* completes this class as a monad
*
* @param f
* @return an either of the new type
*/
public <B> Either<B> bind(Function<A, Either<B>> f) {
return f.apply(value);
}
}
</code></pre>
<p>And here are the unit tests for bind (and sample usage):</p>
<pre><code>static class ToInt implements Function<String, Either<Integer>> {
private final int defaultInt;
/**
* lol closures in java
*
* @param defaultInt
*/
public ToInt(int defaultInt) {
this.defaultInt = defaultInt;
}
@Override
public Either<Integer> apply(String s) {
try {
return Either.with(Integer.parseInt(s));
}
catch (NumberFormatException nfe) {
return Either.with(defaultInt);
}
}
};
private static final Function<Integer, Either<Double>> SQRT = new Function<Integer, Either<Double>>() {
@Override
public Either<Double> apply(Integer i) {
return Either.with(Math.sqrt(i));
}
};
private static final int TEN_THOUSAND = 10000;
private final ToInt TO_INT = new ToInt(TEN_THOUSAND);
// ~=~=~=~=~=~=~=~=~=~=
// Tests
public void bindToIntEmptyEXPECTDefault() {
// Arrange
Either<String> a = Either.with("");
// Act
Either<Double> b = a.bind(TO_INT).bind(SQRT);
// Assert
assertEquals(b.get(), 100.0);
}
public void bindToIntFormatEXPECTDefault() {
// Arrange
Either<String> a = Either.with("zoom");
// Act
Either<Double> b = a.bind(TO_INT).bind(SQRT);
// Assert
assertEquals(b.get(), 100.0);
}
public void bindToIntEXPECTInt() {
// Arrange
Either<String> a = Either.with("144");
// Act
Either<Double> b = a.bind(TO_INT).bind(SQRT);
// Assert
assertEquals(b.get(), 12.0);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:17:43.370",
"Id": "73613",
"Score": "1",
"body": "For what it's worth, in Haskell, the types for Either are `Left` and `Right`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T05:05:20.903",
"Id": "73623",
"Score": "0",
"body": "ack. Thank you. I've been really bad at translating the Haskell functionality over. Well, it's still proven to be useful, though not correct. I should rename it and take another crack at Either, sticking to the Either spec more closely. Oh, well. It's still funny -- I feel like I'm learning a lot from these patterns, even if it's not the intended lesson."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:29:22.907",
"Id": "73669",
"Score": "1",
"body": "I figured you got the A and B from the type signature, but overlooked the important part. When you see `Either a b` in Haskell, the return type is either `Left a` or `Right b`. In this case, `a` and `b` signal that the actual type doesn't matter. The fact that they're different letters indicates that they don't have to be the same type (but they can be)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T23:08:34.383",
"Id": "73802",
"Score": "0",
"body": "@cimmanon I changed the class name to Default (I balked at naming it DefaultMonad as being too pretentious). The usage is `Default.with(\"1\").or(\"2\").get()`, and it supports bind :) But I have need now for an actual Either, so I may give it another go. Thank you for pointing that out!"
}
] | [
{
"body": "<p><strong>Documentation</strong></p>\n\n<p>I don't know if you're using this class as some kind of api are not, but if you're providing documentation, make sure it's useful and clear.</p>\n\n<pre><code>/**\n * constructor sets the default & value the same\n * @param defaultValue\n */\n Either(A value) {\n if (value == null) {\n throw new IllegalArgumentException(\"Either cannot be null\");\n }\n this.value = value;\n } \n/**\n * constructor sets the default & value the same\n * @param defaultValue\n */\n Either(A defaultValue, A value) {\n this.value = (value == null) ? defaultValue : value;\n } \n</code></pre>\n\n<p>Two different constructor, same documentation, one of them does not even specify the second argument. You could add valuable information since you have documentation. In your first constructor, you could specify that you're throwing an <code>IllegalArgumentException</code> if <code>value</code> is <code>null</code>.</p>\n\n<p>Documentation should help to know how to use the class, behavior that will bring exception and others sometimes some examples of uses.</p>\n\n<p><strong>Unit test</strong></p>\n\n<p>I'm glad to see that you have unit tests with good method names. The names don't respect camel-Case convention, but in general you know by the name what it's suppose to test. </p>\n\n<p>I'm wondering why you don't have a more \"standard\" test class. I don't see the <code>@Test</code> annotation. Your method seems to be included within another class, and not on his own test class. </p>\n\n<p>You don't need to always add comment about the structure of your test. If you keep the newlines between all three parts we can understand that you're doing the test in three steps : arrange, act, assert.</p>\n\n<p><strong>Naming</strong></p>\n\n<pre><code>private static final Function<Integer, Either<Double>> SQRT;\n</code></pre>\n\n<p>This is more of an personal taste here, but I find <code>SQRT</code> very unreadable. I would find <code>SQUARE_ROOT</code> more readable in general. I don't like abbreviation, even commons one. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T22:58:34.117",
"Id": "73592",
"Score": "1",
"body": "Excellent comments, thank you! Sorry, I severely truncated the unit tests because the tests for \"with\" and \"or\" were pretty boring. This is just the \"bind\" coverage. I actually aggree (strongly!) with you about abbreviations; if SQRT were in the production code rather than tests, I'd absolutely spell it out. Hm. I think I will here, too. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T02:41:58.450",
"Id": "73606",
"Score": "1",
"body": "@RobY I was wondering how do you run your tests?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:54:51.000",
"Id": "73620",
"Score": "0",
"body": "I've been using testng lately. In eclipse, I just right-click at the package level and run them there, or else through the maven test cycle. I trimmed out almost everything in my code sample except the actual tests. Is that what you use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:40:48.433",
"Id": "73672",
"Score": "0",
"body": "@RobY It's exactly what I have. But as I said in my answer, you were missing the `@Test` annotation for JUnit (the most common library) so I was wondering if you were doing something different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T18:09:17.320",
"Id": "73731",
"Score": "0",
"body": "I don't find SQRT (square root) to be any different from INT (integer) in terms of readability, especially when a quick search will turn up nothing but results for all sorts of topics on square roots."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T18:11:36.267",
"Id": "73733",
"Score": "0",
"body": "@cimmanon This is why I specify that this was a personal taste."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T22:52:15.230",
"Id": "42706",
"ParentId": "42702",
"Score": "5"
}
},
{
"body": "<p>I have a nit-pick with the logic in your <code>Either.or(A)</code> method. You have:</p>\n\n<blockquote>\n<pre><code>public Either<A> or(A value) {\n return new Either<A>(this.value, value);\n}\n</code></pre>\n</blockquote>\n\n<p>but, since <code>Either</code> is immutable (oh, should <code>Either</code> be a final class? ... I think so...), it makes sense that the <code>or</code> method can return the exact instance if it is valid.... why does it have to create a new instance each time? In a stream that can create a lot of GC churn....</p>\n\n<p>I would write that method:</p>\n\n<pre><code>public Either<A> or(A value) {\n return value == null ? this : new Either<A>(value);\n}\n</code></pre>\n\n<p>I know that essentially duplicates the constructor, but, doing it this way avoids the constructor in (hopefully) many places entirely.</p>\n\n<p>This leads on to your question:</p>\n\n<blockquote>\n <p>One question I wasn't sure of the the semantics of multiple calls.\n Should I carry along the original default value, or does each new\n value become the default? So in psuedo code, should</p>\n\n<pre><code>Either.with(\"A\").or(\"B\").or(null)\n</code></pre>\n \n <p>result in \"A\" (the original default) or \"B\"? I thought \"B\" made more\n sense.</p>\n</blockquote>\n\n<p>If the <code>or(A)</code> method does not need to construct a new instance, then it makes sense to me that the semantics should return <code>\"A\"</code>, since that allows skipping new instances for <code>\"B\"</code> and <code>null</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:28:40.193",
"Id": "73596",
"Score": "1",
"body": "Good call! Fixed. This logic does preserve the \"B\" response semantics, but the way I'm actually using it is this: `public static final Either<String> DEFAULT_STRING ...` and then applying `DEFAULT_STRING.or(s)` over and over. Your fix will spare the creating of a bunch of duplicates. (If I did want to return \"A\" every time it sees null, I could carry a `Either<A> defaultValue` in addition to the value. Then `or` would return `defaultEither` or `new Either...` The first implementation actually carried defaultValue forward each time, but just as the plain type.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:46:12.107",
"Id": "73598",
"Score": "0",
"body": "actually, it's even better... I can get rid of the 2nd overloaded constructor altogether. That's an overload (which I don't like but find handy) and 3 unit tests that just disappear. So that's a big win."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T23:50:11.993",
"Id": "42709",
"ParentId": "42702",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "42709",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:31:09.493",
"Id": "42702",
"Score": "10",
"Tags": [
"java",
"monads"
],
"Title": "An Either Monad in Java"
} | 42702 |
<p>I've hacked together some code to read the content from a sequence of files:</p>
<pre><code>let fileContents =
[ "filename1"; "filename2"; "etc" ]
|> Seq.map(fun file -> async {
use fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)
let data = Array.create(int fs.Length) 0uy
let! _ = fs.AsyncRead(data, 0, data.Length)
return data
})
|> Async.Parallel
|> Async.RunSynchronously
|> Seq.map System.Text.Encoding.ASCII.GetString
</code></pre>
<p>It works, but I'm not really sure about it. For one thing, is <code>async</code> actually giving me any benefit here? Also inside the <code>async</code> function I need to wait for <code>AsyncRead</code> to finish, but I don't need the returned value from it. Is there a better way of doing this than <code>let! _ = ...</code>?</p>
| [] | [
{
"body": "<p>You can take advantage of async to do parallel IO which Async.Parallel makes very easy. Also, when you don't need the return value of an async call you can use Async.ignore in combination with do!: <code>do! fs.AsyncRead(data, 0, data.Length) |> Async.ignore</code></p>\n\n<p>However this specific snipper can be made much simpler since there is no reason to await the result of the computations when using Async.Parallel:</p>\n\n<pre><code>open System.IO\n\nlet fileContents = \n [ \"filename1\"; \"filename2\"; \"etc\" ]\n |> List.map(fun file -> async { use fs = File.OpenRead(file) in return! fs.AsyncRead(fs.Length |> int)})\n |> Async.Parallel \n |> Async.RunSynchronously\n |> Seq.map System.Text.Encoding.ASCII.GetString\n</code></pre>\n\n<p>One caveat - if the size of your file is more than 2GB it won't work due to long->int conversion - but that would be a crazy big file to just read the content of like that :-D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:46:27.727",
"Id": "73787",
"Score": "0",
"body": "Cool tips. I was trying `|> ignore instead of |> Async.Ignore` which doesn't compile. Can you tell me what `in` is doing in `let fs = File.OpenRead(file) in fs.AsyncRead(fs.Length |> int)` and how the let binding is also returning a value please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:34:09.470",
"Id": "73844",
"Score": "0",
"body": "Hi NickL, the `in` keyword is a way to bind a value as part of the next expression and is something f# inherited from OCaml. It's similar to doing a line-break after the let expression, but the value (in this case `fs`) is only available in the next expression. The let binding isn't returning a value but just binding the expression File.OpenRead(file) to it. Primary reason you would use `in` in f# is to skip a line-break and thus write a one-liner or if you already had a binding of the same name that you wanted to `shadow` only in the next expression on the same line. Hope this makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:47:30.867",
"Id": "73848",
"Score": "0",
"body": "@NickL Btw, notice that I changed my response since my previous one actually was problematic since I never closed the stream. So now I use the async computation expression in order to be able to await the async read so that the `use`-expression will work and dispose the file-stream. It's still running it in parallel though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:13:03.280",
"Id": "42799",
"ParentId": "42703",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:33:37.803",
"Id": "42703",
"Score": "2",
"Tags": [
"asynchronous",
"f#",
"concurrency"
],
"Title": "Is this a good use of Async in F#?"
} | 42703 |
<p>Recently I needed to save session state in cookies, instead of server side. I looked around and didn't see anything similar, so I decided to write something to handle the encryption, decryption, and validation of the cookies. I wanted some opinions before/if I release it on packagist.</p>
<p>Any feedback would be great, thanks</p>
<p><a href="https://github.com/Rosio/Encrypted-Cookies" rel="nofollow">https://github.com/Rosio/Encrypted-Cookies</a></p>
<p>Below are the important files, the exceptions are just child classes of <code>Exception</code>.</p>
<p>EncryptedCookie.php</p>
<pre><code><?php
namespace Rosio\EncryptedCookie;
use Rosio\EncryptedCookie\CookieStorage;
use Rosio\EncryptedCookie\CryptoSystem\iCryptoSystem;
use Rosio\EncryptedCookie\Exception\InputTooLargeException;
use Rosio\EncryptedCookie\Exception\InputTamperedException;
use Rosio\EncryptedCookie\Exception\InputExpiredException;
use Rosio\EncryptedCookie\Exception\TIDMismatchException;
class EncryptedCookie
{
protected $name;
protected $data;
protected $domain;
protected $path;
protected $expiration;
protected $isSecure;
protected $isHttpOnly;
/**
* The system which encryptes and decryptes cookies.
*/
protected $cryptoSystem;
/**
* The system which stores and retrieves cookies.
*/
protected $cookieStorage;
function __construct ($name)
{
$this->name = $name;
$this->domain = '';
$this->path = '/';
$this->expiration = 0;
$this->isSecure = false;
$this->isHttpOnly = true;
}
/**
* Load a cookie's data if available.
*
* @throws InputTamperedException If The returned cookie was modified locally.
*/
function load ()
{
if (!$this->getCookieStorage()->has($this->name))
return false;
$data = $this->getCookieStorage()->get($this->name);
try {
$data = $this->getCryptoSystem()->decrypt($data);
}
catch (\Exception $e) {
return false;
}
$this->data = $data;
return $this;
}
/**
* Save a cookie's data.
*
* @throws InputTooLargeException If the encrypted cookie is larger than 4kb (the max size a cookie can be).
*/
function save ()
{
$this->getCookieStorage()->set($this);
return $this;
}
/**
* Get the data for the cookie in its encrypted form.
* @return string
*
* @throws InputTooLargeException If the encrypted cookie's data will be truncated by the browser.
*/
function getEncryptedData ()
{
$edata = $this->getCryptoSystem()->encrypt($this->data, $this->expiration);
if (strlen($edata) >= 4096)
throw new InputTooLargeException('Total encrypted data must be less than 4kb, or it will be truncated on the client.');
return $edata;
}
/* =============================================================================
Setters
========================================================================== */
/**
* Set the cryptographic system used to encrypt/decrypt the cookie.
* @param iCryptoSystem $cryptoSystem
*/
function setCryptoSystem (iCryptoSystem $cryptoSystem)
{
$this->cryptoSystem = $cryptoSystem;
return $this;
}
/**
* Set the system used to store and retrieve cookies.
* This has been abstracted mainly for testing purposes.
* @param CookieStorage $cookieStorage
*/
function setCookieStorage (CookieStorage $cookieStorage)
{
$this->cookieStorage = $cookieStorage;
return $this;
}
/**
* Set the data to be stored in the cookie.
* Max is about 2.8kb (encrypting adds size).
* @param mixed $data Data to be stored in the cookie. If it isn't a string it will be serialized.
*/
function setData ($data)
{
$this->data = serialize($data);
return $this;
}
/**
* Set the expiration of the cookie. This also corresponds to the date the cookie's data is considered invalid.
* @param int $expiration A Unix timestamp.
*
* @throws InvalidArgumentException If the given expiration isn't a valid unix timestamp.
*/
function setExpiration ($expiration)
{
if (!is_numeric($expiration) || $expiration < 0)
throw new \InvalidArgumentException('Expiration must be a unix timestamp.');
$this->expiration = $expiration;
return $this;
}
/**
* The domain the cookie is valid for.
* @param string $domain
*/
function setDomain ($domain)
{
$this->domain = $domain;
return $this;
}
/**
* The path the cookie is valid for.
* @param string $path
*/
function setPath ($path)
{
$this->path = $path;
return $this;
}
/**
* Should this cookie only be sent to the server if there is a secure connection?
* @param boolean $isSecure
*/
function setSecure ($isSecure)
{
$this->isSecure = $isSecure;
return $this;
}
/**
* Should this cookie only be available to the server (and not client-side scripts)?
* @param boolean $isHttpOnly
*/
function setHttpOnly ($isHttpOnly)
{
$this->isHttpOnly = $isHttpOnly;
return $this;
}
/* =============================================================================
Getters
========================================================================== */
function getData ()
{
return unserialize($this->data);
}
function getExpiration ()
{
return $this->expiration;
}
function getPath ()
{
return $this->path;
}
function getDomain ()
{
return $this->domain;
}
function isSecure ()
{
return $this->isSecure;
}
function isHttpOnly ()
{
return $this->isHttpOnly;
}
/**
* Retrieve the cookie storage in use by this cookie.
* @return CookieStorage
*/
protected function getCookieStorage ()
{
// Lazy load a default if one wasn't set
if ($this->cookieStorage === null)
$this->cookieStorage = new CookieStorage();
return $this->cookieStorage;
}
/**
* Retrieve the crypto system in use by this encrypted cookie.
* @return iCryptoSystem
*
* @throws BadMethodCallException If the crypto system has not been set.
*/
protected function getCryptoSystem ()
{
if ($this->cryptoSystem === null)
throw new \BadMethodCallException('Crypto system must be set before a cookie can be encrypted/decrypted.');
return $this->cryptoSystem;
}
}
</code></pre>
<p>CookieStorage.php</p>
<pre><code><?php
namespace Rosio\EncryptedCookie;
use Rosio\EncryptedCookie\EncryptedCookie;
class CookieStorage
{
protected $group;
public function __construct ($group = null)
{
$this->group = $group;
}
public function has ($name)
{
return isset($_COOKIE[$this->getCookieName($name)]);
}
public function get ($name)
{
return $_COOKIE[$this->getCookieName($name)];
}
public function set (EncryptedCookie $cookie)
{
setcookie($cookie->getName(), $cookie->getEncryptedData(), $cookie->getExpiration(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
}
protected function getCookieName ($name)
{
return $this->group === null ? $name : $this->group . '_' . $name;
}
}
</code></pre>
<p>CookieFactory.php</p>
<pre><code><?php
namespace Rosio\EncryptedCookie;
use Rosio\EncryptedCookie\CryptoSystem\iCryptoSystem;
use Rosio\EncryptedCookie\CookieStorage;
class CookieFactory
{
private $cryptoSystem;
private $cookieStorage;
function __construct (iCryptoSystem $cryptoSystem, CookieStorage $cookieStorage = null)
{
$this->cryptoSystem = $cryptoSystem;
if ($cookieStorage === null)
$this->cookieStorage = new CookieStorage;
else
$this->cookieStorage = $cookieStorage;
}
function create ($name)
{
$cookie = new EncryptedCookie ($name);
$cookie->setCryptoSystem($this->cryptoSystem);
$cookie->setCookieStorage($this->cookieStorage);
return $cookie;
}
function get ($name)
{
$cookie = new EncryptedCookie ($name);
$cookie->setCryptoSystem($this->cryptoSystem);
$cookie->setCookieStorage($this->cookieStorage);
$cookie->load();
return $cookie;
}
}
</code></pre>
<p>CryptoSystem/iCryptoSystem.php</p>
<pre><code><?php
namespace Rosio\EncryptedCookie\CryptoSystem;
interface iCryptoSystem
{
public function encrypt ($data, $expiration);
public function decrypt ($data);
}
</code></pre>
<p>CryptoSystem/AES_SHA1.php</p>
<pre><code><?php
namespace Rosio\EncryptedCookie\CryptoSystem;
use Rosio\EncryptedCookie\Exception\RNGUnavailableException;
use Rosio\EncryptedCookie\Exception\InputTamperedException;
use Rosio\EncryptedCookie\Exception\InputExpiredException;
use Rosio\EncryptedCookie\Exception\TIDMismatchException;
class AES_SHA1 implements iCryptoSystem
{
const IV_SIZE = 32;
private $symmetricKey;
private $HMACKey;
public function __construct($symmetricKey, $HMACKey)
{
$this->symmetricKey = $symmetricKey;
$this->HMACKey = $HMACKey;
}
public function encrypt ($data, $expiration)
{
$iv = $this->getRandom(self::IV_SIZE);
$atime = time();
$tid = $this->getTID();
$encData = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->symmetricKey, $data, MCRYPT_MODE_CBC, $iv);
$hmac = $this->getHMAC($encData, $atime, $expiration, $tid, $iv);
return base64_encode($encData) . '|' . base64_encode($atime) . '|' . base64_encode($expiration) . '|' . base64_encode($tid) . '|' . base64_encode($iv) . '|' . base64_encode($hmac);
}
public function decrypt ($data)
{
list($encData, $atime, $expiration, $tid, $iv, $hmac) = array_map('base64_decode', explode('|', $data));
if ($tid !== $this->getTID())
throw new TIDMismatchException('The data TID no longer matches the crypto system TID.');
$generatedHMAC = $this->getHMAC($encData, $atime, $expiration, $tid, $iv);
if ($hmac !== $generatedHMAC)
throw new InputTamperedException('The data HMAC no longer matches.');
if ($expiration > 0 && $atime + $expiration < time())
throw new InputExpiredException('The expiration time on the data has been reached.');
$data = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->symmetricKey, $encData, MCRYPT_MODE_CBC, $iv), chr(0));
return $data;
}
protected function getRandom ($length)
{
$wasCryptoSecure = false;
$random = openssl_random_pseudo_bytes($length, $wasCryptoSecure);
if ($wasCryptoSecure !== true)
throw new RNGUnavailableException('The RNG was unable to provide truely random numbers.');
return $random;
}
protected function getHMAC ($encryptedData, $aTime, $expiration, $tid, $iv)
{
return hash_hmac('sha1', base64_encode($encryptedData) . base64_encode($aTime) . base64_encode($expiration) . base64_encode($tid) . base64_encode($iv), $this->HMACKey, true);
}
function setIVSize ($size)
{
$this->IVSize = $size;
}
/**
* Get a string which uniquely represents the algorithms and keys used to encrypt the data.
* @return string
*/
function getTID ()
{
return substr(md5(md5($this->symmetricKey) . 'AES_SHA1' . md5($this->HMACKey)), 0, 8);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:35:13.563",
"Id": "73586",
"Score": "0",
"body": "Please embed the code you'd like reviewed. It shouldn't just be behind a link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:36:28.893",
"Id": "73587",
"Score": "0",
"body": "@Jamal, it's 10+ files, I'll start embedding it, but I'm not sure how practical it'd be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:37:03.277",
"Id": "73588",
"Score": "0",
"body": "You may split it up amongst different questions if necessary."
}
] | [
{
"body": "<p>Overall your design looks good for me. Nothing really bad here. Some suggestions on your architecture though:</p>\n\n<p>Your cookie implementation is dependent on the <code>CryptoSystem</code> and the <code>CookieStorage</code>. But then a Cookie doesn't actually care about how it is stored or if its content is encrypted. This makes your cookie class very long though with three different responsibilities: representation of the cookie itself, storing & encryption. Furthermore, storing and encryption just delegate. </p>\n\n<p>I'd consider a cookie as a simple value object which can be created everywhere (without a factory). The storage on the other hand is responsible for how the information is stored. One possibility of this <code>how</code> seems to be <code>encrypted</code> for me. </p>\n\n<p>My two recommendations regarding the architecture are:</p>\n\n<ul>\n<li>Remove storage and encryption from the cookie class</li>\n<li>Make a cookie-storage that encrypts / decrypts on save/load</li>\n</ul>\n\n<p>This puts each responsibility in exactly one class and slightly less coupling. Furthermore you the factory is not required any more :) .The result would end up like:</p>\n\n<pre><code>class Cookie\n{\n protected $name;\n protected $data;\n\n protected $domain;\n protected $path;\n protected $expiration;\n protected $isSecure;\n protected $isHttpOnly;\n\n // getters/setters here\n}\n\nclass EncryptedCookieStorage {\n public function __construct(iCryptoSystem $crypto, $group = null) {};\n}\n\n// usage\n$cookie = new Cookie();\n$storage->save($cookie);\n</code></pre>\n\n<p>Some other remarks not related to this suggestion:</p>\n\n<ul>\n<li>I usually prefer constructor injection of required dependencies and setter injection for optional dependencies. If your class requires more then two dependencies it most likely has too many responsibilities. </li>\n<li>I use <code>protected</code> only if I want subclasses to modify variables. This is almost never the case though. Someone sublcassing my class might forget some integrity checks or whatever. Subclasses should use getters/setters for this in my opinion. </li>\n<li>I hope all your exceptions inherit from a common abstraction specific for this component.</li>\n<li>Not sure if cookie expiration is really an exception</li>\n<li>Do type-validation on your scalars (or where you expect scalars): CookieFactory::get(new \\Exception) is probably not what you expect.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:22:52.410",
"Id": "74814",
"Score": "0",
"body": "Thanks a ton for the write up. I knew the code itself wasn't bad, but I'm not particularly strong when it comes to architecture. I'll look at reworking the design before 1.0."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T14:42:45.100",
"Id": "42874",
"ParentId": "42704",
"Score": "3"
}
},
{
"body": "<p>I only looked at the crypto, not the rest of the code. I found some minor issues, but it's pretty rare to see crypto code with so few flaws.</p>\n\n<ul>\n<li><p>You're using a variable time comparison to validate the MAC. So the time taken to execute the comparison depends on the number of characters that match the correct MAC. It might be possible to exploit that timing side-channel to forge a MAC.</p>\n\n<p>Constant time comparisons typically look something like this:</p>\n\n<pre><code>$differentBits = 0;\nfor ($i = 0; $i < length; $i++) {\n $differentBits |= (ord($s1[$i]) ^ ord($s2[$i]));\n}\nreturn $differentBits === 0;\n</code></pre></li>\n<li><p>You claim to use AES-256 which has 128 bit blocks and a 256 key, but you're actually using Rijndael with 256 bit block. Either use AES (Rijndael 128), or update the documentation.</p></li>\n<li>Consider using HMAC-SHA-256 (possibly with truncated output). While HMAC-SHA-1 isn't broken, I recommend going with the stronger choice.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:13:20.223",
"Id": "74829",
"Score": "0",
"body": "One question I had specifically was if a truncated md5 of the secret keys was a bad idea for the TID? It feels like I shouldn't expose any part of the secret key, but I couldn't think of another way to generate a unique TID"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:18:26.873",
"Id": "74903",
"Score": "0",
"body": "Assuming you use proper high entropy keys, publishing their hash should be no problem if the hash is first pre-image resistant. I'd rather choose truncated SHA-2 over MD5, but even with MD5 I'm not aware of any practical attacks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T13:54:33.030",
"Id": "43062",
"ParentId": "42704",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42874",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T21:34:18.620",
"Id": "42704",
"Score": "4",
"Tags": [
"php",
"cryptography"
],
"Title": "Cookie encryption library"
} | 42704 |
<p>I need some help reviewing this code in terms of making as fast as possible. This is a modified version of BFS that does quite a bit of processing on the side.</p>
<p><strong>Use case:</strong></p>
<p>I have a large graph (probably tens of thousands of nodes). Every edge is defined by three parameters currently - bandwidth, latency and cost. I need to compute a list of pareto optimal paths from source to destination (for simplicity sake, let us assume that BFS runs to completion). The way I am doing this is computing the paths to each neighbor from the current node as BFS runs and checking if any paths exist on the neighbor that are optimal as compared to the current path (check definition of optimality below). I then update the node's path tables accordingly.</p>
<p><strong>Optimality Criteria</strong></p>
<p>A pareto optimal path for my case is defined as one that is non-dominated by ANY other path in consideration. For our case, non-dominated means that a path should have more bandwidth, lesser latency and lesser cost than the one it is being compared to. If a decision cannot be made, we keep both paths.</p>
<p><strong>What is important</strong></p>
<ol>
<li>Code needs to be optimized for speed (so I need to make sure I am doing things the good, Pythonic way)</li>
<li>Any alterations to code that can cut down the LoC.</li>
<li><strong>I have used the NetworkX code base, so any use of short hand methods are the same as what NetworkX supports.</strong> (I will provide my versions of graph.py and multigraph.py if required, though they are essentially stripped down versions of the NetworkX classes)</li>
</ol>
<p><strong>Observations</strong></p>
<p>I know that there is repeated code, but I haven't figured out how to refactor it correctly. Inputs are welcome. Also, the big path comparison method at the end is a set of if-else blocks. Is there a better way to do this?</p>
<p><strong>Code</strong></p>
<pre><code>def bfs_pathfinder(graph, source, destination):
""" This method computes the pareto optimal paths during
a BFS run of the graph. When the BFS run completes, the
destination will have a list of optimal paths in its
table
Parameters
----------
graph: required
This is the topology graph (or copy) to be operated on
source, destination: required
The source and destination vertices in the service request
Returns
-------
A list of optimal path options
Raises
------
AlgorithmError on any error encountered during operation
"""
initial_path, path_bound = astar.astar_path(graph, source,
destination, None)
pf_logger.debug("Initial bound on path to destination : " +
', '.join(map(str, path_bound)))
graph.node_list[source]['predecessor'] = None
#----------------------------------------------------------------------
# Set the initial AStar path as the bound on the destination node,
# use the whole path as the key. These are the only two types that
# can be used as a predecessor, a string for the initial path
# and a vertex object for every other partial path created on the BFS
# search
#----------------------------------------------------------------------
graph.node_list[destination]['path_table'][(initial_path)] =
(path_bound)
pf_logger.debug("Start Node : " + str(source))
pf_logger.debug("End Node : " + str(destination))
bfs_queue = deque(source)
while bfs_queue:
current_vertex = bfs_queue.popleft()
try:
# Calculate the new path for each existing path on the current
vertex -
# path - existing path to the current vertex
# existing_cost - path cost to current vertex using 'path'
# for path, existing_cost in graph.node_list[current_vertex]
# ['path_table'].items():
# entry = [nbrs for nbrs in G[current_vertex] - list of
# neighbors
# G[current_vertex][entry][attr] - outgoing edge attributes from
# current vertex
for neighbor in [nbrs for nbrs in graph[current_vertex]]:
link_bandwidth = graph[current_vertex][neighbor]
['bandwidth']
link_latency = graph[current_vertex][neighbor]['latency']
link_cost = graph[current_vertex][neighbor]['cost']
updated_cost = ((existing_cost[0] if (existing_cost[0] <
link_bandwidth) else link_bandwidth,
(existing_cost[1] + link_latency),
(existing_cost[2] + link_cost))
# Check if node hasn't been visited at all, or has been
# queued for processing
if (graph.node_list[neighbor]['color'] == 'White'):
# First, set color to 'Gray' to indicate it is queued,
# then update 'path_table'
graph.node_list[neighbor]['color'] = 'Gray'
graph.node_list[neighbor]['predecessor'] =
current_vertex
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
bfs_queue.append(neighbor)
elif (graph.node_list[neighbor]['color'] == 'Gray'):
# If, by chance the queued neighbor doesn't have a
# 'path_table' AT ALL, which normally should not happen
if not graph.node_list[neighbor]['path_table']:
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
# In the eventuality that the neighbor already has
# calculated paths in the 'path_table',
# we need to compare the updated_path to the existing
# ones on the node and update accordingly.
# This is taken care of by the _path_comparison method
else:
for current_optimal_path, current_optimal_parameters
in graph.node_list[neighbor]['path_table'].items():
# See _path_comparison for return value
# indications
insert_decision =
_path_comparison(current_optimal_parameters,
updated_cost)
if (insert_decision == 1):
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
del graph.node_list[neighbor]['path_table']
[current_optimal_path]
elif (insert_decision == 0):
pass
elif (insert_decision == -1):
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
continue
else:
pf_logger.error("This is an unaccounted
outcome.Re-check outcomes.")
raise AlgorithmError("This is an unaccounted
outcome for path
comparison.")
else:
# Vertex is black and has already been evaluated. Skip
# node (hopefully this is what controls
# infinite looping in the BFS traversal
pf_logger.debug("Vertex is colored black. Skipping
node.")
continue
pf_logger.debug("All edges explored. Coloring " +
str(current_vertex) + " black")
graph.node_list[current_vertex]['color'] = 'Black'
except NameError:
# This means that the node doesn't have any existing 'path_table'
# entries
for neighbor in [nbrs for nbrs in graph[current_vertex]]:
link_bandwidth = graph[current_vertex][neighbor]['bandwidth']
link_latency = graph[current_vertex][neighbor]['latency']
link_cost = graph[current_vertex][neighbor]['cost']
updated_cost = (link_bandwidth, link_latency, link_cost)
# Check if node hasn't been visited at all, or has been queued
# for processing
if (graph.node_list[neighbor]['color'] == 'White'):
# First, set color to 'Gray' to indicate it is queued, then
# update 'path_table'
graph.node_list[neighbor]['color'] = 'Gray'
graph.node_list[neighbor]['predecessor'] = current_vertex
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table'][tuple(updated_path)]
= updated_cost
bfs_queue.append(neighbor)
elif (graph.node_list[neighbor]['color'] == 'Gray'):
# If, by chance the queued neighbor doesn't have a
# 'path_table' AT ALL,
# which normally should not happen
if not graph.node_list[neighbor]['path_table']:
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
# In the eventuality that the neighbor already has
# calculated paths in the 'path_table',
# we need to compare the updated_path to the existing ones
# on the node and update accordingly.
# This is taken care of by the _path_comparison method
else:
for current_optimal_path, current_optimal_parameters in
graph.node_list[neighbor]['path_table'].items():
# See _path_comparison for return value indications
insert_decision =
_path_comparison(current_optimal_parameters,
updated_cost)
if (insert_decision == 1):
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
del graph.node_list[neighbor]['path_table']
[current_optimal_path]
elif (insert_decision == 0):
pass
elif (insert_decision == -1):
updated_path = list(path)
updated_path.append(current_vertex)
graph.node_list[neighbor]['path_table']
[tuple(updated_path)] = updated_cost
continue
else:
pf_logger.error("This is an unaccounted
outcome.Re-check outcomes.")
raise AlgorithmError("This is an unaccounted
outcome for path
comparison.")
else:
# Vertex is black and has already been evaluated. Skip node
# (hopefully this is what controls
# infinite looping in the BFS traversal
pf_logger.debug("Vertex is colored black. Skipping node.")
continue
pf_logger.debug("All edges explored. Coloring " + str(current_vertex) +
" black")
graph.node_list[current_vertex]['color'] = 'Black'
#---------------------------------------------------------------------------
# This method compares an existing path on a node with a newly calculated
# partial path from a different predecessor.
# Use an insertFlag to figure out the scenario of Solution A vs Solution B
# 1. insert_decision = 0 -> nothing to insert, keep solution A
# 2. insert_decision = 1 -> Solution B is better. Add B, remove Solution A
# 3. insert_decision = -1 -> Both are optimal. Keep Solution A, add Solution
# B
#---------------------------------------------------------------------------
def _path_comparison(existing_path, incoming_path):
if (existing_path[0] == incoming_path[0]):
if (existing_path[1] > incoming_path[1]):
if (existing_path[2] >= incoming_path[2]):
return 1
elif (existing_path[2] < incoming_path[2]):
return -1
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[1] < incoming_path[1]):
if (existing_path[2] <= incoming_path[2]):
return 0
elif (existing_path[2] > incoming_path[2]):
return -1
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[1] == incoming_path[1]):
if (existing_path[2] > incoming_path[2]):
return 1
elif (existing_path[2] <= incoming_path[2]):
return 0
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[0] > incoming_path[0]):
if (existing_path[1] > incoming_path[1]):
if (existing_path[2] > incoming_path[2]):
return 1
elif (existing_path[2] == incoming_path[2]):
return -1
elif (existing_path[2] < incoming_path[2]):
return 0
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[1] < incoming_path[1]):
if ((existing_path[2] < incoming_path[2]) or
(existing_path[2] == incoming_path[2]) or
(existing_path[2] > incoming_path[2])):
return 0
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[1] == incoming_path[1]):
if (existing_path[2] > incoming_path[2]):
return -1
elif (existing_path[2] <= incoming_path[2]):
return 0
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[0] < incoming_path[0]):
if (existing_path[1] > incoming_path[1]):
if ((existing_path[2] > incoming_path[2]) or
(existing_path[2] > incoming_path[2]) or
(existing_path[2] > incoming_path[2])):
return 1
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[1] < incoming_path[1]):
if (existing_path[2] == incoming_path[2]):
return -1
elif (existing_path[2] < incoming_path[2]):
return 0
elif (existing_path[2] > incoming_path[2]):
return 1
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
if (existing_path[1] == incoming_path[1]):
if (existing_path[2] < incoming_path[2]):
return -1
elif (existing_path[2] >= incoming_path[2]):
return 1
else:
pf_logger.error("This is an outcome " +
"that should not be encountered")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T06:18:23.823",
"Id": "73627",
"Score": "0",
"body": "Wow...that is a lot of code. I won't even worry about the bfs implementation if I were you, instead I would be looking for a way to make that path comparison code have less code in it."
}
] | [
{
"body": "<p>I'd suggest having a look at <a href=\"http://lukauskas.co.uk/articles/2014/02/13/why-your-python-runs-slow-part-1-data-structures/\" rel=\"nofollow\">Why Your Python Runs Slow. Part 1: Data Structures</a> as it seems to apply to your code.</p>\n\n<hr>\n\n<p>Your <code>_path_comparison</code> is amazingly convoluted. Among other things, it involves unreachable code.</p>\n\n<pre><code> if (existing_path[2] >= incoming_path[2]):\n return 1\n elif (existing_path[2] < incoming_path[2]):\n return -1\n else:\n pf_logger.error(\"This is an outcome that should not be encountered\")\n</code></pre>\n\n<p>should be :</p>\n\n<pre><code> if (existing_path[2] >= incoming_path[2]):\n return 1\n else:\n return -1\n</code></pre>\n\n<p>which could be :</p>\n\n<pre><code> return 1 if (existing_path[2] >= incoming_path[2]) else -1\n</code></pre>\n\n<p>Also :</p>\n\n<pre><code> if ((existing_path[2] > incoming_path[2]) or\n (existing_path[2] > incoming_path[2]) or\n (existing_path[2] > incoming_path[2])):\n return 1 \n</code></pre>\n\n<p>definitly looks wrong to me.</p>\n\n<p>My re-written version of the code would be :</p>\n\n<pre><code>def _path_comparison(existing_path, incoming_path):\n e0,e1,e2 = existing_path \n i0,i1,i2 = incoming_path\n if (e0 == i0): \n if (e1 > i1):\n return 1 if (e2 >= i2) else -1\n elif (e1 < i1):\n return 0 if (e2 <= i2) else -1\n else:\n assert(e1 == i1)\n return 1 if (e2 > i2) else 0\n elif (e0 > i0):\n if (e1 > i1):\n if (e2 > i2):\n return 1 \n elif (e2 == i2):\n return -1 \n else:\n assert(e2 < i2)\n return 0\n elif (e1 < i1):\n return 0\n else:\n assert (e1 == i1)\n return -1 if (e2 > i2) else 0\n else:\n assert (e0 < i0)\n if (e1 > i1):\n assert(e2 > i2)\n return 1 \n elif (e1 < i1):\n if (e2 == i2):\n return -1\n elif (e2 < i2):\n return 0\n else:\n assert (e2 > i2)\n return 1\n else:\n assert (e1 == i1):\n return -1 (e2 < i2) else 1\n</code></pre>\n\n<p>If something was wrong before (which is likely to be the case), it is still wrong after my rewriting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T20:25:12.337",
"Id": "73765",
"Score": "0",
"body": "True that. It is convoluted in the sense that I went with the basic logic flow of evaluating triplet conditions. I had a flow-sheet for all the logic comparisons and just translated them as if-else blocks. This kind of help is what I was looking for. Thanks a ton. As for my data structures, they are the same as NetworkX uses. And given that NetworkX performs pretty well on large graph sets, I just wanted to make sure my code wasn't crappy, because I know the data structure usage is optimized. I did not want my usage to screw that up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T20:39:20.740",
"Id": "73767",
"Score": "0",
"body": "@adwaraki, if the answer isn't correct, state that in a comment, do not edit the code in the answer, let the Author do that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:17:32.147",
"Id": "73773",
"Score": "0",
"body": "@Malachi: He wasn't wrong in his answer. His answer transcribed my incorrect code correctly. I corrected mine from his comment and hence that renders the answer correctly incorrect? I thought it needed to be kept in sync?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:30:02.943",
"Id": "73777",
"Score": "0",
"body": "so you changed your code after he reviewed and showed you what was wrong with it? you should have posted the new code as a new question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T23:34:01.463",
"Id": "73806",
"Score": "0",
"body": "@Malachi: I don't have a follow up question. I was just incorporating his suggestions to clean up the code. I assumed since this was a code review site, I was supposed to do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T00:05:39.617",
"Id": "73814",
"Score": "0",
"body": "nope, accepting an answer and upvoting is what we are looking for, @adwaraki"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T00:35:14.513",
"Id": "73816",
"Score": "1",
"body": "@Malachi: Got it. Will do from next time."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:28:52.030",
"Id": "42757",
"ParentId": "42708",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42757",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T23:23:39.137",
"Id": "42708",
"Score": "5",
"Tags": [
"python",
"optimization",
"python-3.x",
"graph",
"breadth-first-search"
],
"Title": "Modified BFS code optimizations"
} | 42708 |
<p>Based on my understanding of Verlet integration I tryed to use it over my Euler method to move my character in a 2D space.
I will put only the neccessery code, but if anything else is needed I will edit my post.</p>
<p>This is my Character class (which I probably need to rename to Charactor)</p>
<pre><code>class PlayerData(object):
def __init__(self):
self.applied_force = Vector(0, 0)
self.mass = 70 /killograms
self.position = Vector(15, 200)
self.old_position = Vector(self.position.x, self.position.y)
self.acceleration = Vector(self.applied_force.x / self.mass, 0)
# These methods seems smelly
def on_left_key_pressed(self):
self.applied_force.x = -200
self.old_position.x = self.position.x + 3
def on_right_key_pressed(self):
self.applied_force.x = 200
self.old_position.x = self.position.x - 3
def on_left_key_released(self):
self.applied_force.x = 0
self.old_position.x = self.position.x
def on_right_key_released(self):
self.applied_force.x = 0
self.old_position.x = self.position.x
def keys_up(self):
self.applied_force = Vector(0, 0)
self.old_position = Vector(self.position.x, self.position.y)
def verlet(self, dt):
self.acceleration = Vector(self.applied_force.x / self.mass, 0)
temp = Vector(self.position.x, self.position.y)
self.position.x += self.position.x - self.old_position.x + \
self.acceleration.x * dt * dt
self.old_position = Vector(temp.x, temp.y)
def update(self, dt):
self.verlet(dt)
// here be a collision detection method which I need to write
self.rect.left = self.position.x
self.rect.top = self.position.y
</code></pre>
<p>And this is the Event class which has 2 main methods - listener and handler</p>
<pre><code>class EventManager(object):
def __init__(self, player):
self.player = player
# few bools to indicate key states, the listener method toggles them
def handler(self):
''' Calls Player on_x_key_pressed(), on_x_key_released()
methods according to event bools set from the listener method.
'''
# Moving
if self.left:
self.player.on_left_key_pressed()
elif self.right:
self.player.on_right_key_pressed()
else:
self.player.on_keys_up()
</code></pre>
<p>I have jumping but I'm still trying to understand the right aproach to writing a proper verlet integration method.
I can controll how fast my object is moving by setting the <code>self.old_position.x = self.position.x + 3</code> to <code>self.old_position.x = self.position.x + 20</code> for example.
This also stops the movement, but I truly suspect that this is incorect or simply a very bad aproach.</p>
<p>EDIT: Redesigned the event handler method and shortened the bool names for simplicity.
I have no problems running the code, it is working as intented.
The thing I dont like is how my <code>on_x_key_pressed()</code> methods look, you can find them in <code>PlayerData</code> class.
I have the feeling that, to stop my character from continues move in some direction I have to set <code>old_position.x = position.x</code>.
Is this the right aproach to stop character movement?
And to control how fast the object is moving (the velocity), I have to manually set <code>old_position</code> to some value bigger/lower than <code>position.x</code> as seen in <code>on_left_key_pressed()</code> and <code>on_right_key_pressed()</code>.
I wonder if there is better aproach to control the velocity?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:52:36.373",
"Id": "73849",
"Score": "0",
"body": "Hello! Does your code work? The question is currently unclear. We cannot really help with the integration method per se, but can help to get cleaner code. For example, simplifying your ifs in the EventManager class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T09:34:12.343",
"Id": "73851",
"Score": "0",
"body": "@QuentinPradet My biggest issue is that I'm not sure how to start/end the movement of my character, through on_key_press methods in the Player class.\nThank's for the heads up for the Event class, I will look into it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T09:55:42.643",
"Id": "73854",
"Score": "0",
"body": "The question you face is 'how can I apply the verlet integration method?'. We can only answer to 'how can I make this working code better?'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T11:25:50.053",
"Id": "73862",
"Score": "0",
"body": "@QuentinPradet Currently my code is functioning and the real question was how can I make this working code better, as you said it. Excuse my english. I know that pos - old_pos is actualy acting like a velocity. In my previous attempt with Euler method I did set velocity values inside on_key_pressed methods, so I did something similliar here. I think it's not the right aproach even if the code is working.\nIm kind of perfectionist person and I'm struggling to write a good method for moving in space and time."
}
] | [
{
"body": "<pre><code> def handler(self):\n '''\n Calls Player on_x_key_pressed(), on_x_key_released()\n methods according to event bools set from the listener method.\n '''\n # Moving\n if self.left_key_pressed and self.right_key_pressed:\n self.player.keys_up()\n</code></pre>\n\n<p>From this point, you know that both keys cannot be pressed at the same time, so you can continue with:</p>\n\n<pre><code> elif self.left_key_pressed:\n self.player.on_left_key_pressed()\n elif self.right_key_pressed:\n self.player.on_right_key_pressed()\n else:\n self.player.keys_up()\n</code></pre>\n\n<p>It's up to you to see if you find it more easy to read.</p>\n\n<p>I'm afraid I can't help much with the way you use verlet integration. Last comment: Try to avoid passing the key events around too much, or try to be more 'semantic', eg. send <code>move_left</code> to <code>self.player</code> instead of <code>on_left_key_pressed</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T09:17:50.393",
"Id": "42946",
"ParentId": "42710",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:10:21.280",
"Id": "42710",
"Score": "3",
"Tags": [
"python",
"game",
"python-3.x"
],
"Title": "Verlet integration movement - doubt for on_key_press() methods"
} | 42710 |
<p>Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). It is a main task of exploratory data mining, and a common technique for statistical data analysis, used in many fields, including machine learning, pattern recognition, image analysis, information retrieval, bioinformatics, data compression, and computer graphics.</p>
<p>Source: <a href="https://en.wikipedia.org/wiki/Cluster_analysis" rel="nofollow">Wikipedia article</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:58:28.837",
"Id": "42715",
"Score": "0",
"Tags": null,
"Title": null
} | 42715 |
Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T00:58:28.837",
"Id": "42716",
"Score": "0",
"Tags": null,
"Title": null
} | 42716 |
<p>I have an image and a text title that I'm trying to center in a div. I would like the image to be to the left of the title, and for both of these elements to be centered both horizontally and vertically in the div.</p>
<p>I've found one way to do it, by nesting the image inside of a paragraph. I'm assuming this is <em>not</em> the proper way to do it, but I haven't been able to figure out any other way.</p>
<p>Here is a jsfiddle: <a href="http://jsfiddle.net/FvpV3/" rel="nofollow">http://jsfiddle.net/FvpV3/</a></p>
<p>And here is the code:</p>
<pre><code><body>
<div style="text-align:center;">
<div style="width:50%;display:inline-block;border:1px solid;border-radius:6px;border-color:#CFCFCF;background-color:#EFEFEF;">
<div style="background-color:#E4E4E4;min-height:50px;width:100%;">
<div style="display:inline-block;vertical-align:middle;">
<p style="float:left;">
<img src="cid:logo-img" style="float:left;"/>
</p>
<p style="color:#000000;float:left;padding-left:10px;">Title</p>
</div>
</div>
<div>
<p>message</p>
</div>
</div>
</div>
</body>
</code></pre>
<p>Does anyone know of a better way to position the image and title?</p>
| [] | [
{
"body": "<p>You can simplify your HTML to this:</p>\n\n<pre><code><div id=\"parent\">\n <div class=\"floaters right\"><img src=\"cid:logo-img\" /></div>\n <div class=\"floaters\">Title</div>\n <div class=\"centerme\">$message</div>\n</div>\n</code></pre>\n\n<p>By adding classes, you can re-use CSS on more than one HTML element. The class <code>floaters</code> is applied to both of the <code>div</code>s that make up the top line. The class <code>right</code> is only applied to the left <code>div</code> on the first line to make it right aligned. </p>\n\n<p>The <code>#parent:after</code> is one example of a <a href=\"http://www.webtoolkit.info/css-clearfix.html#.UwwCz_ldVBk\" rel=\"nofollow\">clearfix</a>. There are several other versions of clearfixes.</p>\n\n<pre><code>* {\n box-sizing: border-box;\n}\n#parent {\n margin: 0px auto;\n width: 50%;\n border-radius: 6px;\n border: 1px solid #CFCFCF;\n}\n#parent:after {\n content: \"\";\n display: table;\n clear: both;\n}\n.floaters {\n float: left;\n background-color:#E4E4E4;\n width: 50%;\n height: 3em;\n padding: 5px 12px 5px 0;\n}\n.right {\n text-align: right;\n}\n.centerme {\n float: left;\n clear: both;\n text-align: center;\n background-color:#EFEFEF;\n height: 3em;\n width: 100%;\n padding-top: 12px;\n}\n</code></pre>\n\n<p>I have a working <a href=\"http://jsfiddle.net/azuckerman/Nv4Pb/\" rel=\"nofollow\">jsfiddle</a> for you to look at.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T02:42:46.650",
"Id": "42723",
"ParentId": "42717",
"Score": "2"
}
},
{
"body": "<p>You can have it <a href=\"http://jsfiddle.net/FvpV3/2/\" rel=\"nofollow\">as simple as this</a>:</p>\n\n<p>HTML:</p>\n\n<pre><code><div class=\"dialog\">\n <div class=\"header\">\n <img class=\"icon\" src=\"cid:logo-img\" />\n <h1>Title</h1>\n </div>\n <div class=\"body\">\n $message\n </div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.dialog {\n margin: 0 auto;\n width:50%;\n border : 1px solid #CFCFCF;\n border-radius:6px;\n background-color:#EFEFEF;\n text-align: center;\n}\n\n.dialog > *{\n padding: 20px;\n}\n\n.dialog > .header {\n background-color:#E4E4E4;\n}\n\n.dialog > .header > *{\n display:inline-block;\n vertical-align:middle;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T03:42:48.047",
"Id": "73609",
"Score": "0",
"body": "Why the choice of an H1 tag for the title? Also significantly simpler than mine!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:05:20.363",
"Id": "73611",
"Score": "0",
"body": "@AdamZuckerman Titles are usually represented by `<hN>` tags. [Bootstrap uses `<h4>` in their modal samples](http://getbootstrap.com/javascript/#modals) as well. In fact, I modeled my version from Bootstrap, minus the intricacies."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T02:58:01.193",
"Id": "42724",
"ParentId": "42717",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:00:44.483",
"Id": "42717",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "Vertically and horizontally center these HTML elements"
} | 42717 |
<p>I have coded up an implementation of Conway's Game of Life and I have a performance bottleneck in it which I wish to be optimized. The main logic is in the <code>Universe</code> class. I have omitted all code which is not applicable here for brewity:</p>
<pre><code>public class Universe {
private static final int FLIP_INDEX = 0;
private static final int FLOP_INDEX = 1;
private final boolean[][][] universeDoubleBuffer;
private final int height;
private final int width;
private int flipFlopIndex = FLIP_INDEX;
public Universe(boolean[][] universeState) {
height = universeState.length;
width = universeState[0].length;
universeDoubleBuffer = new boolean[2][height][width];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
universeDoubleBuffer[FLIP_INDEX][y][x] = universeState[y][x];
}
}
}
public boolean[][] recalculateUniverseState() {
int newFlipFlopIndex = (flipFlopIndex == FLIP_INDEX ? FLOP_INDEX : FLIP_INDEX);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int liveNeighbors = countLiveNeighbors(x, y);
boolean isLiving = universeDoubleBuffer[flipFlopIndex][y][x];
if (!isLiving && liveNeighbors == 3) {
universeDoubleBuffer[newFlipFlopIndex][y][x] = true;
} else if (isLiving && (liveNeighbors == 2 || liveNeighbors == 3)) {
universeDoubleBuffer[newFlipFlopIndex][y][x] = true;
} else {
universeDoubleBuffer[newFlipFlopIndex][y][x] = false;
}
}
}
stampPatterns();
logger.info("Old:" + Arrays.deepToString(universeDoubleBuffer[flipFlopIndex]));
logger.info("New:" + Arrays.deepToString(universeDoubleBuffer[newFlipFlopIndex]));
flipFlopIndex = newFlipFlopIndex;
return universeDoubleBuffer[flipFlopIndex];
}
private int countLiveNeighbors(int x, int y) {
int result = 0;
for (CellNeighbor neighbor : CellNeighbor.values()) {
try {
boolean isLiving = universeDoubleBuffer[flipFlopIndex][y + neighbor.getYOffset()][x + neighbor.getXOffset()];
if (isLiving) {
result++;
}
} catch (IndexOutOfBoundsException e) {
logger.info("Cell's neighbor was off the grid.", e);
}
}
return result;
}
}
</code></pre>
<p>Here is the code for <code>CellNeighbor</code>:</p>
<pre><code>public enum CellNeighbor {
TOP_LEFT(-1, 1), TOP(0, 1), TOP_RIGHT(1, 1), RIGHT(1, 0), BOTTOM_RIGHT(1, -1), BOTTOM(0, -1), BOTTOM_LEFT(-1, -1), LEFT(-1, 0);
private int xOffset;
private int yOffset;
private CellNeighbor(int xOffset, int yOffset) {
this.xOffset = xOffset;
this.yOffset = yOffset;
}
public int getXOffset() {
return xOffset;
}
public int getYOffset() {
return yOffset;
}
}
</code></pre>
<p>My problem is that if I create a world big enough (I tested with <code>5000 * 5000</code> for example) life really slows down and the time spent in <code>recalculateUniverseState()</code> reaches almost a second (with an <code>5000 * 5000</code> universe the average was 766ms).</p>
<p>I have tried without a double buffer (swapping new <code>boolean[][]</code> arrays) and without the <code>try</code>/<code>catch</code> block but it yielded no significant performance improvements.</p>
<p>My question is that how can I optimize the above code to be faster?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:12:03.050",
"Id": "73599",
"Score": "0",
"body": "What was the problem with the old title?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T03:33:27.897",
"Id": "73608",
"Score": "0",
"body": "A little trick to dodge the array range exceptions and help with performance is to make the array have a border around the \"world\". You can then safely access cell values \"off the edge of the world\". You don't update the edge cells, but access them in the `countLiveNeightbours` call. Alternatively, for Conway's life, you can use a torus; i.e. wrap the index values to stay in range."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T03:43:18.363",
"Id": "73610",
"Score": "0",
"body": "Also, that cascaded conditional on mapping number of live neighbours and current state to new state could be done as a table look up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:30:41.547",
"Id": "73615",
"Score": "3",
"body": "A final thought - provided you have a grid that size, a simple algorithm will require 25M updates per frame. So 766ms in Java is actually not that bad. You could get a fair bit with some threading - Java is great for that. But a major speed up could be achieved by not updating large \"blank\" areas, i.e. dividing into regions via a quad tree or such. The usefulness of this would depend on the current state/ initial conditions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T04:43:38.593",
"Id": "73617",
"Score": "5",
"body": "About the title edit: the title should summarize the context of your code (what the code is about), and not what you think is wrong with it. This makes it easier to search for questions, it makes the related-questions lists more accurate, etc. The original title was also a very narrow request, but code review is about [all aspects of the code](http://codereview.stackexchange.com/help/on-topic), with special attention paid to your requested areas of focus."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T21:25:50.243",
"Id": "73950",
"Score": "0",
"body": "I'm surprised that no one mentioned parallelism yet. This task can be paralellized quite easily."
}
] | [
{
"body": "<p>That <code>countLiveNeighbors</code> function looks expensive; are you sure <code>for (CellNeighbor neighbor : CellNeighbor.values())</code> isn't doing a whole bunch of <code>new CellNeighbor</code> calls (and garbage-collection) behind the scenes?</p>\n\n<p>Even more importantly: All that exception-handling is <strong>expensive!</strong></p>\n\n<blockquote>\n <p>Use exception-handling for exceptional control flow. Don't use it for the usual case.</p>\n</blockquote>\n\n<p>I suggest rewriting just that portion of the code as follows, and then profiling to see if the bottleneck is gone.</p>\n\n<p>However, writing that just reminded me: Have you <strong>tried</strong> profiling your code? (<a href=\"http://www.infoq.com/articles/java-profiling-with-open-source\">Random Google link.</a> Someone in the comments may have better advice about how to profile Java code.)</p>\n\n<pre><code>private int countLiveNeighbors(int x, int y) {\n int result = 0;\n for (int dx = -1; dx <= 1; ++dx) {\n int x2 = x + dx;\n if (x2 < 0 || width <= x) continue;\n for (int dy = -1; dy <= 1; ++dy) {\n int y2 = y + dy;\n if (y2 < 0 || height <= y) continue;\n boolean isLiving = universeDoubleBuffer[flipFlopIndex][y2][x2];\n if (isLiving) {\n result++;\n }\n }\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:59:06.843",
"Id": "73604",
"Score": "2",
"body": "Hmm, you've recently been active. You should come join us in the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:17:09.967",
"Id": "73648",
"Score": "0",
"body": "I tested the running times without the `try` block but it did not yield significant improvement. I will check `CellNeighbor`, thanks for the idea!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:36:05.050",
"Id": "73658",
"Score": "0",
"body": "As `CellNeighbor` is an enum, I'm quite sure that it doesn't do any `new CellNeighbor`. Iterating on ints only will probably help a bit, but I doubt that it will be significant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T18:02:03.787",
"Id": "73730",
"Score": "2",
"body": "Calling `values` on an enum will create a new array each time. So better to save it locally somewhere once."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:48:45.080",
"Id": "42721",
"ParentId": "42718",
"Score": "6"
}
},
{
"body": "<p>Not about performance, just some quick generic notes:</p>\n\n<ol>\n<li><pre><code>try {\n boolean isLiving = universeDoubleBuffer[flipFlopIndex][y + neighbor.getYOffset()][x\n + neighbor.getXOffset()];\n if (isLiving) {\n result++;\n }\n} catch (final IndexOutOfBoundsException e) {\n logger.info(\"Cell's neighbor was off the grid.\", e);\n}\n</code></pre>\n\n<p>You shouldn't use exceptions for normal cases. (See <em>Effective Java, Second Edition, Item 57: Use exceptions only for exceptional conditions</em>)</p></li>\n<li><p>The <code>isLiving</code> explanatory variable is great here.</p></li>\n<li><p>I think using two separate buffers (<code>inputBuffer</code>, <code>outputBuffer</code>) would be readable than the flip-flop.</p></li>\n<li><p>Instead of <code>2</code>, <code>3</code> use constants, they're magic numbers.</p></li>\n<li><p>I don't see why is the following comment here, since there's not any sign of that this class is used by multiple threads:</p>\n\n<pre><code>flipFlopIndex = newFlipFlopIndex; // assignment is atomic, no\n // synchronization needed\n</code></pre>\n\n<p>Anyway, assigments might be atomic but you might need proper synchronization.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em>.</p>\n\n<blockquote>\n <p>Locking is not just about mutual exclusion; it is also about memory visibility.\n To ensure that all threads see the most up-to-date values of shared mutable \n variables, the reading and writing threads must synchronize on a common lock.</p>\n</blockquote>\n\n<p>From <em>Java Concurrency in Practice, 3.1.3. Locking and Visibility</em>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:22:18.003",
"Id": "73649",
"Score": "1",
"body": "The fact is that I can't name them `inputBuffer, outputBuffer` because their roles get swapped with each new generation. Others mentioned the `try` block's logic fault so I'll remove it. The comment there is a leftover, but thanks for pointing it out. This game of life will be used from multiple threads (in a web application) but the `recalculateUniverseState()` will only be called from one thread. There is an option in the code which is not shown for stamping game of life patterns onto the universe but I solved that problem with a concurrent queue. (code omitted)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:49:59.117",
"Id": "42722",
"ParentId": "42718",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>instead of <code>universeDoubleBuffer[someIndex]</code> use 2 separate fields and 2 separate local variables, swapping values of local variables each step of the loop. Thus one expensive array access operation is excluded.</p></li>\n<li><p>Conditional and unconditional branches should be avoided for fast execution.\nIn countLiveNeighbors, explicitly read 4 neighbour cells instead of loop.</p></li>\n<li><p>To represent liveness, use byte 0 or 1 instead of boolean. Instead of <code>if (isLiving && liveNeighbors ...</code> use predefined table for values of next states depending on previous state, and just read new state from table instead of using conditional statements.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T21:14:47.397",
"Id": "73946",
"Score": "0",
"body": "Do you think that a `byte[][]` will be faster than a `boolean[][]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T02:22:06.503",
"Id": "74009",
"Score": "0",
"body": "I mean that in `countLiveNeighbors`, `if (isLiving){result++;}` can be replaced with `result+=isLiving`, which is faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T10:25:31.333",
"Id": "74036",
"Score": "0",
"body": "I've already implemented @Ilmari Karonen`s suggestions which does away with this problem."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:19:48.183",
"Id": "42736",
"ParentId": "42718",
"Score": "1"
}
},
{
"body": "<p>One way to improve performance is to use a different data structure. For example, you can encode the state of a cell's neighbours using 8 bits (one bit for each neighbour).</p>\n\n<p>You can have a look-up table with 256 elements, which decides what to do for any combination of neighbour-bits: that's a single table look-up.</p>\n\n<p>If a cell-state changes (which happens very rarely) update the corresponding bits in its neighbours' neighbour-bits.</p>\n\n<p>Your universe is something like:</p>\n\n<pre><code>boolean state;\nbyte neighbours;\n</code></pre>\n\n<p>Your recalculateUniverseState method is something like:</p>\n\n<pre><code>foreach (cell in universe)\n{\n boolean newState = (state) ? liveState[neighbours] : deadState[neighbours];\n if (newState != state)\n changedCells.add(cell);\n}\nforeach (cell in changedCells)\n{\n // change the state of this cell\n // update the bits in this cell's neighbours\n}\n</code></pre>\n\n<p>This is just an example from memory; there's a more efficient way to do it: Abrash's <a href=\"http://rads.stackoverflow.com/amzn/click/1883577039\">Zen of Code Optimization</a> describes an structure which encode the cell's state and its neighbour's states in 8 bits (relying on the fact that at least one bit is redundent because it's encoded in a next-door neighbour).</p>\n\n<p>There are algorithmic speedups suggested on <a href=\"http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Algorithms\">Wikipedia</a> and probably <a href=\"http://www.conwaylife.com/\">on this site too</a>: for example, remember which cells or areas of the board aren't changing and don't recalculate those. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T09:03:09.403",
"Id": "73642",
"Score": "1",
"body": "I made this 'community wiki' because it's such a generic answer applicable to any question about improving [tag:game-of-life] questions that it's not really a code review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:49:48.410",
"Id": "42738",
"ParentId": "42718",
"Score": "5"
}
},
{
"body": "<p>First of all, this should be obvious, but when you have performance issues in code that involves a tight inner loop, you want to <strong>simplify that loop as much as you can</strong>. If you can save one cycle in the loop by spending a dozen or a hundred cycles somewhere else, do it, because every cycle in the loop gets multiplied by 5000².</p>\n\n<p>Also, what you <em>really</em> want to minimize in the inner loop are memory accesses. Accessing local variables is fast, since they're typically cached and the JVM knows that their values cannot change unless the code in the method itself changes them. In comparison, pulling a random element from a large array is relatively slow, since it requires a full RAM access, as is, typically, accessing a member variable or calling an uncached method.</p>\n\n<p>I've <a href=\"http://vyznev.net/ca/neumann/\" rel=\"nofollow noreferrer\">done something like this</a> before,<sup>*</sup> so, rather than listing every improvement I might make to your code, let me start by sketching how I might rewrite your core update loop:</p>\n\n<pre><code>// assume these arrays are (height + 2) by (width + 2)\nboolean[][] oldBuffer = universeDoubleBuffer[flipFlopIndex],\n newBuffer = universeDoubleBuffer[newFlipFlopIndex];\n\nfor (int y = 1; y <= height; y++) {\n int environment\n = (oldBuffer[y-1][0] ? 32 : 0) + (oldBuffer[y-1][1] ? 4 : 0)\n + (oldBuffer[y ][0] ? 16 : 0) + (oldBuffer[y ][1] ? 2 : 0)\n + (oldBuffer[y+1][0] ? 8 : 0) + (oldBuffer[y+1][1] ? 1 : 0);\n\n for (int x = 1; x <= width; x++) {\n environment = ((environment % 64) * 8)\n + (oldBuffer[y-1][x+1] ? 4 : 0)\n + (oldBuffer[y ][x+1] ? 2 : 0)\n + (oldBuffer[y+1][x+1] ? 1 : 0);\n\n newBuffer[y][x] = lookupTable[ environment ];\n }\n}\n</code></pre>\n\n<p>A few things to note about this code:</p>\n\n<ul>\n<li><p>There is no <code>countLiveNeightbors()</code> method; in fact, the code does not explicitly count live neighbors at all. Instead, the <em>pattern</em> of the nine cells including and surrounding the cell at (<em>x</em>, <em>y</em>) is maintained in the variable <code>environment</code>, which is used as an index to a <strong>512-element lookup table</strong>.</p>\n\n<p>For example, if the surroundings of the current cell look like this (<code>#</code> = live cell, <code>_</code> = dead cell):</p>\n\n<pre><code># # _\n_ # #\n# _ _\n</code></pre>\n\n<p>then the value of the <code>environment</code> variable will be:</p>\n\n<pre><code>(1 * 256) + (1 * 32) + (0 * 4) +\n(0 * 128) + (1 * 16) + (1 * 2) +\n(1 * 64) + (0 * 8) + (0 * 1) = 370\n</code></pre>\n\n<p>Of course, you'll have to set up this lookup table before using it, but that is something you can do <em>outside</em> the core loop (e.g. in your constructor), so it's not performance-critical.</p>\n\n<p>(In fact, while I haven't benchmarked this, I'd at least consider making <code>lookupTable</code> a local variable and rebuilding it every time the update method is called, as the extra cost of rebuilding the table <em>might</em> be balanced out by extra optimization opportunities available to the compiler / JVM if it knows that no other code can modify the table. You may want to test it both ways and see which one is faster.)</p>\n\n<p>One additional advantage of such a lookup table based implementation is that, by changing the lookup table, it can simulate <em>any</em> two-state cellular automaton using the <a href=\"http://en.wikipedia.org/wiki/Moore_neighborhood\" rel=\"nofollow noreferrer\">Moore neighborhood</a>, not just Conway's Game of Life specifically.</p></li>\n<li><p>By reusing the parts of the environment pattern that are shared between adjacent cells, the code <strong>only needs to do three reads</strong> from the <code>oldBuffer</code> array per cell, as opposed to nine in your version. Uncached array access is expensive, so this is likely to provide a significant speedup. (Also, like your code, mine also makes sure to access the buffers as close to sequentially as possible, iterating first by rows and then by columns. This is also important for CPU cache locality.)</p></li>\n<li><p>The code above doesn't update the cells at the edges of the array, which means it doesn't have to worry about (literal) <strong>edge cases</strong> such as array indices being out of bounds. (Hopefully, the compiler / JVM may notice this too, and may omit some of its internal array bounds checks.)</p>\n\n<p>If you want your grid to be surrounded by dead cells, you can just initially mark these border cells as dead and leave them untouched in your update method. Alternatively, if, say, you want the grid to wrap around, you can update the edge cells in a separate loop (which can be less efficient, since it only runs for a tiny fraction of all the cells).</p></li>\n</ul>\n\n<p>Actually, there are a few ways in which the code I suggested above could be optimized further. For example, an obvious optimization is to <strong>get rid of the two-dimensional array accesses</strong> in the inner loop, since they require two array lookups each.</p>\n\n<p>There are (at least) two ways you could do this:</p>\n\n<ul>\n<li><p>a) In the outer loop, save the previous, current, and next rows of <code>oldBuffer</code> in local variables, like this:</p>\n\n<pre><code>boolean[] prevRow = oldBuffer[y-1],\n currRow = oldBuffer[y],\n nextRow = oldBuffer[y+1];\n</code></pre></li>\n<li><p>b) Make the buffers themselves one-dimensional arrays, and adjust the indexing so that, instead of <code>buffer[y][x]</code>, you use <code>buffer[ y * (width+2) + x ]</code>. You can precalculate the offset <code>y * (width+2)</code>, and possibly also <code>(y ± 1) * (width+2)</code>, in the outer loop to save a bit of arithmetic, or you could rely on the compiler / JVM to do this for you. Again, you could try it both ways and see if there's any difference.</p></li>\n</ul>\n\n<p>Also, for cellular automata like the Game of Life, where only a small fraction of the cells typically change in each time step, there are <strong>much faster algorithms</strong> available than even the generic table lookup method described above.</p>\n\n<ul>\n<li><p>As a first step, <a href=\"https://codereview.stackexchange.com/a/42738\">ChrisW's suggestion</a> of caching the live neighbor count is likely to be faster whenever the environment of each cell changes relatively infrequently.</p></li>\n<li><p>An even greater speedup may be obtained by storing a <strong>list of active cells</strong>, i.e. cells that changed or had at least one of their neighbors change state during the previous update step, and only iterating through those cells on the next update. (Since the total number of active cells is bounded above by the size of the grid, you can use a simple array as a <a href=\"//en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow noreferrer\">circular buffer</a> to efficiently store this list.)</p>\n\n<p>Effectively combining active cell lists with double buffering can be somewhat tricky. An alternative solution is to use a single buffer, but divide your update method into two phases:</p>\n\n<ol>\n<li>In the first phase, you iterate through the list, calculate the new state for each active cell, and store it <em>in the list</em>.</li>\n<li>In the second phase, you iterate through the list again and update the grid buffer to match the new states calculated in the first phase.</li>\n</ol>\n\n<p>(That said, using <em>both</em> activity lists and double buffering does have one advantage: it allows you to treat cells that oscillate with a period of two, which are quite common in the Game of Life, as inactive. This does require you to maintain separate active cell lists for each buffer.)</p></li>\n<li><p>Finally, if you want a <em>really</em> fast algorithm for simulating Conway's Game of Life, look up <a href=\"//en.wikipedia.org/wiki/Hashlife\" rel=\"nofollow noreferrer\">Hashlife</a>. It's literally orders of magnitude faster than any \"naïve\" simulation algorithm, especially for sparse and highly repetitive patterns like many constructed ones.</p></li>\n</ul>\n\n<p><sup>*) Please don't take that code as an example of good coding style. It <em>is</em> pretty fast, though.</sup></p>\n\n<hr>\n\n<p><strong>Addendum:</strong> Here's a basic implementation of the activity list method, using a single buffer, and with the Conway's Game of Life rules hardcoded.</p>\n\n<p>It uses a byte-packed cell state buffer, where the lowest bit of the byte indicates whether the cell is currently in the activity list, the second bit stores the actual state of the cell, and the following (four) bits store the number of surrounding live cells (to avoid having to recalculate it whenever the cell is examined):</p>\n\n<pre><code>// assume that buffer is a (height) by (width) byte array, and that\n// xQueue and yQueue are (height * width) int arrays, of which the\n// first (activeCells) elements contain the current active cell coords\n\n// loop over active cells, and find those whose state will change\nint changedCells = 0;\nfor (int i = 0; i < activeCells; i++) {\n int x = xQueue[i], y = yQueue[i];\n byte packedState = buffer[y][x]; // = 4*neighbors + 2*state + active\n boolean wasAlive = (oldState & 2 == 2);\n\n // quickly check if cell will live under the Game of Life rules\n // (10-11 = alive, 2 neighbors; 12-13 = dead, 3 neighbors; 14-15 = alive, 3 neighbors)\n boolean isAlive = (10 <= packedState && packedState <= 15);\n\n // add cell to queue if it died or was born\n // we know that changedCells <= i, so it's safe to reuse the same queue space\n if (wasAlive != isAlive) {\n xQueue[changedCells] = x;\n yQueue[changedCells] = y;\n changedCells++;\n // assume active bit is already 1, so no need to change\n }\n else {\n buffer[y][x] = packedState - (byte)1; // unset active bit\n }\n}\n\n// carry out deferred state updates\nactiveCells = changedCells;\nfor (int i = 0; i < changedCells; i++) {\n int x = xQueue[i], y = yQueue[i];\n boolean wasAlive = (buffer[y][x] & 2 == 2);\n byte delta = (byte)(wasAlive ? -4 : +4); // change in neighbor count * 4\n\n // update neighbor counts of adjacent cells, and mark them as active\n int yMin = (y > 0 ? y-1 : 0), yMax = (y < height-1 ? y+1 : height-1);\n int xMin = (x > 0 ? x-1 : 0), xMax = (x < width-1 ? x+1 : width-1);\n for (int ny = yMin; ny <= yMax; ny++) {\n for (int nx = xMin; nx <= xMax; nx++) {\n byte newState = buffer[ny][nx] + delta;\n // if this cell is not yet active, add it to the queue for next time step\n if (newState & 1 == 0) {\n xQueue[activeCells] = nx;\n yQueue[activeCells] = ny;\n activeCells++;\n newState += (byte)1;\n }\n buffer[ny][nx] = newState;\n }\n }\n // the middle cell only needs to adjusted by +/-2\n buffer[y][x] -= (byte)(delta / 2);\n}\n</code></pre>\n\n<p>Before the first pass, all cells should be initialized to have the correct neighbor counts, have the active bit set and be added to the active cell queue. I've omitted this part of the code, since it's not performance-critical.</p>\n\n<p>Note that this method does not use any padding cells along the edges of the state array. Alternatively, we could add the padding and permanently set the active bit for those cells, but not include them in the queue, allowing the min/max coords calculations to be simplified. I suspect this would not make much difference, but there's no way to be sure without trying it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T19:48:56.193",
"Id": "73923",
"Score": "0",
"body": "Thanks for the thorough explanation! For some reason using a bitvector(like) structure did not came into mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T20:20:36.057",
"Id": "73927",
"Score": "0",
"body": "Can you please explain the `environment` variable's calculation? I don't understand how you calculate its initial value without knowing about `x`. The `((environment % 64) * 8)` part is not clear either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T20:25:32.827",
"Id": "73931",
"Score": "0",
"body": "`((environment % 64) * 8)` strips away all but the lowest six bits of the environment pattern, and then shifts the remaining bits left by three. You could equally well write it with bit operators as `((environment & 0b111111) << 3)`. The initial value is, in effect, the environment for `x = 0`, consisting of the states of the six cells in rows `y-1`, `y` and `y+1` and columns `0` and `1`. It doesn't include the (non-existent) column `-1`, since the bits that would encode those cell states will just get shifted out of the environment in the inner loop anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T20:36:17.083",
"Id": "73934",
"Score": "0",
"body": "But why would I use columns `0` and `1` if I don't know `x` yet? Sorry, I've only used bit vectors once (with SWT) and I don't really get this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T20:43:29.317",
"Id": "73935",
"Score": "0",
"body": "Oh I get it. We can pre-calculate it because `x` will start at `0`. I tend to forget that my computer speaks binary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T20:52:13.100",
"Id": "73936",
"Score": "0",
"body": "Right. To be a bit more specific, the statement `environment = ...` in the inner loop modifies the `environment` variable so that it encodes the pattern of live/dead cells around cell `(x, y)`, *assuming that* it previously encoded the pattern around cell `(x-1, y)`. Since, on the first iteration, `x = 1`, to satisfy this assumption we need to initialize `environment` (or at least the lowest six bits of it) to the value it *should've* had at `x = 0`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T21:00:15.487",
"Id": "73939",
"Score": "1",
"body": "And I can create the lookup by simply converting the numbers from 0 to 511 to a binary arrays and applying the game of life rules to them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T21:03:58.053",
"Id": "73943",
"Score": "1",
"body": "You definitely need more upvotes. The preliminary implementation resulted in a **10x** speedup!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T18:00:11.030",
"Id": "42790",
"ParentId": "42718",
"Score": "17"
}
},
{
"body": "<p>[A bit of topic, as it's not really helping correct \"the code above\"... but to get at the source of the problem: fast Game of Life generations]</p>\n\n<p>I'm surprised no-one mentionned Bill Gosper yet (if you google \"Bill Gosper life\" you'll see some conferences he made on the subject). Here is a link that you will probably find interresting :</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Hashlife\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Hashlife</a> ( Bill Gosper's Hashlife algorithm )</p>\n\n<p>Optimizing a loop is ok, but first of all should be optimizing the way to look at the problem, and the ways to solve it. </p>\n\n<p>Hashlife is probably quite a good starting point for Conway's Game of Life:</p>\n\n<p>An example on the wikipedia page for hashlife talks about <em>\"The 6,366,548,773,467,669,985,195,496,000 (6 octillionth) generation of a very complicated Game of Life pattern computed in less than 30 seconds on an Intel Core Duo 2GHz CPU using hashlife in Golly. Computed by detecting a repeating cycle in the pattern, and skipping ahead to any requested generation.\"</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-08T09:29:32.067",
"Id": "62260",
"ParentId": "42718",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42790",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T01:07:01.227",
"Id": "42718",
"Score": "22",
"Tags": [
"java",
"performance",
"game-of-life"
],
"Title": "Optimize Conway's Game of Life"
} | 42718 |
<p>I wanted to find out which states and cities the USA hockey team was from, but I didn't want to manually count from the roster site <a href="http://olympics.usahockey.com/page/show/1067902-roster" rel="noreferrer">here</a>.</p>
<p>I'm really interested to see if someone has a more elegant way to do what I've done (which feels like glue and duct tape) for future purposes. I read about 12 different Stack Overflow questions to get here.</p>
<pre><code>from bs4 import BeautifulSoup
from collections import Counter
import urllib2
url='http://olympics.usahockey.com/page/show/1067902-roster'
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
locations = []
city = []
state = []
counter = 0
tables = soup.findAll("table", { "class" : "dataTable" })
for table in tables:
rows = table.findAll("tr")
for row in rows:
entries = row.findAll("td")
for entry in entries:
counter = counter + 1
if counter == 7:
locations.append(entry.get_text().encode('ascii'))
counter = 0
for i in locations:
splitter = i.split(", ")
city.append(splitter[0])
state.append(splitter[1])
print Counter(state)
print Counter(city)
</code></pre>
<p>I essentially did a three tier loop for <code>table->tr->td</code>, and then used a counter to grab the 7th column and added it to a list. Then I iterated through the list splitting the first word to one list, and the second word to a second list. Then ran it through Counter to print the cities and states. I get a hunch this could be done a lot simpler, curious for opinions.</p>
| [] | [
{
"body": "<ul>\n<li><p>You can use <a href=\"http://docs.python.org/2/library/functions.html#enumerate\" rel=\"nofollow\">enumerate</a> in order not to play with <code>counter</code>.</p>\n\n<pre><code>for counter,entry in enumerate(entries):\n if counter == 6:\n locations.append(entry.get_text().encode('ascii'))\n</code></pre></li>\n<li><p><code>states</code> and <code>cities</code> would probably be a better name for collections of states/cities.</p></li>\n<li><p>You can use unpacking when splitting the string</p></li>\n</ul>\n\n<p>For instance :</p>\n\n<pre><code>for i in locations:\n city, state = i.split(\", \")\n cities.append(city)\n states.append(state)\n</code></pre>\n\n<ul>\n<li>You don't need to store locations in a list and then iterate over the locations, you can handle them directly without storing them.</li>\n</ul>\n\n<p>This is pretty much what my code is like at this stage :</p>\n\n<pre><code>#!/usr/bin/python\n\nfrom bs4 import BeautifulSoup\nfrom collections import Counter\nimport urllib2\n\nurl='http://olympics.usahockey.com/page/show/1067902-roster'\nsoup = BeautifulSoup(urllib2.urlopen(url).read())\n\ncities = []\nstates = []\n\nfor table in soup.findAll(\"table\", { \"class\" : \"dataTable\" }):\n for row in table.findAll(\"tr\"):\n for counter,entry in enumerate(row.findAll(\"td\")):\n if counter == 6:\n city, state = entry.get_text().encode('ascii').split(\", \")\n cities.append(city)\n states.append(state)\n\nprint Counter(states)\nprint Counter(cities)\n</code></pre>\n\n<p>Now, because of the way American cities are named, it might be worth counting the cities keeping their state into account (because <a href=\"http://en.wikipedia.org/wiki/Portland,_Oregon\" rel=\"nofollow\">Portand</a> and <a href=\"http://en.wikipedia.org/wiki/Portland,_Maine\" rel=\"nofollow\">Portland</a> are not quite the same city). Thus, it might be worth storing information about city and state as a tuple.</p>\n\n<p>This is how I'd do it :</p>\n\n<pre><code>#!/usr/bin/python\n\nfrom bs4 import BeautifulSoup\nfrom collections import Counter\nimport urllib2\n\nurl='http://olympics.usahockey.com/page/show/1067902-roster'\nsoup = BeautifulSoup(urllib2.urlopen(url).read())\n\ncities = []\nfor table in soup.findAll(\"table\", { \"class\" : \"dataTable\" }):\n for row in table.findAll(\"tr\"):\n for counter,entry in enumerate(row.findAll(\"td\")):\n if counter == 6:\n city, state = entry.get_text().encode('ascii').split(\", \")\n cities.append((state,city))\n\nprint Counter(cities)\nprint Counter(state for state,city in cities)\n</code></pre>\n\n<p>Also, something I have forgotten but might be useful to you is to use <a href=\"http://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"nofollow\">defaultdict</a> if all you want is to count elements.</p>\n\n<pre><code>from collections import defaultdict\n\nurl='http://olympics.usahockey.com/page/show/1067902-roster'\nsoup = BeautifulSoup(urllib2.urlopen(url).read())\n\ncities = defaultdict(int)\nfor table in soup.findAll(\"table\", { \"class\" : \"dataTable\" }):\n for row in table.findAll(\"tr\"):\n for counter,entry in enumerate(row.findAll(\"td\")):\n if counter == 6:\n city, state = entry.get_text().encode('ascii').split(\", \")\n cities[state,city] += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:00:24.877",
"Id": "73677",
"Score": "0",
"body": "The unpacking is what I was looking for, that makes much more sense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T09:02:32.163",
"Id": "42739",
"ParentId": "42727",
"Score": "3"
}
},
{
"body": "<p>It looks like you're just trying to get the <code>n</code>-th column from a bunch of tables on the page, in that case, there's no need to iterate through all the <code>find_all()</code> results, just use list indexing:</p>\n\n<pre><code>for row in soup.find_all('tr'):\n myList.append(row.find_all('td')[n])\n</code></pre>\n\n<p>This is also a good use case for generators because you are iterating over the same set of data several times. Here is an example:</p>\n\n<pre><code>from bs4 import BeautifulSoup\nfrom collections import Counter\nfrom itertools import chain\nimport urllib2\n\nurl = 'http://olympics.usahockey.com/page/show/1067902-roster'\nsoup = BeautifulSoup(urllib2.urlopen(url).read())\n\ndef get_table_column(table, n):\n rows = (row.find_all(\"td\") for row in table.find_all(\"tr\"))\n return (cells[n-1] for cells in rows)\n\ntables = soup.find_all(\"table\", class_=\"dataTable\")\ncolumn = chain.from_iterable(get_table_column(table, 7) for table in tables)\ncity, state = zip(*(cell.get_text().encode('ascii').split(', ') for cell in column))\n\nprint Counter(state)\nprint Counter(city)\n</code></pre>\n\n<p>While this works, it also might be a good idea to anticipate possible errors and validate your data:</p>\n\n<p>To anticipate cases where not all rows have <code>n>=7</code> <code>td</code> elements, we would change the last line in <code>get_table_column</code> to:</p>\n\n<pre><code>return (cells[n-1] for cells in rows if len(cells) >= n)\n</code></pre>\n\n<p>We should also anticipate cases where the cell contents does not contain a comma. Let's expand the line where we split on a comma:</p>\n\n<pre><code>splits = (cell.get_text().encode('ascii').split(',') for cell in column)\ncity, state = zip(*(split for split in splits if len(split) == 2))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T17:22:14.417",
"Id": "42785",
"ParentId": "42727",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42785",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T03:44:09.983",
"Id": "42727",
"Score": "6",
"Tags": [
"python",
"html",
"parsing"
],
"Title": "First program with scraping, lists, string manipulation"
} | 42727 |
<p>I have two <code>div</code>s as seen in this <a href="http://jsfiddle.net/y7PEp/12/" rel="nofollow">JSFiddle</a>. To recreate the problem, keep clicking on the Gray container till both divisions touch each other.</p>
<p>The purpose is to execute a certain function once the green <code>div</code> touches the red one. The problem is that, this step callback as seen from the following code and demo, gets called multiple times. It is not something that I want to happen.</p>
<p>One method that would fix the problem is to keep a certain flag variable which turns <code>True</code> once step is executed. But I'm not sure that's enough as there needs to be a way to break out of the step callback.</p>
<p>I want to know:</p>
<ol>
<li><p>If there is a better/efficient way to detect collision of two <code>div</code>s than using <a href="http://sourceforge.net/projects/jquerycollision/" rel="nofollow">jQuery Collision</a>.</p></li>
<li><p>How to stop the step callback after its executed once.</p></li>
</ol>
<p><strong>HTML:</strong></p>
<pre><code><div class="container">
<div class="test"></div>
<div class="menu"></div>
</div>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code>$(document).ready(function () {
var hit_list;
$(".container").click(function () {
$(".menu").stop().animate({
left: "+=100px"
}, {
duration: 300,
complete: function () {
$(".menu").animate({
left: "0"
}, 800);
},
step: function(){
//Test for collision
hit_list = $(".menu").collision(".test");
if (hit_list.length != 0) {
$(".container").append("Welcome Earthling");
}
}
});
});
});
</code></pre>
| [] | [
{
"body": "<p><a href=\"http://jsfiddle.net/y7PEp/15/\" rel=\"nofollow\">You can do this</a>:</p>\n\n<pre><code>// Let's make it a jQuery plugin so each element acts independently\n$.fn.collider = function () {\n return $.each(this, function () {\n\n // a flag when done\n var done = false;\n\n // Cache a few values\n var container = $(this);\n var menu = container.find('.menu');\n var menuWidth = menu.width();\n var test = container.find('.test');\n var testLeft = test.position().left;\n\n container.on('click', function () {\n // prevent click when already hit\n if(done) return;\n\n menu.stop().animate({\n left: \"+=100px\"\n }, {\n duration: 300,\n complete: function () {\n menu.animate({\n left: \"0\"\n }, 800);\n },\n step: function () {\n // We can just check the right of the green with the left of the red\n if (!done && menu.position().left + menuWidth >= testLeft) {\n done = true;\n console.log('done!');\n }\n }\n });\n });\n });\n}\n\n$(function () {\n $('.container').collider();\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:03:43.887",
"Id": "73634",
"Score": "0",
"body": "How well will it scale for detecting on all four sides? As in adding more conditions will affect the animation smoothness in any way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T08:10:30.337",
"Id": "73636",
"Score": "0",
"body": "@vineetrok In the context of your demo, you only used one side."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:56:05.167",
"Id": "42737",
"ParentId": "42735",
"Score": "4"
}
},
{
"body": "<p>Interesting question,</p>\n\n<p>there is no support in browsers for collision events, so you have to check every so often, which feels wrong. But that's the way it is.</p>\n\n<p>There is no way to stop calling <code>step</code> but you can put of course an <code>if</code> statement to prevent <code>Welcome Earthling</code> from being shown multiple times:</p>\n\n<pre><code> step: function(){\n //Test for collision\n if(!hitList.length)\n {\n hitList = $menu.collision( $test );\n if (hitList.length != 0) {\n $(\".container\").append(\"Welcome Earthling\");\n }\n }\n }\n</code></pre>\n\n<p>I did change <code>hit_list</code> to <code>hitList</code>, lowerCamelCase FTW! I also assume you would cache <code>$('.menu')</code> and <code>$('.test')</code>. And finally I assume here that you would initialize <code>hitList</code> to <code>[]</code>.</p>\n\n<p>Another way to approach this is to not use a <code>step</code> function at all, simply keep checking for a collision separately, once the collision has occurred, stop checking. You would use a function similar to this:</p>\n\n<pre><code>function detectMenuTestCollision() \n{\n var hit_list = $(\".menu\").collision(\".test\");\n if(hit_list.length) \n {\n $(\".container\").append(\"Welcome Earthling\");\n }\n else\n {\n setTimeout(detectMenuTestCollision, 250); \n }\n}\n</code></pre>\n\n<p>Of course, you ought to cache those jQuery lookups ;)</p>\n\n<p>Finally, you can look at the code of the collision plugin <a href=\"http://sourceforge.net/p/jquerycollision/code/ci/master/tree/jquery-collision.js\" rel=\"nofollow\">here</a>, I think this code is pretty tight already, you could simplify this down to your needs, but I think that would fall in the realm of premature optimization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:57:06.453",
"Id": "42762",
"ParentId": "42735",
"Score": "3"
}
},
{
"body": "<p>I didn't know the jQuery collision code, thanks to konijn for posting.</p>\n\n<p>Even the best universal library can be optimized for a specific case. Another issue if it is worth the effort or not.</p>\n\n<p>In your case, one common optimization approach can work: move all the dimensions from one object to the other. Then, you only need to check if the first object (that is a dimensionless point) is inside the other.</p>\n\n<p>Lets say that you have 2 squares, of 10px width and height each. To check if they collide, you can check if a point in the center of the first square collides with an square of dimension 20px.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T23:13:33.683",
"Id": "73974",
"Score": "1",
"body": "You're pretty active for a new user, you should come visit us in the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:55:54.877",
"Id": "42816",
"ParentId": "42735",
"Score": "2"
}
},
{
"body": "<p>You can add a flag - this makes it only show \"Welcome Earthling\" once, but does not stop step.</p>\n\n<pre><code>$(document).ready(function () {\n var hit_list;\n var col_flag = 0;\n $(\".container\").click(function () {\n $(\".menu\").stop().animate({\n left: \"+=100px\"\n }, {\n duration: 300,\n complete: function () {\n $(\".menu\").animate({\n left: \"0\"\n }, 800);\n },\n step: function(){\n // Test for collision if collision_flag is not tripped\n if(col_flag == 0){\n hit_list = $(\".menu\").collision(\".test\");\n if (hit_list.length != 0) {\n $(\".container\").append(\"Welcome Earthling\");\n col_flag = 1;\n }\n }\n }\n });\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T16:15:28.323",
"Id": "42879",
"ParentId": "42735",
"Score": "2"
}
},
{
"body": "<p>In response to not triggering the message repeatedly, I would store the previous check for a collision so you know if a collision has started or ended.</p>\n\n<p>If there is a collision but your previous check didn't show a collision, then you have a new collision and you can trigger the event. However, if the previous check did show a collision, don't fire the callback since it has already been fired.</p>\n\n<p>I would also recommend using custom jQuery events. This allows you to separate out the callback from the animation code.</p>\n\n<p>Below I've adapted your code to trigger a custom event when you detect a collision has started or ended. Here's the updated javascript (also available as <a href=\"http://jsfiddle.net/y7PEp/17/\">a modification of your fiddle</a>):</p>\n\n<pre><code>$(document).ready(function () {\n\n $(\".menu\").data(\"collision\", false);\n $(\".menu\").on(\"collision_start\", function () {\n $(\".container\").append(\"Welcome Earthling\");\n });\n\n $(\".container\").click(function () {\n\n $(\".menu\").stop().animate({\n left: \"+=100px\"\n }, {\n duration: 300,\n complete: function () {\n $(\".menu\").animate({\n left: \"0\"\n }, 800);\n },\n step: function () {\n //Test for collision\n var hit_list = $(this).collision(\".test\");\n var current_collision = hit_list.length != 0;\n\n // compare this to what we last observed\n var changed_collision = current_collision != $(this).data(\"collision\");\n\n if (changed_collision) {\n // save this new observation for future comparisons\n $(this).data(\"collision\", current_collision);\n\n // trigger an event\n $(this).trigger(\"collision_\" + (current_collision ? \"start\" : \"stop\"));\n }\n }\n });\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T17:56:25.237",
"Id": "42884",
"ParentId": "42735",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T07:12:24.250",
"Id": "42735",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"collision"
],
"Title": "Detecting collision of two divs"
} | 42735 |
<p>I would love a second opinion / another pair of eyes on this.</p>
<pre><code>db.customers.mapReduce(
function() {
Array.prototype.getUnique = function() {
var u = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
var customer = this;
this.tags.getUnique().forEach(function(tag) {
if (customer.status) {
emit(customer.shop, {
"kind": "unique_customers_submitted",
"tag": tag.tag,
});
} else {
emit(customer.shop, {
"kind": "unique_customers_withheld",
"tag": tag.tag,
});
}
emit(customer.shop, {
"kind": "unique_customers_total",
"tag": tag.tag,
});
})
this.tags.forEach(function(tag) {
if (customer.status) {
emit(customer.shop, {
"kind": "total_customers_submitted",
"tag": tag.tag,
});
} else {
emit(customer.shop, {
"kind": "total_customers_withheld",
"tag": tag.tag,
});
}
emit(customer.shop, {
"kind": "total_customers",
"tag": tag.tag,
});
});
},
function(key, sets) {
var forms = {};
sets.forEach(function(set) {
if (typeof forms[set.tag] == "undefined") forms[set.tag] = {};
if (typeof forms[set.tag][set.kind] == "undefined") forms[set.tag][set.kind] = 0;
forms[set.tag][set.kind] += 1;
});
return forms;
}, {
out: "form_numbers",
},
function(err, results) {
console.log(err);
//console.log(results);
results.find().toArray(function(err, numbers) {
console.log(err);
console.log(JSON.stringify(numbers));
db.server.close();
});
}
);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:39:08.157",
"Id": "73684",
"Score": "1",
"body": "Hi, please provide more context to your code, and ideally put a title that says what the code does - *everybody* posting here is looking for a 2nd pair of eyes ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:53:53.520",
"Id": "73718",
"Score": "0",
"body": "@Mat'sMug Hey sorry, I'll edit it when I get a chance! Thanks for the suggestion!!"
}
] | [
{
"body": "<p>I'm not familiar with MR best practices, but here are some JS-specific comments.</p>\n\n<h1>Key Points</h1>\n\n<ul>\n<li><p>DRY - that emit code is repeated all over the place and has only slight changes - parameterize what varies and put it all in a function</p></li>\n<li><p>You are repeating your loops - either do everything in one loop for better performance (and keep in mind that <a href=\"http://jsperf.com/for-vs-array-foreach\"><code>for</code> is faster than <code>forEach</code></a>, or go fully functional (see next)</p></li>\n<li><p>You are essentially doing a filter within your loop - use <code>filter</code> to remove the <code>if</code> logic from within the loop (or see previous). If you want to go even more functional, maybe you should use <a href=\"http://underscorejs.org/\">underscorejs</a> or <a href=\"http://lodash.com/\">lo-dash</a>, which both have a <code>unique</code> function already.</p></li>\n<li><p>Never change the prototype of a builtin unless you have already checked if the method exists (like a polyfill) and/or you have a really, really good reason to do so. Mostly, just don't.</p></li>\n<li><p>Declare functions so that they are not re-created (unless necessary)</p></li>\n<li><p>You should probably close your db connection ASAP</p></li>\n<li><p>Oh, and name your inline functions to provide better documentation</p></li>\n</ul>\n\n<h2>A simple refactoring <a href=\"https://gist.github.com/pckujawa/9293884\">hosted as a gist for easy forking</a></h2>\n\n<pre><code>function getUnique() {\n var u = {}, a = [];\n for (var i = 0, l = this.length; i < l; ++i) {\n if (u.hasOwnProperty(this[i])) {\n continue;\n }\n a.push(this[i]);\n u[this[i]] = 1;\n }\n return a;\n};\nfunction emitHelper(kind, shop, tag) {\n emit(shop, {\n \"kind\": kind,\n \"tag\": tag,\n });\n};\ndb.customers.mapReduce(\n function mapCustomerToShopWithKindAndTag() {\n var customer = this;\n var kind;\n getUnique(this.tags).forEach(function(tag) {\n kind = customer.status ? \"unique_customers_submitted\" : \"unique_customers_withheld\";\n emitHelper(kind, customer.shop, tag.tag);\n emitHelper(\"unique_customers_total\", customer.shop, tag.tag);\n });\n this.tags.forEach(function(tag) {\n kind = customer.status ? \"total_customers_submitted\" : \"total_customers_withheld\";\n emitHelper(kind, customer.shop, tag.tag);\n emitHelper(\"total_customers_total\", customer.shop, tag.tag);\n });\n },\n function reduceToCountOfKindsPerTag(key, sets) {\n var forms = {};\n sets.forEach(function(set) {\n if (typeof forms[set.tag] == \"undefined\") forms[set.tag] = {};\n if (typeof forms[set.tag][set.kind] == \"undefined\") forms[set.tag][set.kind] = 0;\n forms[set.tag][set.kind] += 1;\n });\n return forms;\n }, {\n out: \"form_numbers\",\n },\n function(err, results) {\n console.log(err);\n //console.log(results);\n results.find().toArray(function(err, numbers) {\n db.server.close(); // Maybe wrap in a try/catch too\n console.log(err);\n console.log(JSON.stringify(numbers));\n });\n }\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:05:06.447",
"Id": "74504",
"Score": "1",
"body": "This is a very nice answer, keep it up!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T18:19:37.810",
"Id": "43157",
"ParentId": "42740",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T09:28:20.717",
"Id": "42740",
"Score": "3",
"Tags": [
"javascript",
"mongodb",
"mapreduce"
],
"Title": "Customer MapReduce implementation"
} | 42740 |
<p>I was wondering if there is a smarter way of doing the following code. Basically what is does is that it opens a data file with a lot of rows and columns. The columns are then sorted so each column is a vector with all the data inside.</p>
<pre><code>"3.2.2 - Declare variables"
lineData = list()
for line in File:
splittedLine = line.split() # split
lineData.append(splittedLine) #collect
</code></pre>
<p>And here the fun begins</p>
<pre><code>"3.2.3 - define desired variables from file"
col1 = "ElemNo"
col2 = "Node1"
col3 = "Node2"
col4 = "Length"
col5 = "Area"
col6 = "Inertia"
col7 = "Fnode1"
col8 = "Fnode2"
col9 = "SigmaMin"
col10 = "SigmaMax"
"3.2.3 - make each variable as a list/vector"
var ={col1:[], col2:[], col3:[], col4:[], col5:[], col6:[], col7:[], col8:[]
,col9:[],col10:[]}
"3.2.3 - take the values from each row in lineData and collect them into the correct variable"
for row in lineData:
var[col1] .append(float(row[0]) ) #[-] ElemNo
var[col2] .append(float(row[1]) ) #[-] Node1
var[col3] .append(float(row[2]) ) #[-] Node2
var[col4] .append(float(row[3]) ) #[mm] Length
var[col5] .append(float(row[4]) ) #[mm^2] Area
var[col6] .append(float(row[5])*10**6) #[mm^4] Inertia
var[col7] .append(float(row[6]) ) #[N] Fnode1
var[col8] .append(float(row[7]) ) #[N] Fnode2
var[col9] .append(float(row[8]) ) #[MPa] SigmaMin
var[col10].append(float(row[9]) ) #[MPa] SigmaMax
</code></pre>
<p>As you see this is a rather annoying way of making each row into a variable. Any suggestions?</p>
| [] | [
{
"body": "<p>First of all don't create variables for those keys, store them in a list.</p>\n\n<pre><code>keys = [\"ElemNo\", \"Node1\", \"Node2\", \"Length\", \"Area\", \"Inertia\",\n \"Fnode1\", \"Fnode2\", \"SigmaMin\", \"SigmaMax\"]\n</code></pre>\n\n<p>You can use <code>collections.defaultdict</code> here, so no need to initialize the dictionary with those keys and empty list. </p>\n\n<pre><code>from collections import defaultdict\nvar = defaultdict(list)\n</code></pre>\n\n<p>Now, instead of storing the data in a list, you can populate the dictionary during iteration over <code>File</code> itself.</p>\n\n<pre><code>for line in File:\n for i, (k, v) in enumerate(zip(keys, line.split())):\n if i == 5:\n var[k].append(float(v)*10**6)\n else:\n var[k].append(float(v)) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:21:24.673",
"Id": "73752",
"Score": "0",
"body": "Maybe `i == 5` -> `k == 'Inertia'`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:25:10.807",
"Id": "73755",
"Score": "0",
"body": "@tokland But you've already included that in your answer. If you don't mind then I can suggest that in my answer as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T09:44:59.743",
"Id": "42742",
"ParentId": "42741",
"Score": "8"
}
},
{
"body": "<p>In functional approach, without refering to meaningless numeric indexes but column names, and creating a dictionary with \"ElemNo\" as keys instead of a dict of lists, I'd write:</p>\n\n<pre><code>columns = [\n \"ElemNo\", \"Node1\", \"Node2\", \"Length\", \"Area\", \"Inertia\",\n \"Fnode1\", \"Fnode2\", \"SigmaMin\", \"SigmaMax\",\n]\n\ndef process_line(line):\n def get_value(column, value):\n if column == \"Inertia\":\n return float(value) * (10**6)\n else:\n return float(value)\n elem = {col: get_value(col, value) for (col, value) in zip(columns, line.split())}\n return (elem[\"ElemNo\"], elem)\n\ndata = dict(process_line(line) for line in fd)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:34:39.197",
"Id": "73670",
"Score": "0",
"body": "How would this be better from the first suggestion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T13:41:46.727",
"Id": "73674",
"Score": "2",
"body": "@MikkelGrauballe: 1) don't use numeric indexes, 2) functional approach, 3) use elemno as key so finding elements is easier. Maybe not better, but it's a different approach."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T12:26:09.217",
"Id": "42754",
"ParentId": "42741",
"Score": "6"
}
},
{
"body": "<p>You can use <code>zip</code> to perform a transpose operation on a list of lists:</p>\n\n<pre><code>column_names = [\n \"ElemNo\", \"Node1\", \"Node2\", \"Length\", \n \"Area\", \"Inertia\", \"Fnode1\", \"Fnode2\", \n \"SigmaMin\", \"SigmaMax\"\n]\n\ncolumns = dict(zip(column_names, (map(float, col) for col in zip(*lineData))))\n# transposes lineData ^^^\n\ncolumns[\"Inertia\"] = [x * 10 ** 6 for x in columns[\"Inertia\"]]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:13:16.947",
"Id": "73748",
"Score": "2",
"body": "I'm +1ing mainly for transforming `Inertia` separately from the transpose. It's a separate \"rule\", so I don't particularly like putting it inside the main transpose loop, however that loop was done."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:39:35.293",
"Id": "42780",
"ParentId": "42741",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "42742",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T09:44:06.953",
"Id": "42741",
"Score": "11",
"Tags": [
"python",
"matrix"
],
"Title": "Row/Column Transpose"
} | 42741 |
<p>I have come up with a Java 8 solution for the following problem:</p>
<blockquote>
<p>In the 20×20 grid below, four numbers along a diagonal line have been marked in red (bold here).</p>
<p>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08<br>
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00<br>
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65<br>
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91<br>
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80<br>
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50<br>
32 98 81 28 64 23 67 10 <strong>26</strong> 38 40 67 59 54 70 66 18 38 64 70<br>
67 26 20 68 02 62 12 20 95 <strong>63</strong> 94 39 63 08 40 91 66 49 94 21<br>
24 55 58 05 66 73 99 26 97 17 <strong>78</strong> 78 96 83 14 88 34 89 63 72<br>
21 36 23 09 75 00 76 44 20 45 35 <strong>14</strong> 00 61 33 97 34 31 33 95<br>
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92<br>
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57<br>
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58<br>
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40<br>
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66<br>
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69<br>
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36<br>
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16<br>
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54<br>
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 </p>
<p>The product of these numbers is 26 × 63 × 78 × 14 = 1788696.</p>
<p>What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?</p>
</blockquote>
<p>I would comments on everything:</p>
<pre><code>public class Problem11 extends Problem<Integer> {
/** The n of the n x n grid. */
private final int n;
/** The grid. */
private final Grid grid;
/**
* Constructs this class.
*
* @param n The n of the n x n grid
* @param gridString The String representation of the grid
*/
public Problem11(final int n, final String gridString) {
this.n = n;
this.grid = new Grid(n, gridString);
}
@Override
public void run() {
List<Integer> list = new ArrayList<>(n * n * 8);
grid.forEach(cell -> processCell(list, cell));
result = list.stream().mapToInt(x -> x).max().getAsInt();
}
/**
* Processes a cell and adds the result to a list.
*
* @param list The list of results
* @param cell The cell to consider
*/
private void processCell(final List<Integer> list, final Cell cell) {
IntBinaryOperator sumOperator = (x, y) -> x * y;
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x + 1, y -> y, sumOperator)); //right
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x - 1, y -> y, sumOperator)); //left
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x, y -> y + 1, sumOperator)); //top
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x, y -> y - 1, sumOperator)); //down
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x + 1, y -> y + 1, sumOperator)); //topright
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x - 1, y -> y - 1, sumOperator)); //downleft
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x + 1, y -> y - 1, sumOperator)); //downright
addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x - 1, y -> y + 1, sumOperator)); //topleft
}
/**
* Adds an integer to the list if the OptionalInt is not empty.
*
* @param list The list to be added to
* @param optionalInt The OptionalInt
* @return The input list, with possibly the element appended
*/
private List<Integer> addIfNotEmpty(final List<Integer> list, final OptionalInt optionalInt) {
if (!optionalInt.isPresent()) {
return list;
}
list.add(optionalInt.getAsInt());
return list;
}
/**
* Returns a calculation on the cell.
*
* @param cell The starting cell
* @param steps The number of steps to take to other cells
* @param steppingXOperator The operator to apply to go to the next cell on x
* @param steppingYOperator The operator to apply to go to the next cell on y
* @param calculationOperator The operator to apply to get the result
* @return An OptionalInt instance that is empty if and only if the calculation did not work
*/
private OptionalInt calculationOnCell(final Cell cell, final int steps, final IntUnaryOperator steppingXOperator, final IntUnaryOperator steppingYOperator, final IntBinaryOperator calculationOperator) {
int x = cell.x;
int y = cell.y;
int calculationResult = cell.value;
for (int i = 0; i < steps; i++) {
x = steppingXOperator.applyAsInt(x);
y = steppingYOperator.applyAsInt(y);
if (!grid.inBounds(x, y)) {
return OptionalInt.empty();
}
calculationResult = calculationOperator.applyAsInt(calculationResult, grid.getCell(x, y).value);
}
return OptionalInt.of(calculationResult);
}
@Override
public String getName() {
return "Problem 11";
}
/**
* Structure holding the cells.
*/
private static class Grid implements Iterable<Cell> {
/** The n of the n x n grid. **/
private final int n;
/** A double array holding the cells. **/
private final Cell[][] cells;
/**
* Constructs the Grid.
*
* @param n The n of the n x n grid
* @param input The String input for the grid
*/
public Grid(final int n, final String input) {
this.n = n;
this.cells = createCellsFromString(input);
}
/**
* Creates the Cell double array from the String input.
*
* @param input The string nput
* @return The cell double array
*/
private Cell[][] createCellsFromString(final String input) {
Cell[][] returnCells = new Cell[n][n];
String[] lines = input.split("\\n");
for (int i = 0; i < lines.length; i++) {
String[] words = lines[i].split(" ");
for (int j = 0; j < words.length; j++) {
String word = words[j];
returnCells[i][j] = new Cell(i, j, Integer.parseInt(word));
}
}
return returnCells;
}
/**
* Checks if the x and y are in bounds.
*
* @param x The x to be tested
* @param y The y to be tested
* @return Whether x and y are in bounds
*/
public boolean inBounds(final int x, final int y) {
return (0 <= x && x < n && 0 <= y && y < n);
}
/**
* Returns a cell based on the coordinates.
*
* Throws an IllegalArgumentException if the x and y coordinates are not in bounds
*
* @param x The x coordinate
* @param y The y coordinate
* @return The cell corresponding to the coordinate
*/
public Cell getCell(final int x, final int y) {
if (!inBounds(x, y)) {
throw new IllegalArgumentException("problems.Problem11.Grid.getCell: !inBounds(x, y): x = " + x + " / y = " + y);
}
return cells[x][y];
}
@Override
public Iterator<Cell> iterator() {
return new Iterator<Cell>() {
/** The current x of the iterator. **/
private int x = 0;
/** The current y of the iterator. **/
private int y = 0;
@Override
public boolean hasNext() {
return !(x == n && y == 0);
}
@Override
public Cell next() {
Cell cell = cells[x][y];
advance();
return cell;
}
/**
* Advanced to the next element in the cell double array.
*/
private void advance() {
y++;
if (y == n) {
y = 0;
x++;
}
}
};
}
}
/**
* Structure holding the cell data.
*/
private static class Cell {
/** The x coordinate of the cell. **/
public final int x;
/** The y coordinate of the cell. **/
public final int y;
/** The value of the cell. **/
public final int value;
/**
* Constructs the Cell.
*
* @param x The x coordinate of the cell
* @param y The y coordinate of the cell
* @param value The value of the cell
*/
public Cell(final int x, final int y, final int value) {
this.x = x;
this.y = y;
this.value = value;
}
}
}
</code></pre>
<hr>
<pre><code>public abstract class Problem<T> implements Runnable {
protected T result;
public String getResult() {
return String.valueOf(result);
}
abstract public String getName();
}
</code></pre>
<p>The code gets called by something along the lines of:</p>
<pre><code>Problem<?> problem11 = new Problem(20,
"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n" +
"49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n" +
"81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n" +
"52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n" +
"22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n" +
"24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n" +
"32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n" +
"67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n" +
"24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n" +
"21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n" +
"78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n" +
"16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n" +
"86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n" +
"19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n" +
"04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n" +
"88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n" +
"04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n" +
"20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n" +
"20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n" +
"01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48");
problem11.run();
System.out.println(problem11.getResult());
</code></pre>
<p>One additional question I have about the code:</p>
<ul>
<li>Is it possible to write the code for the maximum-evaluation such that it does not use storage (ie. the <code>list</code>), nor uses handwritten code for calculating the sum? I don't know whether such thing would be possible with an <code>IntStream</code> for example.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:29:52.717",
"Id": "73650",
"Score": "0",
"body": "Can you please provide the string you give for the creation of your problem and anything else one might need to compile and run your program? Thanks in advance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:33:08.557",
"Id": "73651",
"Score": "0",
"body": "@Josay Added the neccessary parts, I was unaware that the general consensus was to provide compilable code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:36:16.647",
"Id": "73652",
"Score": "0",
"body": "No worries. It is just easier for everyone to tweak the code while being able to test easily at any time."
}
] | [
{
"body": "<p>Your code looks great and I can see that you have put some thought and time into it. Also, you've used pretty fancy concepts that I didn't know (which is not so hard as my Java is pretty rusty). However, it looks slightly over-engineered to me so I'll try to make things more simple.</p>\n\n<ul>\n<li>Don't mess with anyone's brain</li>\n</ul>\n\n<p><code>IntBinaryOperator sumOperator = (x, y) -> x * y;</code> : calling sum a product is one of the most confusing thing you could possibly do :-).</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">Do not repeat yourself</a> - <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">Keep it simple, stupid</a></li>\n</ul>\n\n<p>In many places, things could have been done in a more straightforward way.</p>\n\n<ol>\n<li>First example : <code>addIfNotEmpty</code></li>\n</ol>\n\n<p>You don't need to have two <code>return</code> doing the same thing in :</p>\n\n<pre><code>private List<Integer> addIfNotEmpty(final List<Integer> list, final OptionalInt optionalInt) {\n if (!optionalInt.isPresent()) {\n return list;\n }\n list.add(optionalInt.getAsInt());\n return list;\n}\n</code></pre>\n\n<p>It could easily be written :</p>\n\n<pre><code>private List<Integer> addIfNotEmpty(final List<Integer> list, final OptionalInt optionalInt) {\n if (optionalInt.isPresent()) {\n list.add(optionalInt.getAsInt());\n }\n return list;\n}\n</code></pre>\n\n<ol>\n<li>Second example : <code>n</code></li>\n</ol>\n\n<p>Your <code>Problem11</code> class has a <code>private final int n</code> and a <code>Grid</code>.\nYour <code>Grid</code> has a <code>private final int n;</code> and an Array.\nAn <code>Array</code> has a <code>length</code> attribute.</p>\n\n<p>Do you see the pattern here ? Good news is that you are considering squares because if we were to have 2 dimensions here, it would probably be a mess.</p>\n\n<p>This shows some kind of problem with your design. Maybe you should rely on the <code>length</code> attribute whenever you need to, maybe you shouldn't even need to (cf <a href=\"http://en.wikipedia.org/wiki/Leaky_abstraction\" rel=\"nofollow\">Leaky Abstraction</a>).</p>\n\n<ol>\n<li>Third example : <code>Cell</code></li>\n</ol>\n\n<p>Your <code>Cell</code> is a structure containing a value and its coordinates in an array of <code>Cell</code>s. This reminds me of one of the examples in <a href=\"http://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow\">the \"Stop Writing Classes \" presentation</a> and I have the feeling that we don't really need it.</p>\n\n<p><em>I have no time to go on right now. I'll try to edit my answers and provide a working piece of code. In the meantime, as you have solved the Project Euler already, I suggest you have a look at the solutions posted on the boards. They are a great way to learn about algorithms, math and programming style as well.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:19:43.810",
"Id": "42749",
"ParentId": "42744",
"Score": "4"
}
},
{
"body": "<p>You are doing twice as much work as you need to.... you fell in to 'the trap' of making the code follow the instructions, without thinking about the implications of the instructions.</p>\n\n<p>In the grid:</p>\n\n<pre><code> 1, 2, 3, 4,\n 5, 6, 7, 8,\n 9, 10, 11, 12,\n13, 14, 15, 16\n</code></pre>\n\n<p>The right-to-left product is going to be the same as the left-to-right product, top to bottom will be the same as the bottom to top, etc. There is no need to calculate all the values in both directions. All you need is to track the maximum... Comment out the lines:</p>\n\n<pre><code>private void processCell(final List<Integer> list, final Cell cell) {\n IntBinaryOperator sumOperator = (x, y) -> x * y;\n addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x + 1, y -> y, sumOperator)); //right\n //addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x - 1, y -> y, sumOperator)); //left\n addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x, y -> y + 1, sumOperator)); //top\n //addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x, y -> y - 1, sumOperator)); //down\n addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x + 1, y -> y + 1, sumOperator)); //topright\n //addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x - 1, y -> y - 1, sumOperator)); //downleft\n //addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x + 1, y -> y - 1, sumOperator)); //downright\n addIfNotEmpty(list, calculationOnCell(cell, 3, x -> x - 1, y -> y + 1, sumOperator)); //topleft\n}\n</code></pre>\n\n<p>I agree with other comments, your naming for the product methods as add and sum is very confusing....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T12:40:11.750",
"Id": "42756",
"ParentId": "42744",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42749",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:21:21.387",
"Id": "42744",
"Score": "4",
"Tags": [
"java",
"project-euler",
"lambda"
],
"Title": "Project Euler \"Largest product in a grid\" (#11) in Java 8"
} | 42744 |
<p>I am writing a ASCII dungeon creator inspired from games such as Angband, Moria etc.</p>
<p>The main goal of the project is to allow a user to come along and implement their own "DungeonLevelGenerator" so they can generate dungeons however they wish using the interface and tools I've provided to help speed it up.</p>
<p>Let me just explain the source briefly. Everything in the net.woopa.dungeon.core package is implementation of the API. Everything not in the package is my proposed API.</p>
<p>My questions are:</p>
<ol>
<li><p>Firstly I used a Visitor Pattern for the Materials, allowing users to create their own materials using an enum that can be used within their project with ease. Is this intuitive for the programmer?</p></li>
<li><p>Following this is the API easy to pickup even with little documentation?</p></li>
<li><p>Is the performance reduced in any way by writing it as shown.</p></li>
<li><p>I have a blend of object and static classes, would it be best for the user to have them all static? (Or alternatively all objects)?</p></li>
<li><p>I always try good programming practices (for instance not including hard coded strings and ints) now there are some in there but I plan on moving them soon. Do you feel that this code achieves this with the enums for Materials, Schematics etc?</p></li>
<li><p>Moving to the implementation (net.woopa.dungeon.core) is this as efficient as it could be, I feel like it can be difficult to read in places.</p></li>
</ol>
<p>CODE:
Material.java</p>
<pre><code> package net.woopa.dungeon.datatypes;
public interface Material {
public char getSymbol();
public String getName();
public Boolean isChest();
public Boolean isWall();
public Boolean isFloor();
public Boolean isBoundary();
public Boolean isUndef();
}
</code></pre>
<p>Implementation example:
CoreMaterial.java</p>
<pre><code> package net.woopa.dungeon.core;
import net.woopa.dungeon.datatypes.Material;
public enum CoreMaterial implements Material {
UNDEF(' '), WALL('#'), FIXEDWALL('X'), UPWALL('U'), DOWNWALL('D'), BOTHWALL(
'B'), PRESSURE('x'), RED1('1'), RED2('2'), ARROW('>'), FLOOR('.'), FIXEDFLOOR(
','), FIXEDFLOORUP(';'), FIXEDFLOORDOWN(':'), O_FLOOR('`'), WINDOW(
'G'), BARS('I'), HIGH_BARS('b'), DOOR('+'), UP('^'), DOWN('V'), ARCH(
'A'), HIDDEN('$'), WATER('W'), LAVA('L'), ANVIL('a'), FURNACE('f'), BOOKCASE(
'k'), BOOKCASE2('K'), SIGNPOST('p'), ENCHANT('e'), TORCH('t'), O_TORCH(
'~'), WEB('w'), SHROOM('m'), CAKE('='), SOULSAND('s'), EMPTYCHEST(
'o'), CHEST('c'), MIDCHEST('C'), BIGCHEST('*'), WORKBENCH('T'), SPAWNER(
'M'), BED_H('Z'), BED_F('z'), NONE('!');
private final char ch;
CoreMaterial(char ch) {
this.ch = ch;
}
public Boolean isFloor() {
return this == FLOOR || this == FIXEDFLOOR || this == FIXEDFLOORUP
|| this == FIXEDFLOORDOWN;
}
public Boolean isWall() {
return this == CoreMaterial.WALL || this == CoreMaterial.FIXEDWALL
|| this == CoreMaterial.DOWNWALL
|| this == CoreMaterial.BOTHWALL || this == CoreMaterial.UPWALL;
}
public Boolean isChest() {
return this == CoreMaterial.CHEST || this == CoreMaterial.MIDCHEST
|| this == CoreMaterial.BIGCHEST
|| this == CoreMaterial.EMPTYCHEST;
}
public Boolean isDoor() {
return this == CoreMaterial.DOOR || this == CoreMaterial.ARCH
|| this == CoreMaterial.HIDDEN || this == CoreMaterial.WEB;
}
public Boolean isStair() {
return this == CoreMaterial.UP || this == CoreMaterial.DOWN;
}
public Boolean isUndef() {
return this == CoreMaterial.UNDEF;
}
public Boolean isBoundary() {
return (this.isWall() || this.isStair() || this.isDoor());
}
@Override
public char getSymbol() {
return ch;
}
@Override
public String getName() {
return this.name();
}
}
</code></pre>
<p>4.
package net.woopa.dungeon.core;</p>
<pre><code> import net.woopa.dungeon.datatypes.Direction;
import net.woopa.dungeon.datatypes.Grid;
import net.woopa.dungeon.datatypes.Material;
import net.woopa.dungeon.datatypes.Vector2D;
public class StandardMethods {
public static void build_door(Direction dir, Vector2D loc, Material door,
Grid g) {
int wayin_x = loc.getX();
int wayin_y = loc.getY();
g.set(wayin_x, wayin_y, door);
fixWall(dir.left_x(wayin_x), dir.left_y(wayin_y), g);
fixWall(dir.right_x(wayin_x), dir.right_y(wayin_y), g);
fixFloor(dir.backwards_x(wayin_x), dir.backwards_y(wayin_y), g);
fixFloor(dir.forwards_x(wayin_x), dir.forwards_y(wayin_y), g);
}
public static void fixWall(int x, int y, Grid grid) {
if (grid.get(x, y) == CoreMaterial.WALL
|| grid.get(x, y) == CoreMaterial.UNDEF)
grid.set(x, y, CoreMaterial.FIXEDWALL);
}
public static void fixFloor(int x, int y, Grid grid) {
if (grid.get(x, y) == CoreMaterial.FLOOR
|| grid.get(x, y) == CoreMaterial.UNDEF)
grid.set(x, y, CoreMaterial.FIXEDFLOOR);
}
public static void startUpStaircase(int x, int y, CoreMaterial up,
Grid grid, Direction dir) {
grid.set(x, y, CoreMaterial.UP);
grid.set(dir.forwards_x(x), dir.forwards_y(y),
CoreMaterial.FIXEDFLOORUP);
upWall(dir.backwards_x(x), dir.backwards_y(y), grid);
upWall(dir.left_x(x), dir.left_y(y), grid);
upWall(dir.right_x(x), dir.right_y(y), grid);
}
public static void upWall(int x, int y, Grid grid) {
if (grid.get(x, y) == CoreMaterial.DOWNWALL) {
grid.set(x, y, CoreMaterial.BOTHWALL);
} else if (grid.get(x, y) == CoreMaterial.WALL
|| grid.get(x, y) == CoreMaterial.FIXEDWALL) {
grid.set(x, y, CoreMaterial.UPWALL);
} else if (grid.get(x, y) == CoreMaterial.UNDEF) {
grid.set(x, y, CoreMaterial.UPWALL);
grid.use();
}
}
}
</code></pre>
<p>CoreLevelGenerator.java
package net.woopa.dungeon.core;</p>
<pre><code> import java.util.ArrayList;
import net.woopa.dungeon.core.CoreRoom.RoomType;
import net.woopa.dungeon.datatypes.Direction;
import net.woopa.dungeon.datatypes.Grid;
import net.woopa.dungeon.datatypes.LevelCreator;
import net.woopa.dungeon.datatypes.Vector2D;
public class CoreLevelCreator implements LevelCreator {
private Vector2D levelStart, levelEnd;
private Direction startDir, endDir;
private ArrayList<CoreRoom> rooms = new ArrayList<CoreRoom>();
@Override
public Vector2D levelStart() {
return levelStart;
}
@Override
public Vector2D levelEnd() {
return levelEnd;
}
@Override
public Grid generate(Vector2D levelSize, Vector2D startLocation,
Direction startDirection) {
Grid grid = new Grid(levelSize);
this.levelStart = startLocation;
CoreRoom start = new CoreRoom(grid);
if (!start.startRoom(startLocation.getX(), startLocation.getY(),
startDirection)) {
// Couldn't place the starting room
return null;
}
// start_dir = r.room_dir();
rooms.add(start);
CoreRoom n = new CoreRoom(grid);
CoreRoom from = start;
int max_gen = 0;
// Place rooms until we have to back track too much
for (int t = 0; t < 1000 && from != null; t++) {
if (from.getExtensionAttempts() >= 400) {// TODO hardcoded int
from = getRoomNearEnd();
}
if (from != null && n.nextRoom(from)) {
rooms.add(n);
if (n.getGen() > max_gen)
max_gen = n.getGen();
if (grid.percentUtilized() > 85.0) {// TODO hardcoded float
from = null;
} else {
from = this.rooms.get(RandomUtil.nextInt(rooms.size()));
}
n = new CoreRoom(grid);
}
}
// Find a location for the end room
clearRoomAttempts();
from = getRoomGen();
for (int t = 0; t < 1000 && from != null; t++) {
if (from.getExtensionAttempts() >= 400) {// TODO hardcoded int
from = getRoomGen();
}
if (from != null && n.endRoom(from)) {
levelEnd = n.wayin().clone();
endDir = n.getRoomDir();
from = null;
n = new CoreRoom(grid);
}
}
if (true && from == null) {
// Fill the rest of the map
from = getRoomNearEnd();
for (int t = 0; t < 1000 && from != null; t++) {
if (from.getExtensionAttempts() >= 400) {// TODO hardcoded int
from = getRoomNearEnd();
}
if (from != null && n.nextRoom(from)) {
rooms.add(n);
from = n;
n = new CoreRoom(grid);
}
}
if (endDir == null) {
// No end room
}
} else {
// No start room
}
this.randomlyAddDoors(grid);
return grid;
}
private CoreRoom getRoomGen() {
CoreRoom r = null;
int max = 0;
if (rooms != null) {
for (CoreRoom x : rooms) {
if (!(x.getExtensionAttempts() >= 400)) {// TODO hardcoded int
if (x.getGen() >= max && x.getType().equals(RoomType.ROOM)) {
r = x;
max = x.getGen();
}
}
}
}
return r;
}
private void clearRoomAttempts() {
if (rooms != null) {
for (CoreRoom x : rooms) {
x.clearAttempts();
}
}
}
private void randomlyAddDoors(Grid grid) {
for (int x = 0; x < grid.getSize().getX(); x++) {
for (int y = 0; y < grid.getSize().getY(); y++) {
if (grid.get(x, y).isWall()) {
Direction dir = Direction.randomDirection();
if (grid.get(dir.left_x(x), dir.left_y(y)).equals(
CoreMaterial.WALL)
&& grid.get(dir.right_x(x), dir.right_y(y)).equals(
CoreMaterial.WALL)
&& grid.get(dir.backwards_x(x), dir.backwards_y(y))
.equals(CoreMaterial.FLOOR)
&& grid.get(dir.forwards_x(x), dir.forwards_y(y))
.equals(CoreMaterial.FLOOR)) {
StandardMethods.build_door(dir, new Vector2D(x, y),
CoreMaterial.CAKE, grid);
}
}
}
}
}
private CoreRoom getRoomNearEnd() {
CoreRoom r = null;
if (rooms != null) {
for (CoreRoom x : rooms) {
if (!(x.getExtensionAttempts() >= 400)) { // TODO hardcoded int
r = x;
}
}
}
return r;
}
@Override
public Direction endDirection() {
return endDir;
}
@Override
public Direction startDirection() {
return startDir;
}
public void clean(){
this.rooms.clear();
}
}
</code></pre>
<p>CoreRoom.java
package net.woopa.dungeon.core;</p>
<pre><code> import net.woopa.dungeon.datatypes.Direction;
import net.woopa.dungeon.datatypes.Grid;
import net.woopa.dungeon.datatypes.Schematic;
import net.woopa.dungeon.datatypes.Vector2D;
import net.woopa.dungeon.managers.SchematicManager;
import net.woopa.dungeon.managers.SettingsManager;
public class CoreRoom {
public enum RoomType {
ROOM, CORRIDOR, SPECIAL
}
private int size_x, size_y;
private int origin_x, origin_y;
private int gen = 0;
private int extension_attempts = 0;
private final Grid grid;
private RoomType type;
private Schematic room_map = null;
private Direction special_dir;
private final RoomPopulator roomPopulator;;
private int wayin_x, wayin_y;
private Direction room_dir;
public CoreRoom(Grid grid) {
this.roomPopulator = new RoomPopulator(this);
this.grid = grid;
generateRandom();
placeRandom();
}
public void clearAttempts() {
extension_attempts = 0;
}
// TODO this is better but still horrible
public Boolean startRoom(int x, int y, Direction orig_dir) {
int cnt = 0;
Direction dir;
do {
dir = placeFrom(x, y, orig_dir);
if (!grid.fits(origin_x, origin_y, size_x, size_y) && (dir != null)) {
generateRandom();
} else {
break;
}
cnt++;
} while (cnt < 5000);
if (cnt >= 5000)
// Can't find a place
return false;
renderRoom();
StandardMethods.startUpStaircase(x, y, CoreMaterial.UP, grid, dir);
gen = 1;
roomPopulator.dressRoom();
return true;
}
public Boolean nextRoom(CoreRoom from) {
int cnt = 0;
Direction dir = null;
do {
dir = placeFrom(from);
if (!((dir != null)
&& grid.fits(origin_x, origin_y, size_x, size_y)
&& (grid.get(wayin_x, wayin_y) == CoreMaterial.WALL)
&& grid.isFloor(dir.backwards_x(wayin_x),
dir.backwards_y(wayin_y)))) {
generateRandom();
}else break;
from.extension_attempts++;
cnt++;
} while ((cnt < 20)); // Try different sizes and shapes //TODO
// hardcoded
if (cnt>=20)
// Can't find a place
return false;
renderRoom();
StandardMethods.build_door(dir, new Vector2D(wayin_x, wayin_y),
CoreMaterial.DOOR, grid);
gen = from.gen + 1;
roomPopulator.dressRoom();
return true;
}
public Boolean endRoom(CoreRoom from) {
this.type = RoomType.SPECIAL;
generateSpecialRoomRandom(SchematicManager.randomDownSchematic());
final Direction dir = placeFrom(from);
final Boolean ok = (dir != null)
&& grid.fits(origin_x, origin_y, size_x, size_y)
&& (grid.get(wayin_x, wayin_y) == CoreMaterial.WALL)
&& grid.isFloor(dir.backwards_x(wayin_x),
dir.backwards_y(wayin_y));
if (ok) {
//extension_attempts = 100000; // TODO HC
this.renderRoom();
gen = from.gen + 1;
if (grid.get(wayin_x, wayin_y) == CoreMaterial.DOWN) {
grid.set(dir.backwards_x(wayin_x), dir.backwards_y(wayin_y),
CoreMaterial.FIXEDFLOORDOWN);
} else {
StandardMethods.build_door(dir, new Vector2D(wayin_x, wayin_y),
CoreMaterial.DOOR, grid);
}
roomPopulator.chestDoubleRandom();
}
return ok;
}
private Direction placeFrom(CoreRoom from) {
final Direction dir = Direction.randomDirection();
final int offset = randomOffset(from, dir);
if (offset < 0)
return null;
switch (dir) {
case EAST:
wayin_x = (from.origin_x + from.size_x) - 1;
wayin_y = from.origin_y + offset;
break;
case WEST:
wayin_x = from.origin_x;
wayin_y = from.origin_y + offset;
break;
case NORTH:
wayin_x = from.origin_x + offset;
wayin_y = (from.origin_y + from.size_y) - 1;
break;
case SOUTH:
wayin_x = from.origin_x + offset;
wayin_y = from.origin_y;
break;
}
return this.placeFrom(wayin_x, wayin_y, dir);
}
private Direction placeFrom(int x, int y, Direction dir) {
wayin_x = x;
wayin_y = y;
setRoomDir(dir);
final int offset = randomOffset(this, dir);
if (offset < 0)
return null;
if (dir.isHorizontal()) {
origin_x = (dir == Direction.EAST) ? x : (x - size_x) + 1;
origin_y = y - offset;
} else {
origin_y = (dir == Direction.NORTH) ? y : (y - size_y) + 1;
origin_x = x - offset;
}
return dir;
}
public int corridorWidth() {
if (RandomUtil.chance(SettingsManager
.getInt(CoreSettings.CorridorW3Pct)))
return 3;
if (RandomUtil.chance(SettingsManager
.getInt(CoreSettings.CorridorW3Pct)
+ SettingsManager.getInt(CoreSettings.CorridorW2Pct)))
return 2;
return 1;
}
private void generateCorridorRandom() {
final int width = corridorWidth();
if (RandomUtil.chance(50)) {
size_x = randomCorridorSize() + 2;
size_y = width + 2;
} else {
size_x = width + 2;
size_y = randomCorridorSize() + 2;
}
}
private void generateRandom() {
if (RandomUtil.chance(SettingsManager.getInt(CoreSettings.CorridorPct))) {
generateCorridorRandom();
this.type = RoomType.CORRIDOR;
} else {
if (RandomUtil.chance(SettingsManager
.getInt(CoreSettings.SpecialPct))) {
generateSpecialRoomRandom(null);
this.type = RoomType.SPECIAL;
} else {
generateRoomRandom();
this.type = RoomType.ROOM;
}
}
}
private void generateRoomRandom() {
size_x = randomRoomSize();
size_y = randomRoomSize();
}
private void generateSpecialRoomRandom(Schematic s) {
if (s == null) {
room_map = SchematicManager.randomRoomSchematic();
} else {
room_map = s;
}
special_dir = Direction.randomDirection();
size_x = room_map.sx(special_dir);
size_y = room_map.sy(special_dir);
}
public int getExtensionAttempts() {
return this.extension_attempts;
}
public int getGen() {
return this.gen;
}
public Grid getGrid() {
return this.grid;
}
public int getOriginX() {
return this.origin_x;
}
public int getOriginY() {
return this.origin_y;
}
public Direction getRoomDir() {
return room_dir;
}
public int getSizeX() {
return this.size_x;
}
public int getSizeY() {
return this.size_y;
}
public RoomType getType() {
return type;
}
private void placeRandom() {
if ((((grid.getSize().getX() - size_x) + 1) < 1)
|| (((grid.getSize().getY() - size_y) + 1) < 1)) {
origin_x = 0;
origin_y = 0;
} else {
origin_x = RandomUtil.nextInt((grid.getSize().getX() - size_x) + 1);
origin_y = RandomUtil.nextInt((grid.getSize().getY() - size_y) + 1);
}
}
public int randomCorridorSize() {
final int cmax = SettingsManager.getInt(CoreSettings.CorridorMax);
final int cmin = SettingsManager.getInt(CoreSettings.CorridorMin);
return RandomUtil.nextInt((cmax - cmin) + 1) + cmin;
}
private int randomOffset(CoreRoom from, Direction dir) {
int size = 0;
if (dir.isHorizontal()) {
size = from.size_y - 2;
} else {
size = from.size_x - 2;
}
return (from.getType().equals(RoomType.SPECIAL)) ? from.room_map
.getAccess(dir, from.special_dir)
: RandomUtil.nextInt(size) + 1;
}
private int randomRoomSize() {
final int rmax = SettingsManager.getInt(CoreSettings.RoomMax);
final int rmin = SettingsManager.getInt(CoreSettings.RoomMin);
return RandomUtil.nextInt((rmax - rmin) + 1) + rmin + 2;
}
private void renderRoom() {
if (type == RoomType.SPECIAL) {
grid.renderSchematic(origin_x, origin_y, room_map, special_dir);
} else {
grid.renderBasicEmptyRoom(origin_x, origin_y, size_x, size_y,
CoreMaterial.WALL, CoreMaterial.FLOOR);
}
}
public void setRoomDir(Direction room_dir) {
this.room_dir = room_dir;
}
@Override
public String toString() {
return "ROOM:(" + origin_x + "," + origin_y + ") size(" + size_x + ","
+ size_y + ") gen=" + gen + " att=" + extension_attempts;
}
public Vector2D wayin() {
return new Vector2D(wayin_x, wayin_y);
}
}
</code></pre>
<p>Further study here: See here for source: <a href="https://github.com/samkio/Dungeonator">https://github.com/samkio/Dungeonator</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T17:57:22.887",
"Id": "73728",
"Score": "0",
"body": "I took a look at your `Direction` code on GitHub, and I would suggest that you create a new question about just that class. I have a whole lot of things to say about that one :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:56:49.467",
"Id": "73792",
"Score": "0",
"body": "Thanks, I've created a new question here: http://codereview.stackexchange.com/questions/42817/direction-enum-advice"
}
] | [
{
"body": "<p><strong>Keep your code extendable</strong> - You created your enum <code>CoreMaterial</code> as an extendable enum, but then you implemented the various <code>isXXX()</code> methods repeating the enum values themselves in them. A better solution might be to let each material declare its own type:</p>\n\n<pre><code>public enum MaterialType { Chest, Wall, Floor, Boundary, Undef }\n\npublic enum CoreMaterial implements Material {\nUNDEF(' ', MaterialType.Undef), WALL('#', MaterialType.Wall), \nFIXEDWALL('X', MaterialType.Wall), UPWALL('U', MaterialType.Wall); // etc...\n\nprivate final char ch;\nprivate final MaterialType type;\n\nCoreMaterial(char ch, MaterialType type) {\n this.ch = ch;\n this.type = type;\n}\n\npublic Boolean isFloor() {\n return type == MaterialType.Floor;\n}\n\npublic Boolean isWall() {\n return type == MaterialType.Wall;\n}\n\npublic Boolean isChest() {\n return type == MaterialType.Chest;\n}\n\n// etc...\n}\n</code></pre>\n\n<p><strong>Naming conventions</strong> from time to time your code conventions slip - <code>build_door</code>, <code>special_dir</code>, etc. if you write in java, adhere to its conventions - <code>buildDoor</code>, <code>specialDir</code>, etc.</p>\n\n<p><strong>When static methods scream 'refactor me!'</strong> - in your <code>StandardMethods</code> class you have many static classes. Even the name of the class hints ti the fact that it is not very object-oriented...</p>\n\n<p>When you look at all the methods in this class, you may note that all of them have one parameter in common, and they keep moving it around among themselves - <code>g</code>. This suggests that it may be a good idea to refactor all of them into the <code>Grid</code> class...</p>\n\n<p><strong>Don't override member names</strong> - you use <code>levelStart</code> and <code>levelEnd</code> to both the private members and their method getters. Better naming for the methods would be <code>getLevelStart()</code> and <code>getLevelEnd()</code></p>\n\n<p><code>generate()</code> - TL;DR - you might want to break this method to smaller ones.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T22:55:21.643",
"Id": "73799",
"Score": "0",
"body": "Thank you for your suggestions. I will certainly take them on board and fix accordingly. I will also try and refactor the StandardMethods class. The reason they're not in the Grid class is that the StandardMethods are specific to that level generator whereas the Grid class should be universal and not have any set methods. Which I guess gives me some thought as to what to include in that class and what to exclude from it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:23:06.963",
"Id": "42777",
"ParentId": "42745",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>You have some methods that return <code>Boolean</code>, prefer the primitive type <code>boolean</code> instead. <code>Boolean</code> can be null, <code>boolean</code> can't.</p></li>\n<li><p>I would make a more flexible solution than Uri's for your material types, (although Uri's suggestion is a good start). Either use an array of <code>MaterialType</code> or use an EnumSet of MaterialType. (If you choose to construct it with an array, it can be converted to an EnumSet later, such as in the constructor).</p>\n\n<pre><code>public enum CoreMaterial implements Material {\n UNDEF(' ', EnumSet.of(MaterialType.Undef, MaterialType.SomethingElse)), \n WALL('#', EnumSet.of(MaterialType.Wall, MateiralType.Other)), ...;\n</code></pre></li>\n</ul>\n\n<p>This has the benefit that one Material can have multiple MaterialTypes. Then you can use the <code>.contains</code> method of the enumset to check if the material is of a specific type. See more in the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\" rel=\"nofollow\">EnumSet documentation</a></p>\n\n<ul>\n<li><p>It is a horrible place to put a linebreak after <code>BOTHWALL(</code>. Put a linebreak after a comma <code>,</code> instead. Also try to put the enums that are related to each other on the same line so that it is easier to see which ones belongs together.</p></li>\n<li><p><code>TODO hardcoded float</code>. That tells me that you know what to do about this. <strong>Do it.</strong> Make it a constant. Or a variable. You have a whole bunch of hardcoded values. Not good. In some methods you even have the same hardcoded value at two places. Not not good. Imagine if you would change one and forget the other. Chaos!</p></li>\n<li><p><code>if (true && from == null) {</code> I'm quite sure that true will always be true, so no need to check that. If you keep it for easy disabling, make it a constant. <code>SHOULD_FILL_REST_OF_MAP</code> or something (you can probably come up with a better name).</p></li>\n<li><p>Is this meant as some kind of <code>// TODO</code> ? If so, write <code>// TODO</code>. If not, remove this piece of code:</p>\n\n<pre><code>if (endDir == null) {\n // No end room\n}\n</code></pre></li>\n<li><p><code>for (CoreRoom x : rooms) {</code> and what on earth is x? <code>room</code> would be a better name but that would still not explained what it is being used for. The <code>getRoomGen</code> method is quite unclear. You might want to use better variable names or add some comments about <strong>why</strong> it exists.</p></li>\n<li><p>You might want to extract a method out of <code>randomlyAddDoors</code>, one method can do the iteration and one method can do what needs to be done for one specific door.</p></li>\n</ul>\n\n<p>As for your specific questions:</p>\n\n<blockquote>\n <p>1 Firstly I used a Visitor Pattern for the Materials, allowing users to create their own materials using an enum that can be used within their project with ease. Is this intuitive for the programmer?</p>\n</blockquote>\n\n<p>Allowing users to create their own materials is a good idea. I like your Material interface (although I think it needs to be modified to allow for more flexibility for material types, and you should return <code>boolean</code> as I mentioned...). Visitor pattern? I wouldn't call what you have here a visitor pattern. I think the most intuitive would be to specify which MaterialTypes a material should have when constructing it. In fact, you might want to have <code>Material</code> as a class instead, and the char and MaterialType array/enumset as parameters to the constructor.</p>\n\n<blockquote>\n <p>2 Following this is the API easy to pickup even with little documentation?</p>\n</blockquote>\n\n<p>It's quite easy, but I think it could use a bit more documentation. And I also think that it's not entirely clear which parts are your API and which parts is your implementation here.</p>\n\n<blockquote>\n <p>3 Is the performance reduced in any way by writing it as shown.</p>\n</blockquote>\n\n<p>I'm the wrong person to ask about performance :) Can't comment much on this one. I can't see any big performance issues directly though, which is a good sign.</p>\n\n<blockquote>\n <p>4 I have a blend of object and static classes, would it be best for the user to have them all static? (Or alternatively all objects)?</p>\n</blockquote>\n\n<p>I don't see many static <em>classes</em>, I only see static <em>methods</em>. If you mean the static methods, don't ever consider having them all static again. Not under my watch. Java is an object-oriented language. Use objects and classes. Learn to love the objects. Some utility methods can be static if you really want them to be. But here I see not much reason for them to be.</p>\n\n<blockquote>\n <p>5 I always try good programming practices (for instance not including hard coded strings and ints) now there are some in there but I plan on moving them soon. Do you feel that this code achieves this with the enums for Materials, Schematics etc?</p>\n</blockquote>\n\n<p>I like what you have done with the Materials. I'm not sure which Schematics you're talking about. And please make constants of your hardcoded values ASAP.</p>\n\n<blockquote>\n <p>6 Moving to the implementation (net.woopa.dungeon.core) is this as efficient as it could be, I feel like it can be difficult to read in places.</p>\n</blockquote>\n\n<p>A method should do only one thing, and it should do that one thing well. Yes, it is difficult to read, mostly because you have some unnecessary long methods. Split these long methods into multiple methods. Don't do more than you have to in the same method. For example, the generation process can be split into several sub-steps, make each sub-step it's own method (at least).</p>\n\n<p>I hope that this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T23:01:07.230",
"Id": "73800",
"Score": "0",
"body": "Thank you for your suggestions and advice. I like your extended flexibility of the Material Enum and will take that on board. As from both answers I will stop being lazy and leaving all the hardcoded ints in! Yes I meant static methods and I will move away from them quickly. Thanks for all the suggestions it is much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T18:12:28.287",
"Id": "42793",
"ParentId": "42745",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42793",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T10:48:56.637",
"Id": "42745",
"Score": "6",
"Tags": [
"java",
"game"
],
"Title": "API for Dungeon Generator"
} | 42745 |
<p>I studied a bit and packed all the suggestions that I received here: <a href="https://codereview.stackexchange.com/questions/42647/fluent-interface-and-polymorphism">Fluent interface and polymorphism for building a scene with shapes</a> and I came up with this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
struct Figure {
string _name;
virtual double area() const=0;
virtual ~Figure() {}
};
struct Circle: Figure {
double _radius;
Circle * radius(double r) { _radius=r; return this;}
Circle * name(string str) { _name=str; return this;}
double area() const override {return M_PI*_radius*_radius;}
~Circle() {}
};
struct Square: Figure {
double _side;
Square * side(double s) { _side=s; return this;}
Square * name(string str) { _name=str; return this;}
double area() const override {return _side*_side;}
~Square() {}
};
struct Scene {
vector<Figure*> v;
~Scene() { for (auto & f : v) delete f; }
double total_area() const {
double total=0;
for (auto f : v) total += f->area();
return total;
}
//here we go, this is the standard function with recursion
template<typename T, typename S, typename ...Args>
void apply(T *t, T*(T::*func)(S), const S & par, const Args &... args) {
(t->*func)(par);
apply(t, args...);
}
//this terminates the recursion
template<typename T, typename S>
void apply(T *t, T*(T::*func)(S), const S & par) {
(t->*func)(par);
}
//this is for the empty args call
template<typename T>
void apply(T *t) {
cerr << "Warning: no parameters have been specified" << endl;
}
//here is the interface function
template<typename T, typename ...Args>
Scene& add( const Args &... args ) {
T * t = new T();
apply(t, args...);
v.emplace_back(t);
return *this;
}
};
int main() {
Scene scene;
scene.add<Circle>(&Circle::name,string("c1"),&Circle::radius,1.)
.add<Square>(&Square::side,10.,&Square::name,string("s1"))
.add<Circle>();
cout << "Total area: " << scene.total_area() << endl;
return 0;
}
</code></pre>
<p>The principle looks very nice to me, don't you agree? However the interface is quite heavy. My main concern is about the need to put the name of the object (<code>&Circle::</code> or <code>&Square::</code>) in front of every method in the interface: definitely too rambling, but I have not been able to remove it.</p>
<p>Looking at it for a second time I am thinking that maybe instead of using member function, I could directly access the members in a similar way. However this would not help my main concern right above. </p>
<p>I already know about the improvements that could be made by using the move semantics instead of <code>const &</code>, feel free to write them down for others if you want.</p>
<hr>
<p>I finally achieved an interface that definitely looks nice and clean:</p>
<pre class="lang-cpp prettyprint-override"><code>int main() {
Scene scene;
scene.add<Circle>(Name("c1"),Radius(1.))
.add<Square>(Side(10),Name("s2"))
.add<Circle>();
cout << "Total area: " << scene.total_area() << endl;
return 0;
}
</code></pre>
<p>As I wanted it is named and position independent, it supports any number of parameters that eventually can be skipped in favour of default values and it is fully checked at compile time. It also support implicit conversion between types, so I can set the side of the square with an int instead of a double and templates do not comply.</p>
<p>And here is the full code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
//templated setter for many types
template <typename T>
struct Setter {
T _i;
Setter(const T & i) : _i(i) {}
operator T() const {return _i;}
};
//setter for each parameter
struct Name: Setter<string> { Name(const string & i): Setter(i){} };
struct Side: Setter<double> { Side(double i): Setter(i){} };
struct Radius: Setter<double> { Radius(double i): Setter(i){} };
struct Figure {
string _name;
virtual double area() const=0;
virtual ~Figure() {}
};
struct Circle: Figure {
double _radius;
double area() const override {return M_PI*_radius*_radius;}
void set(const Radius & n) {_radius = n;}
void set(const Name & n) {_name = n;}
};
struct Square: Figure {
double _side;
double area() const override {return _side*_side;}
void set(const Side & n) {_side = n;}
void set(const Name & n) {_name = n;}
};
struct Scene {
vector<Figure*> v;
~Scene() { for (auto & f : v) delete f; }
double total_area() const {
double total=0;
for (auto f : v) total += f->area();
return total;
}
//here we go, this is the standard function with recursion
template<typename T, typename S, typename ...Args>
void apply(T *t, const S & setter, const Args &... args) {
t->set(setter);
apply(t, args...);
}
//this terminates the recursion
template<typename T, typename S>
void apply(T *t, const S & setter) {
t->set(setter);
}
//this is for the empty args call
template<typename T>
void apply(T *t) {
cerr << "Warning: no parameters set for an object" << endl;
}
//here is the interface function
template<typename T, typename ...Args>
Scene& add( const Args &... args ) {
T * t = new T();
apply(t, args...);
v.emplace_back(t);
return *this;
}
};
int main() {
Scene scene;
scene.add<Circle>(Name("c1"),Radius(1.))
.add<Square>(Side(10),Name("s2"))
.add<Circle>();
cout << "Total area: " << scene.total_area() << endl;
return 0;
}
</code></pre>
<p>I think I will place all the setters under a namespace in a separate header. Of course any hint and improvement to this design is more than welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-10T16:44:09.970",
"Id": "145094",
"Score": "0",
"body": "Have you thought about how your design would work with a rectangle? Are you going to create `Length` and `Width` as new types to make `Rectangle` work? It seems to me that there is a flaw in your approach. `Radius`, `Side`, `Length`, and `Width` are essentially same types -- wrappers around `double`. If you have to create a new type every time a member variable of type `double` is needed, it doesn't seem right."
}
] | [
{
"body": "<p>You said that you packed all the suggestions from the previous question, but there are still some pieces of advice that you did not integrate into your code. Here is how you can still improve your it:</p>\n\n<h2><code>math.h</code> legacy</h2>\n\n<p>In your code, you are using the constant <code>M_PI</code>. While it will probably work on most of the compilers I know, this macro isn't defined anywhere in any C or C++ standard. The <code>math.h</code>/<code>cmath</code> constants are only a common POSIX extension. You should define your own math constant somewhere in order to avoid portability problems. Since it was the only feature from <code><cmath></code> you used, you can remove the include.</p>\n\n<h2>Perfect forwarding</h2>\n\n<p>There are many places where you should use <code>std::forward</code> to perfectly forward your arguments from a function to another. For example, you could turn this piece of code:</p>\n\n<pre><code>template<typename T, typename S, typename ...Args>\nvoid apply(T *t, const S & setter, const Args &... args) {\n t->set(setter);\n apply(t, args...);\n}\n</code></pre>\n\n<p>into this one:</p>\n\n<pre><code>template<typename T, typename S, typename ...Args>\nvoid apply(T *t, const S & setter, Args &&... args) {\n t->set(setter);\n apply(t, std::forward<Args>(args)...);\n}\n</code></pre>\n\n<h2><code>std::unique_ptr</code></h2>\n\n<p>Avoid raw pointers. Instead, use a <code>std::unique_ptr</code> which will manage the memory alone. It's by far safer. Since the modified portion of the code is quite huge for this modification, I won't include it in this section. However, you can find the modified code at the end of my post :)</p>\n\n<h2>Constructor inheritance</h2>\n\n<p>Do not bother creating specialized constructors to forward your results to <code>Setter</code> from its derived classes. You can use constructor inheritance:</p>\n\n<pre><code>struct Name: Setter<string> { using Setter::Setter; };\nstruct Side: Setter<double> { using Setter::Setter; };\nstruct Radius: Setter<double> { using Setter::Setter; };\n</code></pre>\n\n<h2>Place of method <code>set</code></h2>\n\n<p>Since <code>_name</code> belongs to <code>Figure</code>, you better define <code>void set(const Name& n)</code> in <code>Figure</code>. That way, its derived classes won't have to duplicate the code, and <code>Figure</code> will handle its member variables by itself. However, remember to add <code>using Figure::set;</code> in the derived classes, otherwise, the name will be hidden by the overloads.</p>\n\n<h2>Choice of the collection</h2>\n\n<p>Using a <code>std::vector</code> to store collections of elements is often the best choice. However, if you plan to remove elements from the middle of your collection at some time, you could consider using <code>std::list</code> instead. Anyway, I don't know what you plan to do with this code, so I did not change the <code>std::vector</code> to an <code>std::list</code> in my revised version of your code (<em>update:</em> <a href=\"http://isocpp.org/blog/2014/06/stroustrup-lists\" rel=\"noreferrer\">actually, be careful anyway if you decide to use an <code>std::list</code></a>).</p>\n\n<h2>Encapsulation</h2>\n\n<p>From what I see, all your variables beginning with an underscore ought to be <code>private</code> members of the classes. However, you may have made them <code>public</code> in order to simplify your code to post it here, I don't know. I did not modidy that in my revised version of the code in order to keep the code simple.</p>\n\n<hr>\n\n<p>Here is the revised version of your code. I applied all the aforementioned modifications, appart from the ones which I explicitely stated are not:</p>\n\n<pre><code>#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n\n// pi constant\nconstexpr double pi = 3.141592653589793;\n\n//templated setter for many types\ntemplate <typename T> \nstruct Setter {\n T _i;\n Setter(const T & i) : _i(i) {}\n operator T() const {return _i;}\n};\n\n//setter for each parameter\nstruct Name: Setter<std::string> { using Setter::Setter; };\nstruct Side: Setter<double> { using Setter::Setter; };\nstruct Radius: Setter<double> { using Setter::Setter; };\n\nstruct Figure {\n std::string _name;\n virtual double area() const=0;\n virtual ~Figure() {}\n void set(const Name & n) { _name = n; }\n};\n\nstruct Circle: Figure {\n double _radius;\n double area() const override { return pi*_radius*_radius; }\n using Figure::set;\n void set(const Radius & n) { _radius = n; }\n};\n\nstruct Square: Figure {\n double _side;\n double area() const override { return _side*_side; }\n using Figure::set;\n void set(const Side & n) { _side = n; }\n};\n\nstruct Scene {\n std::vector<std::unique_ptr<Figure>> v;\n double total_area() const {\n double total{};\n for (const auto& f : v)\n total += f->area();\n return total;\n }\n\n //here we go, this is the standard function with recursion\n template<typename T, typename S, typename ...Args>\n void apply(T& t, const S & setter, Args&&... args) {\n t.set(setter);\n apply(t, std::forward<Args>(args)...);\n }\n\n //this terminates the recursion\n template<typename T, typename S>\n void apply(T& t, const S & setter) {\n t.set(setter);\n }\n\n //this is for the empty args call\n template<typename T>\n void apply(T&) {\n std::cerr << \"Warning: no parameters set for an object\" << std::endl;\n }\n\n //here is the interface function\n template<typename T, typename ...Args>\n Scene& add(Args&&... args ) {\n std::unique_ptr<T> t(new T());\n apply(*t, std::forward<Args>(args)...);\n v.emplace_back(std::move(t));\n return *this;\n }\n};\n\nint main() {\n Scene scene;\n scene.add<Circle>(Name(\"c1\"), Radius(1.))\n .add<Square>(Side(10), Name(\"s2\"))\n .add<Circle>();\n std::cout << \"Total area: \" << scene.total_area() << std::endl;\n}\n</code></pre>\n\n<p>And you can find the working version <a href=\"http://coliru.stacked-crooked.com/a/c8d001e2fbf887c6\" rel=\"noreferrer\">here</a> at Coliru.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:17:20.987",
"Id": "42869",
"ParentId": "42748",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "42869",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:12:33.100",
"Id": "42748",
"Score": "11",
"Tags": [
"c++",
"c++11",
"template",
"interface",
"polymorphism"
],
"Title": "Variadic templates and pointers to member functions to achieve a named-parameters interface in C++"
} | 42748 |
<p>Here is the code for the QuickSort class that I created.</p>
<pre><code>public class QuickSort {
public static void sort(Comparable[] a) {
quicksort(a, 0, a.length-1);
}
private static void quicksort(Comparable[] a, int lo, int hi) {
if(lo >= hi) return;
int pi = partition(a, lo, hi);
quicksort(a, lo, pi-1);
quicksort(a, pi+1, hi);
}
private static int partition(Comparable[] a, int lo, int hi) {
int i = lo + 1;
int j = hi;
while(i <= j) {
if(a[i].compareTo(a[lo]) <= 0) {
i++;
}
else if(a[j].compareTo(a[lo]) > 0) {
j--;
}
else if(j < i) {
break;
}
else
exchange(a, i, j);
}
exchange(a, lo, j);
return j;
}
private static void exchange(Object[] a, int i, int j) {
Object tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
</code></pre>
<p>The code passed some simple tests (including duplicate values). I wonder is any bug in my code? Anywhere to improve?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T14:38:15.300",
"Id": "73892",
"Score": "0",
"body": "Friendly reminder that `java.util.Arrays` has an optimized [`sort` method](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28java.lang.Object[]%29)"
}
] | [
{
"body": "<p>Just three quick notes:</p>\n\n<ol>\n<li><p>You could fix the compiler warnings with the following method declarations:</p>\n\n<pre><code>public static <T extends Comparable<T>> void sort(T[] a)\n\nprivate static <T extends Comparable<T>> void quicksort(T[] a, int lo, int hi)\n\nprivate static <T extends Comparable<T>> int partition(T[] a, int lo, int hi)\n</code></pre></li>\n<li><p>I'd rename <code>a</code> to <code>input</code> or <code>data</code> for better readability.</p></li>\n<li><p><code>exchange</code> is usually called <code>swap</code>. I think more developers would find familiar the latter.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:46:20.197",
"Id": "42752",
"ParentId": "42750",
"Score": "2"
}
},
{
"body": "<p>Javadoc on every method would be nice.</p>\n\n<p>Change signature to <code><T extends Comparable<T>> void sort(T[] a)</code>.</p>\n\n<pre><code>public static void sort(Comparable[] a) {\n</code></pre>\n\n<p>Standard method to specify ranges is from inclusive to exclusive.</p>\n\n<pre><code> quicksort(a, 0, a.length - 1);\n}\n\nprivate static void quicksort(Comparable[] a, int lo, int hi) {\n</code></pre>\n\n<p>Why not \"high\" and \"low\"?</p>\n\n<pre><code> if (lo >= hi) {\n</code></pre>\n\n<p>Your code never invokes quicksort with <code>lo > hi</code>. You'd better throw an <code>IllegalArgument</code> exception in this case.</p>\n\n<pre><code> return;\n }\n int pi = partition(a, lo, hi);\n quicksort(a, lo, pi - 1);\n quicksort(a, pi + 1, hi);\n}\n\nprivate static int partition(Comparable[] a, int lo, int hi) {\n int i = lo + 1;\n int j = hi;\n</code></pre>\n\n<p>You choose the first element as pivotal. Choosing as a pivot the element at a constant position allows construction of an antitest, an array on which your sort works in O(n^2). In your particular case, the antitest is pretty simple - an array in descending order, e.g. (5, 4, 3, 2, 1).</p>\n\n<pre><code> while (i <= j) {\n if (a[i].compareTo(a[lo]) <= 0) {\n i++;\n } else if (a[j].compareTo(a[lo]) > 0) {\n j--;\n } else if (j < i) {\n break;\n } else {\n exchange(a, i, j);\n }\n }\n exchange(a, lo, j);\n return j;\n}\n</code></pre>\n\n<p>It's better to name it swap.</p>\n\n<pre><code>private static void exchange(Object[] a, int i, int j) {\n Object tmp = a[i];\n a[i] = a[j];\n a[j] = tmp;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-02T09:39:20.880",
"Id": "207830",
"Score": "0",
"body": "Very nice answer by abra.\nfor future reference, the most important issue here is the O(n^2) time complexity - because of the pivot selection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T12:18:40.317",
"Id": "42753",
"ParentId": "42750",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T11:28:35.697",
"Id": "42750",
"Score": "6",
"Tags": [
"java",
"recursion",
"quick-sort"
],
"Title": "QuickSort of Comparable[]"
} | 42750 |
<p>Here is a function that I've only slightly modified from its original context, found <a href="https://github.com/sightmachine/SimpleCV/pull/607" rel="nofollow noreferrer">here</a>.</p>
<p>Before mentioning anything else, it should be noted that I'm desperately trying to optimize this code for speed. It presently takes about 5.25 seconds to execute and it appears as though the bottleneck is happening in the <code>for</code>-loop.</p>
<p>In a nutshell, this function expects the user to have <code>SimpleCV</code> installed and expects, at a minimum, to be passed a <code>SimpleCV.Image</code> instance.</p>
<p>Does anybody have some clever approach for speeding things up? Ideally I'd be able to run this on a real-time webcam feed at 30 frames-per-second, but I'm not getting my hopes up.</p>
<pre><code>from itertools import product
from math import floor, pi
import numpy as np
import cv2 # opencv 2
def findHOGFeatures(img, n_divs=6, n_bins=6):
"""
**SUMMARY**
Get HOG(Histogram of Oriented Gradients) features from the image.
**PARAMETERS**
* *img* - SimpleCV.Image instance
* *n_divs* - the number of divisions(cells).
* *n_divs* - the number of orientation bins.
**RETURNS**
Returns the HOG vector in a numpy array
"""
# Size of HOG vector
n_HOG = n_divs * n_divs * n_bins
# Initialize output HOG vector
# HOG = [0.0]*n_HOG
HOG = np.zeros((n_HOG, 1))
# Apply sobel on image to find x and y orientations of the image
Icv = img.getNumpyCv2()
Ix = cv2.Sobel(Icv, ddepth=cv.CV_32F, dx=1, dy=0, ksize=3)
Iy = cv2.Sobel(Icv, ddepth=cv.CV_32F, dx=0, dy=1, ksize=3)
Ix = Ix.transpose(1, 0, 2)
Iy = Iy.transpose(1, 0, 2)
cellx = img.width / n_divs # width of each cell(division)
celly = img.height / n_divs # height of each cell(division)
#Area of image
img_area = img.height * img.width
#Range of each bin
BIN_RANGE = (2 * pi) / n_bins
# m = 0
angles = np.arctan2(Iy, Ix)
magnit = ((Ix ** 2) + (Iy ** 2)) ** 0.5
it = product(xrange(n_divs), xrange(n_divs), xrange(cellx), xrange(celly))
for m, n, i, j in it:
# grad value
grad = magnit[m * cellx + i, n * celly + j][0]
# normalized grad value
norm_grad = grad / img_area
# Orientation Angle
angle = angles[m*cellx + i, n*celly+j][0]
# (-pi,pi) to (0, 2*pi)
if angle < 0:
angle += 2 * pi
nth_bin = floor(float(angle/BIN_RANGE))
HOG[((m * n_divs + n) * n_bins + int(nth_bin))] += norm_grad
return HOG.transpose()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:13:19.520",
"Id": "73678",
"Score": "2",
"body": "Can you add the missing `import` statements so that this is runnable, please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:18:57.063",
"Id": "73680",
"Score": "0",
"body": "@GarethRees, done, sorry about that! Naturally, you'll still need to import `SimpleCV` and create an `Image` instance to pass to the function. I suggest doing so as follows: `img = SimpleCV.Image('lenna')`. Also note, that doing `from SimpleCV import *` will handle all imports correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:29:23.577",
"Id": "73843",
"Score": "0",
"body": "Hello. :) You need to profile your code to know where the bottleneck is, and to see whether you can improve things or not. Maybe you're spending a lot of time in SimpleCV or OpenCV. Unfortunately, \"it looks like the for loop is slow\" doesn't help much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T06:58:58.337",
"Id": "74022",
"Score": "0",
"body": "@QuentinPradet, I did in fact profile using iPython's `%prun` magic -- I should have mentioned that. The reason I point directly to the for-loop iteration is because the function responsible for the most cumulative execution time is `math.floor`, which is called exactly once per loop, and the number of calls to said function matches the number of loop iterations. I'll try GarethRees' vectorization approach and post a more detailed profiler output if needed."
}
] | [
{
"body": "<p>As you indicated in the question, you need to vectorize the <code>for</code> loop:</p>\n\n<pre><code>it = product(xrange(n_divs), xrange(n_divs), xrange(cellx), xrange(celly))\nfor m, n, i, j in it:\n # grad value\n grad = magnit[m * cellx + i, n * celly + j][0]\n # normalized grad value\n norm_grad = grad / img_area\n # Orientation Angle\n angle = angles[m*cellx + i, n*celly+j][0]\n # (-pi,pi) to (0, 2*pi)\n if angle < 0:\n angle += 2 * pi\n nth_bin = floor(float(angle/BIN_RANGE))\n HOG[((m * n_divs + n) * n_bins + int(nth_bin))] += norm_grad\n</code></pre>\n\n<p>If you look at what this is doing, you're effectively labelling every pixel in the <code>magnit</code> array with a number below <code>n_HOG</code>, and then summing the normalized values for the pixels with each label.</p>\n\n<p>Operations on labelled regions of images are jobs for the <a href=\"http://docs.scipy.org/doc/scipy/reference/ndimage.html#module-scipy.ndimage.measurements\"><code>scipy.ndimage.measurements</code></a> module. Here we can use <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.measurements.sum.html\"><code>scipy.ndimage.measurements.sum</code></a>:</p>\n\n<pre><code>bins = (angles[...,0] % (2 * pi) / BIN_RANGE).astype(int)\nx, y = np.mgrid[:width, :height]\nx = x * n_divs // width\ny = y * n_divs // height\nlabels = (x * n_divs + y) * n_bins + bins\nindex = np.arange(n_HOG)\nHOG = scipy.ndimage.measurements.sum(magnit[...,0], labels, index)\nreturn HOG / img_area\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li><p>I've used <code>% (2 * pi)</code> to get the angles in the range [0, 2π). An alternative that's more like your code would be <code>angles[angles < 0] += 2 * pi</code> but using the modulus is shorter and, I think, clearer.</p></li>\n<li><p>I postponed the division by <code>img_area</code> until after the summation, because it looks to me as though in the common case <code>n_HOG</code> is much less than <code>img_area</code> and so it's cheaper to do the division later when there are fewer items. (This means that the results differ very slightly from your code, so bear that in mind when checking.)</p></li>\n<li><p>I measure the vectorized version as being about 60 times faster than your <code>for</code> loop, but it's still not going to be fast enough to run at 30 fps!</p></li>\n<li><p>I've written <code>angles[...,0]</code> and <code>magnit[...,0]</code> here in order to drop the third axis. But I think it would make more sense if you dropped this axis earlier, before computing <code>angles</code> and <code>magnit</code>, by writing <code>Ix = Ix[...,0]</code> or just <code>Ix = Ix.reshape((height, width))</code> if you know that the last axis has length 1.</p></li>\n</ol>\n\n<h3>Update</h3>\n\n<p>Based on comments, it looks as if you are using Python 2.7, where the division operator <code>/</code> takes the floor of the result if both arguments are integers. So I've changed the code above to use:</p>\n\n<pre><code>x = x * n_divs // width\ny = y * n_divs // height\n</code></pre>\n\n<p>which is portable between Python 2 and Python 3, and simpler than my first attempt:</p>\n\n<pre><code>x = (x / width * n_divs).astype(int)\ny = (y / height * n_divs).astype(int)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T07:00:40.030",
"Id": "74023",
"Score": "0",
"body": "Fantastic! Thank you so much! I'll give this a whirl later on today and come back with questions if I have any."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T09:44:29.133",
"Id": "74033",
"Score": "0",
"body": "I've tried running your example and I'm getting zero values for all but the first 6 cells of the output array. Would you mind checking my implementation? I'm not quite sure what the problem could be. The vectorized approach is implemented in the function named `findHOGFeaturesVect`: http://paste.ubuntu.com/7004183/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T10:52:15.827",
"Id": "74037",
"Score": "0",
"body": "Are you using Python 2? If so, see the revised answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T19:10:32.503",
"Id": "110933",
"Score": "0",
"body": "@blz can you copy the final working optimized code as an answer here?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T01:28:00.847",
"Id": "42916",
"ParentId": "42763",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "42916",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:05:44.447",
"Id": "42763",
"Score": "7",
"Tags": [
"python",
"performance",
"image",
"numpy",
"opencv"
],
"Title": "\"Histogram of Oriented Gradients\" (HOG) feature detector for computer vision"
} | 42763 |
<p>I've two table (<code>t1</code> and <code>t2</code>) with 3 identical integer columns: <code>c1</code>, <code>c2</code> and <code>c3</code>. I want to count how many value in <code>t1</code> are in <code>t2</code>.</p>
<pre><code>SELECT count(t1.value) FROM t1 INNER JOIN t2 ON (
t1.c1 = t2.c1 OR t1.c1 = t2.c2 OR t1.c1 = t2.c3 OR
t1.c2 = t2.c1 OR t1.c2 = t2.c2 OR t1.c2 = t2.c3 OR
t1.c3 = t2.c1 OR t1.c3 = t2.c2 OR t1.c3 = t2.c3
)
</code></pre>
<p>It doesn't seems a good way to write it (I'll have to add some columns). Is there a better solution to write it without enumerated any possibilities?</p>
<p>I'm using MySQL version 5.6.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:46:26.753",
"Id": "73695",
"Score": "0",
"body": "If t1 contains `c1 = 1, c2 = 1, and c3 = 2` and the t2 has the values `1` and `2` *somewhere*, should that count as 1, 2, or 3 in the final total?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:52:32.643",
"Id": "73697",
"Score": "0",
"body": "I forget : `t1.c1`, `t1.c2` and `t1.c3` are all different. Idem for t2. So your example @rolfl should count **2**."
}
] | [
{
"body": "<p>Your question is not very clear... but, the way I understand it is:</p>\n\n<p>Collect all the unique values in <code>t1</code>, and count how many of those unique values appear in <code>t2</code>.</p>\n\n<p>Interesting problem.... instead of a straight join with all the <code>or</code> conditions, which may lead to an internal cross-product (thousands of joins and results to run comparisons on), I would state the logic as a couple of subselects ... which represent the two sets of data... the unique values in t1, and the unique values in t2.</p>\n\n<p>Note, the 'union' operator does a distinct as part of the union....</p>\n\n<pre><code>select count(*)\nfrom\n (\n select c1 as val from t1\n union\n select c2 as val from t1\n union\n select c3 as val from t1\n ) as t1vals,\n (\n select c1 as val from t2\n union\n select c2 as val from t2\n union\n select c3 as val from t2\n ) as t2vals\nwhere t1vals.val = t2vals.val\n</code></pre>\n\n<p>The code looks nicer this way, but requires scanning each table three times (which I think will be better than the potentially thousands of times it may have to happen with your query......</p>\n\n<h2><a href=\"http://www.sqlfiddle.com/#!2/e87ca8/2/0\" rel=\"nofollow\">I have put together an sqlfiddle for this</a></h2>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T08:45:20.263",
"Id": "73847",
"Score": "0",
"body": "It works fine, this is a good idea. It´s quite better than enumerate like I done, but it´s not factorized yet (maybe it´s not possible). Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:06:06.977",
"Id": "42776",
"ParentId": "42766",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "42776",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:49:14.540",
"Id": "42766",
"Score": "3",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Check for similar value with SQL"
} | 42766 |
<p>I have some function like:</p>
<pre><code>void foo() { ... }
int main() {
...
try {
...
foo();
...
} catch (const std::exception &e) {
std::cout << "Fatal error: e.what() << std::endl();
return;
}
...
}
</code></pre>
<p>If an exception is thrown from <code>foo</code>, I'd like to know it. Also I want to know the reason of the original exception. I can split the code like this:</p>
<pre><code>int main() {
...
try {
...
} catch (const std::exception &e) {
std::cout << "Fatal error: " << e.what() << std::endl;
return;
}
try {
foo();
} catch (const std::exception &e) {
std::cout << "Fatal error (foo): " << e.what() << std::endl;
return;
}
try {
...
} catch (const std::exception &e) {
std::cout << "Fatal error: " << e.what() << std::endl;
return;
}
...
}
</code></pre>
<p>It doesn't look good. Instead, I can update <code>foo</code>:</p>
<pre><code>void foo()
{
try {
..
} catch (const std::exception &) {
std::cout << "Foo failed. The reason is:" << std::endl;
throw;
}
}
</code></pre>
<p>However, I do not like solution, too (maybe, because error logging is split). What is the right way to raise the exception upward?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:34:43.957",
"Id": "73691",
"Score": "0",
"body": "I'd go for the last one. As it has the least chance of creating weird issues. However, I'd not ever throw (then again, I never used C++ Exceptions, just Python and Java). \n\nAnd I've used it in the Better-to-Ask-Forgiveness kind of way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:51:55.683",
"Id": "73696",
"Score": "0",
"body": "Is this for exceptions which you throw, or for exceptions which are thrown by the STL?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T20:49:08.170",
"Id": "73768",
"Score": "0",
"body": "@ChrisW - It's some exception inherited from `std::exception` (mostly `std::runtime_error`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T12:09:54.550",
"Id": "74044",
"Score": "1",
"body": "I'd use Boost.Exception (http://www.boost.org/doc/libs/1_55_0/libs/exception/doc/boost-exception.html), which allows you add information in the exception. In particular, see the \"Nesting Exception\" last paragraph of http://www.boost.org/doc/libs/1_55_0/libs/exception/doc/exception_ptr.html."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T14:13:52.677",
"Id": "74061",
"Score": "0",
"body": "@ddevienne - Thank you. Interesting idea. I'll try to implement this approach myself. Unfortunately, I do not know `Boost.Exceptions` enough. May be somebody else can implement it."
}
] | [
{
"body": "<p>You can re-throw an exception:</p>\n\n<pre><code>int main() {\n ... \n try {\n ...\n try\n {\n foo();\n }\n catch(std::exception const& e) {\n std::cout << \"Fatal error: \" << e.what() << std::endl;\n\n throw; // re-throw the exception.\n // or you could throw a different exception.\n }\n ... \n } catch (const std::exception &e) {\n std::cout << \"Fatal error: \" << e.what() << std::endl;\n return; \n }\n ... \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T17:59:43.907",
"Id": "42789",
"ParentId": "42767",
"Score": "7"
}
},
{
"body": "<p>Instead of ...</p>\n\n<ul>\n<li>Catching the exception</li>\n<li>Printing a message</li>\n<li>Returning gracefully (from main)</li>\n</ul>\n\n<p>... you can ...</p>\n\n<ul>\n<li>Not catch the exception</li>\n<li>Print a stack trace</li>\n<li>Abort execution</li>\n</ul>\n\n<p>I'm not sure you can print the type of exception (using the <code>what()</code> method) if you do this, but a stack trace tells you not only that it happened inside <code>foo</code> but also in which subroutine of <code>foo</code>.</p>\n\n<p>A <a href=\"https://www.google.com/search?q=C%2B%2B+exception+stack+trace\" rel=\"nofollow noreferrer\">Google search</a> suggests how to get a stack trace from a C++ exception; for example <a href=\"http://oroboro.com/stack-trace-on-crash/\" rel=\"nofollow noreferrer\">this article</a> looks useful (you'll get more-specific information if you specify a specific O/S in your Google search).</p>\n\n<p>Advantages of this over catching an exception are:</p>\n\n<ul>\n<li>Don't clutter your code with <code>catch</code> statements</li>\n<li>A complete (deep) stack trace may be more useful than just knowing that it happened somewhere inside <code>foo</code></li>\n</ul>\n\n<p>(This may not work: <a href=\"https://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c#comment2499431_2445569\">this comment</a> says that it's implementation-defined whether the stack is unwound before the terminate handler is called.)</p>\n\n<hr>\n\n<p>If you're catching exceptions which you throw yourself, then you can have the best of both worlds (a <code>catch</code> and a stack trace): define a type of exception which captures a stack trace in its constructor (when it's thrown), then you can print the stack trace when you catch it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:09:26.430",
"Id": "42810",
"ParentId": "42767",
"Score": "4"
}
},
{
"body": "<p>Here I assume you want to handle exceptions from different fragments/classes inside main and take action accordingly.</p>\n\n<p>You can use Macros to create new Exception and throw the exception to differentiate exceptions in case you have to differentiate.</p>\n\n<pre><code>#define CREATE_EXCEPTION(EXCEPTION_NAME) \\\nclass EXCEPTION_NAME : public std::exception \\\n{ \\\n std::string msg; \\\n public: \\\n EXCEPTION_NAME(std::string mesg):msg(mesg){} \\\n std::string getMessage(){ return msg;}\\\n ~EXCEPTION_NAME()throw (){}\\\n}; \n#define CATCH_THROW_EXCEPTION(CATCH_EXCEPTION,THROW_EXCEPTION) \\\n catch (CATCH_EXCEPTION &e) { \\\n std::cout << \"Foo failed. The reason is:\" << std::endl; \\\n throw THROW_EXCEPTION(e.what()); \\\n }\n\nCREATE_EXCEPTION(Foo_Exception);\nvoid foo()\n{\n try {\n ..\n }\n CATCH_THROW_EXCEPTION(std::exception,FOO_EXCEPTION) \n }\n}\n\nint main() {\n ...\n try {\n ...\n foo();\n ...\n } \n catch (Foo_Exception &e) {\n std::cout << \"Fatal error:\"<< e.getMessage() << std::endl;\n return;\n }\n catch (const std::exception &e) {\n std::cout << \"Fatal error: \"<< e.what() << std::endl;\n return;\n }\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T11:43:53.653",
"Id": "42951",
"ParentId": "42767",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:54:33.463",
"Id": "42767",
"Score": "5",
"Tags": [
"c++",
"exception-handling",
"exception",
"logging"
],
"Title": "How to chain exceptions?"
} | 42767 |
<p>Is there any way to make that code shorter? I still want to use jQuery. I don't want to use any validation script.</p>
<pre><code>$("#form").submit(function (e) {
var tmp = $('#select-1').val();
var tmp1 = $('#select-2').val();
var tmp2 = $('#select-3').val();
var error = $('#error-1');
var error2 = $('#error-2');
var error3 = $('#error-3');
if (tmp == '0' || tmp == 'Select') {
e.preventDefault();
error.show();
} else {
error.hide();
}
if (tmp1 == '0' || tmp1 == 'Select') {
e.preventDefault();
error2.show();
} else {
error2.hide();
}
if (tmp2 == '0' || tmp2 == 'Select') {
e.preventDefault();
error3.show();
} else {
error3.hide();
}
});
});
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><form action="" id="form">
<div>
<label for="select-1">Value 1</label>
<select id="select-1">
<option value="0">Select</option>
<option value="1">Select 1</option>
<option value="2">Select 2</option>
<option value="3">Select 3</option>
</select>
<i id="error-1" class="error">Error</i>
</div>
<div>
<label for="select-2">Value 2</label>
<select id="select-2">
<option value="0">Select</option>
<option value="1">Select 1</option>
<option value="2">Select 2</option>
<option value="3">Select 3</option>
</select>
<i id="error-2" class="error">Error</i>
</div>
<div>
<label for="select-3">Value 3</label>
<select id="select-3">
<option value="0">Select</option>
<option value="1">Select 1</option>
<option value="2">Select 2</option>
<option value="3">Select 3</option>
</select>
<i id="error-3" class="error">Error</i>
</div>
<div> <button type="submit" id="formsubmission">Submit</button></div>
</form>
</code></pre>
| [] | [
{
"body": "<p>You could hide the errors to begin with (just put <code>style=\"display: none;\"</code> on them), then you don't have to hide them in your script. Also you can group your variable declarations:</p>\n\n<pre><code>$(\"#form\").submit(function (e) {\n var tmp = $('#select-1').val(),\n tmp1 = $('#select-2').val(),\n tmp2 = $('#select-3').val(),\n error = $('#error-1'),\n error2 = $('#error-2'),\n error3 = $('#error-3');\n if (tmp == '0' || tmp == 'Select') {\n e.preventDefault();\n error.show();\n }\n if (tmp1 == '0' || tmp1 == 'Select') {\n e.preventDefault();\n error2.show();\n }\n if (tmp2 == '0' || tmp2 == 'Select') {\n e.preventDefault();\n error3.show();\n }\n});\n</code></pre>\n\n<p>If you want to shorten it even further, you can just check for \"falsy\" values:</p>\n\n<pre><code>$(\"#form\").submit(function (e) {\n var tmp = $('#select-1').val(),\n tmp1 = $('#select-2').val(),\n tmp2 = $('#select-3').val(),\n error = $('#error-1'),\n error2 = $('#error-2'),\n error3 = $('#error-3');\n if (!tmp) {\n e.preventDefault();\n error.show();\n }\n if (!tmp1) {\n e.preventDefault();\n error2.show();\n }\n if (!tmp2) {\n e.preventDefault();\n error3.show();\n }\n});\n</code></pre>\n\n<p>Finally, if you can combine your error messages:</p>\n\n<pre><code>$(\"#form\").submit(function (e) {\n var tmp = $('#select-1').val(),\n tmp1 = $('#select-2').val(),\n tmp2 = $('#select-3').val(),\n error = $('#error-1');\n if (!tmp || !tmp1 || !tmp2) {\n e.preventDefault();\n error.show();\n }\n});\n</code></pre>\n\n<p>Actually, the variables aren't necessary at all if you are just checking for nulls:</p>\n\n<pre><code>$(\"#form\").submit(function (e) {\n if (!$('#select-1').val() || !$('#select-2').val() || !$('#select-3').val()) {\n e.preventDefault();\n $('#error-1').show();\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:57:27.723",
"Id": "42775",
"ParentId": "42770",
"Score": "3"
}
},
{
"body": "<p>your html has pattern, so it might be easier if you do this way.</p>\n\n<pre><code>(function ($) {\n $.fn.xSelect = function (e) {\n return this.each(function () {\n var $this = $(this);\n if ($this.val() === '0') {\n e.preventDefault();\n $this.next(\".error\").show();\n }else{\n $this.next(\".error\").hide();\n }\n });\n };\n})(jQuery);\n</code></pre>\n\n<p>then use like</p>\n\n<pre><code>$(\"#form\").submit(function (e) {\n\n $(\"#select-1,#select-2,#select-3\").xSelect(e);\n\n}); \n</code></pre>\n\n<p>notice one thing: the event \"e\" need to pass in xSelect to make preventDefault work.</p>\n\n<p>for the better design. the parameter of jQuery plugin should be a JSON object,so you can make more options. this just give you idea how it's done.</p>\n\n<p>please check my jsfiddle example: <a href=\"http://jsfiddle.net/p4e8y/\" rel=\"nofollow\">jsfiddle</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T00:07:06.283",
"Id": "42827",
"ParentId": "42770",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "42827",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:27:55.033",
"Id": "42770",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"validation"
],
"Title": "Select validation"
} | 42770 |
<p>I am a beginner in PHP-OOP and design patterns. I have got this basic piece of code in <a href="https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5">Singleton Pattern</a> and I changed it in order to understand its behavior. I can see that it works as expected.</p>
<p>However, it is not clear for me exactly how it works. Can anyone explain me? So it is working! My doubt is "Whis <code>$inst</code> is not always null in the <code>if</code> since I am defining it <code>null</code> before entering the <code>if</code>"?</p>
<pre><code><?php
final class UserFactory // "final" prevents child classes from overriding a method by prefixing the definition
{
private $state=1;
/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new UserFactory();
}
return $inst;
}
private function __construct()
{
}
public function addToState(){
$this->state=$this->state+1;
}
public function getState(){
return $this->state;
}
}
// $myFactory=new UserFactory(); //Throws an error
$myFactory=UserFactory::Instance();
print_r($myFactory);
echo "<br>";
echo 'myState: '.$myFactory->getState()."<br>";
$myFactory->addToState();
echo 'myState: '.$myFactory->getState()."<br>";
$myFactory2=UserFactory::Instance();
print_r($myFactory2);
?>
</code></pre>
<p>The output is:</p>
<pre><code>UserFactory Object ( [state:UserFactory:private] => 1 )
myState: 1
myState: 2
UserFactory Object ( [state:UserFactory:private] => 2 ) UserFactory Object ( [state:UserFactory:private] => 2 )
</code></pre>
| [] | [
{
"body": "<p>You're misunderstanding how the <a href=\"http://us1.php.net/manual/en/language.oop5.static.php\">static</a> keyword works.</p>\n\n<p>The first time it is encountered for a specific variable in the method it defines the <code>$inst</code> variable as <code>null</code>, then checks to see if it is <code>null</code> (it is :p) and then sets it to a new object of that class.</p>\n\n<p>The second time, the static definition isn't used because the static variable has already been defined. It then checks to see if it is <code>null</code>, it isn't, it has already been set to a new object of the class, so it skips the if and returns the object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:51:19.780",
"Id": "42774",
"ParentId": "42771",
"Score": "8"
}
},
{
"body": "<p>You're asking a rather specific coding question, and not actually for your code to be reviewed. However, I'm going to, because if you want to learn OOP, you might aswell learn what <em>not</em> to do.</p>\n\n<p>Your basic question is answered <a href=\"https://codereview.stackexchange.com/tags/static/info\">in the static-tag wiki</a> which, <em>cough</em> I wrote <em>cough</em>.<Br>\nBe that as it may, your singleton implementation still has a few omissions:</p>\n\n<ul>\n<li>You can't safely add a second static method</li>\n<li>I can still clone the instance</li>\n<li><code>$state</code> is an unreliable variable</li>\n<li>Singletons in PHP are pointless, untestable, anti-patterns. Don't use them</li>\n<li>Choose: OO or globals, don't serve globals in an OO sauce</li>\n</ul>\n\n<p><em>Second static method:</em><Br>\nIf I add a second static method, that may require access to a non-static method (<code>public static getCurrentState() { /* check if there's an instance already, call getState on that instsance or return 0 */ }</code> for example), that method won't have access to the <code>$inst</code> variable.<br>\nGenerally, singletons have a <em>static property</em> that holds an instance:</p>\n\n<pre><code>class Singleton\n{\n private static $inst = null;\n private $state = null;//<-- why 1?\n\n private function __construct()\n {\n $this->state = 0;\n }\n public static function getInstance()\n {\n if (static::$inst === null)\n {\n static::$inst = new Singleton();\n }\n static::$inst->state += 1;//update refcount here\n return static::$inst;\n }\n public static function getStateCount()\n {\n if (static::$inst === null)\n return 0;\n static::$inst->state;//no need to call a getter, we're in the right scope for private access\n }\n}\n</code></pre>\n\n<p>Great, so now all static (and non-static) methods have access to the <code>$inst</code> property, and we can use that variable in all methods. Since all methods will, by definition, be defined <em>within the class</em>, they have access to private properties anyway, so we don't need getters and setters. We can just access the properties directly (which is faster).</p>\n\n<p><em>Cloning a singleton shouldn't be possible</em><br>\nNow imagine your object actually does something even mildly important. For example, a Singleton is sometimes (ab-)used for DB connections, what would be the result of doing this:</p>\n\n<pre><code>$db = Singleton::getInstance();//as you'd expect $db is now an object\n$clone = clone $db;//You're in trouble!\n</code></pre>\n\n<p>That's why Singletons often implement the magic <code>__clone</code> method (along with other magic methods):</p>\n\n<pre><code>public function __clone()\n{//make singleton un-clonable\n return false;\n //or even:\n throw new RuntimeException('You cannot clone a singleton, hooligan!');\n}\n</code></pre>\n\n<p>Do the same for <code>__toString</code>, <code>__sleep</code> and other magic methods.<Br>\nOk, now we've sorted that out, onwards:</p>\n\n<p><em><code>$state</code> is unreliable:</em><br>\nBecause <code>$state</code> can't be decremented (or no code to decrement it is provided), and because your singleton is clone-able, the value of <code>$state</code> isn't guaranteed to be shared between all instances. Solving the clone issue addresses this, as does making the property <code>static</code>, too. But really, as I'm going to explain now: <em>avoid <code>static</code> whenever you can</em>.</p>\n\n<p><em>Singleton and PHP is pointless:</em><Br>\nPHP is, essentially, stateless. <code>Static</code> and singletons along with it enable you to persist something, to retain a state. But retaining state in a stateless environment is like placing an empty bottle in a fridge: it still won't give you something cool to drink.</p>\n\n<p>Each request that executes your code starts with a blank slate, and your singleton will be re-initialized. Couple that to the fact that static properties and methods are (marginally) slower, and you end up with pointless overhead.<br>\nIf you don't want a second instance of class X, <em>don't create a second instance</em>. Think when writing code, don't write code that sort of <em>fixes</em> coding errors on your part.</p>\n\n<p>Testing a singleton is a nightmare, google <em>\"PHP test singleton\"</em> and read a few articles. It's a well documented downside that will soon have you steer clear of this anti-pattern.</p>\n\n<p><em>Globals in OO drag</em><br>\nSingletons (and basically all statics), then, what do they do: They couple state (data, variables) and functionality (in the form of methods) together, without the safety and flexibility of an actual instance.<Br>\nA static method actually <em>is</em> a global function, that calls on some data (in the form of static properties it can access) to do its job. That's what makes code that uses a lot of <code>static</code>'s harder to maintain and understand.</p>\n\n<p>If you want functionality that requires, for example, a DB connection: use an object that does just that. It's safer, you know that if something fails where to look and it is more flexible, simply because <em>you can pass an instance to other methods/functions as an argument</em>.</p>\n\n<p>If you use <code>ClassName::staticMethod()</code>, you're writing code that looks OO, but could just aswell be written like this: <code>globalFunction($dbConnection, $param);</code>.<br>\nWhereas <em>true</em> OO code would look like this:</p>\n\n<pre><code>$service->queryUsers($dbInstance, $userStatus);\n</code></pre>\n\n<p>The <code>queryUsers</code> method could look like this, then:</p>\n\n<pre><code>public function queryUsers(DBConnection $db, $status = self::USER_ACTIVE)\n{\n if (!in_array($status, $this->acceptedStatusses)\n throw new InvalidArgumentException('Invalid user-status');\n\n return $db->query('SELECT * FROM user WHERE userStatus = '.$status)\n ->fetchResults();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T07:57:29.810",
"Id": "42847",
"ParentId": "42771",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "42774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T15:35:26.713",
"Id": "42771",
"Score": "6",
"Tags": [
"php",
"beginner",
"object-oriented",
"singleton",
"static"
],
"Title": "Singleton design pattern"
} | 42771 |
<h2>The Setup</h2>
<p>This kata is a spin on the old backpack problem. Please give feedback on both the kata itself as well as my solution. I'm not sure if the kata needs to lead the student more or if this is a good open-ended problem. My original intent with this kata was to practice using Hashes. This is why the output is required to be in the form of a hash. That detail led me to create the Change class which inherits from Hash. I think of this as an implementation detail of my solution but I'm considering making it part of the kata. Thanks for your input/reading.</p>
<h2>The Kata</h2>
<pre><code>CashRegister Kata
Create a CashRegister class
- detail: It that is initialized with an Array of Integers
- detail: Each integer in the array represents the value of a type of coin in the cash register
- detail: You can assume that there are an infinite number of coins in the cash register
- detail: The cash register should default to 25, 10, 5 and 1 cent pieces, if no argument is provided.
- detail: The cash register should throw an error if it initialized with an argument that is not an array of integers
- example: CashRegister.new([25,10,5,1])
completed (Y|n):
Create a make_change() method
- detail: It takes an positive integer as an argument.
- detail: It returns a hash showing the smallest combination of coins which sum to that number.
- detail: If a non integer argument is passed in, make_change() should throw an error.
- detail: The hash should have an entry for every coin in the cash register.
- detail: If a coin is not used, it's value should be zero.
- example: CashRegister.new().make_change(123) evaluates to: {'25' => 4, '10' => 2, '5' => 0, '1' => 3}
- example: CashRegister.new([10,7,1]).make_change(14) evaluates to: {'10' => 0, '7' => 2, '1' => 0}
completed (Y|n):
Congratulations!
- Create a CashRegister class 00:21:08
- Create a make_change() method 01:12:09
---------------------------------------------------------------------- --------
Total Time taking CashRegister kata: 01:33:17
</code></pre>
<h2>The Specs</h2>
<pre><code> 1 require 'spec_helper'
2 require 'cashregister'
3
4 describe CashRegister do
5 describe "#new" do
6 subject(:cash_register) { CashRegister.new }
7 let(:bad_argument) { 'A' }
8 let(:bad_array_argument) { [10, 5, 'A', 'B', 'C'] }
9
10 it "should instantiate" do
11 expect { CashRegister.new }.to_not raise_exception
12 end
13 it 'should default to 25,10,5,1' do
14 CashRegister.new.coins.should eq([25,10,5,1])
15 end
16 it 'should reset the coins without reinitialization' do
17 cash_register = CashRegister.new
18 cash_register.coins = [10,5]
19 cash_register.coins.should eq([10,5])
20 end
21 it 'should take an Array of Integers as an argument' do
22 expect { CashRegister.new([25,10,5,1]) }.to_not raise_exception
23 end
24 it 'should throw an error with a bad argument' do
25 expect { CashRegister.new(bad_argument) }.to raise_exception
26 end
27 it 'should throw an error with a bad array argument' do
28 expect { CashRegister.new(bad_array_argument) }.to raise_exception
29 end
30 end
31
32 describe '.make_change()' do
33 subject(:make_change) { cash_register.make_change(amount) }
34 let(:cash_register) { CashRegister.new(coins) }
35 let(:coins) { [25,10,5,1] }
36 let(:amount) { 123 }
37
38 it { should eq({25 => 4, 10 => 2, 5 => 0, 1 => 3}) }
39
40 context 'crazy foreign coins' do
41 let(:coins) { [10,7,1] }
42 let(:amount) { 14 }
43
44 it { should eq({10 => 0, 7 => 2, 1 => 0}) }
45 end
46
47 context 'can\'t make change' do
48 let(:coins) { [2] }
49 let(:amount) { 3 }
50
51 it { should be_nil }
52 end
53
54 context 'memoized zero case' do
55 let(:amount) { 0 }
56
57 it { should eq({25 => 0, 10 => 0, 5 => 0, 1 => 0}) }
58 end
59
60 context 'memoized base case' do
61 let(:amount) { 5 }
62
63 it { should eq({25 => 0, 10 => 0, 5 => 1, 1 => 0}) }
64 end
65 context 'memoized base case' do
66 let(:amount) { 6 }
67
68 it { should eq({25 => 0, 10 => 0, 5 => 1, 1 => 1}) }
69 end
70 end
71 end
72
73 describe Change do
74 subject!(:change) { Change.new(coins) }
75 let(:coins) { [25,10,5,1] }
76
77 describe '#new' do
78
79 it 'should instantiate' do
80 expect { change }.to_not raise_exception
81 end
82 it { should eq({25 => 0, 10 => 0, 5 => 0, 1 => 0}) }
83 end
84
85 describe '.add' do
86 it 'adds coins to the Hash' do
87 change.add(25).should eq({25 => 1, 10 => 0, 5 => 0, 1 => 0})
88 end
89 end
90
91 describe '.value' do
92 its(:value) { should eq(0) }
93
94 it 'is 25 when there is one quarter' do
95 change.add(25).value.should eq(25)
96 end
97 end
98
99 describe '.count' do
100 its(:count) { should eq(0) }
101
102 it 'counts the number of coins' do
103 change.add(25).count.should eq(1)
104 change.add(25).add(10).count.should eq(2)
105 end
106 end
107 end
</code></pre>
<h2>The Code</h2>
<pre><code> 1 class CashRegister
2 attr_reader :coins
3
4 def coins=(coins=[25,10,5,1])
5 if (
6 coins.class != Array ||
7 coins.map { |coin| coin.class.ancestors.include?(Integer) }.include?(false)
8 )
9 raise Exception
10 end
11
12 @optimal_change = Hash.new do |hash, key|
13 hash[key] =
14 if (key < coins.min)
15 Change.new(coins)
16 elsif (coins.include?(key))
17 Change.new(coins).add(key)
18 else
19 coins.map do |coin|
20 hash[key - coin].add(coin)
21 end.reject do |change|
22 change.value != key
23 end.min { |a,b| a.count <=> b.count }
24 end
25 end
26
27 @coins = coins
28 end
29
30 alias :initialize :coins=
31
32 def make_change(amount)
33 return(@optimal_change[amount])
34 end
35 end
36
37 class Change < Hash
38 def initialize(coins)
39 coins.map do |coin|
40 self.merge!({coin => 0})
41 end
42 end
43
44 def add(coin)
45 self.merge({coin => self[coin] + 1})
46 end
47
48 def value
49 self.map do |key, value|
50 key.to_i * value
51 end.reduce(:+)
52 end
53
54 def count
55 self.values.reduce(:+)
56 end
57 end
</code></pre>
| [] | [
{
"body": "<p><strong>Duck typing</strong> - the ruby language is duck-typed, and should be written that way. Checks on an object's class are frowned upon. If something wants to be an integer, and is prepared to go the distance - don't discourage it! I understand that the requirement says 'should throw an error if it initialized with an argument that is not an <em>array</em> of integers', so I guess for the sake of argument asking <code>coins.is_a?(Array)</code> is OK, but for the numbers themselves, a more rubyish way of asking would be:</p>\n\n<pre><code>raise Exception unless coins.is_a?(Array) && coins.all?(&:integer?)\n</code></pre>\n\n<p>I like the way you fill the <code>@optimal_change</code> hash, though I wish you had named your parameters better - <code>key</code> is an obfuscated choice. Also, you could have refactored it into a method</p>\n\n<p><a href=\"http://ruby.learncodethehardway.org/book/ex44.html\" rel=\"nofollow\"><strong>Having is not inheriting</strong></a> - Your <code>Change</code> class is curious - you opted for it to inherit from <code>Hash</code> instead of <em>having</em> a <code>Hash</code>, and then you override <code>count</code> to do something not very Hash-y... The names you chose for this class are very generic and obfuscated... I would have written that class like this:</p>\n\n<pre><code>class Change\n def initialize(coins = Hash.new(0))\n @coins = coins\n @coins.default = 0\n end\n\n # changes the value of this instance\n def add!(coin)\n @coins[coin] = @coins[coin] + 1\n self\n end\n\n # does not change the value of this instance\n def add(coin)\n Change.new(@coins.dup).add!(coin)\n end\n\n def total_value\n @coins.map { |coin, number| coin * number }.reduce(:+)\n end\n\n def coin_count\n @coins.values.reduce(:+)\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T01:10:20.630",
"Id": "73817",
"Score": "0",
"body": "Great answer. I actually did rename the Hash parameters to 'optimal_change' and 'amount'. Definitely going to refactor it into a method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T20:52:18.137",
"Id": "42809",
"ParentId": "42779",
"Score": "3"
}
},
{
"body": "<p>Edit: I just completed changes to the code and explanation to fix problems that @Jonah spotted. Thanks, Jonah. I believe it is working correctly now, but I hope readers will let me know if they find any other problems. </p>\n\n<p>I have just a few comments about your code:</p>\n\n<ul>\n<li><p>the specs are quite good for testing the specified edge cases, but I think you might beef them up for testing whether the algorithm actually produces optimal solutions.</p></li>\n<li><p>I think you missed a few edge cases that were not called for, but are needed (see code below). I don't recall seeing what <code>make_change</code> returns when there is no way to change a particular amount. (I chose <code>nil</code>). </p></li>\n<li><p>When raising an exception, make it more specific (e.g, <code>ArgumentError</code>) and include an explanatory message.</p></li>\n<li><p>in the <code>Change</code> class, none of the <code>self.</code>'s are needed. When no receiver is specified, the default is <code>self</code>. There are only a couple of situations where you need to preface a method being referenced (as opposed to a class method being defined) with <code>self.</code>. One is where you wish to reference an instance variable with an accessor, as <code>self.ivar = 7</code>. Without <code>self.</code>, Ruby would assume <code>ivar</code> is a local variable. The other situation is where you need to convert an instance to its class, as <code>self.class.my_cl_method</code>. <code>self.</code> is required here to tell Ruby you mean the <code>class</code> method rather than the <code>class</code> keyword.</p></li>\n<li><code>Change#value</code> can be simplified a little: <code>def value; reduce(0) { |t,(k,v)| t + k.to_i * v }; end</code>.</li>\n<li>I had difficulty following the <code>CashRegister#make_change</code>, but it doesn't appear to implement a dynamic programming algorithm, though you did observe that that ('knapsack') is what is needed. [Edit: I was incorrect about that. I just didn't understand that part of the code.] Please correct me if I am wrong about that.</li>\n<li>I ran a few tests with your code and in some cases it failed. Here's one: <code>CashRegister.new([2,5,12,18,35,36]).make_change(67)</code>. This raised an exception that indicated that <code>hash[key - coin]</code> in <code>hash[key - coin].add(coin)</code> was <code>nil</code>. (The solution is given below.)</li>\n<li>A few well-placed comments would have been helpful.</li>\n</ul>\n\n<p>Regarding the code that follows:</p>\n\n<ul>\n<li><p>I didn't see the need for a <code>Change</code> class, but I have no objection to there being one, though (as @Uri noted), there doesn't seem to be an advantage to subclassing <code>Hash</code>.</p></li>\n<li><p>I used recursion to obtain minimal change, but the problem does not intrinsically call for recursion; a loop would work as well, but I thought the use of recursion made it easier to understand what's going on.</p></li>\n</ul>\n\n<p>Here's an approach you could use:</p>\n\n<pre><code>class CashRegister\n def initialize(coins = [1,5,25,50])\n check_coins(coins)\n @coins = coins.reject(&:zero?)\n # All coins, if any are now positive\n end\n\n def make_change(amt)\n check_amt_to_change(amt)\n\n # Check edge cases\n return (amt.zero? ? {} : nil) if @coins.empty?\n return Hash[@coins.map(&:to_s).product([0])] if amt == 0\n return nil if @coins.max == 0\n coin = @coins.first\n return ((amt % coin).zero? ? {coin.to_s => amt/coin} : nil) if @coins.size == 1\n\n # To reach this point amt > 0 and @coins.size > 1\n\n # Construct hash to record solution. If the coins are c0, c1,...,cn, and x,\n # 0 <= x <= amt, change[ci][x] => {tot: t, ncoin: n}, where t equals the minimum\n # number of coins c0 through ci needed to change x and n is the number of coin ci\n # of that total. This is only computed for those values of x for which it is possible\n # to make change using coins c0 through ci. change is first computed for coin c0,\n # then for coins, c1, and so on. For the last coin, m = n-1, it is only necessary to\n # calculate change[cm][x] for x = amt.\n\n @change = {}\n\n # Compute @change for the first coin.\n coins = @coins.dup\n coin = coins.shift\n @change[coin] = (0..amt/coin).each_with_object({}) { |i,h|\n h[i*coin] = {tot: i, ncoin: i} }\n\n # Compute the solution for each of the remaining coins.\n minimum_change(amt, coin, coins)\n\n retrieve_solution(amt)\n end\n\n private\n\n def check_coins(coins)\n raise ArgumentError, \"arg in coins(arg) must be an array\" unless (coins.is_a? Array)\n raise ArgumentError, \"elements of of arr in coins(arr) must be non-negative integers\" \\\n unless coins.all? { |c| (c.is_a? Integer) && (c >= 0) }\n end\n\n def check_amt_to_change(amt)\n raise ArgumentError, \"amount to be changed must be a non-negative integer\" \\\n unless ((amt.is_a? Integer) && (amt >= 0))\n end\n\n def minimum_change(amt, last_coin, remaining_coins)\n coin = remaining_coins.shift\n first = (remaining_coins.empty? ? amt : 0)\n @change[coin] = (first..amt).each_with_object({}) do |x,h|\n best = nil\n (0..x/coin).each do |i|\n if (lc = @change[last_coin][x-i*coin])\n best = {tot: i+lc[:tot], ncoin: i} if (best.nil? || i+lc[:tot] < best[:tot])\n end\n end\n h[x] = best unless best.nil? \n end\n minimum_change(amt, coin, remaining_coins) if remaining_coins.any?\n end \n\n def retrieve_solution(amt)\n return nil if @change[@coins.last].empty?\n x = amt\n @coins.reverse.each_with_object({}) do |coin,h|\n k = @change[coin][x][:ncoin]\n h[coin.to_s] = k\n x -= k * coin\n end\n end\nend\n</code></pre>\n\n<p>Some test results</p>\n\n<pre><code>cr = CashRegister.new([1,5,10,25])\n amt\n 123 (9) => {\"25\"=>4, \"10\"=>2, \"5\"=>0, \"1\"=>3}\n 100 (4) => {\"25\"=>4, \"10\"=>0, \"5\"=>0, \"1\"=>0}\n 199 (13) => {\"25\"=>7, \"10\"=>2, \"5\"=>0, \"1\"=>4}\n 23 (5) => {\"25\"=>0, \"10\"=>2, \"5\"=>0, \"1\"=>3}\n 0 (0) => {\"1\"=>0, \"5\"=>0, \"10\"=>0, \"25\"=>0}\n\ncr = CashRegister.new([7,12,25,34]\n amt\n 68 (2) => {\"34\"=>2, \"25\"=>0, \"12\"=>0, \"7\"=>0}\n 233 (10) => {\"34\"=>1, \"25\"=>7, \"12\"=>2, \"7\"=>0}\n 848 (26) => {\"34\"=>22, \"25\"=>4, \"12\"=>0, \"7\"=>0}\n 47 (6) => {\"34\"=>0, \"25\"=>0, \"12\"=>1, \"7\"=>5}\n\ncr = CashRegister.new([2,5,12,18,35,36])\n amt\n 67 (4) => {\"36\"=>0, \"35\"=>1 , \"18\"=>1, \"12\"=>1, \"5\"=>0, \"2\"=>1}\n 233 (7) => {\"36\"=>5, \"35\"=>1 , \"18\"=>1, \"12\"=>0, \"5\"=>0, \"2\"=>0}\n 848 (24) => {\"36\"=>8, \"35\"=>16, \"18\"=>0, \"12\"=>0, \"5\"=>0, \"2\"=>0}\n 47 (2) => {\"36\"=>0, \"35\"=>1 , \"18\"=>0, \"12\"=>1, \"5\"=>0, \"2\"=>0}\n 3 (nil)\n\ncr = CashRegister.new([1,5,10,25,100,500,1000])\n amt\n 9332 (16) => {\"1000\"=>9, \"500\"=>0, \"100\"=>3, \"25\"=>1, \"10\"=>0, \"5\"=>1, \"1\"=>2}\n18445 (25) => {\"1000\"=>18, \"500\"=>0, \"100\"=>4, \"25\"=>1, \"10\"=>2, \"5\"=>0, \"1\"=>0}\n 9999 (23) => {\"1000\"=>9, \"500\"=>1, \"100\"=>4, \"25\"=>3, \"10\"=>2, \"5\"=>0, \"1\"=>4}\n 23 (5) => {\"1000\"=>0, \"500\"=>0, \"100\"=>0, \"25\"=>0, \"10\"=>2, \"5\"=>0, \"1\"=>3}\n 0 (0) => {\"1\"=>0, \"5\"=>0, \"10\"=>0, \"25\"=>0, \"100\"=>0, \"500\"=>0, \"1000\"=>0}\n\ncr = CashRegister.new([])\n amt\n 0 => {}\n 23 => # nil\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T21:44:18.700",
"Id": "74135",
"Score": "0",
"body": "Thanks Cary. These are great points. The dynamic programming is encapsulated here: `hash[key - coin].add(coin)`. The block argument to `Hash.new()` is executed if there is ever a mis in a hash lookup. So, each coin is added to the optimal change for the amount minus the value of the coin. This will recurse down until it bottoms out on one of the base cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T22:06:18.833",
"Id": "74145",
"Score": "0",
"body": "Re: `CashRegister.new([2,5,12,18,35,36]).make_change(67)`, This was due to not handling amounts < coins.min well. I took your advice and returned nil if change cannot be made. Then, added a few tests to make sure that change is not nil. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T03:30:46.707",
"Id": "74186",
"Score": "0",
"body": "You may wish to edit your question to add the corrected code, and to add a few comments to explain the algorithm you are using for the `make_change` calculation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T05:40:47.863",
"Id": "74219",
"Score": "0",
"body": "I'm confused by your spec for `67 => {\"36\"=>0, \"35\"=>1, \"18\"=>0, \"12\"=>2, \"5\"=>0, \"2\"=>4}`. I'm getting `{36=>0, 35=>1, 18=>1, 12=>1, 5=>0, 2=>1}`. What am I missing? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T06:01:19.210",
"Id": "74220",
"Score": "0",
"body": "@Jonah, it appears I'm the one missing something, namely a penny on `848 =>`. Also, I'm over by six cents on 233 =>, and some solutions aren't optimal. I'll fix it tomorrow. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T06:04:59.377",
"Id": "74221",
"Score": "0",
"body": "I'm also curious how fast this should be running. Ie, what the big oh of the optimal solution? Mine runs quick for the first set of test cases but was taking more than a few minutes for the second set with larger coins, and I just killed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T06:14:19.807",
"Id": "74223",
"Score": "0",
"body": "@Jonah, the number of operations is proportional to the product of the number of coins and the magnitude of the amount being changed. Did you get the different result you reported with my code, the asker's code or your own code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T06:18:07.767",
"Id": "74224",
"Score": "0",
"body": "I got that result with my own code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T05:02:16.960",
"Id": "74413",
"Score": "0",
"body": "@Jonah, I believe the code is now OK, but please let me know if your results are the same as mine. Same to you, user341493. Johan, you asked about solution times. Of all the tests that I ran, making change for 18445 took the longest (by a large margin), as you might expect. I didn't time it, but I'd guess it was around two minutes on a newish Macbook Pro."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T03:08:04.353",
"Id": "42923",
"ParentId": "42779",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "42809",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T16:37:58.210",
"Id": "42779",
"Score": "10",
"Tags": [
"ruby",
"rspec",
"hash-map"
],
"Title": "Cash Register Kata"
} | 42779 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.