body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have created a console program where users type in a math equation such as <code>5+4-6</code> or <code>(5+16(8-4))/16</code> that follows order of operations. The equation is sent to a char array that is then parsed. If a <code>#</code> or <code>.</code> is encountered, the char is placed into a buffer. The buffer is tokenized into a token class, followed by the operator itself being tokenized. The program works beautifully and as expected. Exceptions and errors still need to be handled where right now it is only writing to the console and continuing.</p>
<p>What I am looking to do next is add in higher functions, more in-line with a scientific calculator, starting with the constants such as e and pi, then moving into trig functions. It is in handling the functions that I am having an issue with.</p>
<p>Would you recommend storing the chars in a buffer similar to the #'s and treat them as a function if a <code>)</code> is found immediately following, and a constant otherwise? What would you suggest? Also, what could I improve upon?</p>
<p><strong>PROGRAM.CS</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalcTest.Core;
namespace CalcTest
{
class Program
{
static Calculator calculator;
static void Main(string[] args)
{
calculator = new Calculator();
calculator.Entry();
}
}
}
</code></pre>
<p><strong>ENUMS.CS</strong></p>
<pre><code>using CalcTest;
using CalcTest.Core;
namespace CalcTest.Core
{
public enum TokenType
{
Value,
Operand,
Function,
Paramater,
Variable
}
}
</code></pre>
<p><strong>TOKEN.CS</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalcTest.Core
{
public class Token
{
private TokenType type;
private string val;
public TokenType TYPE
{
get { return type; }
set { type = value; }
}
public string VALUE
{
get { return val; }
set { val = value; }
}
public Token(TokenType t, string s)
{
this.TYPE = t;
this.VALUE = s;
//Write();
}
public override string ToString()
{
return String.Format("Token:= Type: {0}; Value: {1}", TYPE.ToString(), VALUE);
}
private void Write()
{
Console.WriteLine(this.ToString());
}
}
}
</code></pre>
<p><strong>CALCULATOR.CS</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalcTest.Core
{
public class Calculator
{
private Stack<Token> tokenStack;
private Queue<Token> tokenQue;
private char[] buffer;
private int bufferLoc;
private TokenType? priorType;
public Calculator()
{
tokenQue = new Queue<Token>();
tokenStack = new Stack<Token>();
buffer = new char[100];
bufferLoc = 0;
priorType = null;
}
#region BasicFunctions
private Token Addition(Token t1, Token t2)
{
//Console.WriteLine("Addition:= Arg1: {0}; Arg2: {1}", t1.VALUE, t2.VALUE);
double arg1 = double.Parse(t1.VALUE);
double arg2 = double.Parse(t2.VALUE);
double sum = arg1 + arg2;
return CreateToken(TokenType.Value, sum.ToString());
}//end Addition
private Token Subtract(Token t1, Token t2)
{
//Console.WriteLine("Subtraction:= Arg1: {0}; Arg2: {1}", t1.VALUE, t2.VALUE);
double arg1 = double.Parse(t1.VALUE);
double arg2 = double.Parse(t2.VALUE);
double sub = arg1 - arg2;
return CreateToken(TokenType.Value, sub.ToString());
}//end Subtract
private Token Multiplication(Token t1, Token t2)
{
//Console.WriteLine("Multiplication:= Arg1: {0}; Arg2: {1}", t1.VALUE, t2.VALUE);
double arg1 = double.Parse(t1.VALUE);
double arg2 = double.Parse(t2.VALUE);
double multi = arg1 * arg2;
return CreateToken(TokenType.Value, multi.ToString());
}//end Multiplication
private Token Division(Token t1, Token t2)
{
//Console.WriteLine("Division:= Arg1: {0}; Arg2: {1}", t1.VALUE, t2.VALUE);
double arg1 = double.Parse(t1.VALUE);
double arg2 = double.Parse(t2.VALUE);
double div = arg1/arg2;
return CreateToken(TokenType.Value, div.ToString());
}//end Division
private Token Power(Token t1, Token t2)
{
//Console.WriteLine("Power:= Arg1: {0}; Arg2: {1}", t1.VALUE, t2.VALUE);
double arg1 = double.Parse(t1.VALUE);
double arg2 = double.Parse(t2.VALUE);
double power = Math.Pow(arg1,arg2);
return CreateToken(TokenType.Value, power.ToString());
}//end Power
#endregion
public void Entry()
{
char[] equation = new char[1];
while (true)
{
Array.Clear(equation, 0, equation.Length);
equation = Console.ReadLine().ToCharArray();
ParseEquation(equation);
foreach (var t in tokenQue)
{
Console.Write(t.VALUE + ", ");
}
Console.WriteLine();
EvalEquation();
if (tokenStack.Count > 0)
Console.WriteLine(tokenStack.Pop().VALUE);
else
Console.WriteLine("Nothing returned");
tokenStack.Clear();
tokenQue.Clear();
}
}//end Entry
#region EvalFunctions
private void EvalEquation()
{
Token temp = null;
while (tokenQue.Count != 0)
{
temp = tokenQue.Dequeue();
if (temp.TYPE == TokenType.Value)
tokenStack.Push(temp);
else
OpperationSwitch(temp);
}
}//end EvalEquation
private void OpperationSwitch(Token t)
{
Token ret = null;
if (tokenStack.Count >= 2)
{
Token t2 = tokenStack.Pop();
Token t1 = tokenStack.Pop();
switch (t.VALUE)
{
case ("*"):
ret = Multiplication(t1, t2);
break;
case ("/"):
ret = Division(t1, t2);
break;
case ("+"):
ret = Addition(t1, t2);
break;
case ("-"):
ret = Subtract(t1, t2);
break;
case ("^"):
ret = Power(t1, t2);
break;
}
if (ret != null)
tokenStack.Push(ret);
}
else
{
Console.WriteLine("Error in OpperationSwitch");
//error code
}
}//end OpperationSwitch
#endregion
#region ParserFunctions
private void ParseEquation(char[] equation)
{
for (int i = 0; i < equation.Length; i++)
{
priorType = null;
//Console.WriteLine("ParseEquation:= i: {0} ; Char: {1}", i, equation[i]);
if (char.IsDigit(equation[i]) || equation[i] == '.')
{
//executes if # or .
AddToBuffer(equation[i]);
}
else
{
//if buffer has data, create token, place in queue, clear buffer, and set prior type.
if (bufferLoc != 0)
{
tokenQue.Enqueue(CreateToken(TokenType.Value, new string(buffer, 0, bufferLoc)));
Array.Clear(buffer, 0, bufferLoc);
bufferLoc = 0;
priorType = TokenType.Value;
}
//handles operands
OperationHandler(equation[i]);
}//end else-if
}//end while
//creates a token of anything remaining in the buffer, and queues it
if (bufferLoc != 0)
{
tokenQue.Enqueue(CreateToken(TokenType.Value, new string(buffer, 0, bufferLoc)));
Array.Clear(buffer, 0, bufferLoc);
bufferLoc = 0;
}
//moves anything remaining on the tokenStack to the que
while (tokenStack.Count > 0)
{
Token temp = tokenStack.Pop();
if (temp.VALUE == "(")
{
//will only run in case of unpaired ()
Console.WriteLine("Error with '(' in ParseEquation");
//error code
}
tokenQue.Enqueue(temp);
}
}//end ParseEquation
private void OperationHandler(char opp)
{
if (opp == ')')
{
//runs if the opp is )
//Console.WriteLine("Entering ')' section of OperationHandler");
Token temp = null;
bool found = false;
//cycles until the most recent ( is found. If not found, error.
while (tokenStack.Count != 0)
{
temp = tokenStack.Pop();
if (temp.VALUE == "(")
{
found = true;
return;
}
else
{
tokenQue.Enqueue(temp);
}
}
if (!found)
{
Console.WriteLine("Error with '(' section of OperationHandler");
//error code
}
}
else
{
Token temp = CreateToken(TokenType.Operand, opp.ToString());
//creates a multiplication incase of implicite multiplication. Ex: 5(4) => 5*4
if (opp == '(' && priorType == TokenType.Value)
{
//Console.WriteLine("Creating a multiplication");
tokenStack.Push(CreateToken(TokenType.Operand, "*"));
}
if (tokenStack.Count == 0)
{
//runs if stack is empty
tokenStack.Push(temp);
}
else
{
OrderOfOpp(temp);
}
}
}//end OperationHandler
private void OrderOfOpp(Token t)
{
string tempVal = null;
Dictionary<string, int> oppDic = new Dictionary<string, int>() {{"(",4 }, {"^",3},{"*",2},{"/",2},{"+",1},{"-",1}};
bool done = false;
while (!done || tokenStack.Count == 0)
{
tempVal = tokenStack.Peek().VALUE;
if (tempVal == "(")
{
//if most recent push to stack was (, auto push t to stack
tokenStack.Push(t);
done = true;
}
else
{
if (oppDic[t.VALUE] >= oppDic[tempVal])
{
//if the t token has a higher precident then the tempVal (Obtained from peek), pushes t to que
tokenStack.Push(t);
done = true;
}
else
{
//if the tempVal has a higher precident then pop and enqueue
tokenQue.Enqueue(tokenStack.Pop());
}
}
if (tokenStack.Count == 0)
{
//if stack is empty, push to stack
tokenStack.Push(t);
done = true;
}
}//end while
if (!done)
{
Console.WriteLine("Error in OrderOfOpp");
//error code
}
}//end OrderOfOpp
#endregion
#region HelperFunctions
private void AddToBuffer(char add)
{
buffer[bufferLoc] = add;
bufferLoc++;
}//end AddToBuffer
private Token CreateToken(TokenType type, string value)
{
return new Token(type, value);
}//end CreateToken
#endregion
}
}
</code></pre>
| [] | [
{
"body": "<p>One thing, using a <code>Dictionary<char, Func<double, double, double>></code> will simplify your translation from the parsed formula to the actual calculations:</p>\n\n<pre><code>public class Calculator\n{\n\n public static readonly Dictionary<char, Func<double, double, double>> functions = new Dictionary<char, Func<double, double, double>>()\n {\n {'+',new Func<double,double,double>(Add)},\n {'-', new Func<double,double,double>(Subtract)},\n {'/',new Func<double,double,double>(Divide)},\n {'*',new Func<double,double,double>(Multiply)}\n };\n\n static double Add(double num1, double num2)\n {\n return num1 + num2;\n }\n static double Subtract(double num1, double num2)\n {\n return num1 - num2;\n }\n static double Multiply(double num1, double num2)\n {\n return num1 * num2;\n }\n static double Divide(double num1, double num2)\n {\n return num1 / num2;\n }\n}\n</code></pre>\n\n<p>The calculation becomes a simple look up of the dictionary with the appropriate operator:</p>\n\n<pre><code>char operation = '+';\ndouble num1 = 1;\ndouble num2 = 2;\ndouble newresult = Calculator.functions[operation](num1, num2);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T22:14:42.043",
"Id": "85540",
"Score": "0",
"body": "I never thought of using a delegate.... I've only been coding for a month or so and never encountered/seen a place where one would be useful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:01:03.853",
"Id": "48716",
"ParentId": "48632",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48716",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T00:42:04.683",
"Id": "48632",
"Score": "3",
"Tags": [
"c#",
"parsing",
"math-expression-eval"
],
"Title": "Math equation as string to reverse Polish notation parser"
} | 48632 |
<p>Here's how I implemented <code>concat</code> - flattens a list of lists into just a list of elements.</p>
<pre><code>concat' :: [[a]] -> [a]
concat' ys = foldl (\acc x -> acc ++ x) [] ys
</code></pre>
<p>Is it a problem that I'm using the <code>++</code> function? </p>
<p>What's a better way to write this?</p>
| [] | [
{
"body": "<p>You could eta-contract the definition in two places: <code>\\acc x -> acc ++ x</code> is the eta-expanded version of <code>(++)</code> and <code>concat' ys = (...) ys</code> is the eta-expanded version of <code>concat' = (...)</code>. So that would take you to:</p>\n\n<pre><code>concat' :: [[a]] -> [a]\nconcat' = foldl (++) []\n</code></pre>\n\n<p>Now, in that case it turns out that it's better to use <code>foldr</code> rather than <code>foldl</code> and there is a <a href=\"http://www.haskell.org/haskellwiki/Stack_overflow\" rel=\"nofollow\">good write-up about concat on the haskell wiki</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:51:02.147",
"Id": "48658",
"ParentId": "48634",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T01:55:39.757",
"Id": "48634",
"Score": "1",
"Tags": [
"haskell",
"reinventing-the-wheel"
],
"Title": "Haskell#concat Implementation"
} | 48634 |
<p>I implemented <code>and</code> and <code>or</code>:</p>
<pre><code>-- or is like and, only it returns True if
-- any of the boolean values in a list is True.
or' :: [Bool] -> Bool
or' [] = False
or' (x:xs) = x || or' xs
--and takes a list of boolean values and returns True only if
-- all the values in the list are True.
and' :: [Bool] -> Bool
and' [] = False
and' (x:xs) = x && and' xs
</code></pre>
<p>Is pattern matching the most elegant solution here?</p>
<p>Also, should <code>or' []</code> and <code>and' []</code> return <code>False</code>? It makes sense for them to do so when passing in a non-null input. </p>
<p>Example: <code>or' [False, False]</code></p>
<p>But, how about the behavior of <code>or' []</code> or <code>and' []</code>? Does <code>False</code> make sense here? </p>
| [] | [
{
"body": "<p>Your <code>or'</code> function is fine.</p>\n\n<p><code>and' []</code> should return <code>True</code> — that's what the built-in <code>and []</code> does. As it is, your <code>and'</code> function is broken, and always returns <code>False</code>:</p>\n\n<blockquote>\n<pre><code>*Main> and' [True]\nFalse\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:06:51.747",
"Id": "48641",
"ParentId": "48638",
"Score": "6"
}
},
{
"body": "<p>Consider that <code>Bool</code> is an algebraic data structure like any other in Haskell. Pattern matching is the most elegant solution, but you can use even more of it to be even more elegant!</p>\n\n<pre><code>-- import Prelude hiding (or)\n\nor :: [Bool] -> Bool\nor [] = False\nor (False:bs) = or bs\nor (True :_ ) = True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:28:07.023",
"Id": "85418",
"Score": "0",
"body": "I like that this solution works based on first principles, not even relying on `||` and `&&`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T04:00:29.920",
"Id": "48644",
"ParentId": "48638",
"Score": "8"
}
},
{
"body": "<blockquote>\n <p>Also, should <code>or' []</code> and <code>and' []</code> return False? It makes sense for them to do so when passing in a non-null input.</p>\n</blockquote>\n\n<p>No, it makes sense only for <code>or'</code>. Apart from translating them to basic mathematic quantifiers \"Is any of the items true?\" (<code>False</code> for no items) and \"Are all of the items true?\" (<code>True</code> for no items), you can try to evaluate your function with an example one-item list and confirm whether it meets the expected results:</p>\n\n<pre><code>or' [False] = False\nFalse || or' [] = False\nFalse || False = True\n-- ^^^^^\n\nand' [True] = True\nTrue && and' [] = True\nTrue && True = True\n-- ^^^^\n</code></pre>\n\n<blockquote>\n <p>Is pattern matching the most elegant solution here?</p>\n</blockquote>\n\n<p>It's OK, but most recursive functions can be written more concisely (= elegant?) with folds:</p>\n\n<pre><code>or' = foldr (||) False\nand' = foldr (&&) True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T07:19:05.577",
"Id": "48651",
"ParentId": "48638",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T02:19:31.853",
"Id": "48638",
"Score": "2",
"Tags": [
"haskell",
"reinventing-the-wheel"
],
"Title": "Implementing `and` and `or`"
} | 48638 |
<p>I would much appreciate your advice on this design I am going to implement. I am relatively new to object programming and I am not so sure about the delegate pattern.</p>
<p>I need to provide the implementation of a class that implements several interfaces of different nature. As the class would be huge I am thinking on using the delegate pattern to implement the code for each interface in a separate class. Simplifying the code a bit it goes like this:</p>
<p>The interfaces I have:</p>
<pre><code>public interface DoorControlIF {
public void openDoor(int id);
//some more door operations
}
public interface DoorStatusListenerIF {
public void onDoorOpened(int id);
}
public interface DoorAlarmListenerIF {
public void onDoorAlarm(int id, String alarmType);
}
public interface DoorConnectionIF {
public void connectToDoor(int id);
public void disconnectDoor(int id);
}
public interface DoorNotifierIF {
public void addDoorStatusListener(DoorStatusListenerIF listener);
public void addDoorAlarmListener(DoorAlarmListenerIF listener);
}
</code></pre>
<p>Then the <code>Manager</code> class would be like:</p>
<pre><code>public class DoorManager implements DoorControlIF, DoorConnectionIF, DoorNotifierIF{
SocketController socketController;
DoorController doorController;
DoorNotifier doorNotifier;
public void init() {
socketController = new SocketController();
doorController = new DoorController();
doorController.setSocketController(socketController);
doorNotifier = new DoorNotifier();
doorNotifier.setSocketController(socketController);
}
public void connectToDoor(int id) { socketController.open(id); }
public void disconnectDoor(int id) { socketController.disconnect(id); }
public void openDoor(int id) { doorController.openDoor(id); }
public void addDoorStatusListener(DoorStatusListenerIF listener) { doorNotifier.addDoorStatusListener(listener); }
public void addAlarmStatusListener(DoorAlarmListenerIF listener) { doorNotifier.addDoorAlarmListener(listener); }
</code></pre>
<p>Then we would have all the delegate classes implement each one of them a specific interface:</p>
<pre><code>public SocketController implements DoorConnectionIF{}
public DoorController implements DoorControlIerF{}
public DoorNotifier implements DoorNotifierIF{}
</code></pre>
<p>Particularly I am not so sure if it is right or not having each delegate class implementing again the same interface as the the <code>Manager</code> class. Then there's this forwarding of listeners that are added to the <code>Manager</code> but inside my class I add to my specific notifier. How about passing the <code>SocketController</code> to each of the delegates?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T09:57:43.007",
"Id": "85409",
"Score": "0",
"body": "[Don't use the public modifier in interface methods](http://stackoverflow.com/questions/161633/should-methods-in-a-java-interface-be-declared-with-or-without-a-public-access-m)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:01:32.690",
"Id": "85410",
"Score": "0",
"body": "You can also make the class members `private` and if you instantiate them at their declaration, you can also make them `final`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:44:24.957",
"Id": "85606",
"Score": "0",
"body": "*I need to provide the implementation of a class that implements several interfaces of different nature.* This requirement is flawed. You should never need to know or care whether two interfaces are implemented by the same class. That's the purpose of the interfaces. If you really needed to know A is B and C, then A would be an interface extending both of them and you would program against A only."
}
] | [
{
"body": "<p>I think your initial analysis into classes and interfaces is not quite right. I go by the mantra \"if you can kick it, then it should be a class instance\" (apologies to the purists out there). You can definitely kick a door, so there should be a class Door which will have methods for open(), close() and lock(), plus listeners for onOpen(), onClose() and onAlarm(). A constructor like Door(int id) sounds about right, allowing you to give the door a primary key.</p>\n\n<p>The manager class should maintain a list of doors, and do the work required to:</p>\n\n<ul>\n<li>route incoming commands from the socket interface to the appropriate door instance</li>\n<li>send outgoing events from doors to the socket interface. </li>\n</ul>\n\n<p>The Door class should not know that the socket implementation exists. Your DoorConnectionIF interface is likely superfluous.</p>\n\n<p>But it is good to see someone understanding why God invented listeners. Many experienced programmers misunderstand what listeners are designed for, and end up with tangled circular references between classes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T09:04:05.647",
"Id": "48656",
"ParentId": "48639",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T02:42:42.177",
"Id": "48639",
"Score": "2",
"Tags": [
"java",
"object-oriented"
],
"Title": "Correct use of delegate pattern"
} | 48639 |
<p>I'm trying to solve a practice problem and all is well except for the last 2 inputs my solution is too slow. Just one loop is slowing it down I think.</p>
<blockquote>
<h2>Herd Sums</h2>
<p>Execution Time Limit: 2 seconds</p>
<hr>
<h3>Problem Statement</h3>
<p>The cows if farmer John's herd are numbered and banded with consecutive integers from 1 to <em>N</em> (1 ≤ <em>N</em> ≤ 10,000,000). When the cows come to the barn for milking, they always come in sequential order from 1 to <em>N</em>.</p>
<p>Farmer John, who majored in mathematics in college and loves numbers, often looks for patterns. He has noticed that when he has exactly 15 cows in his herd, there are precisely four ways that the numbers on any set of one or more consecutive cows can add up to 15 (the same as the total number of cows). They are: 15, 7 + 8, 4 + 5 + 6, and 1 + 2 + 3 + 4 + 5.</p>
<p>When the number of cows in the herd is 10, the number of ways he can sum consecutive cows and get 10 drops to two: namely 1 + 2 + 3 + 4 and 10.</p>
<p>Write a program that will compute the number of ways farmer John can sum the numbers on consecutive cows to equal <em>N</em>.</p>
<h3>Input</h3>
<p>The input consists of several test cases, each on a separate line. Each test case consists of a single integer <em>N</em>. The program should terminate when it encounters -1. This should not be processed.</p>
<h3>Output</h3>
<p>For each test case, output the number of ways Farmer John can sum the numbers on consecutive cows to equal <em>N</em>. Print the output for each test case in a separate line.</p>
<h3>Sample Input</h3>
<pre><code>15
10
-1
</code></pre>
<h3>Sample Output</h3>
<pre><code>4
2
</code></pre>
</blockquote>
<hr>
<h3>Full Solution</h3>
<pre><code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
static Map<Integer,Integer> cache = new HashMap<>();
static {
cache.put(0, 0);
}
public static void main(String[] args) {
long start = System.nanoTime();
String[] in = getInput();
int inRead = 0;
while (inRead < in.length) {
int numCows = Integer.parseInt(in[inRead++]);
System.out.println(getNumSums(numCows));
}
long end = System.nanoTime();
long elapsed = (end - start)/1000000000;
System.out.println("Elapsed:" + elapsed);
}
private static int getNumSums(int numCows) {
int count = 0;
for (int i = 1; i <= numCows; i++) {
int sum = sumTo(i);
if (sum >= numCows) {
int j = 1;
while (sum > numCows) {
sum -= j++;
}
if (sum == numCows)
++count;
}
}
return count;
}
private static int sumTo(int end) {
if (cache.get(end) == null) {
int prev = cache.get(end - 1);
cache.put(end, prev + end);
}
return cache.get(end);
}
private static String[] getInput() {
List<String> ret = new ArrayList<>();
String line;
try (BufferedReader br = new BufferedReader(new FileReader("g_input.txt"))){
while(!(line = br.readLine()).equals("-1")) {
ret.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret.toArray(new String[ret.size()]);
}
}
</code></pre>
<h3>Input</h3>
<pre><code>1
2
3
4
5
10
15
99
200
578
690
30007
45000
143929
9909909
10000000
-1
</code></pre>
<h3>Output</h3>
<pre><code>1
1
2
1
2
2
4
6
3
3
8
4
15
4
24
8
</code></pre>
<h3>Problem</h3>
<pre><code>private static int getNumSums(int numCows) {
int count = 0;
for (int i = 1; i <= numCows; i++) {
int sum = sumTo(i);
if (sum >= numCows) {
int j = 1;
while (sum > numCows) { //this is slow
sum -= j++;
}
if (sum == numCows)
++count;
}
}
return count;
}
</code></pre>
<p>This part seems to be the slow one. I've make the <code>sumTo()</code> dynamic but I can't think of a way to make this part dynamic. </p>
<p>It works alright until it reaches <code>numCows = 9909909</code>, when it reaches that part it just becomes really slow.</p>
| [] | [
{
"body": "<p>There are some other Java gurus around here who might know some Java-specific tips and tricks, but... I want to look at something else you're doing in the algorithm.</p>\n\n<p>First of all, we know from the problem statement that any positive integer will have at least 1 possible answer, that is, itself.</p>\n\n<p>What we can also know from basic math knowledge is that the largest starting number is going to be just below half of the total number.</p>\n\n<p>For example, with 100, the largest possible starting number would be 49, because 49+50 is less than 100, but 50+51 is more than 100. 49+50 isn't one of the solutions, but it does represent something important to us: the largest possible starting number. This is where we can stop checking numbers.</p>\n\n<p>We can extend this thinking further. For example, a number that is evenly divisible by 3 will have a solution by starting with the largest number that is less than 1/3rd the number and taking the two following numbers. For example, 1/3rd of 3 is 1. The largest number under this is 0. 0+1+2 = 3. A better example is 6. One third of 6 is 2. The largest number under this is 1. 1+2+3 = 6. This will be exactly true for every multiple of 3.</p>\n\n<p>30: 1/3 = 10. One less than 10 is 9. 9+10+11 = 30.</p>\n\n<hr>\n\n<p>But there's something more to learn from this...</p>\n\n<ul>\n<li>If \\$n_1 + n_2 = N\\$, and \\$(n_1, n_2)\\$ are consecutive, then \\$N\\$ is of the form \\$2n_1 + 1\\$.</li>\n<li><p>If \\$n_1 + n_2 + n_3 = N\\$, and \\$(n_1, n_2, n_3)\\$ are consecutive, then \\$N\\$ is of the form \\$3n_2\\$.</p>\n\n<p>Think of the sum as \\$(n_2 - 1) + n_2 + (n_2 + 1)\\$.</p></li>\n<li><p>If \\$n_1 + n_2 + n_3 + n_4 = N\\$, and \\$(n_1 \\ldots n_4)\\$ are consecutive, then \\$N\\$ is of the form \\$4n_2 + 2\\$.</p></li>\n<li><p>If \\$n_1 + n_2 + n_3 + n_4 + n_5 = N\\$, and \\$(n_1 \\ldots n_5)\\$ are consecutive, then \\$N\\$ is of the form \\$5n_3\\$.</p>\n\n<p>Think of the sum as \\$(n_3 \\underbrace{- 2) + (n_3 \\underbrace{- 1) + n_3 + (n_3 +} 1) + (n_3 +} 2)\\$.</p></li>\n</ul>\n\n<p>For any run length \\$L\\$, there's at most one run of \\$L\\$ consecutive numbers that can sum to \\$N\\$. This is true for any run of positive, consecutive integers. Moreover, each run of length \\$L\\$ will be centered at \\$\\frac{N}{L}\\$.</p>\n\n<p>The point is, the solution should be mostly formulaic. The only searching you need to do is to check whether \\$N\\$ is of the form \\$k,\\ 2k + 1,\\ 3k,\\ 4k + 2,\\ 5k,\\ 6k + 3, \\ldots\\$. You should be able to accomplish that in \\$\\mathrm{O}(N)\\$ time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:28:12.840",
"Id": "85426",
"Score": "0",
"body": "@200_success Thank you for making my math look all fancy. ;) And vastly improving my wording."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:18:18.667",
"Id": "48643",
"ParentId": "48640",
"Score": "13"
}
},
{
"body": "<p>A group of consecutive integers adds up to N. </p>\n\n<p>The number of integers in that group is odd or even. </p>\n\n<p>You may have n integers, n odd. If the middle one is k, then the sum is n*k.\nYou may have 2n integers. If the two in the middle are k and k+1, then the sum is n*(2k + 1). </p>\n\n<p>So the answer is quite closely related to finding all ways to write N as the product of two integers, which is very easily done by trial division with divisors <= sqrt (N). Let N = a*b. If a is odd then we could have n = a integers from b - (a-1)/2 to b + (a-1)/2. If b is odd then we could have n = 2a integers from (b + 1)/2 - a to (b - 1)/2 + a. (You better check this).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:22:49.023",
"Id": "48660",
"ParentId": "48640",
"Score": "2"
}
},
{
"body": "<p>Use maths. Rewrite your <code>getNumSum</code> method like this (you don't need your <code>sumTo</code> and <code>cache</code>):</p>\n\n<pre><code>private static int getNumSums(int numCows)\n{\n int limit = (int)Math.sqrt(2 * numCows);\n int count = 0;\n for (int m = 1; m <= limit; ++m) {\n if ((2 * numCows + m * (m + 1)) % (2 * m) == 0) {\n ++count;\n }\n }\n return count;\n}\n</code></pre>\n\n<p>See <a href=\"https://math.stackexchange.com/questions/139842/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers\">this question</a> and the accepted answer for an explanation of how this works.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:37:35.437",
"Id": "48991",
"ParentId": "48640",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:00:21.467",
"Id": "48640",
"Score": "11",
"Tags": [
"java",
"optimization",
"programming-challenge",
"dynamic-programming"
],
"Title": "Optimizing \"Herd Sums\" problem using dynamic programming"
} | 48640 |
<p>I needed a simple way to trim a string of words based on a max character count. I also needed to cut in-between words. Using WordPress, here is what I came up with, but I feel like it could be more efficient. </p>
<pre><code>function count_words($content) {
$partsArray = explode(' ', $content);
return sizeof($partsArray);
}
function custom_length_excerpt_max_char($content, $max_chars_limit) {
$count = 0;
$word_limit;
while (strlen($content) > $max_chars_limit) {
$word_limit = count_words($content);
$word_limit -= 1;
$content = wp_trim_words($content, $word_limit, '');
$count++;
if ($count > 10) {
break;
}
}
if ($count > 0) {
$content .= '&#8230;';
}
return $content;
}
</code></pre>
<p>I was originally using <code>str_word_count</code> to count the words but it was choking on HTML-encoded characters in the string.</p>
| [] | [
{
"body": "<p>Yes, it's extremely inefficient, because in every iteration you count the number of words twice: once in <code>count_words</code>, and then <code>wp_trim_words</code> internally has to count the words again.</p>\n\n<p>Another problem is that the method won't work for content that is many words larger than the target limit length. For example with a content of 4000 chars and a limit of 100, due to the <code>if ($count > 10) break</code> check in the middle, the method will basically cut off the last 10 words and return a still very large content. Not sure if that was part of your plan.</p>\n\n<p>I don't really know PHP. But here's a naive implementation that should be more efficient and work with long content too:</p>\n\n<pre><code>function is_letter($char) {\n return ctype_alpha($char) || in_array($char, ['-']);\n}\n\nfunction custom_length_excerpt_max_char($content, $max_chars_limit) {\n if (strlen($content) < $max_chars_limit) {\n return $content;\n }\n $cut_at = $max_chars_limit;\n for (; $cut_at >= 0 && is_letter($content{$cut_at}); --$cut_at);\n return substr($content, 0, $cut_at);\n}\n\nfunction test_custom_length_excerpt_max_char() {\n $sample = 'some sample-text some sample-text';\n for ($i = 5; $i < strlen($sample) + 10; ++$i) {\n echo custom_length_excerpt_max_char($sample, $i).\"\\n\";\n }\n}\n</code></pre>\n\n<p>Here's the logic behind the main function:</p>\n\n<ul>\n<li>If the content is shorter than the limit, return it</li>\n<li>Iterate backward from the target limit position, until you find something that's NOT a letter, and break the content there.</li>\n</ul>\n\n<p>If you run the test function, the output is something like:</p>\n\n<pre><code>...\nsome\nsome\nsome sample-text\nsome sample-text\nsome sample-text\nsome sample-text\nsome sample-text\nsome sample-text some\nsome sample-text some\nsome sample-text some\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T05:45:53.753",
"Id": "48647",
"ParentId": "48645",
"Score": "6"
}
},
{
"body": "<p>I revisited this code and came up with a better solution than my first based on the answer by janos and by an answer on stackoverflow.com <a href=\"https://stackoverflow.com/a/3161830/117068\">https://stackoverflow.com/a/3161830/117068</a></p>\n<p>This removes multiple iterations and utilizes better built core functions of php.</p>\n<pre><code> function custom_length_excerpt_max_char($content, $max_chars_limit) {\n $content = wp_strip_all_tags($content);\n $break = '##splitme##';\n\n if ( strlen($content) > $max_chars_limit ) {\n $content = wordwrap($content, ($max_chars_limit - 3), $break);\n $content = explode($break, $content);\n $content = array_shift($content) . '&#8230;';\n }\n\n return $content;\n }\n</code></pre>\n<p>The <code>($max_chars_limit - 3)</code> compensates for the ellipses added on to the end of the trimmed content.</p>\n<h2>Update</h2>\n<p>Because this is specific to wordpress, the content to be trimmed could have HTML tags in it. I realized that before trimming the content, all tags need to be removed first to prevent unclosed tag sets. Wordpress provides <code>wp_strip_all_tags</code> to do just that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T21:37:10.557",
"Id": "52661",
"ParentId": "48645",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "52661",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T04:17:26.073",
"Id": "48645",
"Score": "6",
"Tags": [
"php",
"strings",
"wordpress"
],
"Title": "Trim string of words based on character count"
} | 48645 |
<p>I have wrote simple class that allowing database selection and inserts.Could you please tell me does this a right way to use __call method with any useful advantage of it ?</p>
<pre><code> <?php
class _getDatabase
{
public $db;
public function __construct(PDO $connection)
{
$this->db = $connection;
}
public function __call($function, $args) {
if ($function == 'getSelect') {
$sql = $this->db->prepare($args[0]['query']);
$sql->execute(array(
$args[0]['parameters']
));
return $sql->fetchALL(PDO::FETCH_OBJ);
}
if ($function == 'getInsert') {
$sql = $this->db->prepare($args[0]['query']);
$result = $sql->execute($args[0]['parameters']);
return $result;
}
}
}
$dbh = new PDO("mysql:host=127.0.0.1;dbname=" . DATABASE, USERNAME, PASSWORD, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
$dbFactory = new _getDatabase($dbh);
$select = array();
$insert = array();
$select['query'] = 'SELECT * FROM `branches` WHERE B_CODE = ?';
$select['parameters'] = 'AMB';
$insert['query'] = 'INSERT INTO `commition`(`date`, `reg`, `com`, `oper`) VALUES (?,?,?,?)';
$insert['parameters'] = array('2014-02-20','86869','DITEC','Asuntha');
var_dump($dbFactory->getSelect($select));
var_dump($dbFactory->getInsert($insert));
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:50:47.767",
"Id": "85433",
"Score": "0",
"body": "What do you think? Have you used this class to a demonstrable advantage?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:52:22.387",
"Id": "85434",
"Score": "0",
"body": "i used this.But i can't figure out how this will useful with actual environment"
}
] | [
{
"body": "<p>You are using the __call for a completly wrong purpose. Instead of defining the functions/methods in the class itself, you are in fact defining them in a __call function.</p>\n\n<p>Everytime you call a method on your current class the compiler does this:</p>\n\n<p>doest the method exist? does the scope have privileges to call the method? -> call the method.</p>\n\n<p>No method found? doest the object have a __call method? does the scope have privileges to call the method? -> call the method.</p>\n\n<p>Now you are in the __call method. It now does a lot of string comparisons (could be 'optmized' using switch statements if a lot of calls are made).</p>\n\n<p>Not really optimal, not to mention that the compiler and or other developers now have no clue at all or it/they are passing enough arguments to a method. hell</p>\n\n<p>But, what is the point of the __call method then you may ask. Some argue this should never have been implemented in the first place, some love it. But that is a different argument.</p>\n\n<p>Some neat examples:</p>\n\n<ul>\n<li><a href=\"http://www.garfieldtech.com/blog/magical-php-call\" rel=\"nofollow\">http://www.garfieldtech.com/blog/magical-php-call</a></li>\n<li>Laravel <a href=\"http://laravel.com/docs/facades\" rel=\"nofollow\">facades</a> (click <a href=\"https://github.com/laravel/framework/blob/master/src/Illuminate/Support/Facades/Facade.php\" rel=\"nofollow\">here</a> for the code)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T19:33:18.257",
"Id": "86063",
"Score": "0",
"body": "Great explanation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T12:31:46.417",
"Id": "48975",
"ParentId": "48650",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48975",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T06:57:20.070",
"Id": "48650",
"Score": "4",
"Tags": [
"php",
"mysql",
"classes",
"php5",
"pdo"
],
"Title": "advantage of using __call method"
} | 48650 |
<p>I have a method in my class that eats up something like 80% of my processor time while its running. In-fact one line within the method is responsible for the majority of this.</p>
<p>The idea behind this class is to stabilize the depth readings being returned by the Microsoft Kinect device by obtaining the average value of the last 4 frames plus the current one.</p>
<p>This is a the basic layout of the method concerned.</p>
<pre><code>public event EventHandler<DenoisedDepthReadyEventArgs> DenoisedDepthReady;
private const int HistoricFrameCount = 4;
private readonly KinectSensor _KinectSensor;
private List<DepthImagePixel[]> _LastFrames;
private FilteredDepthPixel[] _FilteredDepths;
private bool _ResolutionFilteredDepthsInitialized;
//This is invoked upto 30 times a second
private void KinectSensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame != null)
{
DepthImagePixel[] currentPixels = new DepthImagePixel[depthFrame.PixelDataLength]; //Note this is huge array, usually 307200
depthFrame.CopyDepthImagePixelDataTo(currentPixels);
this._LastFrames.Add(currentPixels);
this.ReduceNoiseAndInvokeIfRequired(currentPixels, depthFrame.PixelDataLength, depthFrame.MaxDepth, depthFrame.MinDepth);
}
}
}
private void ReduceNoiseAndInvokeIfRequired(DepthImagePixel[] currentPixels, int totalPixels, int maxDepth, int minDepth)
{
if (this._LastFrames.Count == HistoricFrameCount)
{
if (!this._ResolutionFilteredDepthsInitialized)
{
this._FilteredDepths = new FilteredDepthPixel[totalPixels];
for (int i = 0; i < totalPixels; i++)
{
this._FilteredDepths[i] = new FilteredDepthPixel();
}
this._ResolutionFilteredDepthsInitialized = true;
}
for (int i = 0; i < this._LastFrames.Count; i++)
{
DepthImagePixel[] currentFrame = this._LastFrames[i];
for (int p = 0; p < totalPixels; p++)
{
this._FilteredDepths[p].Depth = (this._FilteredDepths[p].Depth + currentFrame[p].Depth) / 2;
}
}
for (int i = 0; i < currentPixels.Length; i++)
{
this._FilteredDepths[i].Depth = (this._FilteredDepths[i].Depth + currentPixels[i].Depth) / 2;
this._FilteredDepths[i].IsKnownDepth = currentPixels[i].IsKnownDepth;
this._FilteredDepths[i].PlayerIndex = currentPixels[i].PlayerIndex;
}
this._LastFrames.RemoveAt(this._LastFrames.Count - 1);
RaiseOnDenoisedDepthEvent(this._FilteredDepths, maxDepth, minDepth);
}
}
</code></pre>
<p>and here is what the performance profiler says about what I'm doing.</p>
<p><img src="https://i.stack.imgur.com/R1dfV.png" alt="enter image description here"></p>
<p>I'm trying to avoid threading and parallelization for the time being. I am also conscious that building a new collection each frame is probably silly too but not sure how to improve this given the immutability of the type I want to return. </p>
<p>Any input or guidance on alternative approaches would be highly appreciated. </p>
| [] | [
{
"body": "<p>Why are you avoiding parallelization? This type of problem is known as \"embarrassingly parallel\" because each loop iteration is independent of any other. Quick replacement makes it happen:</p>\n\n<pre><code>for (int i = 0; i < this._LastFrames.Count; i++)\n{\n DepthImagePixel[] currentFrame = this._LastFrames[i];\n Parallel.For(0, totalPixels, p =>\n {\n this._FilteredDepths[p].Depth = (this._FilteredDepths[p].Depth + currentFrame[p].Depth) / 2;\n });\n}\n\nParallel.For(0, currentPixels.Length, i =>\n{\n this._FilteredDepths[i].Depth = (this._FilteredDepths[i].Depth + currentPixels[i].Depth) / 2;\n this._FilteredDepths[i].IsKnownDepth = currentPixels[i].IsKnownDepth;\n this._FilteredDepths[i].PlayerIndex = currentPixels[i].PlayerIndex;\n});\n</code></pre>\n\n<p>As to the answer to your question, where do you expect your code to be taking the bulk of its time? The rest of the code is initialization, flow control, etc. The hot code is looped calculation. That's a CPU-bound operation that can really only break free with parallelization. You <em>might</em> be able to speed it up by doing a shift right by 1 bit rather than the arithmetic division by 2, but that seems a hit hinkey.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:23:23.663",
"Id": "48701",
"ParentId": "48653",
"Score": "4"
}
},
{
"body": "<p>@Jesse has already addressed the parallelization fun the way I would have addressed it. This answer merely adds a couple of coding style observations.</p>\n\n<blockquote>\n<pre><code>private readonly KinectSensor _KinectSensor;\nprivate List<DepthImagePixel[]> _LastFrames;\nprivate FilteredDepthPixel[] _FilteredDepths;\nprivate bool _ResolutionFilteredDepthsInitialized;\n</code></pre>\n</blockquote>\n\n<p>These private fields don't follow the <code>camelCase</code> convention that's in order for private fields. Should be like this:</p>\n\n<pre><code>private readonly KinectSensor _kinectSensor;\nprivate List<DepthImagePixel[]> _lastFrames;\nprivate FilteredDepthPixel[] _filteredDepths;\nprivate bool _resolutionFilteredDepthsInitialized;\n</code></pre>\n\n<p>Actually the last one, named like this, could be a delegate of some kind. I prefer using <code>is</code> or <code>has</code> as a prefix, it makes it easier to find the Boolean flags in the autocomplete dropdown:</p>\n\n<pre><code>private bool _isResolutionFilteredDepthsInitialized;\n</code></pre>\n\n<p>You're over-qualifying your member variables:</p>\n\n<blockquote>\n<pre><code>this._lastFrames.Add(currentPixels);\nthis.ReduceNoiseAndInvokeIfRequired(currentPixels, depthFrame.PixelDataLength, depthFrame.MaxDepth, depthFrame.MinDepth);\n</code></pre>\n</blockquote>\n\n<p>The <code>this</code> qualifier is redundant here, and is adding noise that's not needed. Ironic when you consider that the method invoked is called <em>ReduceNoise</em> ;)</p>\n\n<pre><code>_lastFrames.Add(currentPixels);\nReduceNoiseAndInvokeIfRequired(currentPixels, depthFrame.PixelDataLength, depthFrame.MaxDepth, depthFrame.MinDepth); \n</code></pre>\n\n<p>In terms of readability, I find it particularly rewarding with cases like this:</p>\n\n<blockquote>\n<pre><code>if (!this._ResolutionFilteredDepthsInitialized)\n</code></pre>\n</blockquote>\n\n<p>That turn into this:</p>\n\n<pre><code>if (!_isResolutionFilteredDepthsInitialized)\n</code></pre>\n\n<p>But then again, your usage of <code>this</code> is consistent all across, so this is basically a matter of personal preference - I <em>prefer</em> only qualifying with <code>this</code> when it's needed.</p>\n\n<p>One thing though, is that if you're going to keep all the <code>this</code> qualifiers, then the <code>_</code> underscore prefix should be dropped on the private fields.</p>\n\n<hr>\n\n<p>Your event here:</p>\n\n<blockquote>\n<pre><code>public event EventHandler<DenoisedDepthReadyEventArgs> DenoisedDepthReady;\n</code></pre>\n</blockquote>\n\n<p>Appears to be raised by this method call:</p>\n\n<blockquote>\n<pre><code>RaiseOnDenoisedDepthEvent(this._FilteredDepths, maxDepth, minDepth);\n</code></pre>\n</blockquote>\n\n<p>Convention would be to raise the event in a method like this:</p>\n\n<pre><code>public void OnDenoisedDepthReady(DenoisedDepthReadyEventArgs args)\n{\n if (DenoisedDepthReady == null) return;\n\n DenoisedDepthReady(this, args);\n}\n</code></pre>\n\n<p>Or (and?):</p>\n\n<pre><code>public void OnDenoisedDepthReady(FilteredDepthPixel[] depths, int minDepth, int maxDepth)\n{\n if (DenoisedDepthReady == null) return;\n\n var args = new DenoisedDepthReadyEventArgs(depths, minDepth, maxDepth); // assuming constructor\n DenoisedDepthReady(this, args); // or pass args to above overload\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T23:24:07.677",
"Id": "86099",
"Score": "1",
"body": "Thanks very much for suggestions. I agree I end up with a bit of redundant code but I've always done it and its kinda become a never ending loop of wanting to stay consistent. Either way might be time for a change. One thing though, your example of invoking an event is a bit off. Check this stackoverflow post out http://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T23:26:27.110",
"Id": "86100",
"Score": "1",
"body": "@Maxim indeed, I should have mentioned that invoking events like this wasn't thread-safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T23:27:16.467",
"Id": "86101",
"Score": "0",
"body": "Appreciate all the thought in your post, lovely to have someone review my code like that cause I work alone..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:04:38.887",
"Id": "48706",
"ParentId": "48653",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48706",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T07:32:00.090",
"Id": "48653",
"Score": "4",
"Tags": [
"c#",
"performance",
"array",
"collections"
],
"Title": "Addition plus division taking up all my CPU - Kinect depth denoising"
} | 48653 |
<p>I'm building a page that downloads a list of Geocaching CWGs for my country in XML, and then parse it. The structure of the XML looks like this:</p>
<pre><code><cwgkatalog>
<cwg>
<cislo>8245</cislo>
<id_katalog>8245</id_katalog>
<kategorie>cwg</kategorie>
<verze>1</verze>
<guid>891a8e4d-9dee-4f77-a9c7-8017c5f16b15</guid>
<jmeno>GarfieldMnHr</jmeno>
<jpg_oficialni>cwg08245-1.jpg</jpg_oficialni>
<img>http://cwg.geog.cz/cwg08245-1.jpg</img>
<odkaz/>
<komentar/>
<zarazeno>2013-12-06 00:00:00</zarazeno>
</cwg>
<cwg>
...
</code></pre>
<p>I have a function that searches for <code>jmeno</code> property and because of that, I have created an array working as an index array for <code>jmeno</code>:</p>
<pre><code>function createAjax() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
function CwgParser(xmlListURL) {
var httpRequest = createAjax(),
mainContext = this,
tree_cwgData = [],
arr_nameIndex = [];
this.findDataByName = function(searchedName) {
var lastIndex = arr_nameIndex.indexOf(searchedName),
arr_foundIndexes = [lastIndex],
arr_resultData = [];
while (lastIndex != -1) {
lastIndex = arr_nameIndex.indexOf(searchedName, lastIndex + 1);
arr_foundIndexes.push(lastIndex);
}
arr_foundIndexes.splice(-1, 1);
arr_foundIndexes.forEach(function(value) {
arr_resultData.push(tree_cwgData[value]);
});
return (arr_resultData.length == 0) ? false : arr_resultData;
};
this.parseXML = function(xmlData) {
var _xmlDoc, _parser, _arr_parts, _node_currentNode, _obj_currentNodeData, arr_cwgList = [], nameIndex = [];
if (window.DOMParser) {
_parser = new DOMParser();
_xmlDoc = _parser.parseFromString(xmlData, 'text/xml');
} else {
_xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
_xmlDoc.async = false;
_xmlDoc.loadXML(xmlData);
}
_arr_parts = _xmlDoc.getElementsByTagName('cwg');
for (var i = 0; i < _arr_parts.length; i++) {
_node_currentNode = _arr_parts[i];
_obj_currentNodeData = {};
for (var j = 1; j < _arr_parts[i].childNodes.length - 1; j=j+2) {
_obj_currentNodeData[_node_currentNode.childNodes[j].nodeName] = _node_currentNode.childNodes[j].innerHTML;
}
nameIndex.push(_obj_currentNodeData.jmeno.trim());
arr_cwgList.push(_obj_currentNodeData);
}
tree_cwgData = arr_cwgList;
arr_nameIndex = nameIndex;
mainContext.ondataparse();
};
this.loadXML = function () {
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4) {
mainContext.ondataload();
mainContext.parseXML(httpRequest.responseText);
}
};
mainContext.onrequeststart();
httpRequest.open('GET', './fileContentProvider.php?url=' + xmlListURL, true);
httpRequest.send(null);
};
this.onrequeststart = function() {};
this.ondataload = function() {};
this.ondataparse = function() {};
}
</code></pre>
<p>and I call it like this (<code>LoadingIcon</code> is just a support class that creates overlay, displaying loading .gif and some text):</p>
<pre><code>var xml = new CwgParser('cwg.geog.cz/cwg.xml'),
loader = new LoadingIcon('./ajax-loader.gif');
xml.ondataparse = function() {
loader.stop();
document.getElementById('container').style.display = 'block';
};
xml.ondataload = function() {
loader.setText('Parsing CWG list...');
};
loader.setText('Loading CWG list...');
loader.start();
xml.loadXML();
</code></pre>
<p>Is there any better way of searching and downloading the data?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:20:07.983",
"Id": "48659",
"Score": "2",
"Tags": [
"javascript",
"optimization",
"ajax"
],
"Title": "Downloading and parsing list of Getcachine CWGs"
} | 48659 |
<p>What's the best way to iterate over two collections of equal length?</p>
<p>Currently I'm using this:</p>
<pre><code>for(var index = 0; index < collection1.Count(); index++)
{
var item1 = collection1[index];
var item2 = collection2[index];
Console.WriteLine(item1.ToString() + ", "+ item2.ToString());
}
</code></pre>
<p>But I'd love to be able to use a <code>foreach</code> instead, e.g.</p>
<pre><code>foreach(item1, item2 in collection1, collection2)
{
Console.WriteLine(item1.ToString() + ", " + item2.ToString();
}
</code></pre>
<p>Now, this would be sort of possible if I zipped my two collections into a dictionary, but is that the best way to go? Would that be a sufficient gain of readability while sacrificing the performance needed to build the dictionary?</p>
<p>Similarly, I'm not sure if a dictionary is idealistically correct here, as there may not necessarily be a link between the two collections (other than their order in the list), merely a guarantee that they both have the same length.</p>
| [] | [
{
"body": "<p>The first one will always be more readable. If you want to start building collections that contain your previous collections, you'll add another layer of abstraction to your code for no reason: this will hurt readability a lot. </p>\n\n<p>One of the limitations of the <code>foreach</code> loop is that it can only iterate one collection at a time. Working around this might seem interesting but I doubt there will be any solution that's more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:58:49.300",
"Id": "48665",
"ParentId": "48661",
"Score": "3"
}
},
{
"body": "<p>You can use LINQ's <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/dd267698.aspx\" rel=\"nofollow noreferrer\"><code>Zip</code></a> method. As usual, it's a bit slower than manually written code, but unless this is in a hot spot it rarely matters. The cost of <code>Console.WriteLine</code> vastly exceeds the cost of LINQ.</p>\n\n<pre><code>foreach(var pair in collection1.Zip(collection2, Tuple.Create))\n{\n Console.WriteLine(\"{0}, {1}\", pair.Item1, pair.Item2);\n}\n</code></pre>\n\n<hr>\n\n<p>You can replace <code>Tuple.Create</code> by <code>ValueTuple.Create</code> if you target .net 4.7 or you referenced the compatibility nuget package. This saves a heap allocation and is usually faster.</p>\n\n<p>In C# 7 you could use named tuples, which enables meaningful property names. It's based on <code>ValueTuple</code> and thus avoid the heap allocation as well.</p>\n\n<pre><code>names.Zip(ages, (name, age) => (Name:name, Age:age))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:55:28.960",
"Id": "85449",
"Score": "1",
"body": "You could use `collection1.Zip(collection2, Tuple.Create)`, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:58:30.067",
"Id": "85450",
"Score": "0",
"body": "@codesparkle Yes, that's better. Thanks for the suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T22:19:15.160",
"Id": "85541",
"Score": "0",
"body": "Swapped solution to here, as result was both readable and concise. Could an anonymous type be used here to make it clearer what one was working with inside the foreach body than simply using \".Item1\" and \".Item2\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:57:40.317",
"Id": "85555",
"Score": "0",
"body": "Just had time to test it, you can swap `Tuple.Create` with `(s,s2)=> new {type1=s,type2=s2}` and reference it with `pair.type1` and `pair.type2` and this lets you use more sensible names later on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T09:46:22.533",
"Id": "380824",
"Score": "0",
"body": "You actually don't even need the `Name:` and `Age:` property names because they can be inferred from `(name, age)` :-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T13:38:21.320",
"Id": "380841",
"Score": "0",
"body": "@t3chb0t I'm a bit picky and prefer property names in `PascalCase` and local variables in `camelCase`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-05-01T12:02:05.210",
"Id": "48666",
"ParentId": "48661",
"Score": "12"
}
},
{
"body": "<p>Another alternative:</p>\n\n<pre><code>using (var enumerator1 = collection1.GetEnumerator())\nusing (var enumerator2 = collection2.GetEnumerator()) {\n while(enumerator1.MoveNext() && enumerator2.MoveNext()) {\n Console.WriteLine(enumerator1.Current.ToString() + \", \" + enumerator1.Current.ToString());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:49:36.453",
"Id": "85448",
"Score": "0",
"body": "I think this is worse than the original code. I would use something like this only if I couldn't use indexers or `Zip`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T09:43:39.297",
"Id": "380823",
"Score": "0",
"body": "@svick this is not worse than the original code, in fact it's even better because this works with any enumerable type whereas OP's code only with ones that implement `IList`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-30T12:26:03.227",
"Id": "380832",
"Score": "0",
"body": "@t3chb0t I think the above code is harder to understand than the original, which is why I said it's worse. And I did acknowledge that it's more general in my previous comment, but I don't think that outweighs the readability issues."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:29:42.113",
"Id": "48669",
"ParentId": "48661",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>What's the best way to iterate over two collections of equal length?</p>\n</blockquote>\n\n<p>Don't. This is often (but not always) an indication that the two collections should instead be one, of some compound type.</p>\n\n<p>For example, if the collections represent 2D points, with the first one containing X coordinates and the second one Y coordinates, you should instead create a new <code>Point</code> type and have a collection of those.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:27:56.960",
"Id": "85459",
"Score": "0",
"body": "Sometimes you have to iterate over two collections of equal length when working with an existing library that you either cannot modify the source of or do not have the time to refactor. Creating a compound collection from those for your own code could work, but might be overkill if you aren't holding on to the data for very long. I do like the zipping technique people have mentioned, but that's likely due to my background in Python, where `zip` is a built-in function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:37:22.743",
"Id": "85464",
"Score": "1",
"body": "@JAB I agree, zipping is a reasonable solution to this when a compound collection doesn't make sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:52:19.260",
"Id": "48675",
"ParentId": "48661",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48666",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:29:41.927",
"Id": "48661",
"Score": "8",
"Tags": [
"c#",
"collections",
"hash-map",
"iteration"
],
"Title": "Iterate over two collections of equal length"
} | 48661 |
<p>This is something myself and a former colleague were working on and I've finally finished it but wanting to see if we've done as well as we can or if it can be further optimised.</p>
<p>Also looking at doing a new feature for getting a list of all services rather than hosts and find the status of the service on each host.</p>
<p>Here's what I've got to so far:</p>
<pre><code>import sys
import re
import os
def get_nagios_status(path):
"""
Parse the Nagios status.dat file into a dict to give the ability to report on host/service information
`path` is the absolute path to the Nagios status.dat
Return dict() if OK, -1 if not
"""
result = {}
record = {}
mode = ''
parse_enabled = False
try:
f = open(path, 'r')
except:
return -1
try:
for line in f.readlines():
line = line.rstrip()
if re.match('^(\w+) \{$', line):
if line.find('host') >= 0:
mode = 'host'
elif line.find('service') >= 0 and not line.find('servicecomment') >= 0:
mode = 'service'
elif line.find('info') >= 0:
mode = 'info'
elif line.find('program') >= 0:
mode = 'program'
else:
continue
record = {}
parse_enabled = True
continue
elif parse_enabled and re.match('^\t\}$', line):
if mode == 'host':
if result.get(mode, None) is None:
result[mode] = {}
result[mode][record['host_name']] = record.copy()
elif mode == 'service':
if result.get(mode, None) is None:
result[mode] = {}
if result[mode].get(record['host_name'], None) is None:
result[mode][record['host_name']] = {}
result[mode][record['host_name']][record['service_description']] = record.copy()
else:
result[mode] = record.copy()
parse_enabled = False
continue
elif re.match('^\t\w', line):
pass
# elif not parse_enabled or re.match('^(\s*)#', line):
# continue
else:
continue
data = line.strip().split('=', 1)
record[data[0]] = data[1]
f.close()
return result
except:
return -1
# Get the status.dat file automatically...
for line in open('/etc/nagios/nagios.cfg').readlines():
if line.startswith('status_file='):
status_file = line.strip('\n').split("=")[1]
break
status = get_nagios_status(status_file)
server = 'server1'
# Get information about a host
print status['host'][server]
# Find any issues on a hoot
for service in status['service'][server]:
if int(status['service'][server][service]['current_state']) != 0:
print(service)
</code></pre>
<p>==== EDIT: Below is an example input file (status.dat) ====</p>
<pre><code>########################################
# NAGIOS STATUS FILE
#
# THIS FILE IS AUTOMATICALLY GENERATED
# BY NAGIOS. DO NOT MODIFY THIS FILE!
########################################
info {
created=1399014558
version=3.3.1
last_update_check=1398994015
update_available=1
last_version=3.3.1
new_version=4.0.6
}
programstatus {
modified_host_attributes=0
modified_service_attributes=0
nagios_pid=2953
daemon_mode=1
program_start=1398953444
last_command_check=1399014554
last_log_rotation=1398985200
enable_notifications=1
active_service_checks_enabled=1
passive_service_checks_enabled=1
active_host_checks_enabled=1
passive_host_checks_enabled=1
enable_event_handlers=1
obsess_over_services=0
obsess_over_hosts=0
check_service_freshness=1
check_host_freshness=0
enable_flap_detection=1
enable_failure_prediction=1
process_performance_data=1
global_host_event_handler=
global_service_event_handler=
next_comment_id=8239
next_downtime_id=52
next_event_id=1334236
next_problem_id=590691
next_notification_id=567984
total_external_command_buffer_slots=4096
used_external_command_buffer_slots=0
high_external_command_buffer_slots=1
active_scheduled_host_check_stats=107,394,1097
active_ondemand_host_check_stats=15,95,286
passive_host_check_stats=0,0,0
active_scheduled_service_check_stats=465,2821,8607
active_ondemand_service_check_stats=0,0,0
passive_service_check_stats=0,0,0
cached_host_check_stats=15,94,282
cached_service_check_stats=0,0,0
external_command_stats=0,0,0
parallel_host_check_stats=107,395,1100
serial_host_check_stats=0,0,0
}
hoststatus {
host_name=deep-thought
modified_attributes=0
check_command=check-host-alive
check_period=24x7
notification_period=24x7
check_interval=1.000000
retry_interval=1.000000
event_handler=
has_been_checked=1
should_be_scheduled=1
check_execution_time=4.015
check_latency=4.569
check_type=0
current_state=0
last_hard_state=0
last_event_id=1180007
current_event_id=1180013
current_problem_id=0
last_problem_id=522333
plugin_output=PING OK - Packet loss = 0%, RTA = 0.75 ms
long_plugin_output=
performance_data=rta=0.755000ms;3000.000000;5000.000000;0.000000 pl=0%;80;100;0
last_check=1399014471
next_check=1399014546
check_options=0
current_attempt=1
max_attempts=10
state_type=1
last_state_change=1391171572
last_hard_state_change=1372696148
last_time_up=1399014486
last_time_down=1391171500
last_time_unreachable=0
last_notification=0
next_notification=0
no_more_notifications=0
current_notification_number=0
current_notification_id=0
notifications_enabled=1
problem_has_been_acknowledged=0
acknowledgement_type=0
active_checks_enabled=1
passive_checks_enabled=1
event_handler_enabled=1
flap_detection_enabled=1
failure_prediction_enabled=1
process_performance_data=1
obsess_over_host=1
last_update=1399014558
is_flapping=0
percent_state_change=0.00
scheduled_downtime_depth=0
}
hoststatus {
host_name=another-host
modified_attributes=1
check_command=check-host-alive
check_period=24x7
notification_period=24x7
check_interval=1.000000
retry_interval=1.000000
event_handler=
has_been_checked=1
should_be_scheduled=1
check_execution_time=30.005
check_latency=2.607
check_type=0
current_state=1
last_hard_state=1
last_event_id=1329401
current_event_id=1329409
current_problem_id=588425
last_problem_id=578077
plugin_output=(Host Check Timed Out)
long_plugin_output=
performance_data=
last_check=1399014431
next_check=1399014529
check_options=0
current_attempt=1
max_attempts=2
state_type=1
last_state_change=1398685630
last_hard_state_change=1398685630
last_time_up=1398685440
last_time_down=1399014469
last_time_unreachable=0
last_notification=0
next_notification=0
no_more_notifications=0
current_notification_number=0
current_notification_id=51079
notifications_enabled=0
problem_has_been_acknowledged=0
acknowledgement_type=0
active_checks_enabled=1
passive_checks_enabled=1
event_handler_enabled=1
flap_detection_enabled=1
failure_prediction_enabled=1
process_performance_data=1
obsess_over_host=1
last_update=1399014558
is_flapping=0
percent_state_change=0.00
scheduled_downtime_depth=0
}
servicestatus {
host_name=deep-thought
service_description=Application McAfee DAT Date
modified_attributes=0
check_command=check_windows_nrpe!check_av!3!5
check_period=24x7
notification_period=24x7
check_interval=60.000000
retry_interval=5.000000
event_handler=
has_been_checked=1
should_be_scheduled=1
check_execution_time=0.658
check_latency=0.268
check_type=0
current_state=0
last_hard_state=0
last_event_id=1084911
current_event_id=1084987
current_problem_id=0
last_problem_id=482213
current_attempt=1
max_attempts=3
state_type=1
last_state_change=1388710304
last_hard_state_change=1372696148
last_time_ok=1399014521
last_time_warning=1388710009
last_time_unknown=0
last_time_critical=1372696455
plugin_output=OK - DAT date (01/05/2014)
long_plugin_output=
performance_data=
last_check=1399014521
next_check=1399018121
check_options=0
current_notification_number=0
current_notification_id=0
last_notification=0
next_notification=0
no_more_notifications=0
notifications_enabled=1
active_checks_enabled=1
passive_checks_enabled=1
event_handler_enabled=1
problem_has_been_acknowledged=0
acknowledgement_type=0
flap_detection_enabled=1
failure_prediction_enabled=1
process_performance_data=1
obsess_over_service=1
last_update=1399014558
is_flapping=0
percent_state_change=0.00
scheduled_downtime_depth=0
}
servicestatus {
host_name=deep-thought
service_description=Application Netbackup Version
modified_attributes=0
check_command=check_windows_nrpe!check_netbackup!6.5!6
check_period=24x7
notification_period=24x7
check_interval=60.000000
retry_interval=5.000000
event_handler=
has_been_checked=1
should_be_scheduled=1
check_execution_time=0.563
check_latency=2.887
check_type=0
current_state=0
last_hard_state=0
last_event_id=557354
current_event_id=557367
current_problem_id=0
last_problem_id=260970
current_attempt=1
max_attempts=3
state_type=1
last_state_change=1372696479
last_hard_state_change=1372696148
last_time_ok=1399011262
last_time_warning=0
last_time_unknown=0
last_time_critical=1372696455
plugin_output=Netbackup Not Installed!
long_plugin_output=
performance_data=
last_check=1399011262
next_check=1399014862
check_options=0
current_notification_number=0
current_notification_id=0
last_notification=0
next_notification=0
no_more_notifications=0
notifications_enabled=1
active_checks_enabled=1
passive_checks_enabled=1
event_handler_enabled=1
problem_has_been_acknowledged=0
acknowledgement_type=0
flap_detection_enabled=1
failure_prediction_enabled=1
process_performance_data=1
obsess_over_service=1
last_update=1399014558
is_flapping=0
percent_state_change=0.00
scheduled_downtime_depth=0
}
servicestatus {
host_name=another-host
service_description=Application PowerPath Status
modified_attributes=0
check_command=check_windows_nrpe!check_powerpath!1
check_period=24x7
notification_period=24x7
check_interval=1.000000
retry_interval=1.000000
event_handler=
has_been_checked=1
should_be_scheduled=1
check_execution_time=0.525
check_latency=2.873
check_type=0
current_state=0
last_hard_state=0
last_event_id=1179979
current_event_id=1180016
current_problem_id=0
last_problem_id=522331
current_attempt=1
max_attempts=3
state_type=1
last_state_change=1391171576
last_hard_state_change=1391171576
last_time_ok=1399014497
last_time_warning=0
last_time_unknown=0
last_time_critical=1391171512
plugin_output=Power Path not installed on this machine
long_plugin_output=
performance_data=
last_check=1399014497
next_check=1399014557
check_options=0
current_notification_number=0
current_notification_id=72470
last_notification=0
next_notification=0
no_more_notifications=0
notifications_enabled=1
active_checks_enabled=1
passive_checks_enabled=1
event_handler_enabled=1
problem_has_been_acknowledged=0
acknowledgement_type=0
flap_detection_enabled=1
failure_prediction_enabled=1
process_performance_data=1
obsess_over_service=1
last_update=1399014558
is_flapping=0
percent_state_change=0.00
scheduled_downtime_depth=0
}
servicestatus {
host_name=another-host
service_description=Application Windows Updates
modified_attributes=0
check_command=check_windows_nrpe!check_updates!/w:1!/c:2!/o:1!/x:2
check_period=24x7
notification_period=24x7
check_interval=60.000000
retry_interval=5.000000
event_handler=
has_been_checked=1
should_be_scheduled=1
check_execution_time=32.098
check_latency=0.453
check_type=0
current_state=2
last_hard_state=2
last_event_id=1309596
current_event_id=1309646
current_problem_id=540922
last_problem_id=260968
current_attempt=3
max_attempts=3
state_type=1
last_state_change=1397242439
last_hard_state_change=1397242439
last_time_ok=1392138849
last_time_warning=1397238837
last_time_unknown=1390021982
last_time_critical=1399011650
plugin_output=Number of critical updates not installed: 10 <br />Number of software updates not installed: 1 <br /> Critical updates name: Security Update for Internet Explorer 8 for Windows Server 2003 (KB2964358)+ Cumulative Security Update for Internet Explorer 8 for Windows Server 2003 (KB2936068)+ Windows Malicious Software Removal Tool - April 2014 (KB890830)+ Security Update for Windows Server 2003 (KB2922229)+ Security Update for Windows Server 2003 (KB2929961)+ Security Update for Windows Server 2003 (KB2930275)+ Security Update for Windows Server 2003 (KB2916036)+ Security Update for Microsoft .NET Framework 1.1 SP1 on Windows Server 2003 and Windows Server 2003 R2 x86 (KB2901115)+ Security Update for Microsoft .NET Framework 1.1 SP1 on Windows Server 2003 and Windows Server 2003 R2 x86 (KB2898860)+ Security Update for Windows Server 2003 (KB2909210)+ <br />Software Updates: Update for Windows Server 2003 (KB2927811)+
long_plugin_output=Total No of Updates:11CritLvl: 2 WarnLvl:1OptCritLvl:OptWarnLvl:1\n
performance_data=
last_check=1399011650
next_check=1399015250
check_options=0
current_notification_number=20
current_notification_id=565252
last_notification=1398972073
next_notification=1399404073
no_more_notifications=0
notifications_enabled=1
active_checks_enabled=1
passive_checks_enabled=1
event_handler_enabled=1
problem_has_been_acknowledged=0
acknowledgement_type=0
flap_detection_enabled=1
failure_prediction_enabled=1
process_performance_data=1
obsess_over_service=1
last_update=1399014558
is_flapping=0
percent_state_change=0.00
scheduled_downtime_depth=0
}
contactstatus {
contact_name=24x7
modified_attributes=0
modified_host_attributes=0
modified_service_attributes=0
host_notification_period=24x7
service_notification_period=24x7
last_host_notification=1397636581
last_service_notification=1394546456
host_notifications_enabled=1
service_notifications_enabled=1
}
servicecomment {
host_name=deep-thought
service_description=Application McAfee DAT Date
entry_type=1
comment_id=4238
source=1
persistent=1
entry_time=1375437640
expires=0
expire_time=0
author=nagiosadmin
comment_data=This server is being replaced as it's failing.
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:06:34.707",
"Id": "85585",
"Score": "0",
"body": "Could you give an example of the file, and the dictionary you get out of it? Also, if a file format specification exists, please point us to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:16:01.613",
"Id": "85586",
"Score": "0",
"body": "I've updated the post to include an example. Can't find any specification for the document but the example should be enough to show how it's layed out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:15:24.050",
"Id": "85656",
"Score": "0",
"body": "Python 2x or 3x?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:37:41.543",
"Id": "85661",
"Score": "0",
"body": "Works on both 2.7 and 3 (tested on Python 4).NB: The print \"\" is the only thing that needs to be changed obviously for Py3, moved the script to a Python 3 install to test."
}
] | [
{
"body": "<p>Firstly, you should use the <code>with</code> context manager to handle your file:</p>\n\n<pre><code>with open(path) as f: # 'r' is the default\n for line in f.readlines():\n ...\n</code></pre>\n\n<p>This will handle any file-related errors and ensure the file is closed correctly.</p>\n\n<p>Second, you could simplify your <code>result</code> dictionary handling with one of a few options:</p>\n\n<ol>\n<li><code>if result.get(mode) is None:</code> (<code>None</code> is the default for <code>d</code>);</li>\n<li>Initialise as <code>result = {'host': {}, 'service': {}, 'info': {}, 'program': {}}</code>; or</li>\n<li>Initialise as <code>result =</code><a href=\"https://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"nofollow\"><code>collections.defaultdict(dict)</code></a>.</li>\n</ol>\n\n<p>Third, your main function is quite long. I would suggest you break a few bits out into smaller functions, e.g.</p>\n\n<pre><code>record.update(parse_data_line(data))\n</code></pre>\n\n<p>where</p>\n\n<pre><code>def parse_data_line(data):\n \"\"\"Parse a single line of the file.\"\"\"\n data = data.strip().split(\"\", 1)\n return {data[0]: data[1]}\n</code></pre>\n\n<p>Another obvious candidate:</p>\n\n<pre><code>elif parse_enabled and re.match('^\\t\\}$', line):\n process_record(record, mode, result)\n</code></pre>\n\n<p>You can also use <code>re</code> more cleverly, and be more explicit about which parts of the file you want:</p>\n\n<pre><code>MODES = {\"hoststatus\": \"host\", \"info\": \"info\", ...} # define modes you want\n...\nmatches = re.findall(r'^(\\w+) \\{$', line)\nif matches:\n mode = MODES.get(matches[0])\n if mode is None:\n continue\n</code></pre>\n\n<p><em>(<strong>Note</strong>: option 2 above can now be <code>result = {k: {} for k in MODES}</code> to reduce duplication)</em></p>\n\n<p>Now your main function looks like:</p>\n\n<pre><code>def get_nagios_status(path):\n MODES = {\"hoststatus\": \"host\", \"info\": \"info\", ...}\n result = {k: {} for k in MODES}\n parse_enabled = False\n with open(path) as f:\n for line in f.readlines():\n line = line.rstrip()\n matches = re.findall(r'^(\\w+) \\{$', line)\n if matches:\n mode = MODES.get(matches[0])\n if mode is None:\n continue\n parse_enabled = True\n record = {}\n elif parse_enabled and re.match('^\\t\\}$', line):\n process_record(record, mode, result)\n parse_enabled = False\n elif parse_enabled and re.match('^\\s*.*=.*$', line):\n record.update(parse_data_line(line))\n return result or -1\n</code></pre>\n\n<p>This is much more readable, partly as that function fits into one screen.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:07:58.780",
"Id": "48800",
"ParentId": "48664",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Catching all exceptions and returning -1 is a bad idea. The exceptions contain information what exactly went wrong. Maybe the file was not accessible, or maybe you have a simple bug in your code, you can't tell.</li>\n<li>What's worse is that you don't even check for the -1 return value after calling the function. If anything goes wrong you'll get a completely unhelpful exception from trying to access <code>status['host']</code> while <code>status</code> is an integer.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T10:07:04.037",
"Id": "86145",
"Score": "0",
"body": "Agreed, this was one of my earlier scripts so returning -1 was perhaps what I thought would be a good idea but just didn't get around to. Thanks for the feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:17:15.563",
"Id": "48802",
"ParentId": "48664",
"Score": "2"
}
},
{
"body": "<p>Unfortunately I was not able to get the code to run and produce any results even though I adjusted it to load the data file. It just returned an empty dict. Rather than try to figure out why, I took a look at the things I would change based on reading through the code and just made those changes, it seems to work after I did that, not really sure what the cause was but I did do the testing on Windows which may have had something to do with it.</p>\n\n<p>Here are the things I focused on:</p>\n\n<ol>\n<li>Use a context manager to do the file opening rather than the try except up top and then closing the file manually at the bottom.</li>\n<li>Don't bother with <code>f.readlines()</code> just do <code>for line in f:</code>.</li>\n<li>Stripped both sides of the line rather than the right side first and then the left side later.</li>\n<li>Pulled out regular expressions and the parse flag, just use the mode as the flag, set it to <code>None</code> if the mode is not of interest.</li>\n<li>Changed the <code>if line.find(...) >= 0</code>, just use <code>if ... in line</code>.... but it may be even easier to just lookup the \"mode\" in a list of \"modes\" you are tracking so I changed that.</li>\n<li>I changed the mode naming to match the file. That was just to make things easier. If you really want them renamed perhaps the modes could be a dict rather than a list.</li>\n<li>Replaced <code>result.get(mode, None) is None:</code> with <code>if 'hoststatus' in mode:</code> style check.</li>\n<li>Before setting the values into the record, I checked to make sure there was something on the right side of the equal <code>if len(data) > 1:</code>. This may be something that the regular expressions avoid but it didn't run right for me.</li>\n<li>At the bottom of your code you should put in the <code>if __name__ == '__main__':</code>.</li>\n<li>There were a couple pep8 issues with line length. I just broke them down a bit.</li>\n<li>Removed all imports since I didn't need them anymore.</li>\n</ol>\n\n<p>As was already mentioned, I also am not crazy about -1 return, I would rather see it raise the exception rather than an odd exception later about integer subscript so I removed the try/except negative 1 return.</p>\n\n<p>Here is the code I came up with after applying the changes mentioned above:</p>\n\n<pre><code>def get_nagios_status(path):\n \"\"\"\n Parse the Nagios status.dat file into a dict to give the ability to report\n on host/service information\n\n `path` is the absolute path to the Nagios status.dat\n\n Return dict() if OK\n \"\"\"\n result = {}\n mode = None\n modes = ['hoststatus', 'servicestatus', 'info', 'programstatus']\n\n with open(path, 'r') as f:\n for line in f:\n line = line.strip()\n\n # Mode starting\n if line.endswith('{'):\n mode = line.split()[0]\n\n if mode in modes:\n record = {}\n if mode not in result:\n result[mode] = {}\n else:\n mode = None\n\n # Mode ending\n elif line.endswith('}') and mode:\n if 'hoststatus' in mode:\n result[mode][record['host_name']] = record.copy()\n\n elif 'servicestatus' in mode:\n if record['host_name'] not in result[mode]:\n result[mode][record['host_name']] = {}\n\n result[mode][record['host_name']][\n record['service_description']] = record.copy()\n else:\n result[mode] = record.copy()\n\n mode = None\n\n # Collect the data if we are interested\n elif mode:\n data = line.split('=', 1)\n if len(data) > 1:\n record[data[0]] = data[1]\n\n return result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T10:04:40.640",
"Id": "86144",
"Score": "0",
"body": "Thank you - great feedback! I think it could be further improved with some of the comments by @jonrsharpe so will have a play but it's looking much better. Funnily enough I use 'with' these days - this was one of my earlier scripts."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T04:50:50.363",
"Id": "48844",
"ParentId": "48664",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48844",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:54:48.740",
"Id": "48664",
"Score": "1",
"Tags": [
"python"
],
"Title": "Nagios status.dat to dict() - Could it be better?"
} | 48664 |
<p>I have <a href="https://github.com/bminer/node-blade" rel="nofollow">this blade</a> template with a main.scss file:</p>
<pre><code>include "layout.blade"
replace block page
ul.brand(data-orbit data-options="animation:slide;\
pause_on_hover:true;\
animation_speed:500;\
slide_number:false;\
navigation_arrows:false;\
bullets:false;\
swipe:true;")
li.cta
.row.slide
.large-5.columns
i.icon-continental-logo
h1="Continental Collection"
h2="Quality Garments, Responsibly Sourced"
a(href="/")="Discover Continental"
.large-7.columns
img.shadow(src="/images/slider/continental_duo_shadow.jpg")
img.figure(src="/images/slider/continental_duo.png")
li.salvage
.row.slide
.large-5.columns
i.icon-salvage-logo
h1="Salvage Collection"
h2="A new range of clothing, 100% Recycled"
a(href="/")="Discover Salvage"
.large-7.columns
img.shadow(src="/images/slider/salvage_duo_shadow.jpg")
img.figure(src="/images/slider/salvage_duo.png")
</code></pre>
<p><strong>main.scss</strong></p>
<pre><code>$header-font-family: "Roboto Condensed", "Arial", "sans-serif";
// Primary colors
$ccc-color-ccc : rgb(137,0,0); // #89000, darkbrown
$ccc-color-continental : rgb(60,113,145); // #3C7191, blue
$ccc-color-earthpositive : rgb(0,151,95); // #00975F, green
$ccc-color-salvage : rgb(205,113,38); // #CD7126, brown
@mixin collection($main-color) {
color: $main-color;
}
h1, h2, h3 {
font-family: $header-font-family;
margin-bottom: 20px;
}
ul.brand {
i {
font-size: 50px;
}
a {
display: table;
padding: 10px 15px;
min-width: 230px;
font-weight: 700;
text-transform: uppercase;
line-height: 1;
margin: 20px auto;
text-align: center;
cursor: pointer;
@include single-transition($ease:0.2s) {
transition-delay: $ease;
};
&:hover {
-webkit-box-shadow: 0px 0px 0px 10px #BCBCBC;
-moz-box-shadow: 0px 0px 0px 10px #BCBCBC;
box-shadow: 0px 0px 0px 10px #BCBCBC;
color: #FFF;
}
}
li.cta {
i, h1, h2, a {
@include collection($ccc-color-continental)
}
a {
border: 1px solid $ccc-color-continental;
&:hover {
background-color: $ccc-color-continental;
color: #FFF;
}
}
}
li.salvage {
i, h1, h2, a {
@include collection($ccc-color-salvage)
}
a {
border: 1px solid $ccc-color-salvage;
&:hover {
background-color: $ccc-color-salvage;
color: #FFF;
}
}
}
}
</code></pre>
<p>I am trying to figure out how best to deal with the <code>a</code>, <code>h1</code>, <code>h2</code> and <code>i</code> block within the <code>li</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:44:01.310",
"Id": "85518",
"Score": "0",
"body": "is your Jade correct? I just glanced at the jade-lang website and it looks like your syntax is off a bit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:42:06.023",
"Id": "85605",
"Score": "0",
"body": "i am using https://github.com/bminer/node-blade which is very similar to jade"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:11:51.557",
"Id": "85638",
"Score": "0",
"body": "You should mention that in your post because the syntax is different, and probably change the title as well. You should also Add the CSS tag and the HTML tag(I only say this because it is an HTML/CSS building Template system)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T12:44:41.480",
"Id": "48667",
"Score": "2",
"Tags": [
"sass",
"mixins"
],
"Title": "Blade (similar to Jade) template with SCSS"
} | 48667 |
<p>I'm building my own micro MVC framework with only the absolute core functionality. My router will call the controller depending on the request method (GET or POST), and if the called action isn't supported it will default to the index action.</p>
<p>Is my approach correct? Any suggestions for improvement?</p>
<pre><code>abstract class Controller
{
protected $action;
protected $params;
public function __construct($action, $params)
{
$this->action = $action;
$this->params = $params;
}
public abstract function GET();
public abstract function POST();
}
class IndexController extends Controller
{
public function GET()
{
$action = $this->action;
$this->$action();
}
public function POST()
{
$this->GET(); //no POST support
}
private function index()
{
$indexView = new View('index');
$indexView->welcome = 'Welcome!';
$indexView->render();
}
}
</code></pre>
| [] | [
{
"body": "<p>I would remove both <code>GET()</code> and <code>POST()</code> methods from both <code>IndexController</code> and from <code>Controller</code> and instead of that I would implement a method <code>getRequest()</code> in <code>Controller</code> class.</p>\n\n<p>The <code>getRequest()</code> method would return <code>Request</code> object with appropriate API for working with HTTP requests, for example:</p>\n\n<ul>\n<li><code>isMethod($method)</code> - usage: <code>isMethod('POST')</code></li>\n<li><code>get($parameterName)</code> - usage: <code>get('id')</code></li>\n<li><code>getLocale()</code></li>\n<li><code>getBaseUrl()</code></li>\n<li><code>getHost()</code></li>\n</ul>\n\n<p>Sample usage would be fore example:</p>\n\n<pre><code>class IndexController extends Controller\n function indexAction(){\n $request = $this->getRequest();\n\n if ($request->isMethod('POST')){\n // Process request \n }\n\n // View relevant code\n }\n}\n</code></pre>\n\n<p>If you really want to build MVC framework then you should work with views, the good way is for example to create a generic view class which will map controller actions to corresponding view files instead of generating content inside your controller, basically, your controller actions should return an array of parameters, like this:</p>\n\n<pre><code>function indexAction(){\n return arrray(\n 'param' => 'value',\n )\n}\n</code></pre>\n\n<p>And after that you should inject the array into view class, which would map the request to proper view file, in your view, which would be called for example <code>index.php</code> you would just do something like this:</p>\n\n<pre><code><html>\n <body>\n <?= escape($param) ?>\n </body>\n</html>\n</code></pre>\n\n<p>Although, it is good to use <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">dependency injection pattern</a>. I am not sure if there actually exists any widely used modern MVC framework which does not use it.</p>\n\n<p>It is good to check how MVC is implemented in modern frameworks like <a href=\"http://symfony.com\" rel=\"nofollow\">Symfony2</a>, <a href=\"http://symfony.com\" rel=\"nofollow\">Laravel</a> and similar, although Laravel is built upon Symfony2 components.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:59:37.193",
"Id": "85509",
"Score": "0",
"body": "I actually am using a similar way of returning parameters from the controller action to the View. By using the magic methods that sets variables on the fly. As with `$indexView->welcome = 'Welcome!';` As you might've seen I have a View class that takes care of rendering the templates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:05:05.303",
"Id": "85510",
"Score": "0",
"body": "@KidDiamond I understand, but this shouldn't be done in Controller action. Controller action should just return corresponding array or Object and rendering, mapping view files etc. should be done somewhere else. Such implementation is hard to cover with tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:08:50.407",
"Id": "85511",
"Score": "0",
"body": "Right now, I'm using one View class to handle every template rendering. So that would mean I have to create a specific View class for every controller or action? And I actually have a RequestHandler that has the exact same methods as you suggested for my Router, so all I would have to do is use this handler and let it work with the Controller too, I think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:13:38.153",
"Id": "85512",
"Score": "0",
"body": "@KidDiamond No, just one generic view class for all Controllers. The view class should accept in its constructor parameters required for rendering corresponding view and the view class should be called automatically at one place. Right now you need to create an instance of view class in each action."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:19:51.970",
"Id": "85513",
"Score": "0",
"body": "So the best would be to instantiate only 1 View object per controller, instead of action. Right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:25:08.510",
"Id": "85515",
"Score": "0",
"body": "And then just set the parameters based on what action is executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:32:37.890",
"Id": "85517",
"Score": "0",
"body": "@KidDiamond You might create an instance of your view class, for example in the abstract controller class and then access it in all controllers which extend the abstract controller class. That's one of solutions, but not the best one. It is good to check how this functionality is implemented in some of modern MVC frameworks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T01:05:13.297",
"Id": "85560",
"Score": "0",
"body": "I updated my code in my post. Does that looks better now? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:54:36.277",
"Id": "85583",
"Score": "0",
"body": "@KidDiamond Yes, definitely better."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:30:37.643",
"Id": "48702",
"ParentId": "48668",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48702",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:19:00.793",
"Id": "48668",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"mvc",
"url-routing"
],
"Title": "Micro MVC framework"
} | 48668 |
<p>How can this be optimized?</p>
<pre><code>$text = "reverseesrever"; // Reverse and esrever
$b = false;
for($i = 0; $i < strlen($text); $i++) {
if($text[$i] !== $text[strlen($text) - 1 - $i]) {
$b = true;
break;
}
}
echo ($b) ? "YES" : "NO"; // result: NO.
</code></pre>
| [] | [
{
"body": "<p>The title of the question is confusing. The code seem to check if the text is not the same if you read it backward. For example, it <code>$b</code> will be true for \"hello\" and false for \"level\". In other words, you're checking if some text is NOT a palindrome. I think you should change the title to better reflect what the code is doing.</p>\n\n<p>Things to improve:</p>\n\n<ul>\n<li>It's enough to iterate until <code>strlen($text) / 2</code>, no need to go all the way until the end</li>\n<li>To avoid re-calculating the length of the string, it's better to calculate it once before the loop and reuse it</li>\n<li>Wrap the whole thing in a function to make it easier to reuse and to test</li>\n<li>The <code>!==</code> is unnecessary, a simple <code>!=</code> would do</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>function isPalindrome($text) {\n $length = strlen($text);\n for ($i = 0; $i < $length / 2; $i++) {\n if ($text[$i] != $text[$length - 1 - $i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction test_isPalindrome($text) {\n printf(\"isPalindrome(%s) -> %s\\n\", $text, isPalindrome($text) ? 'YES' : 'NO');\n}\n\ntest_isPalindrome(\"reverseesrever\");\ntest_isPalindrome(\"hello\");\ntest_isPalindrome(\"aba\");\ntest_isPalindrome(\"aa\");\ntest_isPalindrome(\"ab\");\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>isPalindrome(reverseesrever) -> YES\nisPalindrome(hello) -> NO\nisPalindrome(aba) -> YES\nisPalindrome(aa) -> YES\nisPalindrome(ab) -> NO\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:18:47.553",
"Id": "48673",
"ParentId": "48671",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>You are using <code>strlen</code> method each cycle 2 times, that means that if you have a string which is long 100 characters, then you will use <code>strlen</code> 200 times!</p>\n\n<p>For cycle in PHP works like this:</p>\n\n<pre><code>for (expr1, expr2, expr3){\n\n}\n</code></pre>\n\n<ul>\n<li><code>expr1</code> is evaluated once</li>\n<li><code>expr2</code> is evaluated in the beginning of each iteration </li>\n<li><code>expr3</code> is executed at the end of each iteration</li>\n</ul>\n\n<p>You should calculate the length of string before using it in for cycle.</p>\n\n<p>Read more about for cycle in <a href=\"http://www.php.net/manual/en/control-structures.for.php\" rel=\"nofollow\">PHP documentation</a>.</p></li>\n<li><p>As mentioned in the other answer by @janos, you don't need to iterate over whole string, but you still need to know the length of whole string for this condition:</p>\n\n<pre><code>if($text[$i] !== $text[strlen($text) - 1 - $i]) {\n $b = true;\n break;\n}\n</code></pre>\n\n<p>Otherwise you will always get <code>YES</code> as result.</p></li>\n<li><p>You can use <code>''</code> for wrapping your string instead of <code>\"\"</code>. In the second case PHP interpreter does not need to check for variables inside the string. This does not have any noticable impact on performance.</p></li>\n<li><p>You are using <code>!==</code> but in this case it is sufficient to use <code>!=</code>, however, this does have any noticable impact on performance as well. </p></li>\n<li><p>If you are going to reuse the code, you might consider wrapping it into a function.</p>\n\n<p>I rewrote your code (no function included):</p>\n\n<pre><code>$text = 'reverseesrever';\n$iterateLength = strlen($text) / 2;\n$length = strlen($text) - 1;\n\n$b = false;\nfor($i = 0; $i < $iterateLength; $i++) { \n if($text[$i] != $text[$length - $i]) {\n $b = true;\n break;\n }\n}\n\necho ($b) ? 'YES' : 'NO';\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:17:20.537",
"Id": "48683",
"ParentId": "48671",
"Score": "2"
}
},
{
"body": "<p>I'm not sure if I'm missing the point of your function, but I feel it could be a lot shorter and more efficient.</p>\n\n<p>I suggest using a simple <code>strrev()</code> to reverse the string, for comparison.</p>\n\n<p>Try,</p>\n\n<pre><code>$string = 'reverseesrever';\necho ($string === strrev($string)) ? 'YES' : 'NO';\n</code></pre>\n\n<p>I've used the same strings as a previous answer, and I get the same response.</p>\n\n<pre><code>\"reverseesrever\" -> YES\n\"hello\" -> NO\n\"aba\" -> YES\n\"aa\" -> YES\n\"ab\" -> NO\n</code></pre>\n\n<p>This would cut out iterations and multiple calls to <code>strlen</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T12:35:32.190",
"Id": "48924",
"ParentId": "48671",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48673",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:44:32.397",
"Id": "48671",
"Score": "3",
"Tags": [
"php",
"strings",
"palindrome"
],
"Title": "Find the inverted value of the string"
} | 48671 |
<p>I'm fairly new to C# and I thought this program was so simple it was a great candidate for a good ol' code review. This program syncs the results of one MSSQL database and puts them into a MySQL database based on the datetime value. I always tend to do things the hard way when I start off on a program and I am always seeking to improve this. Let me know if you see anything that needs improvement or if I did anything dumb.</p>
<p><strong>Main Program</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace TransferOfData
{
public class TransferData
{
static void Main(string[] args)
{
ErrorLogger el = new ErrorLogger();
InitializeDB idb = new InitializeDB();
MySqlDataReader myrdr = null;
SqlDataReader msrdr = null;
string strLastDBUpdate = null;
idb.OpenDatabases();
//Run the query that will collect the last date the database was updated from the mssql database
try
{
string sqlLastDBUpdate = "select max(dIntervalStart) intervalStart from forecasts.statistics";
MySqlCommand mycmd = new MySqlCommand(sqlLastDBUpdate, idb.myconn);
myrdr = mycmd.ExecuteReader();
if (myrdr.Read())
{
strLastDBUpdate = myrdr.GetString(0);
}
myrdr.Close();
}
catch (Exception e)
{
el.errorCode = 2;
el.errorDescription = e.ToString();
el.createError();
}
//Now we will get all of the results from the mssql database and transfer them to the mysql database
try
{
string strCatchUp = "select dIntervalStart, nExterntoInternAcdCalls, cName " +
"from IWrkgrpQueueStats " +
"where SiteId = 1 " +
"and cname in ('applications' , 'employer', " +
"'factfind', " +
"'general', " +
"'other') " +
"and cReportGroup = '*' " +
"and dIntervalStart > '" + strLastDBUpdate + "'";
SqlCommand mscmd = new SqlCommand(strCatchUp, idb.msconn);
msrdr = mscmd.ExecuteReader();
while (msrdr.Read())
{
try
{
string strdIntervalStart = msrdr["dIntervalStart"].ToString();
int intnExternToInternAcdCalls = System.Convert.ToInt32(msrdr["nExternToInternAcdCalls"]);
string cName = msrdr["cName"].ToString();
string sqlInsertUpdate = "INSERT INTO `forecasts`.`statistics` (`dIntervalStart`, `nExternToInternAcdCalls`, `cName`, `DateCreated`, `DateModified`) "
+ "VALUES (@dIntervalStart, @nExternToInternAcdCalls, @cName, now(), now())";
MySqlCommand cmdInsertUpdate = new MySqlCommand(sqlInsertUpdate, idb.myconn);
cmdInsertUpdate.Parameters.AddWithValue("@dIntervalStart", System.Convert.ToDateTime(strdIntervalStart));
cmdInsertUpdate.Parameters.AddWithValue("@nExternToInternAcdCalls", intnExternToInternAcdCalls);
cmdInsertUpdate.Parameters.AddWithValue("@cName", cName);
cmdInsertUpdate.ExecuteNonQuery();
}
catch (Exception e)
{
el.errorCode = 3;
el.errorDescription = e.ToString();
el.createError();
}
}
}
catch (Exception e)
{
el.errorCode = 4;
el.errorDescription = e.ToString();
el.createError();
}
idb.myconn.Close();
idb.msconn.Close();
}
}
}
</code></pre>
<p><strong>Initialize Database and create connections</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace TransferOfData
{
public class InitializeDB
{
ErrorLogger el = new ErrorLogger();
public SqlConnection msconn { get; private set;}
public MySqlConnection myconn { get; private set;}
public void OpenDatabases()
{
string msConnectionString = "user id=user;" +
"password='password';server=vsc002sql;" +
"Trusted_Connection=yes;" +
"database=I3_IC; " +
"connection timeout=30";
string myConnectionString = ("SERVER=localhost; DATABASE=forecasts;"
+ "UID=root; PASSWORD=;");
try
{
msconn = new SqlConnection(msConnectionString);
myconn = new MySqlConnection(myConnectionString);
msconn.Open();
myconn.Open();
}
catch (Exception e)
{
el.errorCode = 1;
el.errorDescription = e.ToString();
el.createError();
}
}
}
}
</code></pre>
<p><strong>Logging Errors</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TransferOfData
{
public class ErrorLogger
{
public int errorCode { private get; set; }
public string errorDescription { private get; set; }
public void createError()
{
string logPath = @"C:\Logs\Scheduler\transferFileLog.txt";
string errorFinal;
errorFinal = "TransferData Error code: " + errorCode + "\n";
errorFinal += "Description:\n";
errorFinal += errorDescription + "\n";
errorFinal += "------------------------------------------------------------\n\n";
using (StreamWriter sw = File.AppendText(logPath))
{
sw.Write(errorFinal);
}
Console.WriteLine("An error has occurred. Check the error log at " + logPath + " for further information.");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:06:14.753",
"Id": "85488",
"Score": "0",
"body": "have you tested this code to make sure that it runs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:32:16.223",
"Id": "85496",
"Score": "0",
"body": "`ErrorLogger.createError()` should be `ErrorLogger.CreateError()` to be consistent ;)"
}
] | [
{
"body": "<p>One of the things I see that could be improved is this line:</p>\n\n<pre><code> \"and dIntervalStart > '\" + strLastDBUpdate + \"'\";\n</code></pre>\n\n<p>You should use parameters as you did after.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:44:30.477",
"Id": "85485",
"Score": "0",
"body": "You are correct. I have just added it as a parameter per your suggestion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:25:25.560",
"Id": "48686",
"ParentId": "48672",
"Score": "5"
}
},
{
"body": "<p>you should use some <code>Using</code> statements so that your connections are disposed of no matter what happens with the code, like if there is an exception.</p>\n\n<pre><code>string sqlLastDBUpdate = \"select max(dIntervalStart) intervalStart from forecasts.statistics\";\nUsing (mycmd = new MySqlCommand(sqlLastDBUpdate, idb.myconn))\n{ \n myrdr = mycmd.ExecuteReader();\n if (myrdr.Read())\n {\n strLastDBUpdate = myrdr.GetString(0);\n }\n myrdr.Close();\n}\n</code></pre>\n\n<p>You can also put <code>myrdr = mycmd.ExecuteReader();</code> into a using like this</p>\n\n<pre><code>string sqlLastDBUpdate = \"select max(dIntervalStart) intervalStart from forecasts.statistics\";\nUsing (mycmd = new MySqlCommand(sqlLastDBUpdate, idb.myconn))\n{ \n Using (myrdr = mycmd.ExecuteReader())\n {\n if (myrdr.Read())\n {\n strLastDBUpdate = myrdr.GetString(0);\n }\n }\n}\n</code></pre>\n\n<p>and then you don't actually need the closing statement because the <code>Using</code> does the closing automatically.</p>\n\n<hr>\n\n<p>You should also take advantage of the <code>try catch</code>'s Finally statement, which you actually won't need if you use a <code>Using</code> statement because it automatically closes the connections.</p>\n\n<p>it would look something like this if you decide to use the <code>Try Catch Finally</code></p>\n\n<pre><code>try\n{\n string sqlLastDBUpdate = \"select max(dIntervalStart) intervalStart from forecasts.statistics\";\n MySqlCommand mycmd = new MySqlCommand(sqlLastDBUpdate, idb.myconn);\n myrdr = mycmd.ExecuteReader();\n if (myrdr.Read())\n {\n strLastDBUpdate = myrdr.GetString(0);\n }\n}\ncatch (Exception e)\n{\n el.errorCode = 2;\n el.errorDescription = e.ToString();\n el.createError();\n}\nfinally\n{\n myrdr.Close();\n}\n</code></pre>\n\n<p>with the closing inside the <code>try</code> statement, you don't need it there when you put it in the <code>finally</code>, inside the `finally it will be closed no matter what happens with your code.</p>\n\n<hr>\n\n<p>I don't know what your <code>InitializeDB idb = new InitializeDB();</code> is made up of, but if it makes use of the <code>IDisposable</code> interface you could also use that in a <code>Using</code> statement surrounding your data reader <code>Using</code> statement that way no matter where the exception happens the connection is disposed of and so it the reader, and they would be disposed in the order that they need to be.</p>\n\n<hr>\n\n<p>instead of using a <code>StreamWriter.Write()</code> you could use a <code>StreamWriter.WriteLine()</code> and get rid of an extra variable in the function.</p>\n\n<pre><code> public void createError()\n {\n string logPath = @\"C:\\Logs\\Scheduler\\transferFileLog.txt\";\n Using (StreamWriter sw = File.AppendText(logPath))\n {\n sw.WriteLine(\"TransferData Error code: \" + errorCode);\n sw.WriteLine(\"Description:\");\n sw.WriteLine(errorDescription);\n sw.WriteLine(\"------------------------------------------------------------\\n\");\n //sw.Write(errorFinal);\n }\n Console.WriteLine(\"An error has occurred. Check the error log at \" + logPath + \" for further information.\");\n }\n</code></pre>\n\n<p>you should add parameters to this function as well, then you can send the variables <code>errorCode</code> and <code>errorDescription</code> to it and take care of it in one swift movement, then you can also get rid of the property declarations, I don't think they are necessary.</p>\n\n<p>just change the Method Declaration to:</p>\n\n<pre><code>public void CreateError(int errorCode, string errorDescription)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:05:32.773",
"Id": "48697",
"ParentId": "48672",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48697",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:00:20.210",
"Id": "48672",
"Score": "5",
"Tags": [
"c#",
"beginner"
],
"Title": "Storing synced results of a MSSQL database into a MySQL database"
} | 48672 |
<p>I had a problem where I needed to find the largest amount of passengers in multiple cars/vans etc, so I got the totals from each vehicle and added them to a list, I then created this method to sort the list...</p>
<pre><code>static List<int> SortList(List<int> tobesorted)
{
var j = 0;
int JP = 0;
int value1 = Convert.ToInt32(tobesorted[j]);
int value2 = Convert.ToInt32(tobesorted[JP]);
for (var i = 0; i < tobesorted.Count-1; i++)
{
for (j = 0; j < tobesorted.Count-1; j++)
{
JP = (j + 1);
value1 = Convert.ToInt32(tobesorted[j]);
value2 = Convert.ToInt32(tobesorted[JP]);
if (value2 > value1)
{
tobesorted[j] = value2;
tobesorted[JP] = value1;
}
}
j = 0;
JP = 0;
}
return tobesorted;
}
</code></pre>
<p>I don't understand is this is acceptable, and if not what methods are? It seems quick enough, I know of sorting algorithms, but haven't ever been forced to use any.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:00:30.980",
"Id": "85453",
"Score": "1",
"body": "Why can't you use [sort method](http://msdn.microsoft.com/en-us/library/b0zbh7b6(v=vs.110).aspx)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:01:17.883",
"Id": "85454",
"Score": "0",
"body": "I can, I just wanted to see if I could do it without?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:28:48.360",
"Id": "85460",
"Score": "1",
"body": "I downvoted because I think you COULD put a little more effort in your code/research. Your sort algorithm as is do not sort. CodeReview NORMALY is a place where you provide code that SHOULD be semanthicaly correct or at least as correct as possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:40:06.507",
"Id": "85467",
"Score": "0",
"body": "Well, I disagree, I posted here as I was looking for the answers that I have gotten; so I think I was right to post here as it's shown me exactly what i asked for. The code does sort, at least it does my end, but that depends on your definition of sorting. \n\nI typed my question carefully, and I also believed that the code I wrote to be be as correct as possible at my current knowledge level with C#. If I was just posting correct code, what would be the point? I wrote code that I felt happy with, but needed guidance with too. \n\n\"Share code from projects you are working on for peer review.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:43:56.930",
"Id": "85469",
"Score": "1",
"body": "Actually I am sorry for that. I wasn't expecting a descending sort"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:16:29.810",
"Id": "85477",
"Score": "2",
"body": "@BrunoCosta Nobody expects a descending sort. :-)"
}
] | [
{
"body": "<blockquote>\n<pre><code>int value1 = Convert.ToInt32(tobesorted[j]);\nint value2 = Convert.ToInt32(tobesorted[JP]);\n</code></pre>\n</blockquote>\n\n<p><code>tobesorted</code> is a <code>List<int></code>. Hence, all its items are <code>int</code>. <code>int</code> is a C# language alias / shortcut for <code>System.Int32</code> - therefore, the calls to <code>Convert.ToInt32</code> are redundant and can be safely removed.</p>\n\n<p>Who's JP? (i.e. use <em>meaningful</em> variable names ;)</p>\n\n<p><code>List<T></code> already has a built-in <code>Sort</code> method that should do the trick...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:45:59.387",
"Id": "85470",
"Score": "1",
"body": "Convert.ToInt32 is a bad habit of mine, I do it all over my code so I will take note of that. I think that's a remnant of the strings I was originally dealing with!\n\nHave taken them out though, so thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:10:23.547",
"Id": "48678",
"ParentId": "48676",
"Score": "6"
}
},
{
"body": "<p>Mat's Mug is completly right. You shouldn't be calling Convert.ToInt32 in your method since you already know that your list items are of type int. Here is your sort alghorithm, the selecting sort algorithm.</p>\n\n<pre><code>static List<int> SortList(List<int> list)\n{\n for (int i = 0; i < list.Count-1; i++)\n {\n int idxMin = i;\n for (int j = i+1; j < list.Count; j++)\n {\n if (list[j] < list[idxMin])\n {\n idxMin = j;\n }\n }\n int aux = list[i];\n list[i] = list[idxMin];\n list[idxMin] = aux;\n }\n\n return list;\n}\n</code></pre>\n\n<p>and a test case</p>\n\n<pre><code>List<int> list = new List<int>(){17,7,3,4,11,15,23,5,10,1};\nforeach(int i in SortList(list)){\n Console.Write(\"{0}, \", i);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:09:11.190",
"Id": "85473",
"Score": "1",
"body": "booooo modifying the input parameters booooo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:11:36.017",
"Id": "85474",
"Score": "0",
"body": "it's nothing less than an option, I guess... If you know that the method does that then it's ok. Though I think I would also prefer to do a copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:13:56.567",
"Id": "85476",
"Score": "0",
"body": "I didn't downvote, I'm just being a peanut gallery"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:16:34.350",
"Id": "48682",
"ParentId": "48676",
"Score": "2"
}
},
{
"body": "<p>j is initialized every time the inner loop executes. So there is no need to define it in the outer scope.\nYou can remove j in the outer scope and define the inner loop as</p>\n\n<pre><code>for (int j = 0; j < tobesorted.Count-1; j++)\n {\n // ...\n }\n</code></pre>\n\n<p>With this change there is no need to reset the value of j after the completion of inner loop.</p>\n\n<p>Since tobesorted is a reference type so the method definition can be changed to </p>\n\n<pre><code>static void SortList(List<int> tobesorted)\n{\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:19:09.510",
"Id": "48684",
"ParentId": "48676",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>I needed to find the largest amount of passengers</p>\n</blockquote>\n\n<p>If you need just the largest amount, you don't need to sort the whole list (which is slow*), you can instead walk though the list, remember the largest amount found so far and update that as you iterate the list.</p>\n\n<p>LINQ already contains a method that does just that, called <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb292667\"><code>Max()</code></a>.</p>\n\n<hr>\n\n<p>* Sorting is \\$\\mathcal{O}(n \\log n)\\$ with a good algorithm, or \\$\\mathcal{O}(n^2)\\$ with a trivial algorithm like the one you used; finding maximum is just \\$\\mathcal{O}(n)\\$.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:55:04.880",
"Id": "85472",
"Score": "0",
"body": "Finding max can also be O(1) on a heap but that comes at a cost of O(lg n) in insertion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:12:28.840",
"Id": "85475",
"Score": "1",
"body": "@BrunoCosta Yes, a heap makes sense if you need to find max repeatedly in a changing collection, but I don't think that's the case here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:33:30.130",
"Id": "48687",
"ParentId": "48676",
"Score": "11"
}
},
{
"body": "<p>It looks to me that you're trying to scratch your ear by reaching around your elbow. Assuming you have a class representing the Vehicle, something like this:</p>\n\n<pre><code>enum VehicleType\n{\n None,\n Van,\n Sedan,\n HatchBack,\n PickUp\n}\npublic class Vehicle\n{\n public VehicleType Type = VehicleType.None;\n public int MaxPassengers = 0;\n public int NumPassengers = 0;\n}\n</code></pre>\n\n<p>And a list of these vehicles:</p>\n\n<pre><code>List<Vehicle> vehicles = new List<Vehicle>()\n{\n new Vehicle{Type = VehicleType.Van, MaxPassengers = 8, NumPassengers = 5},\n new Vehicle{Type = VehicleType.Sedan, MaxPassengers = 5, NumPassengers = 3},\n new Vehicle{Type = VehicleType.PickUp,MaxPassengers = 3, NumPassengers = 1},\n};\n</code></pre>\n\n<p>The highest number of passengers would be:</p>\n\n<pre><code>int MostPassengers = vehicles.Max(x => x.NumPassengers);\n</code></pre>\n\n<p>The vehicle list sorted by number of passengers would be something like this:</p>\n\n<pre><code>List<Vehicle> SortedByPassengers = vehicles.OrderBy(x => x.NumPassengers);\n</code></pre>\n\n<p>Every vehicle at the bottom of the list with the same number of passengers will be the highest number of passengers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:50:47.727",
"Id": "48707",
"ParentId": "48676",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:52:53.727",
"Id": "48676",
"Score": "2",
"Tags": [
"c#",
"sorting"
],
"Title": "An acceptable way of sorting List"
} | 48676 |
<p>My task is to add the specified element to the linked list if it is not already present</p>
<pre><code>/**
* Adds the specified element to this set if it is not already present.
* @param o element to be added to this set.
* @return true if this set did not already contain the specified element.
* @throws NullPointerException - if the specified element is null and this set does
not support null elements
*/
</code></pre>
<p>This is my solution</p>
<pre><code>public boolean add(E o) {
if (o == null)
throw new NullPointerException();
ListNode newNode = new ListNode(o, null);
if (contains(o))
{
return false;
}
else {
head.next=newNode;
head=newNode;
return true;
}
}
</code></pre>
<p>Can please anybody check it and correct if there are mistakes, or give hints to correct it?</p>
| [] | [
{
"body": "<p>The first big problem I see is readability. Your code is missing good indentation and the style does not conform with what I'm used to seeing. Your code would read better like this:</p>\n\n<pre><code>public boolean add(E o) {\n if (o == null) {\n throw new NullPointerException();\n }\n\n ListNode newNode = new ListNode(o, null);\n\n if (contains(o)) {\n return false;\n } else {\n head.next=newNode;\n head=newNode;\n return true;\n } \n}\n</code></pre>\n\n<p>I've removed some of the unneeded white space lines, since it was creating some weird space in the code. This can be considered style, but you should try to come up with something that feels natural.</p>\n\n<p>Brackets <code>{}</code> have a standard in Java; you should follow it.</p>\n\n<p>I've added brackets to the <code>if</code> with the <code>throw</code> exception. Note that this is optional and a matter of personal style.</p>\n\n<hr>\n\n<p>Another thing that you could do is reorganize the method a bit. At the moment, you first verify if <code>o</code> is <code>null</code>, then you create <code>newNode</code> and after you check if <code>o</code> is already in the list. If <code>o</code> is in the list, you return <code>false</code> from the method and the new node will be discarded. So why would you create <code>newNode</code> if you're not sure if you will use it later on?</p>\n\n<p>One option could be to move <code>ListNode newNode = new ListNode(o, null);</code> to the <code>else</code> block. You could also remove the <code>else</code> part and move the <code>if (contains(o))</code> just before the initialization, leaving something like this:</p>\n\n<pre><code>public boolean add(E o) {\n if (o == null) {\n throw new NullPointerException();\n }\n\n if (contains(o)) {\n return false;\n }\n\n ListNode newNode = new ListNode(o, null);\n head.next = newNode;\n head = newNode;\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:57:55.553",
"Id": "85526",
"Score": "0",
"body": "There are many commonly-used styles for code, so the one you're used to isn't the only option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:55:32.413",
"Id": "85538",
"Score": "1",
"body": "@Ypnypn perfectly right, but there were no organization in the original code. I presented one of the most common style for Java, but was still mentioning that there was alternative to what I am presenting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:46:04.160",
"Id": "48689",
"ParentId": "48679",
"Score": "10"
}
},
{
"body": "<p>The \"else\" part of the if-else is redundant, since the if contains a return statement.</p>\n\n<p>Also what happens when you add the first element? If head is null, the <code>head.next=newNode</code> line will give a <code>NullPointerException</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:10:35.593",
"Id": "85490",
"Score": "2",
"body": "This answer is incorrect. The contents of the if-branch have nothing to do with the else-branch, hence one cannot be rendered redundant over what another branch does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T01:32:08.353",
"Id": "85561",
"Score": "0",
"body": "@skiwi Since the *only* thing the `if` branch contains is `return false`, there is no need for the rest of the code to be in an `else` block. See [Marc-Andre's answer](http://codereview.stackexchange.com/a/48689/29972), for example. This may not be explained very well here, but I don't see how it's *incorrect*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:37:59.490",
"Id": "85614",
"Score": "0",
"body": "@Geobits That doesn't make the else **part** redundant, that makes the **else { ... }** around the statement be redundant. This answer here is very ambigious as it does not even provide a code sample to demonstrate it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:50:50.163",
"Id": "48696",
"ParentId": "48679",
"Score": "-2"
}
},
{
"body": "<p>Let's say that you are starting with a list containing five elements:</p>\n\n<p>$$\n\\newcommand{ptr}[1]{\\overset{\\mathtt{#1}}{\\longrightarrow}}\n\\mathtt{head} \\ptr{} \\fbox{first} \\ptr{next}\n \\fbox{second} \\ptr{next}\n \\fbox{rest} \\ptr{next}\n \\fbox{of} \\ptr{next}\n \\fbox{list} \\ptr{next} \\mathtt{null}\n$$</p>\n\n<p>Then, you add a non-duplicate item called \"another\". After executing <code>head.next=newNode</code>:</p>\n\n<p>$$\n% \"align\" allows us to do vertical alignment\n% \"\\\\\" separates lines\n% \"&\" is an alignment marker. The markers in different rows\n% are positioned above each other, and horizontally centered.\n\\newcommand{ptr}[1]{\\overset{\\mathtt{#1}}{\\longrightarrow}}\n\\begin{align*}\n &\\mathtt{newNode} \\\\\n &\\quad\\downarrow \\\\\n\\mathtt{head} \\ptr{} \\fbox{first} \\ptr{next} &\\fbox{another} \\ptr{next} \\mathtt{null} \\\\\n &\\fbox{second} \\ptr{next}\n \\fbox{rest} \\ptr{next}\n \\fbox{of} \\ptr{next}\n \\fbox{list} \\ptr{next}\n \\mathtt{null}\n\\end{align*}\n$$</p>\n\n<p>You've just orphaned and discarded everything starting from the second element. Then it gets worse when you set <code>head=newNode</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:12:30.130",
"Id": "85492",
"Score": "0",
"body": "This make me wonder if the OP has tested the code before posting. Just by using his implementation a bit he would have seen that his implementation is missing elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:15:37.253",
"Id": "85493",
"Score": "1",
"body": "@Mat'sMug [Shared on Meta](http://meta.codereview.stackexchange.com/q/1828/9357) for everyone's benefit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:06:35.963",
"Id": "48698",
"ParentId": "48679",
"Score": "11"
}
},
{
"body": "<p>There are a few inconsistencies in your JavaDoc comments (bravo! for using them):</p>\n\n<ul>\n<li>Parameter and exception descriptions don't need to be complete sentences and should not end with a period. This helps keep them short, too.</li>\n<li>Omit the <code>-</code> after the exception type. These lines should look just like the <code>@param</code> lines.</li>\n<li>It's typical to indent the <code>*</code> one space extra so the asterisks form a corner, and make sure every line has an asterisk.</li>\n<li>I like to place a blank line between the method's description and the first attribute (<code>@param</code> in this case), but that's a personal style chosen to aid my poor vision.</li>\n</ul>\n\n<p>Taking these all together produces this:</p>\n\n<pre><code>/**\n * Adds the specified element to this set if it is not already present.\n *\n * @param o element to be added to this set.\n * @return true if this set did not already contain the specified element\n * @throws NullPointerException if the specified element is null\n * and this set does not support null elements\n */\n</code></pre>\n\n<p>Since this set doesn't support <code>null</code> elements, you can drop the \"and this set does not support null elements\" at the end.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:41:27.523",
"Id": "48704",
"ParentId": "48679",
"Score": "7"
}
},
{
"body": "<blockquote>\n <p>throw new NullPointerException();</p>\n</blockquote>\n\n<p>The other reviewers cover other bits sufficiently well, so I just want to point out how odd this looks.</p>\n\n<p>A null pointer exception typically occurs when you try to access a null <code>Object</code> using the dot operator. Ie:</p>\n\n<pre><code>Object obj = null;\nobj.toString(); // NullPointerException!!!\n</code></pre>\n\n<p>In your case, however, you're not accessing an object. You're simply checking if it's null or not. </p>\n\n<p>Also, the rule of thumb is that exceptions should only be thrown when something exceptionally bad happens. Is receiving a null object in this function exceptionally bad? (That's for you to decide). If you regularly expect attempts to insert null objects, then I would say that throwing an exception is extreme, and you should just return <code>false</code> instead.</p>\n\n<p>Also, the javadoc:</p>\n\n<blockquote>\n <p>@throws NullPointerException - if the specified element is null and this set does not support null elements</p>\n</blockquote>\n\n<p>David Harkness pointed this out, but I'll reiterate since I'm on the exception anyway. You say \"and this set does not support null elements\", which either suggests some sets can have a null element, or you're saying that this set class doesn't allow null elements. If some sets are allowed a null element, you need to change your if statement to this:</p>\n\n<pre><code>if (o == null && !isNullSupported()) {\n throw new NullPointerException();\n}\n</code></pre>\n\n<p>Regardless, this bit of documentation would be more fitting in the class' javadoc instead of in this exception's javadoc. Knowing whether a collection takes null values or not is one of the first things people will want to know when they use your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:59:01.187",
"Id": "48715",
"ParentId": "48679",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:10:26.740",
"Id": "48679",
"Score": "6",
"Tags": [
"java",
"linked-list",
"set"
],
"Title": "Implementing a set using a linked list"
} | 48679 |
<p>I would like to receive feedback about my code. Is there any better way to shorten the code or is it fine?</p>
<p><a href="http://jsfiddle.net/Ku4mg/1/" rel="nofollow">Demo</a></p>
<pre><code>var pass_strength;
function IsEnoughLength(str,length){
if ((str == null) || isNaN(length))
return false;
else if (str.length < length)
return false;
return true;
}
function HasMixedCase(passwd){
if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
if ( passwd.split(/[a-z]/).length >= 3 && passwd.split(/[A-Z]/).length >= 3)
return true;
else
return false;
else
return false;
}
function HasNumeral(passwd){
if(passwd.match(/[0-9]/))
return true;
else
return false;
}
function HasSpecialChars(passwd){
if(passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))
return true;
else
return false;
}
function CheckPasswordStrength(pwd)
{
if (IsEnoughLength(pwd,14) && HasMixedCase(pwd) && HasNumeral(pwd) && HasSpecialChars(pwd))
pass_strength = "<b><font style='color:olive'>Very strong</font></b>";
else if (IsEnoughLength(pwd,10) && HasMixedCase(pwd) && HasNumeral(pwd) && HasSpecialChars(pwd))
pass_strength = "<b><font style='color:Blue'>Strong</font></b>";
else if (IsEnoughLength(pwd,10) && HasMixedCase(pwd) && HasNumeral(pwd))
pass_strength = "<b><font style='color:Green'>Medium</font></b>";
else
pass_strength = "<b><font style='color:red'>Weak</font></b>";
document.getElementById('pwd_strength').innerHTML = "Password strength: " + pass_strength;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:27:54.800",
"Id": "85570",
"Score": "0",
"body": "It's worth noting that a password doesn't have to have mixed case, special characters or numbers to be strong - It can be strong with nothing but 4 or 5 english words. See http://xkcd.com/936/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-11T06:31:36.133",
"Id": "86960",
"Score": "1",
"body": "Use an existing [realistic password strength estimator like *zxcvbn*](https://github.com/dropbox/zxcvbn)."
}
] | [
{
"body": "<ol>\n<li><p>You can replace all of the </p>\n\n<pre><code>if(x.match(...))\n return true;\nelse\n return false;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>return x.match(...) !== null;\n</code></pre>\n\n<p>or if you're content with returning a truthy/falsy value instead of proper booleans you can even simplify it to: </p>\n\n<pre><code>return x.match(...)\n</code></pre></li>\n<li><p><code>IsEnoughLength</code> is ungrammatical. I'd use <code>IsLongEnough</code></p></li>\n<li>You're mixing the password strength estimation with presentation logic. You should have one function which returns a value indicating the strength of the password and another which manipulates the DOM.</li>\n<li>Use CSS classes to format the text instead of <code><b></code> and <code><font style=</code></li>\n<li><p>Personally I wouldn't bother with argument checking in such a simple internal function. But if you do, throw an exception on programmer error, don't just return false.</p>\n\n<pre><code>if ((str == null) || isNaN(length))\n return false;\n</code></pre>\n\n<p>should be something like</p>\n\n<pre><code>if (str == null)\n throw new Error(\"str must not be null\");\nif(isNaN(length))\n throw new Error(\"length must be a number\");\n</code></pre>\n\n<p>(or a fancier exception class if you want)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:16:20.263",
"Id": "85456",
"Score": "0",
"body": "Thank you very much for your reply. I will try like that :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:15:39.100",
"Id": "48681",
"ParentId": "48680",
"Score": "10"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/users/1482/codesinchaos\">@CodesInChaos</a> has already pointed out, the boolean expressions can be simplified, a lot. For example:</p>\n\n<pre><code>function HasMixedCase(passwd) {\n return passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)\n && passwd.split(/[a-z]/).length >= 3\n && passwd.split(/[A-Z]/).length >= 3;\n}\nfunction HasNumeral(passwd) {\n return passwd.match(/[0-9]/);\n}\nfunction HasSpecialChars(passwd) {\n return passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/);\n}\n</code></pre>\n\n<p>In addition, I would simplify the method that checks the length like this:</p>\n\n<pre><code>function IsLongEnough(passwd, length) {\n return passwd && passwd.length > length;\n}\n</code></pre>\n\n<p>This will only return true if <code>passwd</code> is not undefined and long enough. </p>\n\n<p>And I dropped the validation of the <code>length</code> parameter. For one thing, it was unnecessary: <code>IsLongEnough(word, undefined)</code> and <code>IsLongEnough(word, NaN)</code> will always return false. For another thing, if you are calling password validation methods with invalid parameters, you are in big trouble!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:53:36.360",
"Id": "48690",
"ParentId": "48680",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:12:16.953",
"Id": "48680",
"Score": "5",
"Tags": [
"javascript",
"security",
"validation",
"authentication"
],
"Title": "Password strength checker"
} | 48680 |
<p>The code is part of a very basic 2D platformer based on code from the book Killer Game Programming in Java.</p>
<p>The methods are part of a <code>TileMapManager</code> class which is handling basic collision detection.</p>
<ul>
<li><p>The first method returns the greatest distance that an entity can travel in the y axis (up to deltaY) without colliding with a tile:</p>
<pre><code>public int getMaxDeltaY(Point initialPoint, int deltaY){
//validate params
if(deltaY>=tileMap.getTileHeight()) throw new IllegalArgumentException("Cannot validate if deltaY is larger than brickHeight");
if(deltaY==0) return deltaY;
int x = initialPoint.x;
int testY = initialPoint.y + deltaY;
if(isInsideTile(x, testY)){
//get which row we are colliding with
int mapRow = testY/tileMap.getTileHeight();
//the distance between our position and
//the top of the tile we are colliding with
int topOffset = testY - (mapRow * tileMap.getTileHeight());
//get the amount we should move to place
//ourselves just next to the tile (top or bottom)
int maxDeltaY = 0;
//moving up case
if(deltaY <0){
maxDeltaY = deltaY + (tileMap.getTileHeight()-topOffset);
}
//moving down case
else if(deltaY >0){
maxDeltaY = deltaY - topOffset;
}
return maxDeltaY;
}
//we won't collide so it's okay to move deltaY
return deltaY;
}
</code></pre></li>
<li><p>The second method does the same thing in the x axis:</p>
<pre><code>public int getMaxDeltaX(Point initialPoint, int deltaX){
//validate params
if(deltaX>=tileMap.getTileWidth()) throw new IllegalArgumentException("Cannot validate if moveStep is larger than brickWidth");
if(deltaX==0) return deltaX;
int testX = (initialPoint.x + deltaX);
int y = initialPoint.y;
//if we collide
if(isInsideTile(testX, y)){
//get which column we are colliding with
int mapCol = testX/tileMap.getTileWidth();
//the distance between our position and
//the left side of the tile we are colliding with
int leftOffset = testX - (mapCol * tileMap.getTileWidth());
//get the amount we should move to place
//ourselves just next to the tile (left or right)
int maxDeltaX = 0;
//moving left
if(deltaX < 0){
maxDeltaX = deltaX + (tileMap.getTileWidth() - leftOffset);
}
//moving right
else if(deltaX > 0){
maxDeltaX = deltaX - leftOffset;
}
return maxDeltaX;
}
//we won't collide so it's okay to move deltaX
return deltaX;
}
</code></pre></li>
</ul>
<p>The algorithm (from the book) is essentially the same so I wanted to remove the duplication.</p>
<p>The code differs in only a few places:</p>
<ol>
<li>use <code>getTileWidth()</code> or <code>getTileHeight()</code></li>
<li>use x or y to create test point</li>
<li>use x or y to create offset</li>
<li>use <code>mapRow</code> or <code>mapCol</code></li>
</ol>
<p>So a basic way could be:</p>
<ol>
<li>pass tile width/height as argument <code>tileDimension</code></li>
<li>create test point before calling method (turn <code>initialPoint</code> into <code>testPoint</code>)</li>
<li>pass test x/y as argument <code>testCoordinate</code></li>
<li>pass row/col as argument? Can't think of good name (<code>mapIndex</code>?)</li>
</ol>
<p>But now I have loads of confusing arguments and duplicate information (<code>testCoordinate</code> is contained in <code>testPoint</code>). I read that this is also a big no no, and even a beginner like me can see that this would be ugly.</p>
<p>Another way might be to pass the basic information and a flag for the axis, x or y. But this would still involve a bunch of arguments and then confusing switching in the body.</p>
<p>So I'm hoping there's a simple pattern that is used in these situations and will magically get rid of all duplication and leave a short method that's easy to read and use...</p>
<p>What is the best way to refactor these methods?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:32:17.083",
"Id": "85497",
"Score": "0",
"body": "What is the type of tileMap?"
}
] | [
{
"body": "<p>It seems this is a job for a Parameter class.</p>\n\n<pre><code>public abstract class DeltaParameters{\n protected ? tileMap;\n protected int x, y;\n\n DeltaParameters(Point point, ? tileMap){\n this.x = point.x;\n this.y = point.y;\n this.tileMap = tileMap;\n }\n\n public int getX(){\n return x;\n }\n\n public int getY(){\n return y;\n }\n public abstract int getTileSideSize();\n public abstract int getMovingCoordinate();\n public abstract void offsetMovingCoordinate(int delta);\n}\n\npublic class DeltaXParameters extends DeltaParameters{\n DeltaXParameters(Point point, ? tileMap){\n super(point, tileMap);\n }\n\n public int getTileSideSize(){\n return tileMap.getTileWidth();\n }\n public int getMovingCoordinate(){\n return x;\n }\n public void offsetMovingCoordinate(int delta){\n x += delta;\n }\n}\n</code></pre>\n\n<p>I leave to you the job of guessing what would be DeltaYParameters :p </p>\n\n<pre><code>public int getMaxDelta(DeltaParameters dparams, int delta){\n if(delta>=dparams.getTileSideSize()) throw new IllegalArgumentException(\"This message is yet to be determined. It could be another method in DeltaParameters\");\n if(delta==0) return delta;\n\n dparams.offsetMovingCoordinate(delta);\n if(isInsideTile(dparams.getX(), dparams.getY())){\n int map = dparams.getMovingCoordinate() /dparams.getTileSideSize() ;\n int offset = dparams.getMovingCoordinate() - (map * dparams.getTileSideSize() );\n int maxDelta = 0;\n\n if(delta < 0){\n maxDelta = delta + (dparams.getTileSideSize() - offset);\n }\n else if(delta > 0){\n maxDelta = delta - offset;\n }\n\n return maxDelta;\n }\n return delta;\n}\n</code></pre>\n\n<p>Now you could call <code>getMaxDelta</code> just like this</p>\n\n<pre><code>getMaxDelta(new DeltaXParameters(new Point(0, 0), tileMap), 5);\n</code></pre>\n\n<p>What I have done here is to take the advantage of polymorphism over DeltaParameters class. Which could not be a so straigthforward method to refactor is now proven to be in a quite simple fashion imho.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:09:52.597",
"Id": "85602",
"Score": "0",
"body": "Thanks Bruno, that's very helpful. I did think about creating a new class, but I couldn't think of the conceptual link between all the data, and that seemed to be a bad thing. Also I was wondering what the difference is between a parameter class, a data transfer object and a poltergeist (antipattern). I'm trying to follow best practices, but it can get pretty confusing!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:10:56.457",
"Id": "85603",
"Score": "0",
"body": "I'm going to implement this right away, but might wait to see if there are any other responses before marking it as accepted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:22:55.557",
"Id": "85604",
"Score": "0",
"body": "I don't know what is a poltergeist but a DTO(data transfer object) wouldn't suit here. As you mentioned in your question you had to pass way to many parameters to refactor the methods into a single one. As per my solution you need to have logic in your classes and DTO's don't ever have any logic and much less make use of polymorphism. I called those classes parameter classes just because they encapsulate some parameter logic needed for the algorithm it's not a official name and maybe some people have other ideias of what is a parameter class.\nThat's fine for me. Glad I could help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:12:51.633",
"Id": "85680",
"Score": "0",
"body": "I see, thanks again! I implemented your method and it worked very well. As I was adding the methods to the parameter class, I realised I might as well add the entire algorithm as well and then use the polymorphism to get the right variables (actually I think I used the polymorphism in the constructor to set the correct variables for the algorithm). In the end I ended up with something more of a delta manager class and snuck in some extra functionality that I was duplicating elsewhere. I added it as a new answer for what its worth."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:48:40.380",
"Id": "48700",
"ParentId": "48693",
"Score": "3"
}
},
{
"body": "<p>This answer is based on Bruno's suggestion, but then developed from there with help from <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow noreferrer\">the template method pattern</a>.</p>\n<p>I don't know if it is the right approach but thought it might be useful to include just for reference sake.</p>\n<p>I created a new abstract DeltaManager class:</p>\n<ul>\n<li>this class manages all calculations and data required to find the delta to put a point alongside a brick in any axis</li>\n<li>this class now contains the getMaxDelta algorithm itself</li>\n<li>this method is now similar to a template method, as the basic algorithm is there, but the variables are created by calls to abstract methods that are implemented in the subclasses</li>\n<li>the DeltaManagerX & DeltaManagerY implement just a few methods that return the appropriate value (ie <code>x</code> or <code>y</code>)</li>\n<li>the super and subclasses are all inner classes nested in TileMapManager which allows them access to a couple of fields/methods (such as the collision detection <code>isInsideTile(Point point)</code>)</li>\n<li>this also allows me to hard code<code>tileWidth</code> or <code>tileHeight</code> into the subclasses</li>\n<li>I added a little more functionality to allow the class to deal with multiple points. This is because I need to check a number of points on a sprite and find the maximum delta the sprite as a whole can move without colliding with a tile. This let me get rid of more duplicate code.</li>\n</ul>\n<p>So now the process is:</p>\n<ol>\n<li><p>create a DeltaManagerX or DeltaManagerY as a DeltaManager when needed</p>\n</li>\n<li><p>construct it with only two parameters, the requested delta you want to move & the point/points you want to move (varargs)</p>\n</li>\n<li><p>call the getMaxDelta() method which returns the result you need</p>\n<p>The code is still a little funky, and the method/variable names are a bit confusing, but otherwise it seems to work quite well:</p>\n</li>\n</ol>\n<h1>DeltaManager:</h1>\n<pre><code>public abstract class DeltaManager{\n\n protected final int requestedDelta;\n protected final int tileDimension;\n protected final int[] testCoordinates;\n\n\n DeltaManager(int requestedDelta, int tileDimension, Point... initialPoints){\n\n //validate params\n if(requestedDelta>=tileDimension) throw new IllegalArgumentException(getDeltaLargerThanTileMessage());\n if (initialPoints==null) throw new NullPointerException("Initial points cannot be null");\n if(initialPoints.length==0) throw new IllegalArgumentException("Must pass some initial points to test");\n\n this.requestedDelta = requestedDelta;\n this.tileDimension=tileDimension;\n\n //no point initializing anything else if delta is 0\n //there can be no collisions\n if(requestedDelta == 0){\n System.out.println("WARNING: requestedDelta is 0");\n testCoordinates = null;\n }else{\n List<Point> collidingPoints = getCollidingPoints(initialPoints);\n this.testCoordinates = getRelevantCoordinates(collidingPoints);\n }\n }\n\n private List<Point> getCollidingPoints(Point[] initialPoints){\n List<Point> collidingPoints = new ArrayList<Point>();\n Point testPoint;\n for(Point initialPoint: initialPoints){\n testPoint = getTestPoint(initialPoint);\n if(isInsideTile(testPoint)){\n collidingPoints.add(testPoint);\n }\n }\n return collidingPoints;\n };\n\n private int[] getRelevantCoordinates(List<Point> collidingPoints){\n int[] coordinates = new int[collidingPoints.size()];\n int index=0;\n for(Point collidingPoint: collidingPoints){\n coordinates[index++]=getRelevantCoordinate(collidingPoint);\n }\n return coordinates;\n }; \n\n public int getMaxDelta(){\n\n if(requestedDelta==0) return 0;\n\n int maxPossibleDelta = requestedDelta;\n int testDelta = 0;\n for(int testCoordinate: testCoordinates){\n testDelta = getMaxDeltaFromSingleCoordinate(testCoordinate);\n if(Math.abs(testDelta) < Math.abs(maxPossibleDelta)) maxPossibleDelta = testDelta;\n }\n return maxPossibleDelta;\n }\n\n private int getMaxDeltaFromSingleCoordinate(int testCoordinate){\n\n //get which column or row we are colliding with\n int mapVector = testCoordinate/tileDimension;\n //the distance between our position and\n //the left or top side of the tile we are colliding with\n int offset = testCoordinate - (mapVector * tileDimension);\n //get the amount we should move to place\n //ourselves just next to the tile\n //(above/below or to the left/right)\n int maxDelta = 0;\n\n //moving left or up\n if(requestedDelta < 0){\n maxDelta = requestedDelta + (tileDimension - offset);\n }\n //moving right or down\n else if(requestedDelta > 0){\n maxDelta = requestedDelta - offset;\n }\n\n return maxDelta;\n }\n\n protected abstract Point getTestPoint(Point initialPoint);\n protected abstract int getRelevantCoordinate(Point point);\n protected abstract String getDeltaLargerThanTileMessage();\n\n}\n</code></pre>\n<h2>DeltaManagerX</h2>\n<pre><code>public class DeltaManagerX extends DeltaManager{\n\n DeltaManagerX( int requestedDeltaX, Point... initialPoints){\n super(requestedDeltaX, TileMapManager.this.tileMap.getTileWidth(), initialPoints);\n }\n\n @Override\n protected String getDeltaLargerThanTileMessage() {\n return "Collision detection cannot work if deltaX is larger than tile width";\n }\n\n @Override\n protected Point getTestPoint(Point initialPoint) {\n int testX = initialPoint.x + requestedDelta;\n return new Point(testX, initialPoint.y);\n }\n\n @Override\n protected int getRelevantCoordinate(Point point) {\n return point.x;\n }\n\n}\n</code></pre>\n<h2>DeltaManagerY</h2>\n<pre><code>public class DeltaManagerY extends DeltaManager{\n\n DeltaManagerY( int requestedDeltaY, Point... initialPoints){\n super(requestedDeltaY, TileMapManager.this.tileMap.getTileHeight(), initialPoints);\n }\n\n @Override\n protected String getDeltaLargerThanTileMessage() {\n return "Collision detection cannot work if deltaY is larger than tile width";\n }\n\n @Override\n protected Point getTestPoint(Point initialPoint) {\n int testY = initialPoint.y + requestedDelta;\n return new Point(initialPoint.x, testY);\n }\n\n @Override\n protected int getRelevantCoordinate(Point point) {\n return point.y;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:21:20.157",
"Id": "85682",
"Score": "0",
"body": "You shouldn't call methods that can be overriden in the constructor (or in their code they do so). See why [here](http://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T17:25:41.953",
"Id": "85687",
"Score": "0",
"body": "Dang, every time I think I've fixed something, I seem to introduce even more problems! Thanks for the link, I have vague recollections of this when I read Effective Java (and promptly forgot it). The link suggests that it would fail immediately, but I've been running my code for a bit and the collision detection seems fine. I wonder if it is because I'm not relying on any fields or state in the overridden methods in the constructor, but they are directly passing arguments instead. I also wonder why Eclipse doesn't warn about this, seems easy enough to detect. Ok, back to the drawing board."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:46:37.350",
"Id": "85696",
"Score": "0",
"body": "I will be able to review your DeltaManager if you edit your question or make a follow up (which I think that could suit better here)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:01:36.510",
"Id": "85769",
"Score": "0",
"body": "Thanks Bruno. I might post this again later on as a new question but first I have much worse code elsewhere in the game to deal with! In the meantime I've accepted your answer as the one that works and doesn't do anything potentially dangerous."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:04:24.133",
"Id": "48799",
"ParentId": "48693",
"Score": "0"
}
},
{
"body": "<p>The max delta idea feels a little awkward. If the idea is to stop something from going out of bounds, there may be easier methods. But if you're following the book, it may be best to stick with it.</p>\n\n<p>To me, the most natural approach to the issue would be introducing the concept of an axis. Ideally, an axis would abstract away other coordinates, translating our input for us:</p>\n\n<pre><code>interface TileMapAxis {\n boolean isInsideTile(int position);\n int getTileSize();\n int position(Point p);\n}\n</code></pre>\n\n<p>We'll also need a way to get such an axis. Since the axis represents an axis in our tile map, that feels like the place to provide them:</p>\n\n<pre><code>class TileMap {\n // ...\n\n TileMapAxis getXAxis(final int y) {\n return new TileMapAxis() {\n public boolean isInsideTile(int position) {\n return isInsideTile(position, y);\n }\n public int getTileSize() {\n return getTileWidth();\n }\n public int position(Point p) {\n return p.x;\n }\n };\n }\n\n TileMapAxis getYAxis(final int x) {\n return new TileMapAxis() {\n public boolean isInsideTile(int position) {\n return isInsideTile(x, position);\n }\n public int getTileSize() {\n return getTileHeight();\n }\n public int position(Point p) {\n return p.y;\n }\n };\n }\n}\n</code></pre>\n\n<p>... at which point your original functions can be hollowed out and the algorithm kept mostly in the same form elsewhere:</p>\n\n<pre><code>public int getMaxDeltaX(Point initialPoint, int deltaX) {\n return getMaxDelta(initialPoint, deltaX, tileMap.getXAxis(initialPoint.y));\n}\n\npublic int getMaxDeltaY(Point initialPoint, int deltaY) {\n return getMaxDelta(initialPoint, deltaY, tileMap.getYAxis(initialPoint.x));\n}\n\npublic int getMaxDelta(Point initialPoint, int delta, TileMapAxis axis) {\n final int size = axis.getTileSize();\n //validate params\n if (delta >= size) {\n throw new IllegalArgumentException(\"Cannot validate if delta is larger than size\");\n }\n if (delta == 0) {\n return delta;\n }\n\n int pos = axis.position(initialPoint);\n int testPos = pos + delta;\n if (axis.isInsideTile(testPos)) {\n //get which tile we are colliding with\n int tile = testPos/size;\n //the distance between our position and\n //the start of the tile we are colliding with\n int offset = testPos - (tile * size);\n //get the amount we should move to place\n //ourselves just next to the tile (start or end)\n int maxDelta = 0;\n\n //moving to start case\n if (delta < 0) {\n maxDelta = delta + (size - offset);\n }\n //moving to end case\n else if (delta > 0) {\n maxDelta = delta - offset;\n }\n return maxDelta;\n }\n //we won't collide so it's okay to move delta\n return delta;\n}\n</code></pre>\n\n<hr>\n\n<p>Depending on your style and preferences, you could also make <code>TileMapAxis</code> an abstract class and move the delta-limiting method there:</p>\n\n<pre><code>abstract class TileMapAxis {\n public abstract boolean isInsideTile(int position);\n public abstract int getTileSize();\n public abstract int position(Point p);\n\n public int getMaxDelta(Point initialPoint, int delta) {\n final int size = getTileSize();\n //validate params\n if (delta >= size) {\n throw new IllegalArgumentException(\"Cannot validate if delta is larger than size\");\n }\n if (delta == 0) {\n return delta;\n }\n\n int pos = position(initialPoint);\n int testPos = pos + delta;\n if (isInsideTile(testPos)) {\n //get which tile we are colliding with\n int tile = testPos/size;\n //the distance between our position and\n //the start of the tile we are colliding with\n int offset = testPos - (tile * size);\n //get the amount we should move to place\n //ourselves just next to the tile (start or end)\n int maxDelta = 0;\n\n //moving to start case\n if (delta < 0) {\n maxDelta = delta + (size - offset);\n }\n //moving to end case\n else if (delta > 0) {\n maxDelta = delta - offset;\n }\n return maxDelta;\n }\n //we won't collide so it's okay to move delta\n return delta;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>As an aside: there is nothing <em>inherently</em> wrong with methods that have four or five parameters, provided their use is well-documented. I'd even argue that it can be cleaner from an algorithmic point of view: separating coordinating from calculating will give code that's easier to test.</p>\n\n<p>Having more than two parameters is not evil, but a traffic jam of parameters can be an indication that a function is taking on too much responsibility and may need reviewing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T13:57:40.217",
"Id": "85768",
"Score": "0",
"body": "Thanks for this, I like the concept of the TileMapAxis class, although I think there might be a typo or two in the getMaxDeltaX() method. The parameter thing was an admonition in the book I'm reading, 'Clean code'. I can kind of see where they come from, as I can find using even conceptually basic methods like the drawImage() methods in Java2D confusing to write and even more to read back. On the other hand trying to force the issue seems to lead to creating worse problems... Trials & tribulations of a newb I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:50:42.283",
"Id": "85775",
"Score": "0",
"body": "@mallardz Yusss, those were errors, good thing you caught them. :s On the parameters... it's everyone's guess and anyone's preference. As you gain experience, you'll gain more foresight into what will or will not be an issue (though it'll never be perfect)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T00:13:20.010",
"Id": "48836",
"ParentId": "48693",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48700",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:20:43.073",
"Id": "48693",
"Score": "5",
"Tags": [
"java"
],
"Title": "Removing duplicate code from basic collision detection implementation"
} | 48693 |
<p>I have recently taken a small technical test in C# and the following were expected:</p>
<ul>
<li>All stories to be completed with an appropriate level of testing.</li>
<li>No actual database implementation is required, feel free to stub it out.</li>
<li>Your code should trend towards being SOLID.</li>
<li>Make sure you write mock objects and do good unit testing with this.</li>
<li>Make sure that your tests actually pass</li>
<li>Do not over engineer the test and make sure there is no repetition of code.</li>
</ul>
<p>Please find my code in GitHub <a href="https://github.com/Shivan4u/GiftAidCalculator" rel="nofollow">Gift Aid Calculator</a>. The story for the test can be found in the <em>read me</em> section of GitHub.</p>
<p><strong>Program.cs</strong></p>
<pre><code>using System;
using GiftAidCalculator.TestConsole.BusinessObject;
using GiftAidCalculator.TestConsole.Helper;
using GiftAidCalculator.TestConsole.Interface;
using GiftAidCalculator.TestConsole.Repositry;
namespace GiftAidCalculator.TestConsole
{
class Program
{
static void Main()
{
IConfigRepositry config = new ConfigRepositry();
Console.WriteLine("Please enter the tax rate:");
decimal taxRate;
if (ValidateHelper.ValidateDecimal(Console.ReadLine(), out taxRate))
{
config.TaxRate = taxRate;
Console.WriteLine("************** Promotion ******************");
Console.WriteLine("***** 5% Supplement added on running *****");
Console.WriteLine("***** 3% Supplement added on swimming *****");
Console.WriteLine("************** Promotion ******************\n");
Console.WriteLine("\n Input 1 for Running, 2 for Swimming and 3 for other events.");
int eventInput;
if (ValidateHelper.ValidateInteger(Console.ReadLine(), out eventInput))
{
Console.WriteLine("\n Please Enter donation amount:");
decimal donationAmount;
if (ValidateHelper.ValidateDecimal(Console.ReadLine(), out donationAmount))
{
var calculateTax = new TaxCalculator(config);
decimal giftAid = MathHelper.RoundDecimal(calculateTax.CalculateGiftAid(donationAmount));
Console.WriteLine("\n Gift aid calculated at the rate of "+ taxRate+" is:" + giftAid + "\n");
Console.WriteLine(EventRepositry.GetEventTypeMessage(eventInput)+ "\n");
Console.WriteLine("\n The calculated gift amount is: " + (donationAmount +giftAid + MathHelper.RoundDecimal(EventRepositry.GetEventSupplementAmount(eventInput, donationAmount))) + "\n");
Console.WriteLine("\n Press any key to exit.");
Console.ReadLine();
}
else
{
Console.WriteLine("Invalid Input");
Console.ReadLine();
}
}
else
{
Console.WriteLine("Invalid Input");
Console.ReadLine();
}
}
else
{
Console.WriteLine("Invalid Input");
Console.ReadLine();
}
}
}}
</code></pre>
<p><strong>Interfaces</strong></p>
<pre><code> namespace GiftAidCalculator.TestConsole.Interface
{
public interface IConfigRepositry
{
decimal TaxRate { get; set; }
}
}
namespace GiftAidCalculator.TestConsole.Interface
{
public interface ITaxCalculator
{
decimal CalculateGiftAid(decimal donationAmount);
}
}
</code></pre>
<p><strong>Repositry</strong></p>
<pre><code>using GiftAidCalculator.TestConsole.Interface;
namespace GiftAidCalculator.TestConsole.Repositry
{
public class ConfigRepositry : IConfigRepositry
{
public decimal TaxRate { get; set; }
}
}
using GiftAidCalculator.TestConsole.Entities;
namespace GiftAidCalculator.TestConsole.Repositry
{
public class EventRepositry
{
/// <summary>
/// Gets the event type supplement message.
/// </summary>
/// <param name="eventCode"></param>
/// <returns></returns>
public static string GetEventTypeMessage(int eventCode)
{
string result = string.Empty;
//validation for invalid event code.
if (eventCode > 3 || eventCode <1){ eventCode = 3;}
switch (eventCode)
{
case (int)GenericEntities.EventType.Running:
result = "\n 5% supplement added for donations to running events.";
break;
case (int)GenericEntities.EventType.Swimming:
result = "\n 3% supplement added for donations to swimming events.";
break;
case (int)GenericEntities.EventType.Others:
result = "\n No supplement should be applied for other events.";
break;
}
return result;
}
/// <summary>
/// Calculate event supplement amount.
/// </summary>
/// <param name="eventCode"></param>
/// <param name="donationAmount"></param>
/// <returns></returns>
public static decimal GetEventSupplementAmount(int eventCode, decimal donationAmount)
{
decimal result = 0;
decimal eventSupplement = 0;
//validation for invalid event code.
if (eventCode > 2 || eventCode < 0) { eventCode = 2; }
switch (eventCode)
{
case (int)GenericEntities.EventType.Running:
eventSupplement = 5;
break;
case (int)GenericEntities.EventType.Swimming:
eventSupplement = 3;
break;
case (int)GenericEntities.EventType.Others:
eventSupplement = 0;
break;
}
result = donationAmount*(eventSupplement/100);
return result;
}
}
}
</code></pre>
<p><strong>Business Object</strong></p>
<pre><code>using GiftAidCalculator.TestConsole.Interface;
namespace GiftAidCalculator.TestConsole.BusinessObject
{
public class TaxCalculator: ITaxCalculator
{
private readonly IConfigRepositry _configRepositry;
public TaxCalculator(IConfigRepositry configRepositry)
{
_configRepositry = configRepositry;
}
public decimal CalculateGiftAid(decimal donationAmount)
{
var giftAidRatio = _configRepositry.TaxRate / (100 - _configRepositry.TaxRate);
return donationAmount * giftAidRatio;
}
}
}
</code></pre>
<p><strong>Helper</strong></p>
<pre><code>using System;
namespace GiftAidCalculator.TestConsole.Helper
{
public static class MathHelper
{
//This can also be set as configurable member.
private const int DecimalPoints = 2;
public static decimal RoundDecimal(decimal giftAidAmount)
{
return decimal.Round(giftAidAmount, DecimalPoints, MidpointRounding.AwayFromZero);
}
}
}
namespace GiftAidCalculator.TestConsole.Helper
{
public class ValidateHelper
{
public static bool ValidateDecimal(string strInput, out decimal dOutput)
{
dOutput = 0;
bool result = decimal.TryParse(strInput, out dOutput);
return result;
}
public static bool ValidateInteger(string strInput, out int dOutput)
{
dOutput = 0;
bool result = int.TryParse(strInput, out dOutput);
return result;
}
}
}
</code></pre>
<p><strong>Entities</strong></p>
<pre><code>namespace GiftAidCalculator.TestConsole.Entities
{
class GenericEntities
{
public enum EventType
{
Running =1,
Swimming = 2,
Others = 3
}
}
}
</code></pre>
<p><strong>UnitTest - As_event_promoter</strong></p>
<pre><code>using System;
using GiftAidCalculator.TestConsole.Repositry;
using NUnit.Framework;
namespace GiftAidCalculator.Tests
{
[TestFixture]
class As_event_promoter
{
[Test]
public void Add_5_percent_supplement_for_running()
{
//Arrange
//Input one for running
const int inputEvent = 1;
const string expected = "\n 5% supplement added for donations to running events.";
//Act
string actual = EventRepositry.GetEventTypeMessage(inputEvent);
//Assert
Assert.AreEqual(actual,expected);
Console.WriteLine(actual);
}
[Test]
public void Add_3_percent_supplement_for_swimming()
{
//Arrange
//Input one for swimming
const int inputEvent = 2;
const string expected = "\n 3% supplement added for donations to swimming events.";
//Act
string actual = EventRepositry.GetEventTypeMessage(inputEvent);
//Assert
Assert.AreEqual(actual, expected);
Console.WriteLine(actual);
}
[Test]
public void No_supplement_for_others()
{
//Arrange
//Input three for others
const int inputEvent = 3;
const string expected = "\n No supplement should be applied for other events.";
//Act
string actual = EventRepositry.GetEventTypeMessage(inputEvent);
//Assert
Assert.AreEqual(actual, expected);
Console.WriteLine(actual);
}
[Test]
public void Show_event_supplement_amount_for_running()
{
//Arrange
const int eventCode = 1; //running
const decimal donationAmount = 45.56m;
const decimal expected = 2.278m;
//Act
decimal actual = EventRepositry.GetEventSupplementAmount(eventCode, donationAmount);
//Assert
Assert.AreEqual(actual,expected);
Console.WriteLine("Calulated supplement amount for running event with donation amount '" + donationAmount + "' will be : " + actual);
}
}
}
</code></pre>
<p><strong>UnitTest - As_site_administrator</strong></p>
<pre><code>using System;
using GiftAidCalculator.TestConsole.Interface;
using GiftAidCalculator.TestConsole.Repositry;
using NUnit.Framework;
namespace GiftAidCalculator.Tests
{
[TestFixture]
class As_site_administrator
{
[Test]
public void Get_me_current_tax_rate()
{
//Arrange
const decimal setCurrentTaxRate = 15.5m;
const decimal expectedCurrentTaxRate = 15.5m;
IConfigRepositry configRepositry = new ConfigRepositry();
//Act
configRepositry.TaxRate = setCurrentTaxRate;
decimal actualCurrentTaxRate = configRepositry.TaxRate;
//Assert
Assert.AreEqual(actualCurrentTaxRate,expectedCurrentTaxRate);
Console.WriteLine("Current Tax Rate ["+ actualCurrentTaxRate + " %] is set and retrieved from data store.");
}
}
}
</code></pre>
<p><strong>UnitTest - As_site_administrator</strong></p>
<pre><code>using System;
using GiftAidCalculator.TestConsole.Interface;
using GiftAidCalculator.TestConsole.Repositry;
using NUnit.Framework;
namespace GiftAidCalculator.Tests
{
[TestFixture]
class As_site_administrator
{
[Test]
public void Get_me_current_tax_rate()
{
//Arrange
const decimal setCurrentTaxRate = 15.5m;
const decimal expectedCurrentTaxRate = 15.5m;
IConfigRepositry configRepositry = new ConfigRepositry();
//Act
configRepositry.TaxRate = setCurrentTaxRate;
decimal actualCurrentTaxRate = configRepositry.TaxRate;
//Assert
Assert.AreEqual(actualCurrentTaxRate,expectedCurrentTaxRate);
Console.WriteLine("Current Tax Rate ["+ actualCurrentTaxRate + " %] is set and retrieved from data store.");
}
}
}
</code></pre>
<p><strong>UnitTest - Gift_aid_should</strong> </p>
<pre><code>using System;
using GiftAidCalculator.TestConsole.BusinessObject;
using GiftAidCalculator.TestConsole.Helper;
using GiftAidCalculator.TestConsole.Interface;
using Moq;
using NUnit.Framework;
namespace GiftAidCalculator.Tests
{
[TestFixture]
class Gift_aid_should
{
private decimal CalculateGiftAid()
{
const decimal currectTaxrate = 15.65m;
const decimal donationAmount = 50.50m;
var mockConfigRepositry = new Mock<IConfigRepositry>();
mockConfigRepositry.Setup(x => x.TaxRate).Returns(currectTaxrate);
ITaxCalculator taxCalculator = new TaxCalculator(mockConfigRepositry.Object);
return taxCalculator.CalculateGiftAid(donationAmount);
}
[Test]
public void Be_rounded_to_two_decimal_digits()
{
//Arrange
const decimal expectedValue = 9.37m;
var calculatedGiftAid = CalculateGiftAid();
//Act
decimal actualValue = MathHelper.RoundDecimal(calculatedGiftAid);
//Assert
Assert.AreEqual(actualValue,expectedValue);
Console.WriteLine("Actual calculated gift aid was [ " + calculatedGiftAid + " ] which is rounded to 2 decimal points : " + actualValue);
}
}
}
</code></pre>
<p><strong>UnitTest - Validate</strong></p>
<pre><code>using GiftAidCalculator.TestConsole.Helper;
using NUnit.Framework;
namespace GiftAidCalculator.Tests
{
[TestFixture]
class Validate
{
[Test]
public void Invalid_decimal_input()
{
//Arrange
const decimal expected = 0;
decimal actual = 0;
//Act
ValidateHelper.ValidateDecimal("invalid", out actual);
//Assert
Assert.AreEqual(actual,expected);
}
[Test]
public void Valid_decimal_input()
{
//Arrange
const decimal expected = 24.536m;
decimal actual = 0;
//Act
ValidateHelper.ValidateDecimal("24.536", out actual);
//Assert
Assert.AreEqual(actual, expected);
}
[Test]
public void Invalid_integer_input()
{
//Arrange
const int expected = 0;
int actual = 0;
//Act
ValidateHelper.ValidateInteger("invalid", out actual);
//Assert
Assert.AreEqual(actual, expected);
}
[Test]
public void Valid_integer_input()
{
//Arrange
const int expected = 145;
int actual = 0;
//Act
ValidateHelper.ValidateInteger("145", out actual);
//Assert
Assert.AreEqual(actual, expected);
}
}
}
</code></pre>
<p><strong>UnitTest - When_calculating_gift_aid</strong></p>
<pre><code>using System;
using GiftAidCalculator.TestConsole.BusinessObject;
using GiftAidCalculator.TestConsole.Interface;
using Moq;
using NUnit.Framework;
namespace GiftAidCalculator.Tests
{
[TestFixture]
class When_calculating_gift_aid
{
[Test]
public void Gift_aid_should_be_calculated_by_current_tax_rate()
{
//Arrange
const decimal currectTaxrate = 20;
const decimal donationAmount = 50;
const decimal expectedResult = 12.5m;
var mockConfigRepositry = new Mock<IConfigRepositry>();
mockConfigRepositry.Setup(x => x.TaxRate).Returns(currectTaxrate);
ITaxCalculator taxCalculator = new TaxCalculator(mockConfigRepositry.Object);
//Act
decimal actualResult = taxCalculator.CalculateGiftAid(donationAmount);
//Assert
Assert.AreEqual(expectedResult,actualResult);
Console.WriteLine("Gift aid calculated at a tax rate of " + currectTaxrate + " is: " + actualResult);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:42:31.983",
"Id": "85553",
"Score": "1",
"body": "You should probably post the stories here, since, like the code, they seem to be critical to doing a review based on your requirements."
}
] | [
{
"body": "<p><strong>class Program.</strong></p>\n\n<p>That's a class. A very high-level <em>abstract</em> notion of something with an <em>entry point</em> - a <code>Main</code> method. \"Program\" could be literally anything.</p>\n\n<p>Writing <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a> code implies <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a>, <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow\">OCP</a>, <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow\">LSP</a>, <a href=\"http://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow\">ISP</a> and <a href=\"http://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow\">DIP</a>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public class ValidateHelper\n</code></pre>\n</blockquote>\n\n<p>Uh-oh. Red flag. <code>Helper</code> smells. Let's see...</p>\n\n<blockquote>\n<pre><code>public static bool ValidateDecimal(string strInput, out decimal dOutput)\n</code></pre>\n \n \n\n<pre><code>public static bool ValidateInteger(string strInput, out int dOutput)\n</code></pre>\n</blockquote>\n\n<p><code>strInput</code> and <code>dOutput</code> ring the <em>Hungarian Notation</em> bell. And there's a <kbd>Copy</kbd>+<kbd>Paste</kbd> error, I'm guessing <code>dOutput</code> in <code>ValidateInteger</code> was meant to be named <code>iOutput</code>... How about this?</p>\n\n<pre><code>public static bool ValidateDecimal(string value, out decimal result)\n</code></pre>\n\n\n\n<pre><code>public static bool ValidateInteger(string value, out int result)\n</code></pre>\n\n<p>I'm only addressing the <em>naming</em> here though.</p>\n\n<p>The main issue I'm seeing, is that the abstraction level at the entry point is very low, but in a SOLID app it's very high.</p>\n\n<p>And the ending isn't very elegant either, and pretty much fails at <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>:</p>\n\n<pre><code> Console.WriteLine(\"\\n Press any key to exit.\");\n Console.ReadLine();\n }\n else\n {\n Console.WriteLine(\"Invalid Input\");\n Console.ReadLine();\n }\n }\n else\n {\n Console.WriteLine(\"Invalid Input\");\n Console.ReadLine();\n }\n }\n else\n {\n Console.WriteLine(\"Invalid Input\");\n Console.ReadLine();\n }\n</code></pre>\n\n<p>Try writing your application top-down. Take the time to put your mindset at the <em>abstraction level</em> that's right for the code you're writing. With the wrong abstraction levels, it's hard to make <em>units</em> for <em>unit testing</em>.</p>\n\n<pre><code>class Program\n{\n static void Main()\n {\n IDataService dataService = new SomeDataService();\n IUserInteractionService interactionService = new ConsoleInteractionService();\n\n var app = new CalculatorApp(dataService, interactionService);\n app.Execute();\n }\n}\n</code></pre>\n\n<p><strong>SRP</strong></p>\n\n<p>The <code>Main()</code> method does one thing: it <em>composes</em> the application, and runs it. The composition is done with <em>Poor Man's DI</em> instead of with an IoC container, but refactoring to use one would be very easy.</p>\n\n<p><strong>OCP</strong></p>\n\n<p>Being <code>static</code>, the <code>Main()</code> method <strong>cannot be extended</strong>. The more code we write here, the more <em>reasons to change</em> we introduce, the further we stray from being <em>open for extension, closed for modification</em>. Writing code at the proper abstraction level helps succeeding here.</p>\n\n<p><strong>LSP</strong></p>\n\n<p>Code against <em>abstractions</em>, code against the <em>interface</em> of objects - don't assume you know what the <em>actual</em> runtime type is going to be (see the \"typical violation\" section <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow\">here</a>). In other words, <code>SomeDataService</code> could very well be fetching its data from async calls to a web service that returns JSON or XML data - <code>Program</code> doesn't need to know that much (abstraction levels again).</p>\n\n<p><strong>ISP</strong></p>\n\n<p><em>Interface Segregation</em> boils down to the fact that <em>modifying an interface is a breaking change</em>. Observe the <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">KISS</a> principle here: the <em>interface</em> of a <code>CalculatorApp</code> object only exposes a parameterless <code>Execute</code> method. It's unlikely that anything else is ever going to be needed, because all the entry point ever needs to be doing is <em>everything it takes</em> to run this <code>Execute</code> method.</p>\n\n<p><strong>DIP</strong></p>\n\n<p><em>Dependency Inversion</em> means that instead of <code>new</code>ing up dependencies, a class will be <em>injected</em> with implementations for its dependencies, preferably through its constructor. Because CalculatorApp requires implementations for <code>IDataService</code> and <code>IUserInteractionService</code>, you already know that this class' responsibility will be to coordinate the interactions between these <em>services</em>, implementing the <em>business logic</em>.</p>\n\n<p>In order to run the <code>Execute</code> method, <code>Main</code> has to instantiate a <code>CalculatorApp</code>. Because I'm injecting <em>abstractions</em>, I can write a unit test suite to cover everything the <em>business rules</em> dictate, where I'm free to inject a mock implementation for every dependency and verify that method X or Y is called N times on the <code>IDataService</code>, or whatever.</p>\n\n<hr>\n\n<p>By building the app <em>top-down</em> by writing the <em>abstractions</em> first (actually with TDD, you'll first write a failing unit test) and peeling off abstraction levels as you dive into the low-level <code>Console.WriteLine</code> calls, you decide how much abstraction is enough abstraction, and it gets easier to realize how much abstraction is outright <em>over-engineered</em>: write only the code you need to write for tests to pass. Writing the app bottom-up in <code>Main</code> and refactoring towards SOLID makes this much harder than <em>expanding the idea</em> as you go from one level of abstraction to the next.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:50:09.950",
"Id": "85607",
"Score": "0",
"body": "Mat that was very helpful. Much appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:23:49.763",
"Id": "48731",
"ParentId": "48695",
"Score": "3"
}
},
{
"body": "<p>I don't like your switch code...</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>switch (eventCode)\n{\n case (int)GenericEntities.EventType.Running:\n result = \"\\n 5% supplement added for donations to running events.\";\n break;\n case (int)GenericEntities.EventType.Swimming:\n result = \"\\n 3% supplement added for donations to swimming events.\";\n break;\n case (int)GenericEntities.EventType.Others:\n result = \"\\n No supplement should be applied for other events.\";\n break; \n}\n</code></pre>\n\n<p>I think it's better idea to operate on objects.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nclass Program\n{\n static void Main(string[] args)\n {\n var chosenEvent = Event.CreateEvent(1);\n\n Console.WriteLine(chosenEvent.GetEventTypeMessage());\n Console.WriteLine(chosenEvent.GetSupplementAmount(1000));\n\n Console.ReadLine();\n }\n}\n\nclass Event\n{\n private readonly string _name;\n private readonly decimal _suplement;\n\n public decimal GetSupplementAmount(decimal donationAmmount)\n {\n return _suplement * donationAmmount;\n }\n\n public string GetEventTypeMessage()\n {\n return String.Format(\"{0}% suplement added for donations to {1} events.\", _suplement * 100, _name);\n }\n\n public static Event CreateEvent(int id)\n {\n if (id == 1)\n return new Event(\"running\", 0.05m);\n else if (id == 2)\n return new Event(\"swimming\", 0.03m);\n else if (id == 3)\n return new Event(\"other\", 0.0m);\n else\n throw new IndexOutOfRangeException();\n }\n\n private Event(string name, decimal suplement)\n {\n _name = name;\n _suplement = suplement;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:53:50.980",
"Id": "48755",
"ParentId": "48695",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48731",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:31:30.250",
"Id": "48695",
"Score": "5",
"Tags": [
"c#",
"design-patterns",
"dependency-injection",
"tdd"
],
"Title": "Gift aid calculator task"
} | 48695 |
<p>I'm doing my best to explain how this works, but it's pretty confusing and lengthy. Let me know if there's something I can do to clarify.</p>
<p>I'm building a class that models a custom Plist and sets its values to properties in the class automatically. Most importantly however is the core concept of populating the properties of the subclass with values from the dictionary if they exist. To do this, it is required that your dictionary key be the same as the name of your property, and you are not messing with Apple's autosynthesized setter. Everything is working, but I'm worried that if its implemented incorrectly, it will cause problems. Can someone tell me if there is something I'm missing? First I retrieve an array of our property names, and then I cycle them through this method to set them to dictionary values like this:</p>
<pre><code>[self setPropertyFromDictionaryValueWithName:propertyNames[0]];
</code></pre>
<p>And here's what happens:</p>
<pre><code>- (void) setPropertyFromDictionaryValueWithName:(NSString *)propertyName {
// Get our setter from our string
SEL propertySetterSelector = [self setterSelectorForPropertyName:propertyName];
// Make sure it exists as a property
if ([self respondsToSelector:propertySetterSelector]) {
if (_realDictionary[propertyName]) {
// Index 0 is object, Index 1 is the selector: arguments start at Index 2
const char * typeOfProperty = [self typeOfArgumentForSelector:propertySetterSelector atIndex:2];
// Get object from our dictionary
id objectFromDictionaryForProperty = _realDictionary[propertyName];
// Set our implementation
IMP imp = [self methodForSelector:propertySetterSelector];
// Set Dictionary to property
if (strcmp(typeOfProperty, @encode(id)) == 0) {
//NSLog(@"Is Object");
void (*func)(id, SEL, id) = (void *)imp;
func(self, propertySetterSelector, objectFromDictionaryForProperty);
}
else if (strcmp(typeOfProperty, @encode(BOOL)) == 0) {
//NSLog(@"Is Bool");
void (*func)(id, SEL, BOOL) = (void *)imp;
func(self, propertySetterSelector, [objectFromDictionaryForProperty boolValue]);
}
else if (strcmp(typeOfProperty, @encode(int)) == 0) {
//NSLog(@"Is Int");
void (*func)(id, SEL, int) = (void *)imp;
func(self, propertySetterSelector, [objectFromDictionaryForProperty intValue]);
}
else if (strcmp(typeOfProperty, @encode(float)) == 0) {
//NSLog(@"Is Float");
void (*func)(id, SEL, float) = (void *)imp;
func(self, propertySetterSelector, [objectFromDictionaryForProperty floatValue]);
}
else if (strcmp(typeOfProperty, @encode(double)) == 0) {
//NSLog(@"Is Double");
void (*func)(id, SEL, double) = (void *)imp;
func(self, propertySetterSelector, [objectFromDictionaryForProperty doubleValue]);
}
}
}
}
- (SEL) setterSelectorForPropertyName:(NSString *)propertyName {
/*
Because apple automatically generates setters to "setPropertyName:", we can use that and return the first argument to get the type of property it is. That way, we can set it to our plist values. Custom setters will cause problems.
*/
// Make our first letter capitalized - Using this because `capitalizedString` causes issues with camelCase => Camelcase
NSString * capitalizedPropertyName = [propertyName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[propertyName substringToIndex:1] capitalizedString]];
// The name of our auto synthesized setter | Custom setters will cause issues
NSString * methodString = [NSString stringWithFormat:@"set%@:", capitalizedPropertyName];
// Set our Selector
SEL propertySetterSelector = NSSelectorFromString(methodString);
// Return it
return propertySetterSelector;
}
- (const char *) typeOfArgumentForSelector:(SEL)selector atIndex:(int)index {
NSMethodSignature * sig = [self methodSignatureForSelector:selector];
// Index 0 is object, Index 1 is the selector: arguments start at Index 2
const char * argType = [sig getArgumentTypeAtIndex:index];
return argType;
}
</code></pre>
<p>The basic logic is this:</p>
<ol>
<li><p>Get property name: <code>propertyName</code></p></li>
<li><p>Generate setter: <code>setPropertyName:(someType)propertyName</code></p></li>
<li><p>Find argument type of setter</p></li>
<li><p>Call setter with value from dictionary</p></li>
</ol>
<p>My idea is that by subclassing and adding your properties, they will automatically be set to the values from your dictionary at runtime. I'm currently using it for easier interaction with Plists, but I think it would be helpful with JSON, or other objects that I would like to interact with as Objective-C objects.</p>
<h3> Example </h3>
<p>You have a plist:</p>
<p><img src="https://i.stack.imgur.com/my4tt.png" alt="Property list editor screenshot"></p>
<p>You declare your properties in a subclass to match the names of keys:</p>
<pre><code>#import "PlistModel.h"
@interface CustomModel : PlistModel
@property (strong, nonatomic) NSString * StringPropertyKey;
@property (strong, nonatomic) NSDate * DatePropertyKey;
@property (strong, nonatomic) NSArray * ArrayPropertyKey;
@property (strong, nonatomic) NSDictionary * DictionaryPropertyKey;
@property int IntPropertyKey;
@property BOOL BoolPropertyKey;
@property float FloatPropertyKey;
@end
</code></pre>
<p>That's it! The values are automatically populated at runtime without any additional code:</p>
<pre><code>[CustomModel plistNamed:@"CustomModel" inBackgroundWithBlock:^(PlistModel *plistModel) {
CustomModel * customModel = (CustomModel *)plistModel;
NSLog(@"StringProperty: %@", customModel.StringPropertyKey);
NSLog(@"DateProperty: %@", customModel.DatePropertyKey);
NSLog(@"ArrayProperty: %@", customModel.ArrayPropertyKey);
NSLog(@"DictionaryProperty: %@", customModel.DictionaryPropertyKey);
NSLog(@"IntProperty: %i", customModel.IntPropertyKey);
NSLog(@"BoolProperty: %@", customModel.BoolPropertyKey ? @"YES" : @"NO");
NSLog(@"FloatProperty: %f", customModel.FloatPropertyKey);
}];
</code></pre>
<p>You can interact and update your plist via properties, and the plist will be automatically saved for you. If you don't include a plist in your project, it will automatically generate and save a new one with the name provided. </p>
<p>I reverse the process before saving so that the plist / dictionary is automatically updated to values from properties. This way anything you have added or updated in your properties is saved.</p>
<h3> Question </h3>
<p>I've seen things like this in the past, but I've never seen how it's done. Is there a better way to set unknown properties at runtime without generating a selector? </p>
<p>Will this cause some unforeseen problem?</p>
<p>Full project is available <a href="https://github.com/LoganWright/PlistModel" rel="nofollow noreferrer">here</a>! I don't have docs ready yet, and there are still probably a few kinks, but if you can piece it together, it's ready to go!</p>
| [] | [
{
"body": "<p>This review is going to have to be in the form of a handful of questions, things perhaps you haven't considered. I don't know the answer to these, but I know they need to be answered.</p>\n\n<p><code>typeOfArgumentForSelector:(SEL)selector atIndex:(int)index</code> and the way you use it is bothering me a little bit. As written, the method is somewhere between fine for reusability and not completely correct for this use. What's clearly missing is a safety net around the call to <code>[sig getArgumentTypeAtIndex:index];</code></p>\n\n<p>Per the documentation, <code>NSMethodSignature</code> is only guaranteed to have two argument indices, for the two hidden arguments that every Objective-C method has. We have no guarantee that there will be anything at index 2. It could be out of bounds and throw an exception. </p>\n\n<p>You could say, \"but I'm only using it to get setters, which always have exactly 1 argument!\" and that'd be fair... but if that's the case, the method is poorly named and shouldn't take two arguments.</p>\n\n<p>So as I said, you're floating in between two spots.</p>\n\n<p>If you want the method to remain generic so you can use it as is in other projects, then you need some safety (I'll come back to this). If you would rather the method stay specific to this project, change the method to:</p>\n\n<pre><code>- (const char *)dataTypeForSetter:(SEL)setter;\n</code></pre>\n\n<p>And before you try grabbing the argument, put this line in:</p>\n\n<pre><code>if ([sig numberOfArguments] != 3) return NULL;\n</code></pre>\n\n<p>Because if the number of arguments isn't exactly 3, then the method isn't a setter.</p>\n\n<p>Now alternatively, if you want to leave the method more flexible, you can, but you still need to put some safety around your call to <code>getArgumentTypeAtIndex:</code>. There's nothing guaranteeing the index exists, and if it doesn't, you have an unhandled exception.</p>\n\n<p>So...</p>\n\n<pre><code>if (index >= [sig numberOfArguments]) return NULL;\n</code></pre>\n\n<p>And just document the method as returning <code>NULL</code> when the requested index greater than the number of arguments.</p>\n\n<hr>\n\n<p>Beyond this, I see a couple problems that you probably didn't think about while implementing this.</p>\n\n<p>First of all, properties marked as <code>readonly</code> in the public header file but then redefined as <code>readwrite</code> in in the <code>.m</code> file.</p>\n\n<p>If the property is only <code>readonly</code> and never <code>readwrite</code>, most likely there's not even a backing instance variable, but the object will return <code>NO</code> for the <code>respondsToSelector</code> call. HOWEVER, if it is redefined as <code>readwrite</code>, it will return <code>YES</code> to the <code>respondsToSelector</code> call, and will attempt to set this property. This may or may not be the intended behavior, but either way it should certainly be tested and well documented.</p>\n\n<hr>\n\n<p>Second, consider how most <code>@property</code> setters actually look:</p>\n\n<pre><code>- (void)setSomeIvar:(int)someIvar {\n _someIvar = someIvar;\n}\n</code></pre>\n\n<p>Now consider how most <code>@property</code> getters actually look:</p>\n\n<pre><code>- (int)someIvar {\n return _someIvar;\n}\n</code></pre>\n\n<p>In this case, this is completely unproblematic. The property is straight forward.</p>\n\n<p>Now consider a class where perhaps we're doing something with angles, and we've got a non-standard setter/getter.</p>\n\n<pre><code>- (void)setDegrees:(int)degrees {\n _degrees = degrees % 360;\n _revolutions = degrees / 360;\n}\n\n- (int)degrees {\n return _degrees;\n}\n\n- (int)revolutions {\n return _revolutions;\n}\n</code></pre>\n\n<p>Now... I'm not arguing that this is good design for a class. Personally, I'd do the opposite and store everything in degrees and calculate revolutions when it's called. But the point here is that this is a perfectly possible class set up. And for argument's sake, we're going to assume that <code>revolutions</code> is <code>readonly @property</code> (so it won't have its own setter).</p>\n\n<p>If I originally set degrees to 390, I'll have 1 revolution and 30 degrees. If your code saves it to a plist, it will save it as such, and then when it tries to write it via the plist, it will end up setting the values to 0 revolutions and 30 degrees, which is different from what was originally in there.</p>\n\n<p>The real point here is that in this example:</p>\n\n<pre><code>NSLog(@\"A: %@\", self.iVar);\n[self setIvar:[self iVar]];\nNSLog(@\"B: %@\", self.iVar);\n</code></pre>\n\n<p>A and B here are not guaranteed to log exactly the same, depending on the implementation of the setter and getter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:11:10.517",
"Id": "85544",
"Score": "0",
"body": "1. I'll put in an exception for if an argument doesn't exist, just so the method can feel more resiliant. 2. I mention a couple times, and will mention in docs that you have to use autosynthesized getters setters. I will also mention not to use readonly properties until I can come up with a solution. Thanks for pointing out a couple possible contingencies that I should account for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:11:51.487",
"Id": "85545",
"Score": "0",
"body": "Code review should have larger comments so I can respond w/ code etc.! Responses in comments are always difficult."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:12:04.850",
"Id": "85546",
"Score": "0",
"body": "You can use `readwrite` property. While `readwrite` is a property attribute, it is only the default property attribute. Every property is either `readonly` or `readwrite`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:12:36.107",
"Id": "85547",
"Score": "1",
"body": "There are chat rooms: http://chat.stackexchange.com/rooms/12918/nschat"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:12:51.527",
"Id": "85548",
"Score": "0",
"body": "Ahh, I didn't mean to say readwrite, I edited my comment! Thanks"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:02:01.347",
"Id": "48723",
"ParentId": "48703",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:32:40.137",
"Id": "48703",
"Score": "4",
"Tags": [
"objective-c",
"objective-c-runtime"
],
"Title": "Dynamically setting unknown properties of a subclass from parent class in Objective-C"
} | 48703 |
<p>I've got some constructors and a factory class that I would like to use in an Angular project. I would like to know how I can convert these to usable Angular services for my project.</p>
<h2>Process Constructor</h2>
<pre><code>/**
* A constructor for Process objects
*
* @param {Object} options An object with an integer processId and an array of roles containing
* roles
*
* @return {Process} A new Process object
*/
function Process (options) {
if ( typeof options.processId !== 'number' ) {
throw 'Process ID is not a number';
}
if ( typeof options.roles !== 'object' || typeof options.roles.length === 'undefined' ) {
throw 'Roles is not an array';
}
if ( options.roles.length === 0 ) {
throw 'No roles passed';
}
this.processId = options.processId;
this.roles = options.roles;
return this;
}
</code></pre>
<p>This is pretty straight forward. A bit of input checking then return the object.</p>
<hr>
<h2>Role Constructor</h2>
<pre><code>/**
* A constructor for Role objects
*
* @param {Integer} processId An integer representing this role's parent process ID
* @param {Integer} number What number to assign the roleName attribute
*
* @return {Object Role} A brand new Role object
*/
function Role (processId, number) {
// typecast
processId = +processId;
number = +number;
if ( !!isNaN(processId) || !!isNaN(number) ) {
throw 'Both processId and number need to be numbers';
}
this.roleName = 'role' + number;
this.startDate = rand(0, new Date().getTime());
this.endDate = rand(this.startDate, new Date().getTime());
this.href = '/v1/transactions/' + processId + '/roles/' + this.roleName;
return this;
}
</code></pre>
<p>Again, pretty straightforward. Some input validation, and then throw some data in and return the object.</p>
<hr>
<h2>Factory to create Process and Role objects</h2>
<pre><code>/**
* A factory class to make some randomly generated processes
* Based on http://addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript
*
* @return {Object Process} A new Process object with random data
*/
function processFactory () {}
/**
* Returns a random 12 digit integer
* @return {Integer} 12 digit integer
*/
processFactory.prototype.makeId = function () {
return Math.round(Math.random() * Math.pow(10, 12));
};
/**
* Makes a new process with random info
*
* @param {Integer} numberOfRoles The amount of roles to put into the process
*
* @return {Object Process} A new Process object
*/
processFactory.prototype.makeProcess = function(numberOfRoles) {
var i = 1;
if ( typeof numberOfRoles === 'undefined' ) {
numberOfRoles = Math.round(Math.random() * 10);
}
this.processId = processFactory.makeId();
this.roles = [];
while ( numberOfRoles-- ) {
i++;
this.roles.push(new Role(this.processId, i));
}
return new Process(this);
};
var processFactory = new processFactory();
</code></pre>
<p>And here's the factory to build me some Processes and Roles for them. I'm not even sure if this is the best way to make a factory in Vanilla JS!</p>
<hr>
<p>I want to be able to instantiate multiple processes and controllers.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:29:26.357",
"Id": "85522",
"Score": "0",
"body": "Based on [this jsbin](http://jsbin.com/ohamub/2640/edit) I think that at least my `processFactory` could be in an Angular service."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T15:29:32.070",
"Id": "87303",
"Score": "0",
"body": "The [Angular Developer Guide for Services](https://docs.angularjs.org/guide/services) would be a good place to start."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:13:07.137",
"Id": "48708",
"Score": "2",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Factories and constructors in Angular?"
} | 48708 |
<p>I created a method that does division without the <code>/</code> operator. I believe this code is a bit slow and can be improved, but I am not sure how to do so. I'm not so good with shift operators (<code>>></code> and <code>>>></code>), but I believe that this will help a bit. How can I change my code to increase the speed of the division. I am open the changing my logic as well.</p>
<pre><code>public class DivisionReplace {
public static void divide(int N, int D) {
int result = 0;
if (D == 0) {
System.out.println("Cannot divide by 0");
}
else if (N == 0) {
System.out.println(0);
}
else if (N == D) {
System.out.println(1);
}
else if (N > 0 && D > 0 && N < D) {
System.out.println(0);
}
else {
// both negative
if (N < 0 && D < 0) {
while (N <= D) {
N += -1 * D;
result++;
}
System.out.println(result);
}
// either N or D negative
else if (N < 0 || D < 0) {
if (N < 0) {
N = -1 * N;
}
else {
D = -1 * D;
}
while (N >= D) {
N -= D;
result--;
}
System.out.println(result);
}
// both positive
else {
while (N >= D) {
N -= D;
result++;
}
System.out.println(result);
}
}
}
public static void main(String[] args) {
divide(-4,-10);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-14T06:53:31.383",
"Id": "228790",
"Score": "1",
"body": "Try running your code with N = 1000000000000L and D = 7. You will need to method to accept long int instead of int."
}
] | [
{
"body": "<p>A couple of comments first</p>\n\n<p>It would be better to let your <code>divide</code> method should return an <code>int</code>, not do the output to <code>System.out</code> itself. Do the output in <code>main</code> like this:</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(divide(-4,-10));\n}\n</code></pre>\n\n<p>The variables N and D are short and don't follow the Java naming conventions. Parameter names should start with a lowercase letter and use <code>camelCase</code>. I would recommend calling them <code>numerator</code> and <code>denominator</code>.</p>\n\n<p>If <code>denominator == 0</code> is a quite exceptional case, I would recommend throwing an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html\"><code>ArithmeticException</code></a> stating that it was caused by division by zero.</p>\n\n<p>You treat more special cases than you need to. I don't think you need to handle either <code>numerator == denominator</code> or <code>numerator == 0</code> as a special case. It should be possible to handle that using the normal logic for division.</p>\n\n<p>If you were doing divisions by a power of 2 (2, 4, 8, 16, etc.) you could use right shift <code>numerator >> 1</code>, <code>numerator >> 2</code> etc. However, your code should support more than just those cases which makes things more difficult.</p>\n\n<p>In the end, you are trying to re-implement division by using repetitive subtraction. It will be slow, no matter what you do. If you want to be possibly somewhat faster for bigger numbers, or want to try another approach (I can't promise you it will be faster, but I believe that for big enough numbers it will be significantly faster), you could try to implement division by using one of the good old \"pen and paper\" ways. Think about the division <code>303364 / 596</code>. Try to solve that <strong>by hand!</strong> and think about what it is that you are doing. (Hint: Also think about how you do multiplications by hand, how would you solve <code>583 * 42</code> ?)</p>\n\n<p>However, in reality though, the fastest solution is to use the <code>/</code> operator in Java, but that wouldn't be a challenge now, would it? So I guess that's out of the question :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:05:00.027",
"Id": "85527",
"Score": "0",
"body": "I see what you're getting at! I'll give it a shot thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:08:51.233",
"Id": "85529",
"Score": "0",
"body": "Would the special cases I added prevent certain calculations from occurring? Thus spitting out the answer and prevent calculations"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:18:21.423",
"Id": "85531",
"Score": "2",
"body": "Another option is to [throw `IllegalArgumentException`](http://stackoverflow.com/a/1657925/285873) since the method was passed an illegal argument and no division by zero was performed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:51:46.150",
"Id": "48712",
"ParentId": "48709",
"Score": "14"
}
},
{
"body": "<p>I disagree (slightly) with Simon Forsberg. Rather than having your division routine return an int, it would be better for it to return an object containing both the dividend <em>and</em> the remainder.</p>\n\n<p>Your routine has another problem: it depends on multiplying by -1 to turn a negative number into a positive number. Unless you also widen the number, this is doomed to failure. The problem is fairly simple: assuming 2's complement (which Java does) there's a negative number for which no corresponding positive number can be represented in the same type. For example, a byte has values from -128 to +127. For an input of -128, there's no corresponding positive number unless you convert to a wider type. The numbers are larger, but there's a corresponding case for <code>short</code>, <code>int</code> and <code>long</code>.</p>\n\n<p>If you can live with restricting the inputs to 32 bits, you can convert them to <code>long</code>, then do the division, and convert back to <code>int</code> when you're done. It's a little ugly, but not too terrible.</p>\n\n<p>If you might at some point want to be able to divide <code>long</code>s correctly, you run into a little bit of a problem: the only wider type available is <code>BigInteger</code>, which is fairly slow and clumsy. Alternatively, if you can live with a rather different restriction, Java 8 (finally) supports an unsigned-long type, so you can use that instead. This, however, basically subsumes the code you're writing by providing an unsigned division routine in the JDK. At least as far as I can see, it doesn't seem to provide you with the tools to do the job (at all conveniently) on your own.</p>\n\n<p>As far as the division algorithm itself goes, you normally want to do binary division. Simon Forsberg alluded to how you'd do long division by hand, and he's right about that. Unfortunately, in all the years I've seen that advice given, I've seen only a handful of people figure out how to do long division in binary based on how you do long division in decimal. Most try to re-do long division in decimal, which is quite painful by comparison.</p>\n\n<p>Let's consider long division in decimal in a little more detail, then think of the same basic idea in binary. If we were going to divide 12345 by (say) 17, at the first step we'd basically \"shift\" 17 to the left until it matched up with 12. Since 17 is larger than 12, we'd shift it to the right one place, so our first real division step is 123/17. We write the 7 into the answer and subtract 17*7 from 123. Our next step is 44/17, and so on. The tricky part of this (as every school kid knows) is having to figure that <code>123/17</code> part. Most people can guess it's going to be somewhere around 7, but few are certain immediately.</p>\n\n<p>Fortunately, in binary division that never arises. Binary division is actually a bit simpler:</p>\n\n<ol>\n<li>Shift the denominator left until it's larger than the numerator (keeping track of how far you've shifted it).</li>\n<li>Shift the denominator right one place.</li>\n<li>If the shifted denominator is smaller than the current numerator, subtract it and put a 1 into the current digit of the answer.</li>\n<li>Otherwise, put a 0 into the current digit of the answer.</li>\n<li>If we've shifted the denominator back to its original value, quit.</li>\n<li>Otherwise, repeat from step 2.</li>\n</ol>\n\n<p>Assuming you do have an unsigned type in which to do the division, the procedure for handling signs correctly is something like this:</p>\n\n<ol>\n<li>check the signs of the inputs\n<ul>\n<li>If they match, the result will be positive</li>\n<li>If they differ, the result will be negative</li>\n</ul></li>\n<li>Convert inputs to unsigned\n<ul>\n<li>if negative, subtract from 0: <code>unsigned intermediate = 0u - (unsigned)input;</code></li>\n<li>if positive, leave unchanged: <code>unsigned intermediate = (unsigned)input;</code></li>\n</ul></li>\n</ol>\n\n<p>Finally, convert the result back signed, and negate it if the result should be negative. This might seem to run into the same problem as we started with, but it really doesn't. The problem arose because in two's complement, there is a negative number for which there is not corresponding positive number. Every positive number <em>does</em> have a corresponding negative number though, so converting back to negative (if needed) at the end is actually pretty trivial.</p>\n\n<p>As far as code goes, I'll use C++ since it has syntax similar to Java, but supports unsigned types directly. Using it, division can look something like this:</p>\n\n<pre><code>// A type to store a quotient and a remainder. Also supports output to a stream.\nstruct result {\n int answer;\n int remainder;\n\n result(int a, int r) : answer(a), remainder(r) {}\n\n friend std::ostream &operator<<(std::ostream &os, result const &r) {\n return os << r.answer << \" remainder \" << r.remainder;\n }\n};\n\nint sign(int x) {\n if (x < 0)\n return -1;\n if (x == 0)\n return 0;\n return 1;\n}\n\nresult divide(int dividend_, int divisor_) {\n int res = 0;\n int current = 1;\n\n if (divisor_ == 0)\n throw std::overflow_error(\"Division by 0\");\n\n if (divisor_ == 1)\n return result(dividend_, 0);\n\n // record whether the result will be negative: \n bool neg = sign(dividend_) != sign(divisor_);\n\n // convert both inputs to unsigned numbers: \n unsigned divisor = divisor_ >= 0 ? divisor_ : 0u - (unsigned) divisor_;\n unsigned dividend = dividend_ >= 0 ? dividend_ : 0u - (unsigned) dividend_;\n\n // shift the denominator left until it's larger than the numerator,\n // recording how many places we've shifted \n while (divisor < dividend) {\n divisor <<= 1;\n current <<= 1;\n }\n\n // shift denominator right one place\n while (current >>= 1) {\n divisor >>= 1;\n\n // if that's less than the numerator, subtract and record a 1 in the quotient\n if (divisor <= dividend) {\n res += current;\n dividend -= divisor;\n }\n }\n\n // if the quotient should be negative, negate it\n if (neg) res = -res;\n return result(res, dividend);\n}\n</code></pre>\n\n<p>This treats both division by 0 and division by 1 as special cases. Division by 0 really is a special case, so that seems pretty obvious. Division by 1 is a special case <em>only</em> because of that nasty asymmetry in 2's complement. If we divide the maximum-magnitude negative number by 1, the result can't be represented as a positive signed number. We could use an unsigned number for the intermediate results, but if we did doing the negation at the end would be more complex. This takes a rather different route, treating division by 1 as a special case. We only really need that special-case code for min_int/1, but it's simpler to use it for all division by 1 than to test both the numerator and the denominator, and use the special case only for the one case that's really special.</p>\n\n<p>Short review of the code above: not the best names. Comments refer to \"numerator\" and \"denominator\", but code uses \"dividend\" and \"divisor\". The comments refer to the quotient, which the code refers to only as <code>res</code> and <code>answer</code>. Likewise, <code>result</code> for the type of the result is a horrible name--saved from colliding with every other result in a program only by the fact that nobody else would be nearly insane enough to use such a general name for anything.</p>\n\n<p>Looking past the names, the most obvious shortcoming is (of course) the mere fact that this exists at all. It's simply a pointless waste (though something vaguely similar could make sense in the implementation of a large integer type, for one example). For really large number, however, there are almost certainly better division algorithms available. This one is fairly simple, but performance isn't the best--it produces only one bit of the quotient per iteration of its main loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:56:28.767",
"Id": "48781",
"ParentId": "48709",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48712",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:31:38.243",
"Id": "48709",
"Score": "11",
"Tags": [
"java",
"performance",
"reinventing-the-wheel",
"integer"
],
"Title": "Division without / operator"
} | 48709 |
<p>In my application there is a "config" object that is accessbile by multiple threads concurrently.
It is a single object (singleton) injected by the DI in the "dependents".
Until now, this (the "config") object was immutable which makes it inherently thread-safe.
However, there is a new requirement that the "config" should be periodically "refreshed/updated".
I wrote a wrapper (decorator) that refreshes itself (from a configProvider), and the refresh happens on the fly, when a method gets called (if the certian amount of time has passed)
The wrapper should be thread safe and non-blocking.</p>
<p>Any (concurrency) issues with the following code?</p>
<pre><code>package xyz;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Implementation of {@link IMyModuleConfig} that periodically refreshes itself from the provided
* {@link IConfiguration}.
* The refresh is done on-the-fly when some method is called, it is thread safe.
*
* @Threadsafe
*/
public class MyModuleRefreshableConfig implements IMyModuleConfig {
private IMyModuleConfig configBean; // Decorated object, Immutable, non-final should be properly fenced
private long lastRefreshTime; // time when we refreshed the configuration last, non-final should be properly fenced
private final IConfiguration configProvider; // refresh source
private final long refreshInterval; // how often we refresh
private final AtomicBoolean refreshConfigMutex; // if true, a thread is refreshing configuration right now
public MyModuleRefreshableConfig(IConfiguration configProvider, long refreshInterval) {
refreshConfigMutex = new AtomicBoolean(false);
this.configBean = refreshConfig();
this.lastRefreshTime = System.currentTimeMillis();
// Do not re-arrange, the assignment to final field latter in the constructor serves as a "store fence"
this.configProvider = configProvider;
this.refreshInterval = refreshInterval;
}
@Override
public boolean getMyBoolean() {
refreshConfigIfNeeded(); // full fence
return this.configBean.getMyBoolean();
}
@Override
public int getTimeout() {
refreshConfigIfNeeded(); // full fence
return this.configBean.getTimeout();
}
private void refreshConfigIfNeeded() {
boolean aquired = refreshConfigMutex.compareAndSet(false, true); // full fence
if (aquired) { // critical section starts, if some thread is in just continue, no need to wait
long cTime = System.currentTimeMillis();
boolean shouldRefresh = (cTime - lastRefreshTime) > refreshInterval;
if (shouldRefresh) {
lastRefreshTime = cTime;
configBean = refreshConfig();
}
refreshConfigMutex.set(false); // critical section ends, write fence
}
}
private IMyModuleConfig refreshConfig() {
// creates new immutable IMyModuleConfig with values provided by configProvider
}
}
</code></pre>
| [] | [
{
"body": "<p>As long as you are 100% certain that all threads will use the same instance of <code>MyModuleRefreshableConfig</code>, this code should work. Just to be certain I would make the <code>refreshConfigMutex</code>static:</p>\n\n<pre><code>private static final AtomicBoolean refreshConfigMutex;\n\npublic MyModuleRefreshableConfig(IConfiguration configProvider, long refreshInterval) {\n synchronized {\n if (refreshConfigMutex == null) {\n refreshConfigMutex = new AtomicBoolean(false);\n }\n }\n ....\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:28:42.067",
"Id": "48772",
"ParentId": "48713",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:55:40.707",
"Id": "48713",
"Score": "3",
"Tags": [
"java",
"concurrency"
],
"Title": "Concurrent non-blocking refresh"
} | 48713 |
<p>I wrote this function to do <code>unordered_set</code> intersection using templates. I have seen <a href="https://stackoverflow.com/a/896440/2912901">this answer</a> but I thought that it was overkill. I would like the method to take in 2 sets and return a set.</p>
<pre><code>class SetUtilites{
public:
template<typename Type>
static boost::unordered_set<Type> intersection(const boost::unordered_set<Type> &set1, const boost::unordered_set<Type> &set2){
if(set1.size() < set2.size()){
boost::unordered_set<Type> iSet;
boost::unordered_set<Type>::iterator it;
for(it = set1.begin(); it != set1.end();++it){
if(set2.find(*it) != set2.end()){
iSet.insert(*it);
}
}
return iSet;
}else{
return intersection(set2,set1);
}
}
};
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p><code>SetUtilites</code> is misspelled; it should be <code>SetUtilities</code>.</p></li>\n<li><p>For better readability, consider doing something about this long line:</p>\n\n<blockquote>\n<pre><code>static boost::unordered_set<Type> intersection(const boost::unordered_set<Type> &set1, const boost::unordered_set<Type> &set2)\n</code></pre>\n</blockquote>\n\n<p>You could shorten the types as such via <code>typedef</code>, but it may not help very much, or it may even make things uglier. You could also wrap the line in some way. Choose whichever works best.</p></li>\n<li><p>Do you even need a <code>class</code> for this? It just contains one function and no data members, so it's not really doing anything relevant as one. Instead, just make this a free function (non-member function) and put it into a <code>namespace</code> with a similar name as the <code>class</code>.</p></li>\n<li><p>The name <code>iSet</code> sort of sounds like Hungarian notation, although it appears to be a shortened form of <code>intersectionSet</code>. If you still don't want to call it something that lengthy, you could rename it to something like <code>finalSet</code>, indicating that it will be returned from the function.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-11T16:25:17.050",
"Id": "56773",
"ParentId": "48714",
"Score": "10"
}
},
{
"body": "<h2>Bug</h2>\n\n<p>When your sets are of equal size you well end up in an endless recursion.\nInstead of <code>if(set1.size() < set2.size())</code> you should use <code>if(set1.size() <= set2.size())</code> (after all it does not make much sense to swap if the sets are of equal size).</p>\n\n<h2>Use C++11 loops ...</h2>\n\n<p>With C++11 I would advise you to use range based for:</p>\n\n<pre><code>for(auto const &element: set1)\n</code></pre>\n\n<p>To avoid having to deal with the element type and with iterators.</p>\n\n<h2>... or an alternative</h2>\n\n<p>I assume you are not using C++11 or you would have taken <code>std::unordered_set</code> instead of the boost one.</p>\n\n<p>Even without C++11 there is <code>BOOST_FOREACH</code> which you could use:</p>\n\n<pre><code>BOOST_FOREACH(Type const &element, set1)\n</code></pre>\n\n<h2>Use easier to understand functions</h2>\n\n<p>Furthermore I would suggest to use the <code>count</code> function so you don't have to compare iterators:</p>\n\n<pre><code>if(set2.count(element) > 0)\n iSet.insert(element);\n</code></pre>\n\n<h2>Wrap Up</h2>\n\n<p>Finally I would avoid the vertical whitespace that does not add clarity which makes the resulting code (with additions from Jamal's answer):</p>\n\n<pre><code>template<typename Type>\nstatic boost::unordered_set<Type> intersection(const boost::unordered_set<Type> &set1, const boost::unordered_set<Type> &set2){\n if(set1.size() <= set2.size()){\n boost::unordered_set<Type> iSet;\n for(auto const &element : set1){\n if(set2.count(element) > 0) {\n iSet.insert(element);\n }\n }\n return iSet;\n }else{\n return intersection(set2,set1);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T16:57:48.827",
"Id": "101297",
"Score": "0",
"body": "Thanks for bug fix. I would guess that count is more expensive than find, no? Comparing against end is common in stl I believe. Your solution is great, but I do not wish to use c++11 features."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T17:04:08.433",
"Id": "101299",
"Score": "1",
"body": "I would say count is internally implemented as end-comparison. End-comparison is a common idiom but still harder to read than count (I believe). In any case it is longer code so it offers more space for errors. Regerding C++11: You can simply transform the C++11 `for` to `BOOST_FOREACH` as I have written and the code should work the same. Explicit iterator loops always have the problem of being very verbose and doing potentially other things than looping over all elements. A foreach does communicate more clearly what it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-13T23:17:18.203",
"Id": "101550",
"Score": "0",
"body": "I agree with the for each point. It is much clearer. I feel a little funny about using count with set because the semantics clash. What I really want would be hasKey or hasElement O(1) of course. I could make another function for that and make it clearer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T16:07:48.623",
"Id": "56856",
"ParentId": "48714",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "56773",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:56:20.357",
"Id": "48714",
"Score": "9",
"Tags": [
"c++",
"performance",
"template",
"boost",
"set"
],
"Title": "boost::unordered_set intersection using templates"
} | 48714 |
<p>I am practicing various tree algorithms and that require code review for it's efficiency, clarity and also if it can be made better etc.</p>
<p>Is there a better way to call <code>parent.findMin(parent)</code></p>
<p><strong>TreeNode.java</strong></p>
<pre><code>package binarytree;
public class TreeNode
{
TreeNode left;
TreeNode right;
int data;
TreeNode parent;
int size=0;
TreeNode(int data)
{
this.data = data;
size = 1;
}
int size()
{
return size;
}
void setLeftChild(TreeNode left)
{
this.left = left;
if(left == null)
{
left.parent = this;
}
}
void setRightChild(TreeNode right)
{
this.right = right;
if(right == null)
{
right.parent = this;
}
}
void insertInOrder(int d)
{
if(d <= data)
{
if(left == null)
{
setLeftChild(new TreeNode(d));
}
else
{
left.insertInOrder(d);
}
}
else{
if(right == null)
{
setRightChild(new TreeNode(d));
}
else{
right.insertInOrder(d);
}
}
size++;
}
void postOrderTraversal(TreeNode parent)
{
if(parent == null) return;
postOrderTraversal(parent.left);
postOrderTraversal(parent.right);
printVal(parent);
}
void preOrderTraversal(TreeNode parent)
{
if(parent == null) return;
printVal(parent);
preOrderTraversal(parent.left);
preOrderTraversal(parent.right);
}
void inOrderTraversal(TreeNode parent)
{
if(parent == null) return;
inOrderTraversal(parent.left);
printVal(parent);
inOrderTraversal(parent.right);
}
void printVal(TreeNode parent)
{
System.out.print(parent.data + "\t");
}
/* binary tree find Minimum */
int findMin(TreeNode parent)
{
if(parent == null) return 0;
int min = parent.data;
if(parent.left !=null)
{
min = Math.min(min, findMin(parent.left));
}
if(parent.right != null)
{
min = Math.min(min, findMin(parent.right));
}
return min;
}
/* binary tree find Maximum */
int findMax(TreeNode parent)
{
if(parent == null) return 0;
int max = parent.data;
if(parent.left !=null)
{
max = Math.max(max, findMax(parent.left));
}
if(parent.right != null)
{
max = Math.max(max, findMax(parent.right));
}
return max;
}
}
</code></pre>
<p><strong>Traversal.java</strong></p>
<pre><code>package binarytree;
import binarytree.TreeNode;
public class Traversals {
public static void main(String[] args)
{
TreeNode parent = new TreeNode(1);
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
TreeNode next = new TreeNode(5);
parent.insertInOrder(left.data);
parent.insertInOrder(right.data);
parent.insertInOrder(next.data);
System.out.println("Pre-order traversal");
parent.preOrderTraversal(parent);
System.out.println();
System.out.println("Post-order traversal");
parent.postOrderTraversal(parent);
System.out.println();
System.out.println("In-order traversal");
parent.inOrderTraversal(parent);
System.out.println();
System.out.println("min element:"+parent.findMin(parent));
System.out.println("max element:"+parent.findMax(parent));
}
}
</code></pre>
| [] | [
{
"body": "<p>Here are a few things you can do to improve this:</p>\n\n<ul>\n<li>You don't specify visibility of your methods or variables. Presumably you want your variables to be <code>private</code>, but I'm not sure which of your methods you want <code>public</code> or not. I imagine you don't want <code>setLeftChild</code> or <code>setRightChild</code> to be public since you can't enforce your ordering constraints if anyone can just change children when they feel like it.</li>\n<li>Both <code>setLeftChild</code> and <code>setRightChild</code> will throw <code>NullPointerException</code>s when passed a null value. You want <code>!=</code> instead of <code>==</code> in your check.</li>\n<li>Do your nodes need references to their parents?</li>\n<li>In your <code>Traversals</code> class you have nodes named <code>parent</code>, but you are actually referring to the root node of your tree. I would rename that.</li>\n<li>You don't need to create the other three <code>TreeNode</code> classes since you only use them to get the value that you passed into them when you call <code>insertInOrder</code>. Just call <code>insertInOrder</code> with the values you want.</li>\n<li>You shouldn't pass in the <code>parent</code> parameter to your traversal methods. These are instance methods and can just refer to the member variables directly.</li>\n<li>Initialize <code>size</code> once. Currently you set it to 0 and then 1.</li>\n<li>I'm assuming you have plans to use <code>size</code> later on. Otherwise you can just remove it entirely.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:17:17.110",
"Id": "85549",
"Score": "0",
"body": "You don't need to create the other three TreeNode... how would I do it otherwise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:21:04.527",
"Id": "85550",
"Score": "1",
"body": "`parent.insertInOrder(2)`, `parent.insertInOrder(3)`, `parent.insertInOrder(5)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T22:57:28.727",
"Id": "48721",
"ParentId": "48719",
"Score": "6"
}
},
{
"body": "<p>Rethink <code>findMax</code>. The way you constructed the tree, a maximal value is never in the left subtree. Similarly, if there is a right subtree, the maximal value is always there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:23:31.220",
"Id": "85551",
"Score": "0",
"body": "true but can u give a example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:24:00.067",
"Id": "85552",
"Score": "0",
"body": "can u suggest a better way to call parent.findMin(parent)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:54:20.943",
"Id": "85554",
"Score": "0",
"body": "`findMax`: follow right branch as long as possible. Return the leaf value. `findMin`: same, but follow left branch. Neither needs to be recursive."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:14:48.763",
"Id": "48724",
"ParentId": "48719",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T22:28:16.927",
"Id": "48719",
"Score": "4",
"Tags": [
"java",
"algorithm",
"tree",
"binary-search"
],
"Title": "BinarySearch Tree implementation & traversals"
} | 48719 |
<p>I wrote this code, based on the Newton-Raphson method, to find the square root of a number. I'm wondering how I can optimise this code, as I am out of ideas.</p>
<pre><code>#include <stdio.h>
int main(void)
{
float n, x, i;
printf("Enter the number you wish to find the square root of.\n");
printf("\n");
scanf("%f", &n);
x = n/2;
for (i = 0; i < 100; i++)
x = x - (((x*x) - n)/(2*x));
printf("The square root of %.0f is %.4f.\n", n, x);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:23:37.000",
"Id": "85641",
"Score": "0",
"body": "Better to use `%e` for output. Else small values will all have a square root of `0.0000` and large number will print with superfluous digits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:07:57.127",
"Id": "85668",
"Score": "1",
"body": "Or just include `math.h` and use `sqrt`... What do you say?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:32:39.593",
"Id": "85753",
"Score": "0",
"body": "The thing is, I'm required to write a function that finds an **approximation** to the square root of a number, without using the sqrt function."
}
] | [
{
"body": "<ul>\n<li><p>Do not rely on a fixed number of iterations. Stop when reaching a desired discrepancy (e.g. <code>fabs(x*x - n) < epsilon</code>)</p></li>\n<li><p>I do not see any reason for not simplifying the calculations into <code>x = (x + n/x)/2.0</code>.</p></li>\n<li><p>Assure that the input is positive. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T00:09:01.170",
"Id": "85556",
"Score": "0",
"body": "Thanks for this! Just one question, what's the value of epsilon or how do I choose it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T00:54:06.710",
"Id": "85559",
"Score": "0",
"body": "@user3182162: With floating-point numbers, it's based on the size of the number. Assuming n is positive, a useful epsilon would be somewhere around `pow(2.0, floor(log2(n)) - 23)`. (Of course, that might not help much if you're trying to find the square root iteratively -- the square root itself is `pow(n, 0.5)`, so the iteration almost wouldn't be worth the trouble. :P)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:08:42.363",
"Id": "85636",
"Score": "1",
"body": "Floating point numbers have a logarithmic distribution. Stopping on a delta value like `epsilon` is a poor approach. Consider `epsilon = 1e-6` and performing `square_root(1e20)` or `square_root(1e-20)`. Better to use a _relative__epsilon_ `e.g. fabs(x*x - n) < (epsilon*n)`. Even better, given the convergence rate of this algorithm, I believe it converges in about `ln2(significand_bits_in_float)` (e.g. 5 or 6) iterations."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T00:05:03.917",
"Id": "48726",
"ParentId": "48725",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>Additional newlines can just be in the first output statement. You should also use <code>puts()</code> instead since this is unformatted output. It also adds an additional newline.</p>\n\n<pre><code>puts(\"Enter the number you wish to find the square root of.\\n\");\n</code></pre></li>\n<li><p>I'd recommend renaming <code>n</code> and <code>x</code> to something like <code>input</code> and <code>result</code> respectively.</p>\n\n<p>Avoid using single-character variables unless they're for loop counters.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:54:45.063",
"Id": "85608",
"Score": "0",
"body": "First point: the compiler will look after that automatically."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T00:17:47.120",
"Id": "48727",
"ParentId": "48725",
"Score": "5"
}
},
{
"body": "<p>Some recommendations and changes in code,</p>\n\n<ul>\n<li>better variable names</li>\n<li>Prompting user if he wants to continue or stop the program preventing infinite loop</li>\n<li>Formula reduced to simple easy to understand format</li>\n</ul>\n\n<p></p>\n\n<pre><code>#include<stdio.h>\n\nint main(void)\n{\n float input_num, output; //better variable names\n int continue_input=1;\n\n while(continue_input == 1) //user input continuous\n {\n puts(\"Enter the number you wish to find the square root of.\\n\");\n scanf(\"%f\", &input_num);\n\n output = input_num/2;\n\n output *= (2 - input_num)/2;\n\n printf(\"The square root of %.0f is %.4f.\\n\", input_num, output);\n\n puts(\"Enter 0 to stop & 1 to continue: \");\n scanf(\"%d\",&continue_input);\n }\n return 0;\n}\n</code></pre>\n\n<p>Why do you need 100 iterations? They seem really unnecessary as you are taking user input and <code>i</code> is not used anywhere, but again you need to check that out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:25:55.877",
"Id": "85563",
"Score": "1",
"body": "You can use `output *= ...` instead of `output = output * ...`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:34:11.510",
"Id": "85564",
"Score": "3",
"body": "This also appears to be an infinite loop (specifically `while (1)`). `val` is never changed within the loop. You could ask the user if they'd like to continue, and `break` if it's a no. If you go with that, then you can just have `while (1)` and remove `val` (which isn't a very good name anyway)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:46:46.847",
"Id": "85567",
"Score": "0",
"body": "@Jamal check the changes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:52:10.200",
"Id": "85568",
"Score": "0",
"body": "Looks better. You can also declare `i` right before the `for` loop to keep it in close scope (assuming the OP is not using C99)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:10:29.780",
"Id": "85569",
"Score": "0",
"body": "The second line of calculations with `output` still doesn't work, based on my tests on Ideone.com. The OP's does work, but I know you're trying to simplify it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:18:25.197",
"Id": "48730",
"ParentId": "48725",
"Score": "0"
}
},
{
"body": "<p>As you probably know, once it iss close, Newton-Raphson converges really quickly.</p>\n\n<p>Therefore, if you start from a reasonable approximation, you need a limited number of iterations.</p>\n\n<p>If you represent <code>n</code> as as power of <code>2</code> times a fraction <code>1.?????</code>, then the square root will be given by half that power of <code>2</code> times a fraction.</p>\n\n<p>So, if you can find that power, you have a good start.</p>\n\n<p>Now, that is exactly how a floating point number is represented internally.\nSee <a href=\"http://en.wikipedia.org/wiki/Double-precision_floating-point_format\" rel=\"nofollow\">Wikipedia</a> for the IEEE 754 double-precision binary floating-point format.</p>\n\n<p>We can therefore write:</p>\n\n<pre><code>#include <stdint.h>\n\nconst int signPosition = 63;\nconst int fractionBits = 52;\n\nconst uint64_t signMask = 1ull << signPosition;\nconst uint64_t fractionMask = (1ull << fractionBits) - 1;\nconst uint64_t exponentMask = (signMask - 1) - fractionMask;\nconst int exponentBias = 1023;\n\nint getExponent(double x)\n{\n uint64_t representation = *(uint64_t*)&x;\n uint64_t exponentBiased = (representation & exponentMask) >> fractionBits;\n return (int)(exponentBiased)-exponentBias;\n}\n\ndouble firstGuessOfSquareRoot(double x)\n{\n unsigned exponent = getExponent(x);\n unsigned rootExponent = exponent / 2;\n double guess = 1 << rootExponent;\n return guess;\n}\n\ndouble root(double x)\n{\n double guess = firstGuessOfSquareRoot(x);\n int loops = 6;\n while (loops > 0)\n {\n guess += (x - guess * guess) / 2 / guess;\n --loops;\n }\n return guess;\n}\n</code></pre>\n\n<p>I'd suggest <code>6</code> loops is not too bad.</p>\n\n<p>Now, you can do even better, getting down to <code>4</code> or maybe <code>3</code> loops if you start with a better guess. That can be done by:</p>\n\n<ul>\n<li>Looking at the fractional part of the <code>double</code> and using a look-up table.</li>\n<li>Handling the case where the original exponent is odd correctly - the above gives an initial <code>guess</code> out by at least <code>sqrt(2)</code> for the case.</li>\n</ul>\n\n<p>Oh - some might ask: Why use a fixed number of iterations? The reason is that you can show that no more than this number is required and also that this number is typically required. Adding an error margin based check will slow down the main case whilst certainly being faster for special cases. I'm not sure as to the tradeoff.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:17:42.193",
"Id": "85640",
"Score": "0",
"body": "+1 for good convergence discussion and better for fix loop count (integer math) rather than FP termination calculation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:38:26.757",
"Id": "85675",
"Score": "1",
"body": "+1 for convergence discussion. For production code, I'd prefer defining getExponent() using the [standard C library frexp() function](http://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Standard_C_Library/Functions/frexp) rather than re-writing yet another redundant implementation of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:41:30.783",
"Id": "85924",
"Score": "0",
"body": "@DavidCary. Didn't know about `frexp()` - agree one should use if possible. But then, we are intentionally reinventing wheels here, so I'll leave the code as is."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T05:31:27.800",
"Id": "48740",
"ParentId": "48725",
"Score": "4"
}
},
{
"body": "<p>The square root procedure could easily be extracted into its own function, and therefore should be.</p>\n\n<p><code>i</code> is a counter, and therefore should be an <code>int</code>, not a <code>float</code>. As @fscore points out, 100 iterations is overkill. Assuming that each iteration gains you an extra bit of precision — in other words, halves the error — there aren't 100 bits in a <code>float</code>! And if you really cared about precision, you should be using <code>double</code>s everywhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:15:10.617",
"Id": "85639",
"Score": "0",
"body": "+1 for `i`. This method doubles the number of corrects bit per iteration. So with `float` about 24 bits, `ln2(24)` --> 5. So about 5 iterations needed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T05:34:38.190",
"Id": "48742",
"ParentId": "48725",
"Score": "5"
}
},
{
"body": "<p>There are a couple of possible ways to optimize the code. @Keith has already done what I'd consider quite a good job of covering the micro-optimizations within this algorithm by improving your initial guess and your loop exit criteria.</p>\n\n<p>The other obvious possibility would be to use a different algorithm. For one example, the binary reducing algorithm can compute square roots to the nearest integer quite a bit faster than the code you posted, and still somewhat faster than the code @keith posted.</p>\n\n<pre><code>int isqrt(int input) {\n int result = 0;\n int bit = 1 << (sizeof(int)*CHAR_BIT-2);\n\n while (input <= bit)\n bit /= 4;\n\n do { \n if (input >= result + bit) {\n input -= result + bit;\n result = result / 2 + bit;\n }\n else\n result /= 2;\n bit /= 4;\n } while (bit != 0);\n\n return result;\n}\n</code></pre>\n\n<p>The primary advantage of the binary reducing method is that the divisions it uses are both by fixed powers of two (specifically, divisions by 2 and 4). On a binary computer with a halfway decent compiler, you can pretty well count on these being implemented as bit shifts.</p>\n\n<p>Translation to floating point isn't quite so straightforward though. In a Newton-Raphson implementation, a better initial guess improves speed, but (at least for square root) basically can't ever result in incorrect results. By contrast, the:</p>\n\n<pre><code>int bit = 1 << (sizeof(int)*CHAR_BIT-2);\n\nwhile (input <= bit)\n bit /= 4;\n</code></pre>\n\n<p>...part of this algorithm <em>must</em> be correct to produce correct results at all. Specifically, it needs to be the largest power of 4 that's less than or equal to the input. \nYou obviously <em>can</em> compute that value in floating point, but doing so is somewhat non-trivial compared to doing it for an integer.</p>\n\n<p>Newton-Raphson will usually require fewer iterations, but each iteration is slower because its divisions are by numbers generated from the input, so they need to be executed as real division operations. For integers this gains speed because although it needs more iterations, each iteration is quite fast. In floating point, you end up using a real divide instruction for each of those division operations, losing most of the potential speed gain. If you're willing to do like @Keith did and directly manipulate the bits of the floating point representation, you might be able to gain this back, because the divisions can actually be simple subtractions from the exponent part of the floating point number.</p>\n\n<p>Bottom line: this produces good results fairly quickly for integers. Conversion to floating point is possible, but somewhat non-trivial. Doing so in a way that retains much (if any) speed advantage starts to move into the decidedly non-trivial range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T17:18:31.343",
"Id": "85907",
"Score": "0",
"body": "Whoa! Thanks dude, quite a detailed description, and easy to follow concepts. The kind of answers that really help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T05:18:48.767",
"Id": "48904",
"ParentId": "48725",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T23:41:15.973",
"Id": "48725",
"Score": "11",
"Tags": [
"optimization",
"c",
"floating-point",
"numerical-methods"
],
"Title": "Approximating the square root using an iterative method"
} | 48725 |
<p>I assume you've all played Pacman, I mean, most people have.</p>
<p>I am a 10th grader, and I am working on building Pacman for my intro to Java class in school. </p>
<p>However, the project I'm working on demands that someone review my code. </p>
<p>About the code: I have not started the graphics yet. I have just done a little work using a two-dimenstional array to store the state of the Pacman, and at the bottom there is a method which randomizes the motion of the Pacman.</p>
<p>The large array in the beginning represents a 5 x 5 grid with vertices in which the Pacman can move through. If you copy the code into a compiler, you can see what I mean. When Pacman is at a vertex , he will make a decision and can thus move to another one. If the value is negative, then there is a vertical distance in which the Pacman can move through, but if the value is positive, then this distance is horizontal.</p>
<p>Please give me any suggestions you have on what my next steps should be and how I should clean up the code. The more specific, the better. But basically, anything you say will be fine.</p>
<pre><code>public class PacmanRoughDraft {
public static void main(String[] args) {
PacmanRoughDraft pacMan = new PacmanRoughDraft();
pacMan.run();
}
//To is on the y-axis, from is on the x-axis.
int[][] graph = {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
{ 0, 4, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 0 */
{ 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 1 */
{ 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 2 */
{ 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 3 */
{ 0, 0, 0, 4, 0, 0, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 4 */
{-4, 0, 0, 0, 0, 0, 4, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 5 */
{ 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 6 */
{ 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 7 */
{ 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 8 */
{ 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 0, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 9 */
{ 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 4, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 10 */
{ 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0, 0 }, /* 11 */
{ 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0, 0 }, /* 12 */
{ 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0, 0, 0, 0 }, /* 13 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 0, 0, 0, 0,-4, 0, 0, 0, 0, 0 }, /* 14 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 4, 0, 0, 0, -4, 0, 0, 0, 0 }, /* 15 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0, 0 }, /* 16 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0, 0 }, /* 17 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0, 0,-4, 0 }, /* 18 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 0, 0, 0, 0,-4 }, /* 19 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 4, 0, 0, 0 }, /* 20 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0, 0 }, /* 21 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4, 0 }, /* 22 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0, 4 }, /* 23 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-4, 0, 0, 0, 4, 0 } /* 24 */
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
};
int[] pacManState = new int[3]; // [0] = from
// [1] = to
// [2] = steps
static final int FROM = 0;
static final int TO = 1;
static final int STEPS = 2;
public PacmanRoughDraft() {
pacManState[FROM] = 12;
pacManState[TO] = 13;
pacManState[STEPS] = 0;
}
public void displayGraph() { //this method will just print out the vertices of the graph if I don't call RenderGraph, but this method so far isn't called, because renderGraph is used instead.
for (int i=0; i<25; ++i) {
for (int j=0; j<25; ++j) {
if (graph[i][j] > 0) System.out.print("+");
else if (graph[i][j] == 0) System.out.print(" ");
System.out.print( ""+graph[i][j] );
if (j < 24) System.out.print(" ");
}
System.out.println();
}
}
public void renderGraph() {
// this is really the output image object
char[][] renderPlane = new char[17][33]; //17 tall by 33 wide
// clear image
for (int i=0; i<17; ++i) {
for (int j=0; j<33; ++j) {
renderPlane[i][j] = ' ';
}
}
// draw the bare graph
// - this should be a separate utility method
int[] rows = new int[]{ 0, 4, 8, 12, 16 };
int[] cols = new int[]{ 0, 8, 16, 24, 32 };
for (int i : rows) {
for (int j=0; j<33; ++j) renderPlane[i][j] = '-';
}
/*
0 8 16 24 32
0 ---------------------------------
4 ---------------------------------
8 ---------------------------------
12 ---------------------------------
16 ---------------------------------
*/
for (int j : cols) {
for (int i=0; i<17; ++i) renderPlane[i][j] = '|';
}
/*
0 8 16 24 32
0 |-------|-------|-------|-------|
| | | | |
| | | | |
| | | | |
4 |-------|-------|-------|-------|
| | | | |
| | | | |
| | | | |
8 |-------|-------|-------|-------|
| | | | |
| | | | |
| | | | |
12 |-------|-------|-------|-------|
| | | | |
| | | | |
| | | | |
16 |-------|-------|-------|-------|
*/
for (int i : rows) {
for (int j : cols) renderPlane[i][j] = '+';
}
/*
0 8 16 24 32
0 +-------+-------+-------+-------+
| | | | |
| | | | |
| | | | |
4 +-------+-------+-------+-------+
| | | | |
| | | | |
| | | | |
8 +-------+-------+-------+-------+
| | | | |
| | | | |
| | | | |
12 +-------+-------+-------+-------+
| | | | |
| | | | |
| | | | |
16 +-------+-------+-------+-------+
*/
// draw PacMan (and ghosts, and energy blobs)
int from = pacManState[FROM]; //12
int to = pacManState[TO]; //13
int steps = pacManState[STEPS]; //0
// translate from abstract graph position to physical render plane position
/*
0 1 2 3 4
0 8 16 24 32
0 0 0-------1-------2-------3-------4
| | | | |
| | | | |
| | | | |
1 4 5-------6-------7-------8-------9
| | | | |
| | | | |
| | | | |
2 8 10------11------12------13------14
| | | | |
| | | | |
| | | | |
3 12 15------16------17------18------19
| | | | |
| | | | |
| | | | |
4 16 20------21------22------23------24
*/
//changes the vertice's number to a position which can be recognized by the renderGraph() method.
int fromRow = (from / 5); //= 2
int fromCol = (from % 5); // = 2
int toRow = ( to / 5); // = 2
int toCol = ( to % 5); // = 3
/* Example:
from(12)-->to(13),
fromRow = 2, fromCol = 2
toRow = 2, toCol = 3
from(16)-->to(11),
fromRow = 3, fromCol = 1
toRow = 2, toCol = 1
*/
if (fromRow == toRow) {
if (fromCol < toCol) { // move right
renderPlane[4*fromRow][8*fromCol + steps] = 'Q';
}
else if (fromCol > toCol) { // move left
renderPlane[4*fromRow][8*fromCol - steps] = 'Q';
}
else { // no move
renderPlane[4*fromRow][8*fromCol] = 'Q';
}
}
else if (fromCol == toCol) {
if (fromRow < toRow) { // move down
renderPlane[4*fromRow + steps][8*fromCol] = 'Q';
}
else if (fromRow > toRow) { // move up
renderPlane[4*fromRow - steps][8*fromCol] = 'Q';
}
else { // no move
}
}
else {
System.out.println( "Illegal move." );
return;
}
// paint image on screen (this is really image.repaint() )
for (int i=0; i<17; ++i) {
for (int j=0; j<33; ++j) {
System.out.print( renderPlane[i][j] );
}
System.out.println();
}
System.out.println();
}
public void run() {
int n = 0;
while (n++ < 1000) {
int from = pacManState[FROM];
int to = pacManState[TO];
int steps = pacManState[STEPS];
System.out.println("(from,to,steps) = ("+from+","+to+","+steps+")");
System.out.println();
renderGraph();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
// update PacMan state with random motion
int edgeLen = Math.abs(graph[from][to]); //gets you the length of the edge between the two vertices of where Pacman is and wants to go.
if (steps < edgeLen) {
++pacManState[STEPS]; //if Pacman hasn't gotten to the other side, his steps go up by one.
}
else if (steps == edgeLen) {
int randomizer = 0;
for (int j=0; j<25; j=j+1) {
if (!(0 == graph[to][j])) {
randomizer=randomizer+1;
}
}
int choice = (int)(randomizer * Math.random());//sets any vertex in the same row or column to the from vertex.
for (int j=0; j<25; j=j+1) {
if (!(0 == graph[to][j])) {
if (0 == (choice)) {
from = to;
to = j;
steps = 0;
}
choice=choice-1;
}
}
pacManState[FROM] = from;
pacManState[TO] = to;
pacManState[STEPS] = steps;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:36:54.507",
"Id": "85613",
"Score": "1",
"body": "Just a small thing: when you need to documemt a method/field/class/etc. Use Javadoc comments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:27:21.807",
"Id": "85711",
"Score": "0",
"body": "I suggest that you do some reading on OO Game Design. Think about what the nouns are, and what are the verbs associated with those nouns. There are many examples out there to learn from. Chess is a popular choice for a problem like this, so you may want to look at some chess examples (like [this one](http://swcodes.blogspot.com/2012/09/chess-game-design.html)) for ideas. And hey look, there are even some [other examples](http://gamedevelopment.tutsplus.com/tutorials/quick-tip-intro-to-object-oriented-programming-for-game-development--gamedev-1805) for arcade games including PacMan."
}
] | [
{
"body": "<p>This is a great code review opportunity because your program 1) works, and 2) has tons of room for improvement. Almost every line of your code could be refactored, but don't take that negatively. Every day I come out of code reviews with changes suggested to my awesome code. It's just how the business works and we should always enjoy the opportunity to learn and write even better code in the future.</p>\n\n<p>With that said, in your main method, you can accomplish the same with the following:</p>\n\n<pre><code>public static void main(String[] args) {\n new PacmanRoughDraft().run();\n}\n</code></pre>\n\n<p>You define the graph in your code, which is okay for early development and quick debugging, but you should really load it from a file. <a href=\"https://www.google.ca/search?q=java%20read%20lines%20from%20text%20file&oq=java%20read%20lines%20from%20&aqs=chrome.2.69i57j0l5.5343j0j8&sourceid=chrome&es_sm=93&ie=UTF-8\">Google will lead you to some Stack Overflow answers on how to do this</a>, and I highly reccommend it. It's quite easy, and it's never to early to have some experience with file IO.</p>\n\n<p>But was does <code>-4</code> in your graph mean? As you'll see, it's a bad idea to use these <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\">Magic Numbers</a>.</p>\n\n<pre><code>int[] pacManState = new int[3]; // [0] = from\n// [1] = to\n// [2] = steps\nstatic final int FROM = 0;\nstatic final int TO = 1;\nstatic final int STEPS = 2;\n</code></pre>\n\n<p>I'm curious why you are using an array to hold the state here. This could simply be:</p>\n\n<pre><code>private int from;\nprivate int to;\nprivate int steps;\n</code></pre>\n\n<p>That way you don't have to worry about the problems that can come along with arrays. Notice also that I declared them <code>private</code>. Without a modifier, they have <code>default</code> access, which means any other class in the same package as it can modify it's values. Rarely a good idea.</p>\n\n<pre><code>public PacmanRoughDraft() {\n pacManState[FROM] = 12;\n pacManState[TO] = 13;\n pacManState[STEPS] = 0;\n}\n</code></pre>\n\n<p><code>12</code> and <code>13</code> here are magic numbers. You should replace them with constants declared near the top of the class so you can easily modify. And with the previous suggestion, this could be rewritten as</p>\n\n<pre><code>// near the top of the class\nprivate static final int INITIAL_FROM = 12;\nprivate static final int INITIAL_TO = 13;\nprivate static final int INITIAL_STEPS = 0;\n\n// later...\npublic PacmanRoughDraft() {\n from = INITIAL_FROM;\n to = INITIAL_TO;\n steps = INITIAL_STEPS;\n}\n</code></pre>\n\n<p>I'll keep bringing up magic numbers because they are evil. Or, if not evil, unnecessary, as the following code shows:</p>\n\n<pre><code>public void displayGraph() { \n for (int i=0; i<25; ++i) { // what is 25? the graph width? \n for (int j=0; j<25; ++j) { // or is it the height?\n if (graph[i][j] > 0) System.out.print(\"+\"); // wait, now I know what -4 means... I think\n else if (graph[i][j] == 0) System.out.print(\" \");\n System.out.print( \"\"+graph[i][j] );\n if (j < 24) System.out.print(\" \");\n }\n System.out.println();\n }\n}\n</code></pre>\n\n<p>This can be rewritten like so:</p>\n\n<pre><code>public void displayGraph() { \n for (int i = 0; i < graph.length; ++i) {\n for (int j = 0; j < graph[i].length; ++j) {\n if (graph[i][j] > 0) {\n System.out.print(\"+\");\n }\n else if (graph[i][j] == 0) {\n System.out.print(\" \");\n }\n\n System.out.print(graph[i][j]);\n\n if (j < graph[i].length - 1) {\n System.out.print(\" \");\n }\n }\n System.out.println();\n }\n}\n</code></pre>\n\n<p>There's a lot going on here that I'll point one:</p>\n\n<ul>\n<li><p>Whitespace between things. <code>for (int i=0; i<25; ++i) {</code> is needlessly hard on the eyes.</p></li>\n<li><p>Getting <code>length</code> of the array means you can change the size of your grid without having to change everything. Seriously, anywhere you have <code>25</code> in your code should be replaced with <code>grid.length</code> or <code>grid[i].length</code>.</p></li>\n<li><p>Avoid (read, <em>never</em>) use an <code>if</code>-statement without curly brackets. It'll only cause bugs when you come back and change things. For example, what if I intended for <code>System.out.print( \"\"+graph[i][j] );</code> to only be called when <code>graph[i][j] == 0</code>.</p></li>\n<li><p>Speaking of, the traditional way to output an array is to use <code>Arrays.toString(graph[i][j])</code>, not <code>\"\"+graph[i][j]</code>.</p></li>\n<li><p>This got me thinking, why is <code>graph</code> an <code>int</code> array anyways? Can you not make it a <code>char</code> array and just print that out, instead of doing all these calculations?</p></li>\n</ul>\n\n<p><strong>renderGraph()</strong></p>\n\n<p>I got confused here. What is <code>renderPlane</code> and how is it different from <code>graph</code>? That being said, you can do some neat improvements to this method.</p>\n\n<pre><code>char[][] renderPlane = new char[17][33];\n</code></pre>\n\n<p>Again, magic numbers. Replace with constants so you can change easily. And is there any relationship from the size of this array to the <code>graph</code> array? </p>\n\n<pre><code> int[] rows = new int[]{ 0, 4, 8, 12, 16 };\n int[] cols = new int[]{ 0, 8, 16, 24, 32 };\n\n for (int i : rows) {\n for (int j=0; j<33; ++j) renderPlane[i][j] = '-';\n }\n</code></pre>\n\n<p>I see what you're doing here, and it works but is not extensible. What if you want to change the size of you renderPlane? You can do away with both <code>rows</code> and <code>cols</code>, and add constants for <code>ROW_SIZE</code> and <code>COL_SIZE</code>. That way you can replace the above code with</p>\n\n<pre><code>private static final int ROW_SIZE = 4;\nprivate static final int COL_SIZE = 4;\n\n// later...\nfor (int i = 0; i < renderPlane.length; i += ROW_SIZE) {\n for (int j = 0; j < renderPlane[i].length; ++j) { \n // Same thing about curly braces applies to for and while statements!\n renderPlane[i][j] = '-';\n }\n}\n</code></pre>\n\n<p>You can apply similar logic to the rest of the method.</p>\n\n<p>I won't go onto the <code>run</code> method, as you can refactor that yourself using some of the comments above. Overall, this is good code. I'm looking forward to when you post your Swing version!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T05:38:37.003",
"Id": "85575",
"Score": "1",
"body": "Thank you so much for this excellent, thorough review! Its getting late where I live, but i'll start working on the changes tomorrow or as soon as I can! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:27:27.693",
"Id": "85578",
"Score": "0",
"body": "@user2279952 About the `\"\"+graph[i][j]` - while it's not necessary here, just in general you should prefer `graph[i][j].toString()`. It should have an identical result, but is more clear about your intention and may even be faster depending on how your compiler optimises."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T12:26:55.233",
"Id": "85629",
"Score": "0",
"body": "Good point @Bob. I was incorrect originally and have updated that section."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T12:41:39.430",
"Id": "85633",
"Score": "4",
"body": "Welcome to Code Review! We're happy to have you here. This is an awesome review. I hope you will stick around. Feel free to drop by [our chatroom](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) if you want to say Hi! (Dropping by our chatroom has been proven to have a positive effect on your reputation)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:29:43.923",
"Id": "48736",
"ParentId": "48728",
"Score": "26"
}
},
{
"body": "<p>This was a fun project to review. In the end, I decided that there were enough problems with the design to justify starting afresh.</p>\n\n<p>The main problems I saw were…</p>\n\n<h3>Drawing the grid</h3>\n\n<p>The <code>renderGraph()</code> method would be better named <code>renderGrid()</code>.</p>\n\n<p>The design is rigid. You have magic numbers everywhere within <code>renderGraph()</code>: 17, 33, 0, 4, 8, 12, 16, 0, 8, 16, 24, 32, 4, 8, 17, 33. If you ever want to extend the grid or expand the spacing, you would have to make changes in many places.</p>\n\n<p>Your graphical comments helped tremendously. Thank you for writing them.</p>\n\n<p>Considering the rigidity of the design and the amount of code to achieve the effect, you would have been better off just hard-coding the entire result directly:</p>\n\n<pre><code>private static final String[] GRID = new String[] {\n \"+-------+-------+-------+-------+\",\n \"| | | | |\",\n \"| | | | |\",\n \"| | | | |\",\n \"+-------+-------+-------+-------+\",\n \"| | | | |\",\n \"| | | | |\",\n \"| | | | |\",\n \"+-------+-------+-------+-------+\",\n \"| | | | |\",\n \"| | | | |\",\n \"| | | | |\",\n \"+-------+-------+-------+-------+\",\n \"| | | | |\",\n \"| | | | |\",\n \"| | | | |\",\n \"+-------+-------+-------+-------+\"\n};\n</code></pre>\n\n<p>Calling <code>System.out.print()</code> to print a character at a time is inefficient. That results in a <code>write()</code> kernel call each time. Compose the string you want to print, and print it all at once.</p>\n\n<h3>The node adjacency table</h3>\n\n<p>I had a fun time puzzling out the <code>int[][] graph</code> enigma. You've numbered the intersection nodes from 0 to 24, in row-major order. The <code>graph</code> matrix indicates the number and direction of the steps to move between a pair of nodes, or 0 if two nodes are not adjacent.</p>\n\n<p>It was probably a lot of work for you to construct the matrix. It would be a lot of work again if you ever needed to expand the grid.</p>\n\n<p>Furthermore, it's a sparse matrix. When you use it to pick the next destination node, you have at best a \\$\\frac{4}{25}\\$ chance of picking a valid adjacent node on each attempt (\\$\\frac{3}{25}\\$ if on an edge, and only \\$\\frac{2}{25}\\$ if at a corner). You would easily expend a dozen random numbers just to get out of a corner.</p>\n\n<h3>Miscellaneous observations</h3>\n\n<ul>\n<li><p><code>displayGraph()</code> and <code>run()</code> are both long functions. You could easily break out subroutines, such as the rendering of the <code>'Q'</code> and the selection of the next destination.</p></li>\n<li><p>In the end, you'll probably want more than one character on the screen. You've attempted to encapsulate the character's movement within a <code>pacManState</code> array, which is a good start, but you really ought to have a proper object. Making a separate class would also help to organize your code.</p></li>\n</ul>\n\n<h2>Recommendations</h2>\n\n<ul>\n<li>Draw the grid by tesselating small squares.</li>\n<li>Get rid of the node-numbering scheme.</li>\n<li>Create a <code>PacmanCharacter</code> class to represent the animated objects.</li>\n<li>Select a destination by picking one of the four cardinal directions, and checking that the destination is in bounds.</li>\n</ul>\n\n<h2>Suggested Implementation</h2>\n\n<p><strong>PacmanDraft</strong></p>\n\n<pre><code>public class PacmanDraft {\n public static final int ROWS = 4, COLS = 4;\n\n private static final String[] SQUARE = {\n \"+-------\",\n \"| \",\n \"| \",\n \"| \"\n };\n\n // SQUARE is 8 chars wide vs. 4 rows high, so ASPECT_RATIO = 2\n public static final int ASPECT_RATIO = 2;\n\n public static final int SQUARE_HEIGHT = SQUARE.length,\n SQUARE_WIDTH = SQUARE[0].length();\n\n public static final int STEPS = SQUARE_HEIGHT;\n\n private char[][] grid;\n\n private PacmanCharacter[] characters;\n\n public PacmanDraft() {\n this.characters = new PacmanCharacter[] {\n new PacmanCharacter('Q', ROWS / 2, COLS / 2)\n };\n }\n\n private static char[][] makeGrid() {\n // +1 so that there is a bottom edge\n char[][] grid = new char[ROWS * SQUARE_HEIGHT + 1][];\n for (int r = 0; r < grid.length; r++) {\n // +1 so that that there is a right edge\n grid[r] = new char[COLS * SQUARE_WIDTH + 1];\n for (int c = 0; c < grid[0].length; c++) {\n grid[r][c] = SQUARE[r % SQUARE_HEIGHT].charAt(c % SQUARE_WIDTH);\n }\n }\n return grid;\n }\n\n private void placeCharacters() {\n int[] coords = new int[2];\n for (PacmanCharacter c : this.characters) {\n c.getScreenCoords(coords);\n this.grid[coords[0]][coords[1]] = c.getSymbol();\n c.step();\n }\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder(this.grid.length * (this.grid[0].length + 1));\n for (char[] row : this.grid) {\n sb.append(row).append('\\n');\n }\n return sb.toString();\n }\n\n public void run(int steps) throws InterruptedException {\n for (int i = steps; i > 0; i--) {\n this.grid = makeGrid();\n this.placeCharacters();\n System.out.println(this);\n\n Thread.sleep(100);\n }\n }\n\n public static void main(String[] args) throws InterruptedException {\n new PacmanDraft().run(1000);\n }\n}\n</code></pre>\n\n<p><strong>PacmanCharacter</strong> </p>\n\n<pre><code>import java.util.Random;\n\npublic class PacmanCharacter {\n private final char symbol;\n\n private int srcRow, srcCol,\n dstRow, dstCol;\n private int steps;\n\n private Random random;\n\n public PacmanCharacter(char symbol, int initRow, int initCol) {\n this.symbol = symbol;\n this.srcRow = this.dstRow = initRow;\n this.srcCol = this.dstCol = initCol;\n this.steps = PacmanDraft.STEPS;\n this.random = new Random();\n }\n\n public char getSymbol() {\n return this.symbol;\n }\n\n public void getScreenCoords(int[] coords) {\n int row = coords[0] = PacmanDraft.SQUARE_HEIGHT * this.srcRow +\n (this.dstRow - this.srcRow) * this.steps;\n int col = coords[1] = PacmanDraft.SQUARE_WIDTH * this.srcCol +\n PacmanDraft.ASPECT_RATIO * (this.dstCol - this.srcCol) * this.steps;\n System.out.printf(\"(%d, %d) -> (%d, %d) step %d = [%d, %d]\\n\",\n this.srcRow, this.srcCol, this.dstRow, this.dstCol,\n this.steps,\n row, col);\n }\n\n public void step() {\n if (this.steps >= PacmanDraft.STEPS) {\n this.nextDestination();\n }\n this.steps++;\n }\n\n private void nextDestination() {\n this.steps = 0;\n this.srcRow = this.dstRow;\n this.srcCol = this.dstCol;\n do {\n switch (this.random.nextInt(4)) {\n case 0:\n this.dstRow = this.srcRow - 1;\n this.dstCol = this.srcCol;\n break;\n case 1:\n this.dstRow = this.srcRow;\n this.dstCol = this.srcCol + 1;\n break;\n case 2:\n this.dstRow = this.srcRow + 1;\n this.dstCol = this.srcCol;\n break;\n case 3:\n this.dstRow = this.srcRow;\n this.dstCol = this.srcCol - 1;\n break;\n }\n } while (this.dstRow < 0 || this.dstRow > PacmanDraft.ROWS ||\n this.dstCol < 0 || this.dstCol > PacmanDraft.COLS);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:38:44.953",
"Id": "85723",
"Score": "4",
"body": "Despite all those criticisms, I should note that this is excellent work for 10th grade — better than what I was capable of at that age."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T20:04:29.293",
"Id": "48815",
"ParentId": "48728",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48736",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T01:55:38.990",
"Id": "48728",
"Score": "30",
"Tags": [
"java",
"game"
],
"Title": "Pacman game implementation in Java"
} | 48728 |
<p>I want to use the output of the terminal command <code>ldd</code>:</p>
<pre><code>root@kali-vm:~/Desktop# ldd simple
linux-gate.so.1 => (0xb7722000)
libcurl-gnutls.so.4 => /usr/lib/i386-linux-gnu/libcurl-gnutls.so.4 (0xb769c000)
libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7539000)
libidn.so.11 => /usr/lib/i386-linux-gnu/libidn.so.11 (0xb7505000)
</code></pre>
<p>And use it to build a dictionary that uses the library name as key and the path to the library as value. I've come up with this little Python snippet:</p>
<pre><code> # Get List of Librairies in Dictionary
lddOut = subprocess.check_output(['ldd', fileName])
libraries = {}
for line in lddOut.splitlines():
arr = line.split(" => ")
library = arr[0].strip('\t')
try:
path = arr[1].split(' (0x')[0]
except:
pass
libraries[library] = path
</code></pre>
<p>It works fine for my needs but I'm at the point where I don't want my code to just work but want it optimized and well structured/programmed. How can I improve this snippet?</p>
<p>EDIT: Note that I do not want the address (ie 0xbxxxxxx) in my dictionary</p>
| [] | [
{
"body": "<p>This kind of parsing by pattern matching is much better done using a regular expression.</p>\n\n<pre><code>import re\n\nlibraries = {}\nfor line in ldd_out.splitlines():\n match = re.match(r'\\t(.*) => (.*) \\(0x', line)\n if match:\n libraries[match.group(1)] = match.group(2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:11:42.000",
"Id": "48735",
"ParentId": "48729",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48735",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:12:42.723",
"Id": "48729",
"Score": "5",
"Tags": [
"python",
"parsing",
"hash-map",
"child-process"
],
"Title": "Output of 'ldd' to dictionary"
} | 48729 |
<p>Consider this naive stack implementation in Elixir:</p>
<pre><code>defmodule Stack do
defstruct name: "", value: 0
def init() do
_s = []
end
def push(name, value, s) do
s_new = [%Stack{name: name, value: value}, s]
{:ok,s_new}
end
def pop(s) do
[h|tail] = s
{:ok, h, tail}
end
def depth(s) do
length(s)
end
end
#Use:
# s = Stack.init()
# {:ok, s} = Stack.push("a",1,s)
# {:ok, item, s} = Stack.pop(s)
# l = Stack.depth(s)
</code></pre>
<p>Am I using structs correctly? Any suggestions for more idiomatic code style?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:38:54.833",
"Id": "85580",
"Score": "1",
"body": "The usage is great. The only question/feedback is if you should rather define a struct named Stack.Item, since the struct is not representing the stack, but its items. Also, you could simply use a tuple (but I assume the point of the exercise is to structs, so... :D)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T11:52:28.857",
"Id": "85622",
"Score": "0",
"body": "Yep, you're right @JoséValim--were this something I were doing for \"real\" I would use a tuple. It'd be simpler. But as you guessed, I did this as a learning exercise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T12:08:20.617",
"Id": "85626",
"Score": "0",
"body": "Drat--and I just noticed that my stack depth is returning incorrectly. Ah well."
}
] | [
{
"body": "<p>Keep in mind there is no reason to call init. Any state is being maintained outside the module. Also you can use recursion to iterate over the list. I don't typically use accumulators but in this case it seemed to fit. I also rely heavily on pattern matching. The EVM was designed with pattern matching optimization in mind so there isn't any drawback. Plus, it cleans up the assignments. Here is a solution that I came up with:</p>\n\n<pre><code>defmodule Stack do\n defstruct name: \"\", value: 0\n\n def push(name, val, s\\\\[]) do\n { :ok, [%Stack{name: name, value: val}] ++ s }\n end\n\n def pop([h]), do: { :ok, h, [] }\n def pop([h|tail]), do: pop(tail, [h])\n\n def pop([h|[]], acc), do: { :ok, h, acc }\n def pop([h|tail], acc), do: pop(tail, acc ++ [h])\n\n def depth(s), do: length s\nend\n\n#{ :ok, s } = Stack.push \"a\", \"1\"\n#{:ok, [%Stack{name: \"a\", value: \"1\"}]}\n#{ :ok, s } = Stack.push \"b\", \"2\"\n#{:ok, [%Stack{name: \"b\", value: \"2\"}, %Stack{name: \"a\", value: \"1\"}]}\n#{ :ok, item, s } = Stack.pop s\n#{:ok, %Stack{name: \"a\", value: \"1\"}, [%Stack{name: \"b\", value: \"2\"}] } \n\n#l = Stack.depth s\n#1\n</code></pre>\n\n<p><code>push</code> should insert into the first position and <code>pop</code> should remove the last item. </p>\n\n<p>I hope this helps and if there is anything else just let me know.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:36:29.053",
"Id": "85579",
"Score": "3",
"body": "Actually, `init` is a good way to start the stack in case he wants to change its representation in the future. I would name it `new/0` though, to map nicely to HashDict and HashSet, etc. Also, I prefer his version of push because the stack is being passed as first argument (which follows Elixir conventions)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T11:57:39.063",
"Id": "85623",
"Score": "0",
"body": "A couple of things Johnny (1) Isn't it idiomatic to return a tuple with :ok as the first element in Elixir? (I'm referring to the four pop functions) (2) I'm not quite following the stuff about the accumulator?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T17:51:35.410",
"Id": "85688",
"Score": "2",
"body": "I would just return `:ok` if the operation can fail or have two results. For example, it doesn't look like push can ever fail, so I wouldn't return a tuple. pop can fail if the list is empty, however, since the response is already a tuple (with the element and new stack) I would simply make it return {element, stack} or :error in case the stack is empty (there is no need for :ok as first element here)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:10:53.240",
"Id": "85702",
"Score": "0",
"body": "Thanks @JoséValim--I guess I was misunderstanding the convention on Elixir code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:53:41.800",
"Id": "48739",
"ParentId": "48733",
"Score": "2"
}
},
{
"body": "<p>The mechanical usage of the struct seems correct, but I'm having some conceptual issues with the original code.</p>\n\n<p>First, the <code>Stack</code> structure models a single element instead of the entire structure. I find this weird, and it makes it impossible to implement custom protocols for the stack abstraction. Your module seems to partially abstract stack elements, and partially the entire stack structure.</p>\n\n<p>Second, what is the purpose of key/value? Stack should work on arbitrary elements. What is in those elements should be left to the client of the structure, and not hardcoded as a requirement of the<code>Stack</code> module.</p>\n\n<p>Then, function <code>push/3</code> accepts the abstraction as the last argument. This is contrary to the recommended conventions (subject as the first argument), and makes it impossible to use the abstraction with pipe operator <code>|></code>.</p>\n\n<p>Even if the last issue was fixed, pipes still won't work since <code>push</code> returns the result in format of <code>{:ok, ...}</code>. This is not needed, especially since there is no possible error outcome.</p>\n\n<p>Notice that this doesn't hold for <code>pop</code>, which must return two values: last element pushed, and the modified structure (a stack containing remaining elements).</p>\n\n<p>Disregarding the fact that stack really doesn't require an abstraction (Elixir list is already a stack), here's my take on it:</p>\n\n<pre><code>defmodule Stack do\n defstruct elements: []\n\n def new, do: %Stack{}\n\n def push(stack, element) do\n %Stack{stack | elements: [element | stack.elements]}\n end\n\n def pop(%Stack{elements: []}), do: raise(\"Stack is empty!\")\n def pop(%Stack{elements: [top | rest]}) do\n {top, %Stack{elements: rest}}\n end\n\n def depth(%Stack{elements: elements}), do: length(elements)\nend\n</code></pre>\n\n<p>This can then be used as:</p>\n\n<pre><code>iex(1)> Stack.new |> Stack.push(1) |> Stack.push(2) |> Stack.pop\n{2, %Stack{elements: [1]}}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:28:48.477",
"Id": "85658",
"Score": "0",
"body": "I agree that normally you wouldn't want a stack on a non-generic type. But since I was trying to learn how to use structs, I sort of pretended that wasn't a concern. As José pointed out, I'd probably use a tuple not a struct (among several other changes I'd make); I was trying to figure out how structs fit into my general understanding of Elixir. Getting a better understanding of idiomatic Elixir code was a secondary benefit too. Regardless, your code looks like a big improvement on mine; thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T11:55:49.673",
"Id": "86719",
"Score": "0",
"body": "For whatever it's worth I created my code _before_ I saw your MEAP book."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T15:18:01.560",
"Id": "86771",
"Score": "0",
"body": "No problem. Please don't understand my response as a criticism. I was just trying to describe what I feel would be a more proper functional idiom. This is also the role of chapter 4 in the book."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T15:26:55.727",
"Id": "86773",
"Score": "0",
"body": "No worries. The feedback you shared was exactly the sort of thing I was hoping to get. I mention that I created my code before I started reading your book because I wouldn't want you to get the impression that I totally ignored the advice you give in the book."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T22:45:18.367",
"Id": "86823",
"Score": "0",
"body": "It's perfectly fine. Every technical book covers a lot of material, so it's normal if you don't remember everything at once. I certainly can't recall all the details after I read the book. I should also add that my book is a personal look on things, and not a collection of rules set in stone. So if you feel you disagree with any technique I'm recommending, and have some reasons for it - feel free to do it your way. After all, for better or worse, programming is not an exact science."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:48:29.717",
"Id": "48777",
"ParentId": "48733",
"Score": "5"
}
},
{
"body": "<p>José - Looking at it again, I see what you are saying about the <code>init</code> function to initiate a clean stack. I was thinking of this as an autonomous example and the <code>init</code> function just seemed superfluous. I was just trying to get away from the sense of state but being more of a pseudo <code>gen_server</code> example, the function fits. The binding also seemed excessive but that may be just a personal preference :)</p>\n\n<p>Onorio - (1) It's idiomatic in Erlang to return a tuple and much of the Elixir standard lib does too. I believe it's to be compatible with Erlang expectations but José would be able to answer that better. There are a number of options in standard lib that add a <code>!</code> to return only the value. That being said, I should have made that function private. I see the advantages of passing a tuple especially for error handling but I tend to use it sparingly. That could totally be an error on my part. (2) On the 3rd & 4th pop functions I use the <code>acc</code> accumulator to rebuild the list. I try to avoid this in my recursive calls like:</p>\n\n<pre><code>defmodule MyMod do\n def map([], _), do: []\n def map([h|t], func) do\n [func.(h)] ++ map(t, func)\n end\nend\n\n# MyMod.map([1,2,3,5], fn(n) -> n + 1 end)\n#>[2,3,4,6]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:20:20.780",
"Id": "48786",
"ParentId": "48733",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48777",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T02:50:45.587",
"Id": "48733",
"Score": "5",
"Tags": [
"stack",
"elixir"
],
"Title": "How Does This Naive Stack Implementation Look?"
} | 48733 |
<p>I found a problem <a href="http://codeforces.com/contest/418/problem/A" rel="nofollow">here</a>. I am sharing the problem and my attempt at solution. I would like to find out if this is the best approach possible.</p>
<blockquote>
<p>One day, at the "Russian Code Cup" event it was decided to play
football as an out of competition event. All participants was divided
into n teams and played several matches, two teams could not play
against each other more than once.</p>
<p>The appointed Judge was the most experienced member - Pavel. But since
he was the wisest of all, he soon got bored of the game and fell
asleep. Waking up, he discovered that the tournament is over and the
teams want to know the results of all the matches.</p>
<p>Pavel didn't want anyone to discover about him sleeping and not
keeping an eye on the results, so he decided to recover the results of
all games. To do this, he asked all the teams and learned that the
real winner was friendship, that is, each team beat the other teams
exactly k times. Help Pavel come up with chronology of the tournir
that meets all the conditions, or otherwise report that there is no
such table.</p>
<p><strong>Input</strong></p>
<p>The first line contains two integers: \$n\$ and \$k\$ (\$1 ≤ n, k ≤ 1000\$).</p>
<p><strong>Output</strong></p>
<p>In the first line print an integer \$m\$ - number of the played
games. The following \$m\$ lines should contain the information about all
the matches, one match per line. The \$i\$-th line should contain two
integers \$ai\$ and \$bi\$ (\$1 ≤ ai\$, \$bi ≤ n\$; \$ai ≠ bi\$). The numbers \$ai\$ and \$bi\$
mean, that in the \$i\$-th match the team with number \$ai\$ won against the
team with number \$bi\$. You can assume, that the teams are numbered from
1 to \$n\$.</p>
<p>If a tournir that meets the conditions of the problem does not exist, then print -1.</p>
</blockquote>
<p>My solution:</p>
<pre><code><?php
//$n = $argv[1];
//$k = $argv[2];
$s = fopen("php://stdin", 'r');
$n = stream_get_contents($s);
$dum= explode(" ",trim($n));
$n=$dum[0];
$k=$dum[1];
if ($n * $k > ($n * ($n - 1)) / 2) {
echo "-1\n";exit;
}
$output = $n*$k."\n";
$winMap = array();
for ($i = 1; $i <= $n; $i++) {
$winMap[$i] = 0;
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $i + 1; $j <= $n; $j++) {
if ($winMap[$i] < $k) {
$output .= "$i $j\n";
$winMap[$i] += 1;
} else if ($winMap[$j] < $k) {
$winMap[$j] += 1;
$output .= "$j $i\n";
}
}
}
echo $output;
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T12:14:56.160",
"Id": "85627",
"Score": "1",
"body": "This looks to me like a nice [code golf](http://codegolf.stackexchange.com/) question."
}
] | [
{
"body": "<p><strong>Style</strong></p>\n\n<p>You are lacking consistency in the spacing in assignments.</p>\n\n<p><strong>Organisation</strong></p>\n\n<p>It might be worth extracting the algorithm in a function. It makes code easier to read and to test.</p>\n\n<pre><code><?php\nfunction guessChronology($n, $k)\n{\n if ($n * $k > ($n * ($n - 1)) / 2) {\n return \"-1\\n\";\n }\n $output = $n*$k.\"\\n\";\n $winMap = array();\n for ($i = 1; $i <= $n; $i++) {\n $winMap[$i] = 0;\n }\n for ($i = 1; $i <= $n; $i++) {\n for ($j = $i + 1; $j <= $n; $j++) {\n if ($winMap[$i] < $k) {\n $output .= \"$i $j\\n\";\n $winMap[$i] += 1;\n } else if ($winMap[$j] < $k) {\n $winMap[$j] += 1;\n $output .= \"$j $i\\n\";\n }\n }\n }\n return $output;\n}\n\n$s = fopen(\"php://stdin\", 'r');\n$n = stream_get_contents($s);\n$dum = explode(\" \",trim($n));\n$n = $dum[0];\n$k = $dum[1];\necho guessChronology($n, $k);\n?>\n</code></pre>\n\n<p><strong>Re-using functions</strong></p>\n\n<p>You can use <a href=\"http://php.net/manual/en/function.array-fill.php\" rel=\"nofollow\">array_fill</a> to write <code>$winMap = array_fill(1, $n, 0);</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T10:09:28.177",
"Id": "60694",
"ParentId": "48738",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:43:22.240",
"Id": "48738",
"Score": "3",
"Tags": [
"php",
"algorithm",
"programming-challenge"
],
"Title": "Programming Puzzle - N Teams K Wins each"
} | 48738 |
<p>I have a jQuery function which adds a tag to the first row of a table. I previously tried using append, however that didn't work. I now have the following solution which is very slow and it gives this warning:</p>
<blockquote>
<p>A script on this page is causing Internet Explorer to run slowly</p>
</blockquote>
<p>Function:</p>
<pre><code>jQuery.fn.fixGridView = function () {
"use strict";
// var start = +new Date(); // log start timestamp
if (jQuery(this).is('table') && this.find('thead').length === 0) {
var theadv = "<thead><tr>" + this.find('tbody tr:first').html(); +"</tr></thead>";
this.find('tbody tr:first').remove();
var htmlv = this.html();
this.html(theadv + htmlv);
}
//var end = +new Date(); // log end timestamp
// var diff = end - start;
// alert(diff);
return this;
};
</code></pre>
<p>I have to use IE8, it is client's requirement.
I have also created a <a href="http://jsfiddle.net/4xLzL/" rel="nofollow">jsfiddle</a>.</p>
| [] | [
{
"body": "<p>As far as I understand, you just want to wrap the first as <code><thead></code> and the rest in <code><tbody></code>. Why it's slow:</p>\n\n<ul>\n<li><p><code>html()</code> is one possible cause. That's because you're reconstructing the DOM rather than reusing what's there already.</p></li>\n<li><p><code>find()</code> is a descendant lookup function. It looks for elements deep into the tree. If you know that the element is a few levels down, then use multiple <code>children()</code> calls instead which only searches one level deep.</p></li>\n<li><p>Just to add, attribute selectors like <code>[id*=\"gvCategories\"]</code> are very slow. Better to use multiple classes instead, like <code>class=\"MainContent gvCategories\"</code>. That way, you can do <code>$('.gvCategories')</code>, which is faster.</p></li>\n</ul>\n\n<p><strong>The fastest and most painless fix is to just write the HTML with the first row in a <code><thead></code></strong>. Plain and simple.</p>\n\n<p>If you really want to go with JS, then <a href=\"http://jsfiddle.net/4xLzL/9/\" rel=\"nofollow\">here's my take on it</a> and the <a href=\"http://jsperf.com/detatch-to-thead\" rel=\"nofollow\">performance test to prove it</a></p>\n\n<pre><code>jQuery.fn.fixGridView = function () {\n \"use strict\";\n\n // A jQuery object may be more than one element. Operate on each using each()\n // Additionally, return the result to allow chainability.\n return this.each(function () {\n // Cache the element to avoid doing DOM refetch\n var element = $(this);\n if (!element.is('table')) return; \n\n // No need for tbody, since the browser automatically adds it\n // http://stackoverflow.com/a/938143/575527\n\n // Now we avoid using find() since it looks for all descendants.\n // Instead, we use children() to limit our search to 2 levels of children\n var rows = element.children('tbody').children('tr');\n var thead = element.children('thead').length;\n\n // Get the first row, wrap it in <thead>, and prepend it to the table\n if(!thead) rows.eq(0).wrap('<thead/>').parent().prependTo(element);\n\n\n });\n\n};\n\n$(document).ready(function () {\n $('.gvCategories').fixGridView();\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:51:29.447",
"Id": "85582",
"Score": "0",
"body": "Thank you so much @Joseph the Dreamer.. This is very fast now, however i still get the error saying \"A script on this page is causing Internet Explorer to run slowly\". I am using JQuery table-sorter, can it be the reason to make my page slow? I have only 50-55 records in my table.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:54:38.513",
"Id": "85584",
"Score": "0",
"body": "@user1181942 Can't really tell and I don't have much experience debugging in IE8. You could try profiling your code in Chrome or Firefox with their dev tools to see which code is taking long to execute. Then fix that part of the code, and then try again on IE8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:27:41.523",
"Id": "85643",
"Score": "0",
"body": "..Yes..I will try that.. Nyways thanks.. You made my code super-fast.."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:21:18.917",
"Id": "48744",
"ParentId": "48741",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48744",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T05:33:44.460",
"Id": "48741",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery"
],
"Title": "Function for adding a tag to the first row of a table is running slowly"
} | 48741 |
<p>I've built a base class that I use a lot in my iOS app to make calls to web services. I built the base class to make the actual call and this base class is only ever used by another class. </p>
<p>The idea was that should I decide to change from <code>AFNetworking</code> to something else, I would not need to rewrite code in many other classes and only need to change it in one class. </p>
<p>The rest of my app has no idea how the web service calls are actually made - it just know how to request them. That's it. </p>
<p>I've been thinking of late that maybe I could improve the code. </p>
<p>Here is the base class: </p>
<p>The header file: </p>
<p><strong>BBWebService.h</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@interface BBWebService : NSObject
#pragma mark - Properties
@property (nonatomic) BOOL isBusy;
@property (assign) int webServiceId;
@property (weak, nonatomic) id <NSObject, WebServiceDelegate> delegate;
#pragma mark - Methods
/**
This method is not allowed to instainsiate this class - cannot setup class correctly
*/
-(instancetype) init __attribute__((unavailable("Please use this classes designated initilizer initWithUrl")));
/**
Creates and runs an `NSURLSessionDataTask` with a HTTPS POST request.
@param initWithURL The URL string used to create the request URL.
@param RequestType HTTP request type - "POST" / "PUT" supported for this method only.
@param UrlParameters The parameters to be encoded according to the client request serializer.
@param PostDataValuesAndKeys POST data (NSDictionary)
*/
- (id) initWithURL: (NSString*) url RequestType: (NSString*) requestType PostDataValuesAndKeys: (NSDictionary*) postData UrlParameters: (NSDictionary*) urlParameters;
/**
Creates and runs an `NSURLSessionDataTask` with a HTTP request.
@param initWithURL The URL string used to create the request URL.
@param RequestType HTTP request type - "GET" / "DELETE" supported for this method only.
@param UrlParameters The parameters to be encoded according to the client request serializer.
*/
- (id) initWithURL: (NSString*) url RequestType: (NSString*) requestType UrlParameters: (NSDictionary*) urlParameters;
@end
</code></pre>
<p><strong>BBWebservice.m</strong></p>
<pre><code>-(instancetype)initWithURL:(NSString *)url RequestType:(NSString *)requestType UrlParameters:(NSDictionary *)urlParameters
{
[self getSessionManager];
if ([requestType isEqualToString:@"GET"]){
self.isBusy = YES;
[self.manager GET:url parameters:urlParameters
success:^(NSURLSessionDataTask *task, id responseObject){
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
int statusCode = (int)response.statusCode;
[self requestDone:responseObject StatusCode:statusCode];
}failure:^(NSURLSessionDataTask *task, NSError *error){
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
int statusCode = (int)response.statusCode;
[self requestFailed:error StatusCode:statusCode];
}];
//--** DELETE Request --**//
}else if ([requestType isEqualToString:@"DELETE"]){
self.isBusy = YES;
[self.manager DELETE:url parameters:urlParameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
int statusCode = (int)response.statusCode;
[self requestDone:responseObject StatusCode:statusCode];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
int statusCode = (int)response.statusCode;
[self requestFailed:error StatusCode:statusCode];
}];
}
self.isBusy = NO;
return self;
}
-(instancetype)initWithURL:(NSString *)url RequestType:(NSString *)requestType PostDataValuesAndKeys:(NSDictionary *)postData UrlParameters:(NSDictionary *)urlParameters
{
[self getSessionManager];
self.isBusy = YES;
[self.manager POST:url parameters:urlParameters
success:^(NSURLSessionDataTask *task, id responseObject){
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
int statusCode = (int)response.statusCode;
[self requestDone:responseObject StatusCode:statusCode];
}failure:^(NSURLSessionDataTask *task, NSError *error){
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
int statusCode = (int)response.statusCode;
[self requestFailed:error StatusCode:statusCode];
}];
return self;
}
-(void) requestDone: (id)responseObject StatusCode: (int)statusCode
{
self.isBusy = NO;
if ([responseObject isKindOfClass:[NSData class]]){
if (statusCode == 200)
{
NSData *data = [[NSData alloc]initWithData:responseObject];
if (self.delegate)
{
if ([self.delegate respondsToSelector:@selector(webService:result:)])
{
[self.delegate webService:self result:data];
}
else
{
[self.delegate result:data WebServiceId:self.webServiceId];
}
}
}
else
{
if ([self.delegate respondsToSelector:@selector(httpError:WebServiceId:ErrorCode:Message:)])
{
[self.delegate httpError:nil WebServiceId:self.webServiceId ErrorCode:statusCode Message:@"Web Service Failed!"];
}
else if ([self.delegate respondsToSelector:@selector(webService:httpError:ErrorCode:Message:)])
{
[self.delegate webService:self httpError:nil ErrorCode:statusCode Message:@"Web Service Failed"];
}
}
}
}
-(void)requestFailed: (NSError *)errorMessage StatusCode: (int)statusCode
{
self.isBusy = NO;
NSLog (@"Request failed - Status Code: %d Error: %@", statusCode, errorMessage);
if (statusCode == 0){
UIAlertView *offlineAlertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Your internet connection appears to be offline. Please check your settings and try again" delegate:self
cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[offlineAlertView show];
}
if ([self.delegate respondsToSelector:@selector(webService:connectionError:)])
{
[self.delegate webService:self connectionError: @"Connection Error!"];
}
else
{
//Add extra handling here
}
}
-(AFHTTPSessionManager *)getSessionManager
{
self.manager = [AFHTTPSessionManager manager];
self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
return self.manager;
}
@end
</code></pre>
<p>As you can see - <code>BBWebService</code> is used to make HTTP POST / GET / DELETE requests. (I need to modify it for PUT requests at some stage) </p>
<p>This class has not given me any issues and has worked just fine. </p>
<p>So to use these methods - I use another class to do the actual request that adds the URL / Dictionary parameters. </p>
<p><strong>Edit</strong>: </p>
<p>The protocols </p>
<p>It's just a header file that has these declarations: </p>
<pre><code>#import <Foundation/Foundation.h>
@protocol WebServiceDelegate
@optional
-(void) result:(id) result WebServiceId: (int) webServiceId;
-(void) connectionError:(id) result WebServiceId: (int) webServiceId;
-(void) generalError:(id) result WebServiceId: (int) webServiceId;
-(void) httpError:(id) result WebServiceId: (int) webServiceId ErrorCode: (int) errorCode Message: (NSString *) errorMessage;
-(void) webService:(id) webService result:(id) result;
-(void) webService:(id) webService connectionError:(id) result;
-(void) webService:(id) webService generalError:(id) result;
-(void) webService:(id) webService httpError:(id) result ErrorCode: (int) errorCode Message: (NSString *) errorMessage;
@end
</code></pre>
<p>I use the <code>-(void) result:(id) result WebServiceId: (int) webServiceId;</code></p>
<p>In another class like so:</p>
<pre><code> #pragma mark - BBWSDelegate methods
-(void)result:(id)result WebServiceId:(int)webServiceId
{
if (![result isKindOfClass:[NSData class]]){
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Result was not of type NSData!" userInfo:nil];
}
}
</code></pre>
<p>This is in My web service class and is designed to stop execution if for some reason I did not get an <code>NSData</code> object back. </p>
<p>I then reuse the <code>-(void) result:(id) result WebServiceId: (int) webServiceId;</code></p>
<p>Again in my XML parsing class - like so:</p>
<pre><code> -(void)result:(id)result WebServiceId:(int)webServiceId
{
if ([result isKindOfClass:[NSData class]]){
NSData *responseData = result;
NSString *xmlData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog (@" BBaseXmlWebService: XML Data Received - %@", xmlData);
self.tbxml = [TBXML newTBXMLWithXMLData:responseData error:nil];
//**-- Start parsing --**//
[self parseResult];
if (self.delegate)
{
[self.delegate result:self.baseResult WebServiceId:webServiceId];
}
}else
{
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Result was not of type NSData!" userInfo:nil];
}
}
</code></pre>
<p>And once again in my data class</p>
<pre><code> -(void)result:(id)result WebServiceId:(int)webServiceId
{
[self webServiceEnded:webServiceId];
if (![self handleWebServiceResult:result WebServiceId:webServiceId])
{
// do the default and store in the cache
NSNumber* webServiceIdNumber = [NSNumber numberWithInt:webServiceId];
[self.dataCache setObject:result forKey:webServiceIdNumber];
}
// update the last updated time in the cache
NSTimeInterval time = [NSDate timeIntervalSinceReferenceDate];
NSNumber* timeNum = [NSNumber numberWithDouble:time];
NSNumber* webServiceIdNumber = [NSNumber numberWithInt:webServiceId];
[self.dataLastUpdateTime setObject:timeNum forKey:webServiceIdNumber];
// notify with success
[self notify:webServiceId Result:NOTIFICATION_WEBSERVICE_RESULT_SUCCESS];
}
</code></pre>
<p>This way, I get valid, parsed data back into my data class ready to use in the app where I need it. </p>
<p><strong>Edit 2</strong></p>
<p>This is to answer some of nhgrif's questions as my reply is too long for comments. </p>
<p>The class needs to have a delegate as that is how I let another class know the request has been completed. </p>
<p>The second problem you mentioned with the init methods; the reason for the init method making the request is that is all I ever do with this class. Here is an example of how I would use this class:</p>
<pre><code>-(void)fetch:(NSDictionary *)urlParameters
{
if (!self.webService.isBusy){
BBWebService *webService = [[BBWebService alloc]initWithURL:self.url RequestType:GET_REQUEST UrlParameters:urlParameters];
self.webService = webService;
self.webService.webServiceId = wsID;
[self.webService setDelegate:self];
}
}
</code></pre>
<p>In this class (<code>ClassB</code>) where I use this method - I initialize the <code>BBWebService</code> class with the URL and parameters I need. I also set the delegate for the <code>BBWebService</code> class here in <code>ClassB</code> at the same time. <code>ClassB</code> conforms to the protocols and once BBWebService class has completed the request - <code>ClassB</code> takes over and handles them - then hands it off to my XML class which parses it and then it moves up the chain to my data store class where I use the parsed data. </p>
<p>This is why I thought it would be best to make sure the <code>BBWebService</code> class could not be setup with just alloc / init as then you would be using it incorrectly. </p>
<p>Maybe there is a better approach to this?</p>
| [] | [
{
"body": "<p>I REALLY like this:</p>\n<pre><code>-(instancetype) init __attribute__((unavailable("Please use this classes designated initilizer initWithUrl")));\n</code></pre>\n<p>I follow this pattern myself a lot. But... is it okay for your class to not have a delegate? I see that the code will survive, but does it ever make sense for this class to be undelegated when instantiated? If not, I suggest the message point the user instead to a <code>initWithDelegate:</code> method and take the delegate during initialization.</p>\n<hr />\n<p>Your <code>init</code> methods have several problems.</p>\n<p>First problem is you're using property accessors in your <code>init</code> methods, which you should never do. Apple themselves recommend directly against this.</p>\n<p>Second problem for me is that your <code>init</code> methods are doing way more than initializing. They're starting the request! And they're doing so without even giving me the chance to set a delegate!</p>\n<p>Methods should do one thing, and their method name should reflect that one thing that they do.</p>\n<p>And in Objective-C, methods in the <code>init</code> family have a very clear scope: setup an object and prepare it to be used. Moreover, all <code>init</code> methods should call either <code>[super init]</code> or call another init method within the same class (which calls super init itself).</p>\n<p>The pattern for Objective-C <code>init</code> methods is very clear.</p>\n<pre><code>- (instancetype)initWithFoo:(Foo *)foo bar:(Bar *)bar {\n self = [super init];\n if (self) {\n _foo = foo;\n _bar = bar;\n // any other initializations\n }\n return self;\n}\n</code></pre>\n<p>You should have a separate method for actually starting the network operations. There are plenty of good, practical reasons for this. But the best of all reasons is that it's OOP standard practice and would be the expected behavior.</p>\n<hr />\n<pre><code>@property (weak, nonatomic) id <NSObject, WebServiceDelegate> delegate; \n</code></pre>\n<p>Is there ever a case where you'd want a property that conforms to the <code>WebServiceDelegate</code> protocol and don't necessarily need it to conform to <code>NSObject</code> protocol? I expect this is highly unlikely. So BETTER would be to mark your <code>WebServiceDelegate</code> protocol itself as conforming to <code>NSObject</code> protocol.</p>\n<p>So, in the protocol declaration:</p>\n<pre><code>@protocol WebServiceDelegate <NSObject>\n</code></pre>\n<p>Now change the property to :</p>\n<pre><code>@property (weak, nonatomic) id <WebServiceDelegate> delegate; \n</code></pre>\n<p>And now you've got a property called <code>delegate</code> which still conforms to both <code>NSObject</code> and <code>WebServiceDelegate</code> protocols, but your code is a little cleaner and makes a bit more sense.</p>\n<p>If we were talking about a protocol other than <code>NSObject</code>, I may or may not necessarily recommend this, but since we're talking about <code>NSObject</code>, I'm definitely recommending this change.</p>\n<hr />\n<hr />\n<hr />\n<p><strong>EDIT:</strong> In response to your latest edit, let me expand on and clarify some things.</p>\n<p>First of all, I understand how delegates work. I understand that it is through the delegate that your class makes callbacks to let whoever needs to know that it's done working (or whatever status update). And I understand that without a delegate, these callbacks can't be made without the current structure.</p>\n<p>But that wasn't actually my question.</p>\n<p>My question, for clarity, was more along the lines of:</p>\n<p>Does it ever make sense for someone to instantiate this class and use <code>nil</code> for the delegate (or just not set it).</p>\n<p>Given that every method in the protocol is flagged as <code>@optional</code>, to me, the answer has to be YES. It will sometimes make sense that someone using this class may not want to bother with a delegate.</p>\n<p>If, however, <code>nil</code> is NEVER an acceptable option for the delegate, then I'm proposing a restructuring of some methods.</p>\n<p>First of all, if <code>nil</code> isn't an acceptable delegate, then not every method in your protocol is really <code>@optional</code>. I don't know which ones aren't, but if the delegate MUST be set, then that can only mean at least one of the methods in the protocol that the delegate conforms to is <code>@required</code>.</p>\n<p>And second of all, if <code>nil</code> isn't an acceptable delegate, then that's just one more reason on top of a big stack of reasons why we shouldn't be starting the networking in <code>init</code>. Because your <code>init</code> methods don't take a <code>delegate</code> argument, there's no guarantee that a delegate will EVER be set, and there's even less of a guarantee that it will be set before your class tries to call a method on a delegate, since it's starting the networking before anyone has an opportunity to set a delegate.</p>\n<hr />\n<p>As for the <code>init</code> methods, I can clearly see from your class structure that the class is used for nothing more than doing the networking. This is not a good enough excuse to put the networking in the <code>init</code> method.</p>\n<p>As I already explained, it's problematic enough that I don't get an opportunity to set the delegate before the networking calls start. So that's one reason to take the networking out <code>init</code> methods. But now you say "Well, I can just make the delegate as one of the <code>init</code> arguments!"</p>\n<p>But that's still not good enough.</p>\n<p>Even if all we're using the class for is making a single networking connection, it's still completely unacceptable for the <code>init</code> method to do anything other than <code>init</code>.</p>\n<p>"This class is only used for making a single networking connection" is decent class design (though arguably it might be better to allow the object to be reused for multiple networking connections with the same delegate). It's not an excuse to cram everything into that objects <code>init</code> method however.</p>\n<p>For a good example of how your class SHOULD work, let's look at similar Foundation class (Foundation classes should ALWAYS be used as an outline for Objective-C best practice).</p>\n<p>In this case, the most similar Foundation class I can think of is <code>NSURLConnection</code>. How does that work?</p>\n<p>There are a few different ways that <code>NSURLConnection</code> can be used, and they're all different from how your class is used.</p>\n<p>First, let's look at the <code>init</code>/factory methods.</p>\n<pre><code>+ connectionWithRequest:delegate:\n- initWithRequest:delegate:\n- initWithRequest:delegate:startImmediately:\n</code></pre>\n<p>The first two don't open a network connection. The third does open a connection, but notice how the init method makes this explicitly clear--it also collects ALL the required information.</p>\n<p>If we use the first two, or send <code>NO</code> as the argument for the third, the object has another method we use to actually start the networking. It's called:</p>\n<pre><code>- start\n</code></pre>\n<p>This actually begins the networking.</p>\n<p>The nice thing for this is, I can instantiate multiple connection objects throughout the course of UI interactions, throw them in an array, and wait till some point later in time and call <code>start</code> on them all at the same time, without having to instantiate all the objects as I want to use them.</p>\n<p>Now then, the important thing to note about <code>NSURLConnection</code> are two other class methods that are available.</p>\n<p>The first is:</p>\n<pre><code>+ sendSynchronousRequest:returningResponse:error:\n</code></pre>\n<p>This one is mostly self explanatory. It sends the request synchronously. It also starts the networking immediately. But the big thing to note here is that the return value from this method is an <code>NSData</code> object. When you use this, whatever thread it's called on waits around for the return, and then you have an <code>NSData</code> return. You never get an <code>NSURLConnection</code> object out of this method, you NEVER create one at all.</p>\n<p>The other one to look at is this:</p>\n<pre><code>+ sendAsynchronousRequest:queue:completionHandler:\n</code></pre>\n<p>Now this method handles the networking asynchronously on a queue that you specify, but what's important to note here is that the return is <code>void</code>. Once again, we never have or need an <code>NSURLConnection</code> object. In this case, we also don't have a delegate. Instead, we send a block for the <code>completionHandler</code> argument, and the code in this block is executed when the request completes.</p>\n<p>So we have 5 ways to use <code>NSURLConnection</code>. Two of don't start the connection immediately and require a call to <code>start</code> to start. The third either does or doesn't start immediately depending on a BOOL argument, but this is sent explicitly by the user, so it's CLEAR what's going on. And the last two do start immediately, but don't actually instantiate an object of this class.</p>\n<p>Your class doesn't follow any of these patterns.</p>\n<hr />\n<hr />\n<h1>UPDATE</h1>\n<p>After taking another look at <code>NSURLConnection</code> class, it seems that most of these <code>init</code> methods actually do start the networking. Still though, those that do either take the delegate as the argument or take a completion handler and return void, or perform the task synchronously and return the <code>NSData</code> object. These are things to keep in mind.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T06:40:01.650",
"Id": "85744",
"Score": "0",
"body": "Thanks for you input. i really appreciate it. I have updated my question in response to your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:59:44.377",
"Id": "85828",
"Score": "0",
"body": "It seems I have a lot more to learn on class structures and making modifications to the BBWebServie class. Thanks for your help and I will take note of all your suggestions. I wish there was a place were we could discuss this more without cluttering up the question. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T20:01:36.370",
"Id": "85829",
"Score": "0",
"body": "There are chat rooms: http://chat.stackexchange.com/rooms/8595/the-2nd-monitor http://chat.stackexchange.com/rooms/12918/nschat but anyway, the general rule of thumb with Objective-C is to model your classes off of similar Foundation classes. These are the classes ObjC developers use the vast majority of the time. The rest of the time, we're using classes that were modeled after these classes... so we don't like seeing classes that don't fit this mold."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T05:50:00.693",
"Id": "85860",
"Score": "0",
"body": "I'll take a look at the foundation classes and also visit the chat rooms. Thanks bud!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:30:10.340",
"Id": "48821",
"ParentId": "48746",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48821",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T06:54:11.350",
"Id": "48746",
"Score": "1",
"Tags": [
"objective-c",
"ios",
"networking"
],
"Title": "App for making calls to web services - AFNetworking 2.0"
} | 48746 |
<p>May there be any performance and/or code standard improvements on the following <code>LineOfSight</code> code?</p>
<pre><code>static List<Coordinate> getIntersects(Coordinate c1, Coordinate c2) {
// Bresenham's line algorithm from http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#C.2B.2B
List<Coordinate> returningVector = new List<Coordinate>();
double y1 = c1.y, x1 = c1.x, y2 = c2.y, x2 = c2.x;
bool steep = (Math.Abs(y2 - y1) > Math.Abs(x2 - x1));
if(steep)
{
double _t;
_t = x1;
x1 = y1;
y1 = _t;
_t = x2;
x2 = y2;
y2 = _t;
}
if(x1 > x2)
{
double _t;
_t = x1;
x1 = x2;
x2 = _t;
_t = y1;
y1 = y2;
y2 = _t;
}
double dx = x2 - x1;
double dy = Math.Abs(y2 - y1);
double error = dx / 2.0f;
int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
int maxX = (int)x2;
for(int x=(int)x1; x<maxX; x++)
{
if(steep)
{
Coordinate tc = new Coordinate(y, x);
returningVector.Add(tc);
}
else
{
Coordinate tc = new Coordinate(x,y);
returningVector.Add(tc);
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
if(steep)
{
Coordinate tc = new Coordinate(y2, x2);
returningVector.Add(tc);
}
else
{
Coordinate tc = new Coordinate(x2,y2);
returningVector.Add(tc);
}
return returningVector;
}
static bool isObstacle(Coordinate c1, Coordinate c2, Coordinate c3) {
double heightOn_c3 = Math.Abs(((c1.height - c2.height) * Tools.distanceXY(c2, c3)) / Tools.distanceXY(c2, c1));
return (heightOn_c3 + c2.height) < c3.height;
}
public static bool calculateLOS(Coordinate c1, Coordinate c2, Map map) {
List<Coordinate> intersects = getIntersects(c1, c2);
for(int i=0; i<intersects.Count; i++) {
if(isObstacle(c1, c2, map.points[(int)intersects[i].x][(int)intersects[i].y].coordinates)){
return false;
}
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T22:20:52.543",
"Id": "85727",
"Score": "0",
"body": "This looks like Java code that had bits changed here and there to turn it into C#."
}
] | [
{
"body": "<p>The least you could do is move <code>if(steep)</code> out of the <code>for</code> loop, saving one conditional in every iteration.</p>\n\n<p>In the initializations, you could use a <code>swap</code> function.</p>\n\n<p>Why is the name of the function <code>getIntersects</code>?</p>\n\n<p>I don't know C#, but if <code>new Coordinate(x,y)</code> is using the heap for every single point, this does not sound very efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:32:25.573",
"Id": "48750",
"ParentId": "48747",
"Score": "4"
}
},
{
"body": "<h2>Conventions:</h2>\n\n<p>That is in my eyes the definitely biggest problem in your current code. Naming conventions. All programmers agree, that naming is one of the most difficult things to do. Therefore it is useful to define conventions to abide when naming. The C# convention for naming methods is not <code>camelCase</code>, but <code>PascalCase</code>. </p>\n\n<p>Next up, your local variables in the <code>getIntersects</code> method.</p>\n\n<p>first thing to criticise is your parameternames. You should stay away from numbers in variable names. Rather prefix <code>first</code>, <code>second</code>, and so on. Or alternatively add a postfix like <code>One</code>, <code>Two</code>... </p>\n\n<p>Another thing here is your placement of curly braces, the C# convention is, that every Curly brace should have it's own line (you use the Java-Convention, egyptian braces).</p>\n\n<p>Rewriting your <code>getIntersects</code> a bit:</p>\n\n<pre><code>static GetIntersects(Coordinate firstCooridinate, Coordinate secondCoordinate)\n{\n List<Coordinate> returningVector = new List<Coordinate>();\n double firstY = firstCoordinate.y;\n double firstX = firstCoordinate.x;\n double secondY = secondCoordinate.y;\n double secondX = secondCoordinate.x;\n\n bool isSteep = (Math.Abs(secondY - firstY) > Math.Abs(secondX - firstX));\n if(isSteep)\n {\n Swap(ref firstX, ref firstY);\n Swap(ref secondX, ref secondY);\n }\n\n if(firstX > secondX)\n {\n Swap(ref firstX, ref secondX);\n Swap(ref firstY, ref secondY);\n }\n\n double deltaX = secondX - firstX;\n double deltaY = Math.Abs(secondY - firstY);\n\n double error = deltaX / 2.0f;\n int ySteps = (firstY < secondY) ? 1 : -1;\n int maxX = int secondX;\n\n //stopping here, the rest is yours to write.\n}\n</code></pre>\n\n<h3>Access Modifiers:</h3>\n\n<p>You should always explicitly write out the access modifiers. This makes clear what your methods are supposed to be used for...</p>\n\n<h3>Minor Nitpicks:</h3>\n\n<p>Personally I prefer not to have more than two parentheses in an assignment statment. Precalculate things you use in the assignment and when you name them nicely, you have free documentation on top of it ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:43:19.683",
"Id": "85589",
"Score": "0",
"body": "you can't swap value types like double, at least not if the parameter is not passed by reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:46:24.373",
"Id": "85592",
"Score": "0",
"body": "I would also put the swap method on coordinate class if I had access to that class. Calling firstCoordinate.Swap() would be more interesting imo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:47:05.460",
"Id": "85593",
"Score": "0",
"body": "Really, what is wrong with `x1`, `x2`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:48:18.700",
"Id": "85595",
"Score": "0",
"body": "@iavr what is wrong with `_t`? why do you want to sacrifice easy readability and thus understanding for character count?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:48:45.530",
"Id": "85596",
"Score": "0",
"body": "@BrunoCosta the problem is, he also swaps between the coordinates... `Swap(ref firstY, ref secondY)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:52:26.613",
"Id": "85597",
"Score": "0",
"body": "@Vogel612 Sorry, I find `x1` clearly more readable than `firstX`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:01:54.120",
"Id": "85600",
"Score": "0",
"body": "@iavr let's agree to disagree then. I feel `firstX` / `xOne` is a much better naming-choice than `x1`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:40:41.077",
"Id": "48752",
"ParentId": "48747",
"Score": "3"
}
},
{
"body": "<p>I would take Vogel612 refactoring even further and implement some more logic in your Coordinate class so I can have a tidier looking <code>GetIntersects</code> method. I would also get rid all of those variables and use coordinates X and Y as much as possible.</p>\n\n<pre><code>public class Coordinate{\n public int X{get; set;}\n public int Y{get; set;}\n\n public Coordinate(){}\n\n public Coordinate(int x, int y){\n X = x;\n y = y;\n }\n\n public static Coordinate operator +(Coordinate c1, Coordinate c2){\n return new Coordinate(){\n X = c1.X + c2.X,\n Y = c1.Y + c2.Y\n };\n }\n\n public static Coordinate operator -(Coordinate c1, Coordinate c2){\n return new Coordinate(){\n X = c1.X - c2.X,\n Y = c1.Y - c2.Y\n };\n }\n\n public void Swap(){\n int aux = X;\n X = Y;\n Y = aux;\n }\n\n public override string ToString(){\n return string.Format(\"Coordinate ({0}, {1})\", X, Y);\n }\n}\n\nstatic List<Coordinate> getIntersects(Coordinate c1, Coordinate c2) {\n List<Coordinate> returningVector = new List<Coordinate>();\n\n bool steep = (Math.Abs(c2.Y - c1.Y) > Math.Abs(c2.X - c1.X)); \n if(steep)\n {\n c1.Swap();\n }\n\n if(c1.X > c2.X)\n {\n Coordinate aux = c1;\n c1 = c2;\n c2 = aux;\n }\n\n Coordinate dc = c2 - c1;\n dc.Y = Math.Abs(dc.Y);\n\n double error = dc.X / 2.0f;\n int ystep = (c1.Y < c2.Y) ? 1 : -1;\n int y = dc.Y;\n for(int x = c1.X; x < c2.X; x++)\n {\n if(steep)\n {\n Coordinate tc = new Coordinate(y, x);\n returningVector.Add(tc);\n }\n else\n {\n Coordinate tc = new Coordinate(x, y);\n returningVector.Add(tc);\n }\n\n error -= y;\n if(error < 0)\n {\n y += ystep;\n error += dc.X;\n }\n }\n if(steep)\n {\n Coordinate tc = new Coordinate(c2.Y, c2.X);\n returningVector.Add(tc);\n }\n else\n {\n Coordinate tc = new Coordinate(c2.X,c2.Y);\n returningVector.Add(tc);\n }\n return returningVector;\n}\n</code></pre>\n\n<p>Please don't blame me if I misplaced a X for a Y <.<</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:29:55.647",
"Id": "48754",
"ParentId": "48747",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:14:01.350",
"Id": "48747",
"Score": "4",
"Tags": [
"c#",
"performance",
"graphics",
"coordinate-system"
],
"Title": "Bresenham's line algorithm implementation"
} | 48747 |
<p>Continuation of this question: <a href="https://codereview.stackexchange.com/questions/38901/unit-of-work-with-generic-repository-pattern-mvvm-vol-3">Unit of Work with Generic Repository Pattern MVVM, vol. 3</a></p>
<p>I have made some changes.</p>
<ul>
<li>The methods <code>GetFeedBySomething()</code> have been replaced by <code>Find()</code></li>
<li><code>GetRepository()</code> has been added to <code>UoW</code></li>
<li>I separated <code>DAL</code> from <code>Model</code></li>
<li><code>Model</code> inherits <code>IBaseEntity</code> from <code>DAL</code> (not sure is it correct)</li>
<li><code>IRepositoryWithId</code> made <code>TEntity</code> to become <code>IBaseEntity</code> because I need to have <code>Id</code> property. (again not sure is it correct, maybe shall I use <code>reflection</code>?) </li>
</ul>
<p><strong>This is my code map: <img src="https://i.stack.imgur.com/DbwVH.png" alt="Code Map"></strong></p>
<p><strong>And here are my code</strong></p>
<p><strong><code>DAL</code> CLASSES</strong></p>
<p><strong>IRepository</strong></p>
<pre><code>public interface IRepository<TEntity> where TEntity : class
{
TEntity Add(TEntity entity);
TEntity Update(TEntity entity);
IQueryable<TEntity> Find(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate);
IEnumerable<TEntity> GetAll();
void Remove(TEntity entity);
}
</code></pre>
<p><strong>IRepositoryWithId</strong></p>
<pre><code>public interface IRepositoryWithId<T> : IRepository<T> where T : class, IBaseEntity
{
int Count { get; }
T GetById(int feedId);
void RemoveById(int feedId);
}
</code></pre>
<p><strong>IBaseEntity</strong></p>
<pre><code>public interface IBaseEntity
{
int Id { get; set; }
}
</code></pre>
<p><strong>IFeedRepository</strong></p>
<pre><code>internal class FeedRepository<T> : IRepositoryWithId<T>
where T : class, IBaseEntity, new()
{
private readonly SQLiteConnection _dbConnection;
protected Lazy<IList<T>> _feeds;
public int Count
{
get
{
if (this._feeds.IsValueCreated)
return this._feeds.Value.Count;
return this._dbConnection.Table<T>().Count();
}
}
public FeedRepository(SQLiteConnection dbConnection)
{
this._dbConnection = dbConnection;
this._feeds = new Lazy<IList<T>>(() => this._dbConnection.Table<T>().ToList());
}
public T Add(T feed)
{
if (this._feeds.IsValueCreated)
this._feeds.Value.Add(feed);
this._dbConnection.Insert(feed);
return feed;
}
public T GetById(int feedId)
{
return this._feeds.Value.Where(feed => int.Equals(feed.Id, feedId)).SingleOrDefault();
//return this._feeds.Value.Where(feed => int.Equals(typeof(T).GetRuntimeProperty("Id").GetValue(feed), feedId)).SingleOrDefault();
}
public T Update(T feed)
{
int indexOfFeed = this.GetIndexOfFeed(feed);
if (indexOfFeed != -1)
this._feeds.Value[indexOfFeed] = feed;
this._dbConnection.Update(feed);
return feed;
}
public IEnumerable<T> GetAll()
{
return this._feeds.Value;
}
public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
if (predicate != null)
return this._feeds.Value.AsQueryable().Where(predicate);
return this._feeds.Value.AsQueryable();
}
public void Remove(T feed)
{
int indexOfFeed = this.GetIndexOfFeed(feed);
if (indexOfFeed != -1)
this._feeds.Value.RemoveAt(indexOfFeed);
this._dbConnection.Delete(feed);
}
public void RemoveById(int feedId)
{
T feed = this.GetById(feedId);
if (feed != null)
this.Remove(this.GetById(feedId));
}
private int GetIndexOfFeed(T feed)
{
if (this._feeds.IsValueCreated)
{
//int id = (int)typeof(T).GetRuntimeProperty("Id").GetValue(feed);
int indexOfFeed = this._feeds.Value.IndexOf(this.GetById(feed.Id));
return indexOfFeed;
}
return -1;
}
}
</code></pre>
<p><strong>IUnitOfWork</strong></p>
<pre><code>internal interface IUnitOfWork
{
bool IsInTransaction { get; }
IRepositoryWithId<TEntity> GetFeedRepository<TEntity>() where TEntity : class, IBaseEntity, new();
void Commit();
void Rollback();
}
</code></pre>
<p><strong>UnitOfWork</strong></p>
<pre><code>public class UnitOfWork : IUnitOfWork
{
private readonly SQLiteConnection _dbConnection;
private readonly Dictionary<Type, object> _repositories;
public bool IsInTransaction
{
get { return this._dbConnection.IsInTransaction; }
}
public UnitOfWork(SQLiteConnection dbConnection)
{
this._repositories = new Dictionary<Type, object>();
this._dbConnection = dbConnection;
this._dbConnection.BeginTransaction();
}
public IRepositoryWithId<TEntity> GetFeedRepository<TEntity>()
where TEntity : class, IBaseEntity, new()
{
if (this._repositories.Keys.Contains(typeof(TEntity)))
return this._repositories[typeof(TEntity)] as IRepositoryWithId<TEntity>;
var repository = new FeedRepository<TEntity>(this._dbConnection);
this._repositories.Add(typeof(TEntity), repository);
return repository;
}
public void Commit()
{
this._dbConnection.Commit();
}
public void Rollback()
{
this._dbConnection.Rollback();
}
}
</code></pre>
<p><strong><code>MODEL</code> CLASSES</strong></p>
<p><strong>IFeed</strong></p>
<pre><code>public interface IFeed : IBaseEntity
{
string Title { get; set; }
Uri Link { get; set; }
DateTime PubDate { get; set; }
}
</code></pre>
<p><strong>FeedData and FeedItem</strong></p>
<pre><code>public sealed class FeedData : IFeed, INotifyPropertyChanged { }
public sealed class FeedItem : IFeed, INotifyPropertyChanged { }
</code></pre>
<p>And now I have some questions about:</p>
<ul>
<li><code>IBaseEntity</code> is it necessary or shall I use <code>reflection</code></li>
</ul>
| [] | [
{
"body": "<p>Use <code>IBaseEntity</code>, reflection should never be used unless you really need to.</p>\n\n<p>I'm not a fan of returning a not executed <code>IQueryable<></code> as you do in your <code>Find</code> method, you should consider executing the query and returning the <code>IEnumerable<></code>, otherwise you expose yourself to potential bugs (If the client of the method messes up with the query) and it is harder to debug after since you might not know when is your query executed.</p>\n\n<p>You should consider commenting your code, one day you will be happy you did it!</p>\n\n<p>I'm not sure why your generic repository is named <code>FeedRepository</code>, maybe it's because it has a meaning I don't understand in english but you might want to rename it in a more generic way (Say... <code>SqLiteRepository</code> since it is an implementation of your interface for an SqlLite data access). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T15:44:40.027",
"Id": "60726",
"ParentId": "48749",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:27:44.870",
"Id": "48749",
"Score": "3",
"Tags": [
"c#",
"mvvm"
],
"Title": "Unit of Work with Generic Repository Pattern MVVM, vol. 4"
} | 48749 |
<p>I've been working on improving my website code. I've noticed that querying from a table inside a PHP <code>while</code> function, where <code>while</code> loop is also querying another table:</p>
<pre><code>while($row = mysql_fetch_assoc($table1)){
$table2 = mysql_query(select);
mysql_fetch_assoc($table2);
}
</code></pre>
<p>It might be slowing down the performance, depending on the fact that we're querying the second table for each row of the first table.</p>
<p>So I've decided to select both of the tables from the same query. I came up with <a href="http://sqlfiddle.com/#!2/d198f/2" rel="nofollow">this code</a> to accomplish what I think is more sufficient.</p>
<p>Now I have few questions:</p>
<ol>
<li>Am I correct for what I've said about the way my old code is slow?</li>
<li>Would using PHP functions to query from each table individually be more sufficient?</li>
<li>Is there anything that I need to add or change in my code, that I've made?</li>
</ol>
<p>Code:</p>
<pre><code>SELECT posts.*, users.username, SUM(IF(rates.hash = posts.hash, (rates.likes - rates.dislikes), 0)) AS rate
FROM posts,users,rates WHERE posts.position = posts.submitter AND users.username = posts.submitter GROUP BY posts.hash ORDER BY posts.ID DESC LIMIT 5
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:43:21.997",
"Id": "85590",
"Score": "0",
"body": "Please include all of the code here. We cannot review code behind a link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:47:12.370",
"Id": "85594",
"Score": "0",
"body": "it's a demo link from sqlfiddle.com however, i've posted the code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:09:38.297",
"Id": "85637",
"Score": "0",
"body": "So are you working with two tables or three ? Also, can you give the PHP code that creates select ?"
}
] | [
{
"body": "<p>I don't really understand what this join is trying to accomplish? Seems redundant since the information is the same, but perhaps with your real world data it is not always the case.</p>\n\n<p><code>WHERE posts.position = posts.submitter</code></p>\n\n<p>Old-style <code>JOIN</code>s are not recommended. Use <code>INNER JOIN</code> instead. This may also cause performance issues because <code>rates</code> is not explicitly joined so it would be trying to do a <code>CROSS JOIN</code> and those are very slow not to mention it can mess up your result set.</p>\n\n<pre><code>FROM posts,\n users,\n rates\nWHERE posts.position = posts.submitter \nAND users.username = posts.submitter\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>SELECT posts.*, \n users.username, \n SUM(\n IF(rates.hash = posts.hash, (rates.likes - rates.dislikes), 0)\n ) AS rate \nFROM posts \nINNER JOIN users\n ON users.username = posts.submitter\nINNER JOIN rates\n ON users.username = rates.username\nWHERE posts.position = posts.submitter \nGROUP BY posts.hash \nORDER BY posts.ID DESC LIMIT 5;\n</code></pre>\n\n<p>I also formatted it for ease of reading. Executes in 2 ms using your data.\nTry it: <a href=\"http://sqlfiddle.com/#!2/d198f/4\" rel=\"nofollow\">http://sqlfiddle.com/#!2/d198f/4</a></p>\n\n<p>Edit: fixed a typo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-19T21:21:50.433",
"Id": "88309",
"Score": "0",
"body": "I also see some potential changes to your DDL that could improve performance, but that would require a redesign of your tables. Let me know if you would like for me to make suggestions on that specifically and I can write another answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-19T20:57:57.917",
"Id": "51164",
"ParentId": "48751",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T07:35:57.230",
"Id": "48751",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "Selecting three tables with relationship"
} | 48751 |
<p>I've been trying to figure out a clean way of managing mappings between two objects. In the case of this example, it's two hashes. This spec should illustrate the problem at hand:</p>
<pre><code>describe 'key mapping' do
let(:have) { { data1: 'foo', data2: 'bar', data3: 'baz' } }
let(:want) { { LINE1: 'foo', LINE2: 'bar', LINE3: 'baz' } }
let(:result) { {} }
after(:each) do
expect(result).to eq want
end
it 'by assigning manually' do
result[:LINE1] = have[:data1]
result[:LINE2] = have[:data2]
result[:LINE3] = have[:data3]
end
it 'by reading keys from a hash' do
mappings = { data1: :LINE1, data2: :LINE2, data3: :LINE3 }
mappings.each do |k, v|
result[v] = have[k]
end
end
end
</code></pre>
<p>The notable thing here is that the source and destination can be mapped by known keys and unlike in the example there is no numeric correlation between the source and destination (example lists numbered keys just to make it easier to read)</p>
<p>The number of keys could be rather high, so the latter example will make code more readable, but is there an even better way of handling this?</p>
| [] | [
{
"body": "<p>If there's no \"logical\" correlation between the key you have, and the key you want (i.e. no consistent way to rewrite them) then you basically have to use a lookup of some sort to do the translation.</p>\n\n<p>So your \"reading keys from a hash\" strategy is your best bet, but it can be improved a little.</p>\n\n<p>You can be more functional and just use <code>map</code>:</p>\n\n<pre><code>lookup = { data1: :LINE1, data2: :LINE2, data3: :LINE3 }\n\nresult = Hash[ lookup.map { |in, out| [out, have[in]] } ]\n</code></pre>\n\n<p>Or you can just go through the ones in the input hash, and translate the ones that are actually there, discarding ones without a translation:</p>\n\n<pre><code>result = Hash[ have.map { |k, v| [lookup[k], v] if lookup[k] }.compact ]\n</code></pre>\n\n<p>And for either of those, if you ever need to translate the other way, you can just use <code>lookup.invert</code> to flip the keys/values around.</p>\n\n<p>Lastly, for you spec, don't put an expectation in a <code>after(:each)</code> block. Put the expectation in the spec itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T10:05:19.813",
"Id": "85619",
"Score": "0",
"body": "I agree that using an array of arrays makes things more functional. I actually even considered using each_with_object, which would make things more readable. As for the expect in after block, that was just to simplify the example. Generally I avoid doing that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T05:26:27.607",
"Id": "85743",
"Score": "0",
"body": "`lookup.invert.tap { |h| h.each_key { |k| h[k] = have[h[k]] } }` is another way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:46:07.620",
"Id": "85794",
"Score": "0",
"body": "@CarySwoveland So essentially that's a more complicated way of doing the original second example, or is there some added benefit of doing it your way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:59:56.507",
"Id": "85799",
"Score": "0",
"body": "Ressu, there is no benefit, and I didn't claim one, though I don't think it's any more complicated than the other ways. If only solutions that were claimed to be superior were posted, we would all be poorer for it. Maybe someone who has read my comment will think of using `invert` to advantage (in another time and place), or is unfamiliar with `tap`, looks it up and discovers that it's very handy indeed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T07:07:31.040",
"Id": "85961",
"Score": "0",
"body": "@CarySwoveland Sorry, I didn't mean to sound offensive. I just tried to understand if there was more to the method you used. And indeed, the tap method was an useful discovery. I had completely overlooked it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T07:09:30.370",
"Id": "85962",
"Score": "1",
"body": "I wasn't offended in the least."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:48:35.133",
"Id": "48757",
"ParentId": "48753",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48757",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T08:19:39.653",
"Id": "48753",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Key and value mapping from one object to another"
} | 48753 |
<p>Recently I've attended an interview, where I faced the below question:</p>
<blockquote>
<p><strong>Question:</strong> "There is an sorted array. You need to find all the missing numbers. Write the complete code, without using any generics
or inbuilt function or binary operators. First and last terms will be
given. Array will be sorted. Array always starts with zero."</p>
<p><strong>Example:</strong></p>
<pre><code>Input:
int array[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };
Output:
Missing number(s): 5, 16, 17, 19, 22.
</code></pre>
<p>If its single missing term, we can calculate the required total using
summation formula, and find the difference between the actual total.
Which gives the missing term.</p>
</blockquote>
<p>Since there are multiple values missing, I came up with below approach. </p>
<p><strong>Code:</strong></p>
<pre><code>public class MissingNumber {
public static int count = 0;
public static int position = 0;
public static boolean flag = false;
public static void main(String[] args) {
int a[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };
findMissingNumbers(a, position);
}
private static void findMissingNumbers(int a[], int position) {
if (position == a.length - 1)
return;
for (; position < a[a.length - 1]; position++) {
if ((a[position] - count) != position) {
System.out.println("Missing Number: " + (position + count));
flag = true;
count++;
break;
}
}
if (flag) {
flag = false;
findMissingNumbers(a, position);
}
}
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>Missing Number: 5
Missing Number: 16
Missing Number: 17
Missing Number: 19
Missing Number: 22
</code></pre>
<p>This gives the required solution. But, is the code fine or can this be done with a better approach?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:52:22.537",
"Id": "85615",
"Score": "0",
"body": "Is the difference between 2 succesive numbers always constant?."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:53:03.730",
"Id": "85616",
"Score": "0",
"body": "Yes. Its is in natural order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:53:20.127",
"Id": "85617",
"Score": "0",
"body": "and difference is always 1?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:10:36.573",
"Id": "85671",
"Score": "0",
"body": "Example Output is different than your output. One line `Missing Value(s):1,2,3...` vs `Missing Value:1\\newlineMissing Value:2\\newline...`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:21:50.740",
"Id": "85683",
"Score": "12",
"body": "\"Without using ... binary operators\" I'm not a java expert, but aren't these all binary operators:== < != - +"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T20:28:33.960",
"Id": "85714",
"Score": "0",
"body": "Second thing I just noticed: `if missing a single term... use summation formula to get missing term`. That's not anywhere in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:10:03.593",
"Id": "85751",
"Score": "1",
"body": "I see what's going on here. The person who made the interview question probably comes from a maths background and not a programming background. Binary Operator in maths means a set operation. So in essence the question prohibits SQL, Linq etc. In programming Binary Operator is < , == etc. I think in this case, I would walk away from the job opportunity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:23:11.387",
"Id": "85758",
"Score": "3",
"body": "@Sentinel: The wording could also be wrong in that the requierent means: No bitwise operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T09:21:29.550",
"Id": "85973",
"Score": "0",
"body": "@Nobody - could be right, and it would certainly help to get it clarified! Otherwise it's hard to review code against it."
}
] | [
{
"body": "<p>There are three places where numbers may be missing:</p>\n\n<ul>\n<li>before the first number in the array ;</li>\n<li>inside the array ;</li>\n<li>after the last element in the array.</li>\n</ul>\n\n<p>Here is what I would do:</p>\n\n<pre><code>static void findMissingNumbers(int[] a, int first, int last) {\n // before the array: numbers between first and a[0]-1\n for (int i = first; i < a[0]; i++) {\n System.out.println(i);\n }\n // inside the array: at index i, a number is missing if it is between a[i-1]+1 and a[i]-1\n for (int i = 1; i < a.length; i++) {\n for (int j = 1+a[i-1]; j < a[i]; j++) {\n System.out.println(j);\n }\n }\n // after the array: numbers between a[a.length-1] and last\n for (int i = 1+a[a.length-1]; i <= last; i++) {\n System.out.println(i);\n }\n}\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre><code>public static void main(String[] args) {\n int a[] = { 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };\n findMissingNumbers(a, 0, 25);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:34:43.917",
"Id": "85645",
"Score": "4",
"body": "It it clearly stated that the array always starts with `0`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:47:39.370",
"Id": "85648",
"Score": "5",
"body": "And I'm pretty sure that you can't have missing numbers at the end. The upperbound is defined as the last element it seems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:06:12.503",
"Id": "85655",
"Score": "2",
"body": "You are probably (both) right, but I have been burnt so often with poorly stated problems that I am now over-cautious. I saw *First and last terms will be given*: where ? In the array, or separately ? Also, *Array always starts with zero* could mean that the first int is always 0, or that the index of the first element is 0, as opposed to 1 in some languages. I would expect the first interpretation to hold if the problem statement is well written, but it is rarely the case. Again, I suppose you are both right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T08:51:37.120",
"Id": "85747",
"Score": "0",
"body": "This is wrong. < is a binary operator, which is prohibited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:24:59.543",
"Id": "85791",
"Score": "2",
"body": "@Sentinel `less than` is a binary operator? I'm pretty sure the question is referring to [Java bitwise operators](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T07:39:36.230",
"Id": "85963",
"Score": "1",
"body": "@Sentinel I am not really sure about the binary operator restriction. Is it possible to do without it? Can you give an example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T07:49:23.430",
"Id": "85964",
"Score": "1",
"body": "What can you possibly do without any binary operator, if it is really intended to mean any 2-argument operator (as opposed to bitwise operator) ? For starters, the data is in an array, and any loop on an array requires a binary operator (affectation) to initialize the counter and another one (a comparison) to check if the bound is reached. Also, the OP talks about summation (not sure if it is in the actual interview question or a comment) but of course, + is a binary operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T09:09:33.393",
"Id": "85971",
"Score": "0",
"body": "Yeah I added a comment to the question - I think the question is badly phrased and the author is coming from a maths background. \"Binary Operator\" in maths refers to a operations like set subtraction, which can be done using Java Streams, Linq, SQL, etc. In programming it means + , < ..So we can only assume the author meant \"do not use set operations\" etc.(I come from a C# background, so using Linq you can use a syntax like Enumerable.Except(Enumerable) to show the missing values, and in Java I should imagine that whatever equivalent could be used if you wanted to avoid true binary operators )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T09:15:24.373",
"Id": "85972",
"Score": "0",
"body": "So for example: http://www.techopedia.com/definition/23953/binary-operator versus http://en.wikipedia.org/wiki/Binary_operation I think the author meant set binary operations, though the author badly screwed up the question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T12:08:16.843",
"Id": "85989",
"Score": "0",
"body": "@Zoyd I can \"easily\" iterate through an array in Java or C# without doing a single bounds check ;-) (well with an extended for loop that's actually really easy, but otherwise `ArrayOutOfBoundsException`s exist) Incrementing the counter without any binary operation is obviously impossible if we define \"binary operation\" as \"changing some bits\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-20T22:17:01.387",
"Id": "158150",
"Score": "0",
"body": "@Zoyd Is the time complexity of this algorithm O(n) or O(n^2)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-22T06:47:38.467",
"Id": "158412",
"Score": "1",
"body": "@user224567893 Each element in the array is reached exactly once, so O(n). Of course it also depends on the number of missing numbers (see discussion below)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:53:39.977",
"Id": "48760",
"ParentId": "48756",
"Score": "14"
}
},
{
"body": "<p>You can use logic to compare current and previous number. If the current value is greater than the previous by more than 1, then add 1 to the current value for length = difference value.</p>\n\n<pre><code>int prev = a[0];\nint current = 0;\n\nfor(int i=1;i<a.length;i++)\n{\n current = a[i];\n int differenceValue = current-prev;\n if(differenceValue > 1)\n {\n for(int j=1;j<differenceValue;j++)\n System.out.println(\"Missing Value : \"+(prev+j));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:56:27.803",
"Id": "48762",
"ParentId": "48756",
"Score": "3"
}
},
{
"body": "<p>Regarding your current code:</p>\n<h1>Public or private</h1>\n<p>You have three <code>public static</code> variables, but your <code>findMissingNumbers</code> method is <code>private</code>. It would be <em>better</em> having it the other way around. You wouldn't want outside code to modify your static variables, those are meant to be used only by your <code>findMissingNumbers</code> method.</p>\n<p>The <code>findMissingNumbers</code> method that you provide is meant to be a method that provides some calculations, it should be able to be called from other classes - hence it should be <code>public</code>.</p>\n<h1>Naming</h1>\n<p><code>boolean flag = false;</code> It's a boolean, of course it's a flag! What is the flag used for? Reading this variable name now doesn't help me understand the variable's purpose at all. It should describe why it is being used.</p>\n<h1>Static variables</h1>\n<pre><code>public static int count = 0;\npublic static int position = 0;\npublic static boolean flag = false;\n</code></pre>\n<p>Having static variables are usually only used for constants. Are these variables supposed to be constants? Constants should be marked <code>final</code>. If you would mark them final you will quickly see that you will get compiler errors on <code>count</code> and on <code>flag</code>, because you modify those values inside the method. There is a good reason to <strong>not use them as public static variables!!</strong></p>\n<p>Consider what would happen if your main method would look like this:</p>\n<pre><code>public static void main(String[] args) {\n int a[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };\n findMissingNumbers(a, position);\n\n int b[] = { 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 16, 17, 18, 20, 21, 23 };\n findMissingNumbers(b, position);\n}\n</code></pre>\n<p>After the first call to <code>findMissingNumbers</code>, your <code>public static</code> variables would have changed, which would modify the behavior of the second method call. Actually, in this case it would change the behavior in such a big way that it would cause a <code>StackOverflowError</code>. <strong>These two method calls should be independent.</strong></p>\n<p>By the way: I think that the <code>position</code> parameter that you send to the method is not needed, the method should start searching at zero by default.</p>\n<h1>Solution:</h1>\n<p>Use more <strong>local variables</strong>. <code>boolean flag</code> does not need to be a static variable. It should only be used within the method itself. It should be a local variable and initialized to false. Making this change actually solves the <code>StackOverflowError</code> that would occur when calling this method twice.</p>\n<p>The variables that is used inside the method, and gets changed, can be passed as parameters to the method. <code>position</code> is already a parameter so the public static variable is in fact not used, other than to provide a starting value to the method.</p>\n<p>To provide default values for the method, we can use a method that only calls the "real" method with some parameters.</p>\n<p>Here is a better implementation with these flaws fixed of your code. Note that one of the <code>findMissingNumbers</code> methods are <code>public</code> (as it is the one that is meant to be called), while one remains <code>private</code>. Also note the improved variable names, and how the parameters are passed between the methods - removing the big flaw of static variables.</p>\n<pre><code>public static void main(String[] args) {\n\n int a[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };\n findMissingNumbers(a);\n \n int b[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };\n findMissingNumbers(b);\n\n}\n\nprivate static void findMissingNumbers(int values[], int position, int count) {\n boolean foundMissingNumber = false;\n if (position == values.length - 1)\n return;\n\n for (; position < values[values.length - 1]; position++) {\n\n if ((values[position] - count) != position) {\n System.out.println("Missing Number: " + (position + count));\n foundMissingNumber = true;\n count++;\n break;\n }\n }\n\n if (foundMissingNumber) {\n findMissingNumbers(values, position, count);\n }\n}\n\npublic static void findMissingNumbers(int values[]) {\n findMissingNumbers(values, 0, 0);\n}\n</code></pre>\n<p>Another improvement that would be helpful to make is to let your methods <strong>return</strong> the missing numbers, instead of doing the output inside the method. Consider for example if you would want to calculate the sum of the missing numbers, or the sum of the squares of the missing numbers. Currently, you would perhaps do some <strong>code duplication</strong> (which is a known <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"noreferrer\">code smell</a>) to do this, but if you let your methods return the missing numbers, you would not need to do any code duplication. I'd recommend looking into a <code>ArrayList<Integer></code> for returning the values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T08:58:30.757",
"Id": "85749",
"Score": "0",
"body": "Wrong again. You are using binary operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:05:38.207",
"Id": "85750",
"Score": "6",
"body": "@Sentinel I wasn't trying to fix that problem, I was trying to perform a decent review of the OP's code, which many of the other answers haven't done (instead, most just provided \"Here's what I would do\"), so I don't consider this review to be \"wrong\" at all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T11:57:36.407",
"Id": "48769",
"ParentId": "48756",
"Score": "17"
}
},
{
"body": "<p>From a once over, possibly repeating some of the other answers:</p>\n\n<ul>\n<li><code>static</code> -> I don't see a good reason</li>\n<li>You are mixing computation and output, for interviews, that's a strike against you</li>\n<li><code>main</code> gets called with an array of arguments, for extra points in an interview I would have checked for arguments and use those</li>\n<li>You have zero comments, and some tricky parts, strike 2</li>\n<li><code>flag</code>.. -> that is too generic a name</li>\n<li><code>position</code> -> seems like a useless <code>static</code> actually, you could just do <code>findMissingNumbers(a, 0);</code></li>\n<li>From an OO perspective you would want to re-use that code, that'll be hard if your one interesting method is <code>private</code> ;)</li>\n<li>The questions states : <em>First and last terms will be given.</em> You are not using any first or last term in your code, strike 3</li>\n</ul>\n\n<p>I like to think I can read Java pretty okay. But I can't figure out what your code does. You have a problem when it is easier to run your code through a debugger to see what it does than simply reading it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:37:49.340",
"Id": "48774",
"ParentId": "48756",
"Score": "3"
}
},
{
"body": "<p>The problem as stated was:</p>\n\n<blockquote>\n <p>There is an sorted array. You need to find all the missing numbers. Write the complete code, without using any generics or inbuilt function or binary operators. First and last terms will be given. Array will be sorted. Array always starts with zero.</p>\n</blockquote>\n\n<p>When I ask questions like this in interviews, one of the things that I'm looking for is <em>can the candidate read a specification and make good decisions on implementing it?</em> The spec says what the inputs are and what the outputs are, so I would expect that somewhere in the code there would be a method with signature</p>\n\n<pre><code>int[] findMissingElements(int[] elements, int first, int last)\n</code></pre>\n\n<p>Note that the method is not <code>void</code>. This idea that a method prints out its result is found only in interviews and college assignments; it is nowhere found in industry.</p>\n\n<p>I would also like to see some verification of the <em>method preconditions</em> given. If the method is private then an assertion is appropriate. I'd also like to see the candidate take initiative to add some more preconditions that I did not give. I often give <em>underspecified</em> problems to see how the candidate deals with ambiguity: by asking clarifying questions, or by ignoring the problem and hoping for the best. In this case it is not stated that <code>first</code> is less than or equal to <code>last</code> but it seems reasonable to assume that.</p>\n\n<pre><code>int[] findMissingElements(int[] elements, int first, int last)\n{\n assert(elements.Count > 0);\n assert(isSorted(elements));\n assert(elements[0] == 0);\n assert(first <= last); \n</code></pre>\n\n<p>If the method is public then these should be <code>if(!precondition) throw ...</code> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:13:08.457",
"Id": "85673",
"Score": "2",
"body": "+1 `int[] findMissingElements(int[] elements, int first, int last)` My thoughts exactly. Separation of concerns. Input array and resulting array with another method to print to screen."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T08:52:27.383",
"Id": "85748",
"Score": "0",
"body": "This is also wrong. You are using binary operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-15T22:53:34.717",
"Id": "197718",
"Score": "1",
"body": "@Sentinel: by \"binary operators\" I understood the original poster to mean bitwise arithmetic operations on integers, not operators that take two operands. It is hard to see how the problem could possibly be solved in a program that uses no operators that take two operands."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:42:56.330",
"Id": "48775",
"ParentId": "48756",
"Score": "33"
}
},
{
"body": "<p>Just a few thoughts on how you might improve your algorithm as stated:</p>\n\n<ol>\n<li>The question doesn't state that there will always be a missing number. So might it be good (given that the first value is guaranteed to be 0 so <code>array[0] == 0</code>) then if <code>array[n] != n</code> you have 'missing' values.</li>\n<li>If we accept that we have missing values in that case, then the difference between n and the value stored in <code>array[n]</code> tells us how many 'missings' we have.</li>\n</ol>\n\n<p>Those two bits of information would allow us to truncate your algorithm to:</p>\n\n<ol>\n<li>Do no work if there are no missing values.</li>\n<li>Stop work as soon as it finds the requisite number of 'missings'.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:56:29.893",
"Id": "85650",
"Score": "0",
"body": "+1, it is actually two very valid points that can have significant effect for some cases! For example, having an array of one million length where the only missing number is at the beginning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-16T07:52:53.333",
"Id": "197766",
"Score": "0",
"body": "Specification Lawyering: Duplicate values are not rules out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:51:12.893",
"Id": "48778",
"ParentId": "48756",
"Score": "9"
}
},
{
"body": "<p>In addition to comments about static (global variables...), naming variables correctly (Boolean flag) and other tidbits that others have mentioned, I think <strong>two things</strong> haven't been mentioned: Code doesn't meet spec, and it's missing summation formula option.</p>\n\n<p><strong>Your code doesn't meet the specs as listed.</strong></p>\n\n<p>The spec asks for output: </p>\n\n<blockquote>\n <p>Missing number(s): 5, 16, 17, 19, 22.</p>\n</blockquote>\n\n<p>Your code however shows: </p>\n\n<pre><code>Missing Number: 5 \nMissing Number: 16 \nMissing Number: 17 \nMissing Number: 19 \nMissing Number: 22\n</code></pre>\n\n<p>That's not the right output.</p>\n\n<p>You should pair @EricLippers suggest of a method that uses</p>\n\n<pre><code>int[] findMissingElements(int[] elements, int first, int last)\n</code></pre>\n\n<p>with a secondary method to print out the resulting array</p>\n\n<pre><code>void printElement(int[] elements)\n</code></pre>\n\n<hr>\n\n<pre><code>public static void main(String[] args) {\n int a[] = { 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23 };\n int b[] = findMissingNumbers(a, 0, 25);\n printArrayToScreen(b[]);\n}\nint[] findMissingElements(int[] elements, int first, int last) {\n ...\n}\nvoid printArrayToScreen(int[] elements){\n ...\n}\n</code></pre>\n\n<p>It separates the responsibilities. It will make future changes easier </p>\n\n<ul>\n<li>What happens when you need to change the algorithm but don't want to affect the printing? </li>\n<li>Add another method for unsorted arrays? </li>\n<li>Add tests for the algorithm? For the printing?</li>\n<li>Print to screen?</li>\n<li>Format for Website in HTML</li>\n<li>Send to another process/application</li>\n</ul>\n\n<p><strong>Its missing summation formula option</strong> </p>\n\n<blockquote>\n <p>If its single missing term, we can calculate the required total using summation formula, and find the difference between the actual total. Which gives the missing term.</p>\n</blockquote>\n\n<p>IF the array is missing one item, use summation formula to determine missing item:</p>\n\n<pre><code>a[] = {0,1,3}\n4 = `1,3` = 1 + 3\n6 = 1 + 2 + 3\n2 = 6 - 4\n2 is *the* missing number\n</code></pre>\n\n<p>That could be easier than going through an unknown number of elements. programmers like options after all :)</p>\n\n<pre><code>public static void main(String[] args) {\n int start = 0;\n int end = 5;\n int a[] = {0, 1, 3, 4, 5};\n b[] = findMissingNumbers(a, start, end);\n printArrayToScreen(b[]);\n}\nint[] findMissingNumbers(int[] elements, int first, int last) {\n // Length is End+1 with 0 added. Are we only missing one item?\n int numMissing = a.Length - (last + 1);\n if (numMissing = 1) return findMissingNumber(a, start, end);\n // Otherwise, find missing numbers\n ....\n}\nint[] findMissingNumber(int[] elements, int first, int last) {\n ...\n}\nvoid printArrayToScreen(int[] elements){\n ...\n}\n</code></pre>\n\n<p>You want to separate the methods so you can change A without affecting B and A can reused elsewhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T20:29:35.223",
"Id": "85715",
"Score": "0",
"body": "Thanks for the edit. Also, adding Summation Formula notes, since I think that might be an issue as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:26:55.213",
"Id": "48791",
"ParentId": "48756",
"Score": "5"
}
},
{
"body": "<p>The other answers about style and encapsulation are correct, but they miss an important optimization. Given a number of missing values m, and a total array length n, your solution and the others on this page return in O(n) time. <strong>You can actually do this in just O(m log n) time.</strong></p>\n\n<p>The main insight here is that given the length of the <em>sorted</em> input array, you can tell how many numbers are missing for any given set of endpoints. If the number of indexes matches the number of expected values (i.e. 10 numbers expected in an array of length 10), you can safely assume that no numbers are missing.</p>\n\n<p>Therefore, if you bisect the array recursively, like in binary search, then it should be easy to tell if either half contains no missing numbers, and only investigate the halves that don't.</p>\n\n<pre><code>0 1 2 4 5 7 8 9 10 11 12 13 14 15 // missing 3 and 6\n[-----------] [-----------------]\n7 indices, 7 indices,\n9 values: 7 values\n2 missing 0 missing: do not evaluate!\n\n0 1 2 4 5 7 8\n[-----] [---]\n4 idxs 3 idxs\n5 vals 4 vals\n1 msng 1 msng\n</code></pre>\n\n<p>It follows that your recursive function should look roughly like this:</p>\n\n<pre><code>int[] missingValues(int[] inputArray, int startIndex, int endIndex, int min, int max)\n</code></pre>\n\n<p>...which is left as an exercise to the reader. :) Naturally, if there are a lot of missing numbers, this algorithm might not beat an O(n) algorithm, but if <code>m</code> is much less than <code>log2(n)</code> this is by far a better algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T08:40:52.663",
"Id": "85968",
"Score": "0",
"body": "Strictly speaking m <= n, so O(mlogn) is O(nlogn), which is worse than O(n). It is better only when m < n/logn. So use only when you can guarantee that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T16:05:11.537",
"Id": "86022",
"Score": "0",
"body": "@user568109 Very true, as mentioned in my last paragraph; luckily, calculating m and n is simple and O(1). It shouldn't be that surprising that the best algorithm varies depending on the number of needles and size of the haystack."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T23:59:18.987",
"Id": "48892",
"ParentId": "48756",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48760",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:44:07.477",
"Id": "48756",
"Score": "30",
"Tags": [
"java",
"array",
"interview-questions",
"search"
],
"Title": "Find all the missing number(s)"
} | 48756 |
<p>I have made a program in C++ simulating a dictionary with very basic functionality. I do not have much experience in file handling with C++. Also, I want it to run on Linux and Windows.</p>
<p>It would be great if you could review/improve it on these things: </p>
<ol>
<li>The file handling part of the code </li>
<li>Detecting whether the program is being compiled on Windows or Linux</li>
<li>Code readability (variable/function naming)</li>
<li>Displaying error messages</li>
<li>Removing redundant code</li>
<li>Improving fault-tolerance of the code</li>
<li>C++ standard practices (I promise I will remove <code>using namespace std;</code> later)</li>
<li>Any other general optimization improvement</li>
</ol>
<p>Here is the code: </p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#include<Debug.h>
#endif
//*********************************************************************************************
// Global Declarations begin...
#if defined linux || defined __linux__ || defined __linux // Linux
const char* config_path=strcat(getenv("HOME"),"/.dict_config.txt"); // Path to store configuration File which will contain location of dictionary and its backup on Linux...
const char* clear_screen="reset";
#elif defined __WIN32 || defined __WIN64 // Windows
const char* config_path=strcat(getenv("USERPROFILE"),"\\My Documents\\dict_config.txt"); // Path to store configuration File which will contain location of dictionary and its backup on Windows...
const char* clear_screen="cls";
#endif
map<string,string> dictionary,dictionary_bak; // The underlying Data Structure for dictionary...
char dict_path[1001]; // dict_path stores the location of the dictionary..
char bak_dict_path[1001]; // bak_dict_path stores the location of the backup dictionary..
// Global Declarations end...
//**********************************************************************************************
// Check if a file having the address "path" exists..
bool fileExists(const char* path)
{
ifstream fin(path);
return fin.good();
}
// Check if the location of a file having the address "path" is a valid location..
bool locationExists(const char* path)
{
if(fileExists(path)) // A file already exists there.. so OK..
return true;
ofstream fout(path); // Try to create a file with write permissions...
if(fout.good()) // File is writable...
{
fout.close();
if(remove(path)) // Remove the file which was created...
{
perror("Fatal Error ");
cout<<"Unable to remove file - \""<<path<<"\"\nExiting\n"; // Permission Errors most probably...
exit(1);
}
return true;
}
return false;
}
// Input locations of dictionary and its backup from the user...
void getLocations()
{
while(1)
{
cout<<"\nEnter the path to store dictionary\n[ For example - /home/anmol/Documents/dictionary.txt ]\n";
cin.getline(dict_path,1000);
if(!locationExists(dict_path))
{
perror("Error ");
cout<<"Unable to create file at - \""<<dict_path<<"\"\nPlease Enter an alternate location\n";
}
else
{
break;
}
}
while(1)
{
cout<<"\nEnter the path to store backup of dictionary\n[ For example - /home/anmol/Documents/dictionary_bak.txt ]\n";
cin.getline(bak_dict_path,1000);
if(!locationExists(bak_dict_path))
{
perror("Error ");
cout<<"Unable to create file at - \""<<bak_dict_path<<"\"\nPlease Enter an alternate location\n";
}
else
{
break;
}
}
}
// Check if the configuration file is present or not
// If it is present, then read it and check if the path to the dictionary file is valid or not...
void checkConfig()
{
if(!locationExists(config_path))
{
perror("Fatal Error ");
cout<<"Unable to create configuration file at - \""<<config_path<<"\"\nExiting\n";
exit(1);
}
if(!fileExists(config_path))
{
ofstream fout(config_path); // Create a new configuration file...
if(fout.good())
{
fout<<"\n\t\t\tDo not modify this file!!!!\n\n#"; // Write warning message...
getLocations(); // Get the locations of dictionary and its backup...
fout<<dict_path<<"\n"<<bak_dict_path<<"\n"; // Write the locations to the config file...
}
else
{
perror("Fatal Error ");
cout<<"Unable to create configuration file at - \""<<config_path<<"\"\nExiting\n";
exit(1);
}
}
ifstream fin(config_path);
fin.ignore (std::numeric_limits<std::streamsize>::max(),'#'); // Eat the warning message...
fin.getline(dict_path,1000); // Input the location of the dictionary from the config file into "dict_path"...
if(!locationExists(dict_path))
{
perror("Fatal Error ");
cout<<"The path for dictionary - \""<<dict_path<<"\" is invalid\nTry restarting the program\n";
if(remove(config_path)) // Remove the configuration file so that getLocations() gets invoked again...
{
perror("Fatal Error ");
cout<<"Unable to remove file - \""<<config_path<<"\"\nExiting\n"; // Permission Errors most probably...
}
exit(1);
}
fin.getline(bak_dict_path,1000); // Input the location of the backup dictionary from the config file into "bak_dict_path"...
if(!locationExists(bak_dict_path))
{
perror("Fatal Error ");
cout<<"The path for dictionary backup- \""<<bak_dict_path<<"\" is invalid\nTry restarting the program\n";
if(remove(config_path)) // Remove the configuration file so that getLocations() gets invoked again...
{
perror("Fatal Error ");
cout<<"Unable to remove file - \""<<config_path<<"\"\nExiting\n"; // Permission Errors most probably...
}
exit(1);
}
fin.close();
}
// Get the contents of the dictionary from "path" and store it in "mapping"..
void readFromFile(const char* path,map<string,string> &mapping)
{
if(!fileExists(path)) // File is not present at "path"...
{
cout<<"Creating a new file at - "<<path<<"\n";
ofstream fout(path); // Create a blank file at "path" to store the dictionary/dictionary_bak..
if(!fout.good())
{
perror("Fatal Error ");
cout<<"Unable to create a new file - \""<<path<<"\"\nExiting\n";
exit(1);
}
fout.close();
}
mapping.clear();
string word,meaning;
ifstream fin(path);
while(1)
{
getline(fin,word,'\n'); // A word is terminated by a '\n'..
if(fin.eof()) // End-Of-File reached..
break;
if(word.empty())
continue;
getline(fin,meaning,'$'); // A meaning is terminated by a '$'...
if(meaning.empty())
continue;
fin.get(); // Take the remaining '\n'..
mapping[word]=meaning;
}
}
// Save the dictionary to the file..
void writeToFile(const char* path,map<string,string> &mapping)
{
ofstream fout;
fout.open(path);
if(!fout.good()) // Unable to open file for writing...
{
perror("Fatal Error ");
cout<<"Unable to create a new file - \""<<path<<"\"\nExiting\n";
exit(1);
}
for(const auto& it:mapping)
{
fout<<it.first<<"\n"<<it.second<<"$\n";
// Word terminated by a '\n'..
// Meaning terminated by a "0\n"..
}
}
inline void show(const map<string,string> &mapping=dictionary,int at_a_time=0)
{
// Show the contents of "mapping" with "at_a_time" word-meaning pairs displayed at a time...
int i=1;
cout<<"\t\t\t"<<"No. of Entries = "<<mapping.size()<<"\n\n";
if(at_a_time==0) // Show all the contents at once..
at_a_time=mapping.size();
for(const auto& it:mapping)
{
cout<<i<<"). "<<it.first<<"\n\n"<<it.second<<"\n";
if( (i%at_a_time == 0) && i!=(int)mapping.size() )
{
cout<<"\t\tPress <Enter> to resume.. ";
cin.get(); // Wait for the user...
}
++i;
}
}
// Retrieve the part of "s" before a " " is encountered..
inline string beforeSpace(const string &query)
{
stringstream ss(query);
string ans="";
ss>>ans;
return ans;
}
// Retrieve the part of "s" after a " " is encountered..
inline string afterSpace(const string &query)
{
stringstream ss(query);
string ans="";
ss>>ans>>ans;
return ans;
}
// Check if the query recieved is a keyword ..
inline bool isReserved(string query)
{
transform(query.begin(),query.end(),query.begin(),::tolower);
static set<string> reserved= {"help","clear","rebuild","show","bak","showbak","loadbak","test","refresh","remove"};
return reserved.find(beforeSpace(query))!=reserved.end();
}
// Show the help menu..
void showHelp()
{
static map<string,string> help;
help["\n\"clear\""]="Clear screen...\n";
help["\n\"rebuild\""]="Delete all the present entries of the dictionary...\n";
help["\n\"show [no. of entries at a time]\""]="Show all the present entries of the dictionary...\n";
help["\n\"bak\""]="Backup all the present entries of the dictionary...\n";
help["\n\"showbak [no. of entries at a time]\""]="Show all the present entries of the Backup dictionary...\n";
help["\n\"loadbak\""]="Replace the current dictionary with the most recent backup...\n";
help["\n\"test\""]="Take a self-test by showing any randomly chosen word from the dictionary and making you guess its meaning...\n";
help["\n\"refresh\""]="Reload the dictionary from the file...\n";
help["\n\"remove <word>\""]="Remove a word...\n";
for(const auto& it:help)
{
cout<<it.first<<" -- "<<it.second;
}
}
// Empty the dictionary..
void rebuild()
{
dictionary.clear();
cout<<"Dictionary cleared!!\n\n";
}
// Remove a word-meaning pair from the dictionary..
void removeWord(const string& word)
{
decltype(dictionary.begin()) it;
if((it=dictionary.find(word))!=dictionary.end())
{
dictionary.erase(it);
cout<<word<<" erased!!\n";
}
else
{
cout<<"Word not found!!\n\n";
}
}
// Show a random word-meaning pair from the dictionary..
void showRand()
{
if(!dictionary.size()) // Dictionary is empty..
return;
decltype(dictionary.begin()) it=dictionary.begin();
advance(it,rand()%dictionary.size());
cout<<"\t\t\t\""<<it->first<<"\"\n\t\tPress <Enter> to show meaning.. ";
cin.get(); // Wait for an "enter"...
cout<<"\n\n"<<it->second<<"\n";
}
// Run the query..
void process(const string &query)
{
string before_space=beforeSpace(query);
string after_space=afterSpace(query);
transform(before_space.begin(),before_space.end(),before_space.begin(),::tolower);
if(before_space=="help")
{
showHelp();
}
else if(before_space=="rebuild")
{
rebuild();
}
else if(before_space=="show")
{
show(dictionary,atoi(after_space.c_str()));
}
else if(before_space=="clear")
{
system(clear_screen);
// The compiler keeps warning the value returned here is unused, but I do not know how to use it !!!
}
else if(before_space=="bak")
{
writeToFile(bak_dict_path,dictionary);
}
else if(before_space=="showbak")
{
readFromFile(bak_dict_path,dictionary_bak);
show(dictionary_bak,atoi(after_space.c_str()));
}
else if(before_space=="loadbak")
{
readFromFile(bak_dict_path,dictionary);
writeToFile(dict_path,dictionary);
}
else if(before_space=="test")
{
showRand();
}
else if(before_space=="remove")
{
removeWord(after_space);
}
else if(before_space=="refresh")
{
readFromFile(dict_path,dictionary);
}
}
// Input a Word/Query..
inline string getQuery()
{
string query="";
cout<<"\nEnter query.. ";
getline(cin,query,'\n');
return query;
}
// Input the meaning of a word..
inline string getMeaning()
{
string meaning="";
cout<<"\nEnter meaning.. ";
char c;
while(1)
{
c=cin.get();
if(meaning.size()&&meaning[meaning.size()-1]=='\n'&&c=='\n')
break;
meaning+=c;
}
return meaning;
}
// Add a word to the dictionary..
void addWord(const string &word)
{
decltype(dictionary.begin()) it;
if((it=dictionary.find(word))!=dictionary.end())
{
cout<<"'"<<it->first<<"' already exists!!...\n\n"<<it->second<<"\n\nWant to overwrite?? (y/n) ";
char option;
cin>>option;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
if(option=='y'||option=='Y')
{
string temp=getMeaning();
if(temp!=string("\n"))
it->second=temp;
}
}
else
{
string temp=getMeaning();
if(temp!=string("\n"))
dictionary[word]=temp;
}
}
// Main starts from here...
int main()
{
srand(time(NULL)); // For showRand()...
checkConfig();
readFromFile(dict_path,dictionary);
while(1)
{
string query=getQuery();
if(query=="") // Exit if the query entered is blank...
break;
else if(isReserved(query))
process(query);
else
addWord(query);
}
writeToFile(dict_path,dictionary);
}
</code></pre>
<p>In case you want to read a little more about how it should work, here is the <a href="https://github.com/jaggi1234/Dictionary" rel="nofollow">Github Link</a> .</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:38:51.283",
"Id": "85662",
"Score": "0",
"body": "Just two little things I noticed while scrolling over your code. 1) When comparing an `std::string` with a C-style string you use `x != string(\"y\")` at some locations. This is a) inconsistent as you use `x != \"y\"` at other points and b) inefficient as you are building an `std::string` where it is not necessary (there are overloads for C-style strings for `operator==`, `operator!=`, `compare()`, ...). 2) To check that an `std::string` is empty you sometimes use `x == \"\"` and sometimes `x.empty()`. Here, too, stay consistent. I generally prefer `empty()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:23:59.027",
"Id": "85692",
"Score": "1",
"body": "This is really C code pretending to be C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:32:31.177",
"Id": "86538",
"Score": "0",
"body": "Sorry for replying so late. My practical exams had been preponed."
}
] | [
{
"body": "<p>The main problem with this code is that it is not C++.</p>\n\n<p>It is basically a set of functions (ie. Just C code that happens to use some C++ structures and objects in passing). There is nothing inherently C++ about this code.</p>\n\n<p>You should never be including this.</p>\n\n<pre><code>#include<bits/stdc++.h> \n</code></pre>\n\n<p>Its an implementation file. Stick to the header files defined by the standard (they don't have <code>.h</code> on the end).</p>\n\n<p>You covered this yourself:</p>\n\n<pre><code>using namespace std; \n</code></pre>\n\n<p>Don't conditionally include headers.</p>\n\n<pre><code>#ifdef DEBUG \n#include<Debug.h> \n#endif \n</code></pre>\n\n<p>If things are turned on/off by Debug it should be done inside the <code>Debug.h</code> file. As a user of the file I should not need to remember that I conditionally include it.</p>\n\n<p>Don't put variables inside conditional blocks. You put the values that can be defined in the platform specific part but the variable declaration then use the definitions you use. and you should always put a check for untested platforms so that when it is ported it is easy to find the places that need to be ported.</p>\n\n<pre><code>#if defined linux || defined __linux__ || defined __linux // Linux \nconst char* config_path=strcat(getenv(\"HOME\"),\"/.dict_config.txt\"); // Path to store configuration File which will contain location of dictionary and its backup on Linux... \nconst char* clear_screen=\"reset\"; \n#elif defined __WIN32 || defined __WIN64 // Windows \nconst char* config_path=strcat(getenv(\"USERPROFILE\"),\"\\\\My Documents\\\\dict_config.txt\"); // Path to store configuration File which will contain location of dictionary and its backup on Windows... \nconst char* clear_screen=\"cls\"; \n#endif \n</code></pre>\n\n<p>This is how I would do it:</p>\n\n<pre><code>#if defined linux || defined __linux__ || defined __linux // Linux \n#define PLATFORM_CONFIG_PATH strcat(getenv(\"HOME\"),\"/.dict_config.txt\")\n#define PLATFORM_RESET_COMMAND \"reset\"\n\n#elif defined __WIN32 || defined __WIN64 // Windows \n#define PLATFORM_CONFIG_PATH strcat(getenv(\"USERPROFILE\"),\"\\\\My Documents\\\\dict_config.txt\")\n#define PLATFORM_RESET_COMMAND \"cls\"\n\n#else\n#error \"Untested platform\"\n#endif \n\n\n/*\n * Path to store configuration File\n * which will contain location of dictionary and its backup on Linux...\n */\nconst char* config_path = PLATFORM_CONFIG_PATH; \nconst char* clear_screen = PLATFORM_RESET_COMMAND; \n</code></pre>\n\n<p><strong>PS</strong> The above code is also broken.<br>\nThe <code>strcat()</code> command assumes there is enough space in the destination. This is not true. Additionally the result of <code>getenv()</code> is not modifiable (even if does return <code>char*</code> (C is not know for its const correctness)). So copy data onto the end of the string is not allowed</p>\n\n<p>Looks like this is your main object. Global mutable state is a bad idea. Looks like this should be a class and all the following methods members of that class. It also makes the re-using the object easier (Note: The above is <code>config_path</code> is not mutable so it is OK to make it global).</p>\n\n<pre><code>map<string,string> dictionary,dictionary_bak; // The underlying Data Structure for dictionary... \nchar dict_path[1001]; // dict_path stores the location of the dictionary.. \nchar bak_dict_path[1001]; // bak_dict_path stores the location of the backup dictionary.. \n</code></pre>\n\n<p>If you are doing filesystem level stuff. It may be better to use file system API calls. </p>\n\n<pre><code>// Check if a file having the address \"path\" exists.. \nbool fileExists(const char* path) \n{ \n ifstream fin(path); \n return fin.good(); \n} \n</code></pre>\n\n<p>Technically the above does not test for existence. It tests if you can open <strong>AND</strong> read it. So the code is wrong based on the comments (and its name).</p>\n\n<p>Boost provides a cross platform API for file system access <code>boost::file_system</code>.</p>\n\n<p>I have a problem with the following. As depending on the state of the file system it returns different things.</p>\n\n<pre><code>// Check if the location of a file having the address \"path\" is a valid location.. \nbool locationExists(const char* path) \n{ \n if(fileExists(path)) // A file already exists there.. so OK.. \n return true; \n\n ofstream fout(path); // Try to create a file with write permissions... \n if(fout.good()) // File is writable... \n { \n fout.close(); \n if(remove(path)) // Remove the file which was created... \n { \n perror(\"Fatal Error \"); \n cout<<\"Unable to remove file - \\\"\"<<path<<\"\\\"\\nExiting\\n\"; // Permission Errors most probably... \n exit(1); \n } \n return true; \n } \n return false; \n} \n</code></pre>\n\n<ol>\n<li>Return true if the file exists.<br>\nActually: If the file exists and is readable (but misleading name).</li>\n<li>OR Return true if the File can be created as writable.<br>\nNote: Subtle difference between one and two (readable/writable)</li>\n<li>If not readable and writable but not deletable <code>exit(1)</code></li>\n<li>Otherwise return false.</li>\n</ol>\n\n<p>None of these conditions match the name of the function.<br>\nAlso I would prefer it throw an exception rather than call <code>exit(1)</code>. The result is probably the same (application termination). But this would allow you to handle all logging in the same way (catch all exceptions in main and have the same logging applied to all points in your code). Or potentially the exception could be fixed.</p>\n\n<p>Don't use this version of getline.</p>\n\n<pre><code> cin.getline(dict_path,1000); \n</code></pre>\n\n<p>What happens if the user enters a really long path. Prefer to use <code>std::getline()</code>. This version reads from a stream into a string that is auto resized to make room for user input.</p>\n\n<p>Don't manually close a file (let RAII do it). Unless you are explicitly checking for a close error and prepared to compensate for it.</p>\n\n<pre><code> fin.close(); \n</code></pre>\n\n<p>It is easier to put the read as part of the while condition (so that the loop is entered only if both reads succeed).</p>\n\n<p>A couple of other things to note (they may be intentional and if so they should be commented). If <code>word</code> is valid then an empty meaning causes both to be dropped (ie not put in the map). If <code>meaning</code> hits eof (ie there is none) you don't test for this (thus meaning is left unchanged) you don't exit the loop. This will put random (probably the last value) value into the map.</p>\n\n<pre><code> mapping.clear(); \n string word,meaning; \n ifstream fin(path); \n while(1) \n { \n getline(fin,word,'\\n'); // A word is terminated by a '\\n'.. \n if(fin.eof()) // End-Of-File reached.. \n break; \n if(word.empty()) \n continue; \n getline(fin,meaning,'$'); // A meaning is terminated by a '$'... \n if(meaning.empty()) \n continue; \n fin.get(); // Take the remaining '\\n'.. \n mapping[word]=meaning; \n } \n} \n</code></pre>\n\n<p>I would write it like this:</p>\n\n<pre><code> mapping.clear(); \n std::string word;\n std::string meaning; \n ifstream fin(path); \n while(std::getline(fin, word)) \n { \n if(word.empty()) \n continue; \n\n if (getline(fin,meaning,'$') && (!meaning.empty()) \n {\n mapping.insert(std::make_pair(word, meaning));\n // I believe C++11 has emplace for this.\n }\n fin.get(); // Take the remaining '\\n'.. \n } \n} \n</code></pre>\n\n<p>Your code also assumes that meaning is terminated by '$\\n'. I don't see the point in having a double set of character to terminate meaning. I would just make it '\\n' terminated.</p>\n\n<p>The keyword <code>inline</code> is usless. Don't use it unless the language requires. You don't need it here so don't use it.</p>\n\n<pre><code>inline void show(const map<string,string> &mapping=dictionary,int at_a_time=0) \n</code></pre>\n\n<p>This does not do what the comment (and the function name says).</p>\n\n<pre><code>// Retrieve the part of \"s\" before a \" \" is encountered.. \ninline string beforeSpace(const string &query) \n{ \n stringstream ss(query); \n string ans=\"\"; \n ss>>ans; \n return ans; \n} \n</code></pre>\n\n<p>This drops leading space. The returns the first white space separated word.</p>\n\n<p>This sort of says what it does (but not very accurately).</p>\n\n<pre><code>// Retrieve the part of \"s\" after a \" \" is encountered.. \ninline string afterSpace(const string &query) \n{ \n stringstream ss(query); \n string ans=\"\"; \n ss>>ans>>ans; \n return ans; \n} \n</code></pre>\n\n<p>It returns the second space separated word.</p>\n\n<p>Hmmm.\n decltype(dictionary.begin()) it; </p>\n\n<p>Easier to write:</p>\n\n<pre><code> auto it = dictionary.begin();\n</code></pre>\n\n<p>Hmm.</p>\n\n<pre><code> string before_space=beforeSpace(query); \n string after_space=afterSpace(query); \n\n // easier to write as:\n string before_space; \n string after_space;\n std::stringstream(query) >> before_space >> after_space;\n</code></pre>\n\n<p>Rather than have a big if statement.</p>\n\n<pre><code> transform(before_space.begin(),before_space.end(),before_space.begin(),::tolower); \n if(before_space==\"help\") \n { \n showHelp(); \n } \n else ......\n</code></pre>\n\n<p>Look up the <code>Command Pattern</code> this will make it much easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T14:06:15.300",
"Id": "86518",
"Score": "0",
"body": "1. *Its an implementation file. Stick to the header files defined by the standard (they don't have .h on the end).* I am compiling using these compiler flags -: `mingw32-g++.exe -O2 -Wshadow -Winit-self -Wredundant-decls -Wfloat-equal -Winline -Wunreachable-code -pedantic -std=c++11 -Wfatal-errors -Wextra -Wall` What other flags do I need to include to enforce the standards ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T14:30:05.480",
"Id": "86523",
"Score": "0",
"body": "*Don't conditionally include headers.* Thanks for the suggestion. I have instead changed my IDE's settings to include that header file from the command line using the compiler flag `-include`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T14:42:03.783",
"Id": "86524",
"Score": "0",
"body": "*PS The above code is also broken.\nThe strcat() command assumes there is enough space in the destination. This is not true. Additionally the result of getenv() is not modifiable (even if does return char* (C is not know for its const correctness)). So copy data onto the end of the string is not allowed* Is there any alternative correct way to implement this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T14:52:38.403",
"Id": "86525",
"Score": "0",
"body": "*Technically the above does not test for existence. It tests if you can open AND read it. So the code is wrong based on the comments (and its name).* Actually I wanted to check if I could read the file or not. Maybe I should change the function name to something like `bool isFileReadable(const char* path)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T14:59:08.947",
"Id": "86527",
"Score": "0",
"body": "`bool locationExists(const char* path)` Actually I want this function to create a new file with write pemissions if a file of the same name does not exist. If a file with the same name exists already, I want to check that it we can still write to the file. But since the only way of doing so in my knowledge is opening that file using `ofstream`, I have to successfully remove the file which was created by `ofstream fout(path);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:08:02.437",
"Id": "86530",
"Score": "0",
"body": "*What happens if the user enters a really long path. Prefer to use `std::getline()`.* But `std::getline()` does not work for C-strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:12:37.903",
"Id": "86532",
"Score": "0",
"body": "*Your code also assumes that meaning is terminated by '$\\n'. I don't see the point in having a double set of character to terminate meaning. I would just make it '\\n' terminated.* A meaning can have mutiple '\\n'- terminated lines. How will I differentiate the 2nd line of a meaning from the next word-meaning pair while reading the file?? Also, If the meaning entered is empty, I did want that word-meaning pair to be completely ignored. I am sorry I should have mentioned this in the code itself rather than in the README file in its github repository."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:18:36.887",
"Id": "86533",
"Score": "0",
"body": "*`mapping.insert(std::make_pair(word, meaning));`* Is it different from writing `mapping[word]=meaning;` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:21:24.320",
"Id": "86534",
"Score": "0",
"body": "*The keyword inline is usless. Don't use it unless the language requires. You don't need it here so don't use it.* How is it useless? I expect some functions to be called many times more than the rest of the functions. Won't the inlining make the program run faster in that case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:28:56.473",
"Id": "86536",
"Score": "0",
"body": "These are the warning flags I use: `-Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code` The only one I would add is `-Werror`. All my code compiles with **zero** warnings as warnings are really logical errors in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:32:26.007",
"Id": "86537",
"Score": "0",
"body": "Referencing strcat(). `This is not true`. **YES** it is. See any documentation of strcat() the dest **MUST** have enough space to hold src and dest strings. See [man strcat](http://linux.die.net/man/3/strcat). A better solution is not to use C-Strings. Use the C++ std::string all memory management will then be handled correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:34:24.630",
"Id": "86539",
"Score": "0",
"body": "`But std::getline() does not work for C-strings.`: So **STOP** using C-Strings they are a blight on a C++ code base. The memory management is not well defined. They are inefficient and a source of major bugs (as shown by your code)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:36:42.887",
"Id": "86542",
"Score": "0",
"body": "`map::insert` Vs `map::operator[]` Is it different. The result is the same. The insert is more efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:37:53.730",
"Id": "86544",
"Score": "0",
"body": "`inlining` will potentially make the code run faster but actually making the correct decision is usually done badly by humans (in fact humans were so bad at this it can actually make the code slower (the extra size of the code causes less of the program to be in memory and thus causes processor stalls slowing down the wall clock time). **SO** the keyword `inline` will have **no affect** on whether the compiler inlines the code (the compiler decides). All modern compilers ignore the keyword `inline` for `inlining purposes`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T15:43:14.710",
"Id": "86546",
"Score": "0",
"body": "`How will I differentiate the 2nd line of a meaning from the next word-meaning pair while reading the file??`: Always have the result on two lines. Just read one line for the key and one line for the value. I don't see why you think this is hard. std::getline() only reads up to the first '\\n' character."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T16:27:22.217",
"Id": "86554",
"Score": "0",
"body": "Isn't there any compiler flag which will throw an error on non - standard actions like including `#include<bits/stdc++.h>` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T16:30:46.013",
"Id": "86556",
"Score": "0",
"body": "I don't like using C-strings myself; I used them only because `std::fstream` takes only C-strings as input to the filename to open. Otherwise I'll have to to append `.c_str()` to the filename everytime while opening files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T16:35:08.310",
"Id": "86561",
"Score": "0",
"body": "Take an example -: Let the word entered by the user be `sentinel` and its entered meaning be `A soldier or guard whose job is to stand and keep watch.<Enter>\nStation a soldier or guard by (a place) to keep watch.<Enter>`. In this case, if I read the meaning by a single of `getline()`, I'll get only the first line of the meaning - \"*A soldier or guard whose job is to stand and keep watch.*\" The second line og the meaning won't be read. That is why I decided to terminate meaning by a `$`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T17:17:06.253",
"Id": "86571",
"Score": "0",
"body": "[Here](https://github.com/jaggi1234/Dictionary/blob/master/dictionary.txt) is a sample of how the word-meaning pairs are actually stored in the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T17:52:29.703",
"Id": "86573",
"Score": "0",
"body": "`I'll have to to append .c_str() to the filename everytime` Considering the downside to C-Strings I don't see this as an issue. In C++11 they fixed this and you can now use std::string for the filename but even so the cost of typing an extra five letters is insignificant compared to the cost of memory management of C-Strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T17:53:31.350",
"Id": "86574",
"Score": "0",
"body": "`Isn't there any compiler flag which will throw an error on non - standard actions`. No. How do you define something as non standard? There are a whole bunch of third party and C header files that you could be picking up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T17:57:56.017",
"Id": "86575",
"Score": "0",
"body": "This conversation has just been auto-flagged. If you'd like to continue, please take it to chat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T18:24:14.657",
"Id": "86579",
"Score": "1",
"body": "@AnmolSinghJaggi Loki has made many excellent points in this review, which may be overwhelming for you. Please take some time to research each point. Many of your follow-up queries would make good Stack Overflow questions, e.g. \"I wrote `const char* config_path=strcat(getenv(\"HOME\"),\"/.dict_config.txt\");` and was [told in a review](http://codereview.stackexchange.com/q/48759) that the code was broken. Why?\" Or, \"I was told not to `#include <bits/stdc++.h>` in my C++ program. What should I write instead, and why?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T18:57:35.393",
"Id": "86596",
"Score": "0",
"body": "@200_success Thank you for the advice. One last query, regarding this site's usage - How do you quote someone in the comments? Is putting the required text in italics; \"*quoted-text*\" correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T19:08:19.047",
"Id": "86602",
"Score": "0",
"body": "@AnmolSinghJaggi: http://stackoverflow.com/editing-help"
}
],
"meta_data": {
"CommentCount": "25",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:27:43.607",
"Id": "48813",
"ParentId": "48759",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>Do not pollute the global namespace. Put this stuff:</p>\n\n<pre><code>#if defined linux || defined __linux__ || defined __linux // Linux \nconst char* config_path=strcat(getenv(\"HOME\"),\"/.dict_config.txt\"); // Path to store configuration File which will contain location of dictionary and its backup on Linux... \nconst char* clear_screen=\"reset\"; \n#elif defined __WIN32 || defined __WIN64 // Windows \nconst char* config_path=strcat(getenv(\"USERPROFILE\"),\"\\\\My Documents\\\\dict_config.txt\"); // Path to store configuration File which will contain location of dictionary and its backup on Windows... \nconst char* clear_screen=\"cls\"; \n#endif\n</code></pre>\n\n<p>into its own namespace.<br>\nUsing your own namespace can help you avoid any possible name clashes.</p></li>\n<li><p>I could be wrong, but <code>#include<bits/stdc++.h></code> does not seem to be a standard, portable header. I would manually include all of the headers that you need instead of using it.</p></li>\n<li><p>In most cases, prefer <code>std::string</code> over <code>const char *</code>, especially for buffers. <code>std::string</code>, like all the other standard containers, manages its own memory and provides less headaches to use. </p>\n\n<p>Let's take a look at this code: </p>\n\n<pre><code>cout<<\"\\nEnter the path to store dictionary\\n[ For example - /home/anmol/Documents/dictionary.txt ]\\n\"; \ncin.getline(dict_path,1000);\n</code></pre>\n\n<p>Rather than worrying about buffer sizes, you could do something like this:</p>\n\n<pre><code>std::string strDictionaryPath ;\nstd::cout<<\"\\nEnter the path to store dictionary\\n[ For example - /home/anmol/Documents/dictionary.txt ]\\n\";\nstd::cin >> strDictionaryPath ;\n</code></pre></li>\n<li><p>Using C-functions in a C++ application is almost always the wrong thing to do. At the very minimum, you should not mix C-IO functions with C++-IO functions. </p>\n\n<p>Rather than using <code>perror</code>, write to <code>std::cerr</code> instead. If you really need the error message that <code>perror</code> gives, then take a look at this <a href=\"https://stackoverflow.com/questions/3320898/c-alternative-to-perror\">solution</a>.</p></li>\n<li><p>Avoid using <code>exit</code>. If anybody else has to use your code, then it would be very frustrating to have their software close whenever one of your functions fail. It would be better to throw an exception in most cases.</p></li>\n</ol>\n\n<p>Below I have a rather incomplete and somewhat messy interface. This is not the best way of doing this, it is just to give you an idea of how to do it the \"C++ way\". To keep things simple (for myself), I use an <code>std::vector</code> instead of an <code>std::map</code>, but once again, this is just to give you a rough idea on how to do this.</p>\n\n<p>For my own convenience, I did this all in a single file. You should break this up into multiple files. Here are the headers that I used:</p>\n\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <vector>\n</code></pre>\n\n<p>First, we would create a struct to store each dictionary entry.</p>\n\n<pre><code>struct DictionaryEntry\n{\n DictionaryEntry () ;\n DictionaryEntry (const std::string &word, const std::string definition) ;\n\n std::string word_ ;\n std::string definition_ ;\n};\n</code></pre>\n\n<p>For convenience, we'll implement a default constructor and a constructor that takes two arguments. Notice that we use a <a href=\"http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/\" rel=\"nofollow noreferrer\">constructor initialization list</a> with the second constructor.</p>\n\n<pre><code>DictionaryEntry::DictionaryEntry ()\n{\n}\n\nDictionaryEntry::DictionaryEntry (const std::string &word, const std::string definition) : word_(word), definition_(definition)\n{\n}\n</code></pre>\n\n<p>Then we overload a few operators. Please note that these are not member functions. Here is a good <a href=\"https://stackoverflow.com/questions/4421706/operator-overloading\">guide</a> for operator overloading.</p>\n\n<pre><code>// This will be useful for finding words in our dictionary.\nbool operator== (const DictionaryEntry &lhs, const DictionaryEntry &rhs)\n{\n return lhs.word_ == rhs.word_ ;\n}\n\n// This will be useful for sorting words in our dictionary.\nbool operator< (const DictionaryEntry &lhs, const DictionaryEntry &rhs)\n{\n return lhs.word_ < rhs.word_ ;\n}\n\n// This will be useful for saving dictionary entries to a file.\ntemplate <class Stream>\nStream& operator<< (Stream &os, const DictionaryEntry &de)\n{\n os << de.word_ << de.definition_ << \"$\" \"\\n\" ;\n return os ;\n}\n\n// This will be useful for extracting words from a file.\ntemplate <class Stream>\nStream& operator>> (Stream &is, DictionaryEntry &de)\n{\n is >> de.word_ ;\n std::getline (is, de.definition_, '$') ;\n return is ;\n}\n</code></pre>\n\n<p>Then we would create a dictionary class. Here's an idea of what the interface could look like. Please note that this interface is incomplete and not the greatest design, but it should get you going in the right direction. Also note, as I said before, I'm using <code>std::vector</code> just as an example here. I'll leave altering this class to use <code>std::map</code> as an exercise for you. </p>\n\n<pre><code>class Dictionary\n{\n typedef std::vector <DictionaryEntry>::const_iterator const_iterator ;\n\npublic:\n Dictionary () ;\n Dictionary (const std::string &file_path) ;\n ~Dictionary () ;\n\n const_iterator cbegin () const {\n return entries_.cbegin () ;\n }\n\n const_iterator cend () const {\n return entries_.cend () ;\n }\n\n void Insert (DictionaryEntry de) ;\n void Insert (const std::string &word, const std::string &definition) ;\n\n void Load (std::string file_path) ;\n void Save (const std::string &file_path) ;\n\n const_iterator LookupWord (const std::string &word) const ;\n\nprivate:\n bool valid_ ;\n std::string file_path_ ;\n std::vector <DictionaryEntry> entries_ ;\n};\n</code></pre>\n\n<p>In the second constructor for <code>Dictionary</code>, we attempt to load the file right away. This is somewhat similar to calling the constructor of an <code>std::ofstream</code>, but not quite.</p>\n\n<pre><code>Dictionary::Dictionary () : valid_ (false) \n{\n}\n\nDictionary::Dictionary (const std::string &file_path) : valid_ (false)\n{\n this->Load (file_path) ;\n}\n</code></pre>\n\n<p>If an exception is thrown for some reason, as long as our <code>Dictionary</code> contains valid values, our destructor will attempt to write the values back to a file. This way, <code>Dictionary</code> manages its own resources and you do not have to worry about calling <code>save</code> manually. This concept is called <a href=\"https://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c\">Resource Acquisition Is Initialization (RAII)</a>. Note the <code>try-catch</code> block. It's there because a <a href=\"https://stackoverflow.com/questions/130117/throwing-exceptions-out-of-a-destructor\">destructor should not throw exceptions</a>.</p>\n\n<pre><code>Dictionary::~Dictionary ()\n{\n // A destructor must not throw an exception.\n try {\n this->Save (file_path_) ;\n }\n\n catch (std::ios_base::failure &e) {\n std::cerr << e.what () ;\n }\n}\n</code></pre>\n\n<p>This <code>Insert</code> method does the job, but not really well. Because I used <code>std::vector</code> rather than <code>std::map</code>, I have somehow take care of duplicate words. My strategy here (out of laziness) is to simply allow them. Also note that my <code>operator>></code> stores <code>'\\n'</code>, which makes this even more ugly.</p>\n\n<pre><code>void Dictionary::Insert (DictionaryEntry de)\n{\n std::string &word = de.word_ ;\n std::transform (std::begin (word), std::end (word), std::begin (word), std::tolower) ;\n\n word += \"\\n\" ; // ugly, but '\\n' are embedded already.\n de.definition_ += \"\\n\" ; // ugly, but '\\n' are embedded already.\n\n entries_.push_back (de) ;\n valid_ = true ; // Useful if we are creating the dictionary from scratch.\n}\n\nvoid Dictionary::Insert (const std::string &word, const std::string &definition)\n{\n this->Insert (DictionaryEntry (word, definition)) ;\n}\n</code></pre>\n\n<p>In this <code>Load</code> function, I do not set the <code>failbit</code> as a condition to throw an exception. This is because <code>std::copy</code> will set the <code>failbit</code> when its done (at least on Visual Studio 2012). Because of this, we have to manually check if the file was properly opened. Notice how member variable are not modified until the very end of this function. This is so that in case the function decides to throw an exception, the class will not be placed in an invalid state. This means this function is conscious about <a href=\"https://stackoverflow.com/questions/1853243/c-do-you-really-write-exception-safe-code\">exception safety</a>.</p>\n\n<pre><code>void Dictionary::Load (std::string file_path)\n{\n std::ifstream file (file_path) ;\n file.exceptions (std::ios::badbit) ;\n\n if (file.is_open () == false) {\n throw std::ios_base::failure (\"Could not open file.\") ;\n }\n\n std::vector <DictionaryEntry> entries ;\n\n auto begin = std::istream_iterator <DictionaryEntry> (file) ;\n auto end = std::istream_iterator <DictionaryEntry> () ;\n std::copy (begin, end, std::back_inserter (entries)) ;\n\n // Copy data to member functions:\n std::swap (file_path_, file_path) ;\n std::swap (entries_, entries) ;\n valid_ = true ;\n}\n</code></pre>\n\n<p>Here is where the <code>operator<</code> becomes useful. Before we write our dictionary entries back to disk, we need to sort them. Other than that, this <code>Save</code> function is pretty straight forward.</p>\n\n<pre><code>void Dictionary::Save (const std::string &file_path)\n{\n if (valid_) {\n std::sort (std::begin (entries_), std::end (entries_)) ;\n\n std::ofstream file (file_path) ;\n file.exceptions (std::ios::badbit) ;\n\n if (file.is_open () == false) {\n throw std::ios_base::failure (\"Could not open file.\") ;\n }\n\n auto out = std::ostream_iterator <DictionaryEntry> (file) ;\n std::copy (std::begin (entries_), std::end (entries_), out) ;\n }\n}\n</code></pre>\n\n<p>This is somewhat ugly for this interface, but this is a more <code>std</code>-like approach. This is also where our <code>operator==</code> comes in handy. Basically, if we do not find the word, we return <code>entries.cend()</code>, which is basically a pointer that points past the end of our <code>vector</code>.</p>\n\n<pre><code>Dictionary::const_iterator Dictionary::LookupWord (const std::string &word) const\n{\n return std::find (std::begin (entries_), std::end (entries_), DictionaryEntry (word, \"\")) ; \n}\n</code></pre>\n\n<p>And here is a sample <code>main</code> function:</p>\n\n<pre><code>int main (void) \n{\n Dictionary dictionary ;\n\n try {\n dictionary.Load (\"dictionary.txt\") ;\n\n auto entry = dictionary.LookupWord (\"proliferate\") ;\n if (entry != dictionary.cend ()) {\n std::cout << *entry ;\n }\n\n dictionary.Insert (\"MyNewWord\", \"My new definition.\") ;\n }\n\n catch (std::ios_base::failure &e) {\n std::cerr << e.what () << \"\\n\" ;\n return 1 ;\n }\n\n return 0 ;\n}\n</code></pre>\n\n<p>Once again, this isn't the best way to do it. This is just to get you to start writing <em>C++</em> instead of <em>C with Classes</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:00:04.953",
"Id": "48817",
"ParentId": "48759",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48813",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:49:12.570",
"Id": "48759",
"Score": "3",
"Tags": [
"c++",
"file-system",
"error-handling"
],
"Title": "Program simulating dictionary using file handling"
} | 48759 |
<p>Basically I want some help in reducing the bloat of this code. I am new to JavaScript so this represents an attempt at learning jQuery by doing. All of this code works as I want it to, but it is not efficient or maintainable long term.</p>
<p>I realize there is no context for what is going on, but I figure that someone could immediately see places to create reusable chunks of code at a glance. If someone is willing to help me reduce the length and improve the quality dramatically I would be happy to provide a link to the website that utilizes it. Foregoing that I am mostly looking for someone to provide insight and point me in the right direction.</p>
<pre><code>jQuery(document).ready(function($){
/*RIGHT ANIMATIONS*/
$("body").on('click', '.right-tog', function(event) {
$('.right').animate({right: 0}),
$('#content').animate({right: 300}),
$('header nav, header div, .right-tog, .bkgd-desc').fadeOut(300);
});
$("body").on('click', '#content, .click-thru, a[role=close]', function(event) {
var divpos = parseInt($('.right').css('right'));
if (divpos == 0) {
$('.right').animate({right: '-100%'}),
$('#content').animate({right: 0}),
$('header nav, header div, .right-tog, .bkgd-desc').fadeIn(300);
};
});
/*LINKS ANIMATIONS*/
$("body").on('click', '.events', function(event) {
$('#events').animate({top: 0}),
$('#content').animate({top: 100}),
$('header nav, #right-tog, .bkgd-desc').fadeOut(300);
var rightpos = parseInt($('.right').css('right'));
if (rightpos == 0) {
$('.right').animate({right: -600}),
$('#content').animate({right: 0}),
$('#main-menu, #right-tog, .bkgd-desc').fadeIn(300);
};
});
$("body").on('click', '.links, .links-thru', function(event) {
$('#footer').animate({bottom: 0}),
$('#content').animate({bottom: 100}),
$('header nav, #right-tog, .bkgd-desc').fadeOut(300);
var rightpos = parseInt($('.right').css('right'));
if (rightpos == 0) {
$('.right').animate({right: -600}),
$('#content').animate({right: 0}),
$('#main-menu, #right-tog, .bkgd-desc').fadeIn(300);
};
});
/*LEFT ANIMATIONS*/
$("body").on('click', '.work', function(event) {
$('.left').animate({left: 0}),
$('#content').animate({left: 200}),
$('header nav, #right-tog, .bkgd-desc').fadeOut(300);
});
$("body").on('click', '#content, .work-link, a[role=close]', function(event) {
var divPosition = parseInt($('.left').css('left'));
if (divPosition == 0) {
$('.left').animate({left: -1000}),
$('#content').animate({left: 0}),
$('header nav, #right-tog, .bkgd-desc').fadeIn(300);
};
});
$("body").on('click', 'header navi', function(event) {
var target = $( event.target );
var divWidth = parseInt($(this).css('width'));
if (divWidth < 130 & target.is('header nav') ) {
$(this).animate({width: 130}, 100),
$('header h1').animate({left: 160}, 150, function(){
$(this).delay(60).animate({left: 140}, 100);
});
} else {
$(this).animate({width: 60}, 100),
$('header h1').animate({left: 70}, 100);
}
});
/*LINKS ANIMATIONS*/
$("body").on('click', '#content', function(event) {
var divpos = parseInt($('footer').css('bottom'));
var eventspos = parseInt($('#events').css('top'));
if (divpos == 0 || eventspos == 0) {
$('footer').animate({bottom: '-60%'}),
$('#events').animate({top: -200}),
$('#content').animate({bottom: 0, top: 0}),
$('header nav, #right-tog, .bkgd-desc').fadeIn(300);
};
});
/*CLICK THRU FUNCTIONS*/
$("body").on('click', '#work-thru', function(event) {
$('#left').animate({left: 0}),
$('#main').animate({left: 300}),
$('#right').animate({right: -600}),
$('#main').animate({right: 0}),
$('header nav, #right-tog, .bkgd-desc').fadeOut(300);
});
$("body").on('click', '#about-thru', function(event) {
$('#right').animate({right: -600}),
$('#main').animate({right: 0}),
$('header nav, #right-tog, .bkgd-desc').fadeIn(300);
});
/*CATEGORY FILTER*/
$('#filter li a').click(function() {
$('#filter li .current').removeClass('current');
$(this).parent().addClass('current');
var filterVal = $(this).text().replace(/ /g,'-');
if(filterVal == 'All') {
$('.work-grid li.hidden').fadeIn('slow').removeClass('hidden');
} else {
$('.work-grid li').each(function() {
if(!$(this).hasClass(filterVal)) {
$(this).fadeOut(600).addClass('hidden');
} else {
$(this).fadeIn(600).removeClass('hidden');
}
});
}
return false;
});
});
</code></pre>
| [] | [
{
"body": "<p>A minor thing that I see right away is that I see a bunch of <code>$(selector).animate({options});</code> calls with slightly different parameters. What I'd do is write a single function for these:</p>\n\n<pre><code>function animateSelector(selector, options){\n $(selector).animate(options);\n}\n</code></pre>\n\n<p>This way the construct \"I select this, then I animate it with these options\" is abstracted away to \"animate this selector with these options\". it doesn't change the performance, but it makes slightly clearer what's going on.</p>\n\n<p>Another problem, slightly bigger, is that in a lot of places, you have an inline function (nothing wrong with that) which uses commas as line endings, which should be semicolons (;). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:43:40.627",
"Id": "48776",
"ParentId": "48771",
"Score": "1"
}
},
{
"body": "<p>It looks to me like there a lot of differences in each function, it might take just as much code to account for all the differences, and by the time you are done it might be significantly more complicated! One thing that can help performance is caching your nodes by storing them as variables. To illustrate:</p>\n\n<pre><code> jQuery(document).ready(function($){\n\nvar $rightDiv = $('.right');\nvar $navsOne = $('header nav, #right-tog, .bkgd-desc');\nvar $navsTwo = $('header nav, header div, .right-tog, .bkgd-desc');\nvar $content = $('#content'); \n\n/*RIGHT ANIMATIONS*/\n$(\"body\").on('click', '.right-tog', function(event) {\n $rightDiv.animate({right: 0}),\n $content.animate({right: 300}),\n $navsTwo.fadeOut(300);\n});\n\n$(\"body\").on('click', '#content, .click-thru, a[role=close]', function(event) {\n var divpos = parseInt(rightDiv.css('right'));\n\n if (divpos == 0) {\n $rightDiv.animate({right: '-100%'}),\n $content.animate({right: 0}),\n $navsTwo.fadeIn(300);\n };\n});\n\n/*LEFT ANIMATIONS*/\n$(\"body\").on('click', '.work', function(event) {\n $('.left').animate({left: 0}),\n $content.animate({left: 200}),\n $navsOne.fadeOut(300);\n});\n\n$(\"body\").on('click', '#content, .work-link, a[role=close]', function(event) {\n var divPosition = parseInt($('.left').css('left'));\n\n if (divPosition == 0) {\n $('.left').animate({left: -1000}),\n $content.animate({left: 0}),\n $navsOne.fadeIn(300);\n };\n});\n</code></pre>\n\n<p>etc... <a href=\"http://jsperf.com/ns-jq-cached/4\" rel=\"nofollow\">here is a little test that illustrates performance differences</a>. That's a lot of animation!! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T02:08:27.553",
"Id": "85736",
"Score": "0",
"body": "Yes it is! I am a proponent of pure CSS solutions but in this case the build relies on click events. Also this is mostly a buddy's code that I am adapting. He is roughly at the same skill level with jQuery as I. Thank you for the suggestion!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T23:14:53.857",
"Id": "48832",
"ParentId": "48771",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:23:14.873",
"Id": "48771",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "Major code bloat reduction with jQuery"
} | 48771 |
<p>Okay, so I'm a self-taught programmer and have been brushing up on all the 'boring' bits that CS students do that most of us self-taught ignore. Things like Algorithms and Data Structures (particularly). So I found a nice exercise book that explains how algorithms work, but then leaves the implementation to the reader. </p>
<p>This works well for me as I'm the kind of person for whom knowledge 'sticks' better if I can "figure it out for myself". </p>
<p>So, I've just finished the Chapter on Sorting and quite easily managed to implement working Bubble Sort, Radix Sort, Mergesort etc. I really struggled getting Quicksort to work though - lots of out of bounds errors that I found hard to track down. So, now I do have it working - I'm wondering whether I just set about coding the algorithm (I'm using C#) the wrong way in the first place. </p>
<p>So, my question, I'll post my code below, and I'd really appreciate it if you guys could tell me (mentor style I guess) how I could have done a better job if I did it again. What I don't want is a long discussion of "you chose a silly pivot value", remember I implemented this from an exercise and that told me explicitly to use the left-most value of each sub-array as the pivot for each partition.</p>
<p>So, here's the code that basically creates the object and calls the sort method:</p>
<pre><code>class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Exercise 24.10 - Quicksort\n\n");
Quicksort sort = new Quicksort(12);
Console.WriteLine("Unsorted: {0}\n", sort);
sort.Sort();
Console.WriteLine("\n Sorted: " + sort);
Console.Write("\nPress any key to continue . . . ");
Console.ReadKey(true);
}
}
</code></pre>
<p>and here's the object that implements the Quicksort & the partitioning:</p>
<pre><code>class Quicksort
{
private int[] data;
private Random rng = new Random();
public Quicksort(int size)
{
data = new int[size];
//Test Data from TextBook:
//data = new int[] {37, 2, 6, 4, 89, 8, 10, 12, 68, 45};
// Generate some Random Data
for(int i=0; i<data.Length;i++)
data[i]=rng.Next(0,100);
} // end constructor
public void Sort()
{
// Calls the 'private' recursive Quicksort method
recSort(0, data.Length-1);
}
private void recSort(int left, int right)
{
// Recursively calls itself until the pointers collide
// And as the partitioning works in-place there's no
// writing at the end, the array is already sorted
if(left<right) {
int pivot = Partition(left, right);
recSort(left, pivot-1);
recSort(pivot+1, right);
}
}
private int Partition(int left, int right)
{
// Takes the leftmost value of our input array
// and puts it in its correct final position
// ie. all values larger than it above and all values
// lower than it below
int i=left; // i is our bot->top travelling "pointer"
int j=right+1; // j if our top->bot travelling "pointer"
while(i<j) {
do {
j--;
} while (data[i]<data[j]);
if(i<j)
Swap(i,j);
do {
i++;
} while (data[j]>data[i]);
if(i<j)
Swap(i,j);
}
return j;
}
private void Swap(int i, int j)
{
int temp=data[i];
data[i]=data[j];
data[j]=temp;
// DEBUG: Uncomment to show swap details
//Console.WriteLine ("SW {0:00}/{1:00}: {2}",data[j],
//data[i],this.ToString());
}
public override string ToString()
{
// Display a pretty version of the array
// Make sure SB doesn't have to increase capacity as it appends
StringBuilder temp = new StringBuilder((data.Length*6)+1);
for(int i=0; i<data.Length; i++)
temp.AppendFormat("[{0:00}] ", data[i]);
return temp.ToString();
}
} // end class
</code></pre>
<p>Sample output (with debugging turned on) looks like this:</p>
<pre><code>Exercise 24.10 - Quicksort
Unsorted: [64] [48] [79] [43] [75] [54] [81] [94] [75] [66] [57] [61]
SW 64/61: [61] [48] [79] [43] [75] [54] [81] [94] [75] [66] [57] [64]
SW 79/64: [61] [48] [64] [43] [75] [54] [81] [94] [75] [66] [57] [79]
SW 64/57: [61] [48] [57] [43] [75] [54] [81] [94] [75] [66] [64] [79]
SW 75/64: [61] [48] [57] [43] [64] [54] [81] [94] [75] [66] [75] [79]
SW 64/54: [61] [48] [57] [43] [54] [64] [81] [94] [75] [66] [75] [79]
SW 61/54: [54] [48] [57] [43] [61] [64] [81] [94] [75] [66] [75] [79]
SW 54/43: [43] [48] [57] [54] [61] [64] [81] [94] [75] [66] [75] [79]
SW 57/54: [43] [48] [54] [57] [61] [64] [81] [94] [75] [66] [75] [79]
SW 81/79: [43] [48] [54] [57] [61] [64] [79] [94] [75] [66] [75] [81]
SW 94/81: [43] [48] [54] [57] [61] [64] [79] [81] [75] [66] [75] [94]
SW 81/75: [43] [48] [54] [57] [61] [64] [79] [75] [75] [66] [81] [94]
SW 79/66: [43] [48] [54] [57] [61] [64] [66] [75] [75] [79] [81] [94]
SW 75/75: [43] [48] [54] [57] [61] [64] [66] [75] [75] [79] [81] [94]
Sorted: [43] [48] [54] [57] [61] [64] [66] [75] [75] [79] [81] [94]
</code></pre>
<p>I really am hoping for some guidance on how I could have done things better, perhaps things I've done well, and general stuff like how I've designed my class/methods, general style etc.</p>
| [] | [
{
"body": "<p>One thing that comes to mind is that you don't need to retain an instance of Random in your QuickSort class. Since it is only used during initialization, the Random instance should be a variable in the constructor, which would allow it to be garbage-collected as soon as the constructor is done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:56:49.297",
"Id": "85651",
"Score": "0",
"body": "Ah, yes - you're absolutely right!\nI guess I was thinking that a Sort object wouldn't - in reality - 'create' any data (normally it'd take an unsorted array as input) so my whole constructor/use of random is 'fake'. So I was sloppy in how I implemented that for sure. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:52:39.837",
"Id": "48779",
"ParentId": "48773",
"Score": "1"
}
},
{
"body": "<p>I really like how you're keeping the <code>Program</code> class nice and clean, and that the first thing you do is instantiate a class that encapsulates the logic you want to run.</p>\n\n<p>However you have mixed concerns there, it shouldn't be <code>QuickSort</code>'s job to generate the data to be sorted, and this:</p>\n\n<pre><code>Quicksort sort = new Quicksort(12);\n</code></pre>\n\n<p>Is rather off-putting when you realize that the 12 is really...</p>\n\n<pre><code>public Quicksort(int size)\n{\n data = new int[size];\n //Test Data from TextBook:\n //data = new int[] {37, 2, 6, 4, 89, 8, 10, 12, 68, 45};\n\n // Generate some Random Data\n for(int i=0; i<data.Length;i++)\n data[i]=rng.Next(0,100);\n\n} // end constructor\n</code></pre>\n\n<p>...the <em>size</em> of the array we want to generate random numbers for... @Zoyd's answer is correct, the <code>Random</code> instance is pretty.. random there. In fact, it doesn't belong in <code>QuickSort</code> <em>at all</em>.</p>\n\n<p>While I'm here, this:</p>\n\n<pre><code>} // end constructor\n</code></pre>\n\n<p>Is not a comment, it's <em>noise</em>. Remove it, and anything similar (like, <code>// end class</code>).</p>\n\n<p>Let's look at your public interface:</p>\n\n<pre><code>public Quicksort(int size)\npublic void Sort()\npublic override string ToString()\n</code></pre>\n\n<p>I realize this isn't touching your <em>implementation</em> and only scratches the surface, but just by looking at these three lines it's possible to see what's <em>sloppy</em>. I'd be expecting something like this:</p>\n\n<pre><code>public Quicksort()\npublic void Sort(int[] data)\n</code></pre>\n\n<p>Because <code>Sort</code> <em>has a side-effect</em> - it <em>sorts</em> the <code>int[] data</code> parameter. The <code>QuickSort</code> class itself <s>doesn't</s> <em>shouldn't</em> own the data, so overriding <code>ToString</code> to output that data makes no sense, at least not if you're trying to be following the Single Responsibility Principle.</p>\n\n<hr>\n\n<p>Let's see what's under the hood:</p>\n\n<pre><code>private void recSort(int left, int right)\nprivate int Partition(int left, int right)\nprivate void Swap(int i, int j)\n</code></pre>\n\n<p>The only thing I don't like, is the name of <code>recSort</code> - its casing isn't consistent (should be <em>PascalCase</em>), and is it <code>RecordSort</code>, <code>RecreationalSort</code>, or <code>RecursiveSort</code>? Keep names meaningful, don't chop them off just because <em>you know what it stands for</em>.</p>\n\n<p>This is a little hard to read:</p>\n\n<pre><code> while(i<j) {\n do {\n j--;\n } while (data[i]<data[j]);\n</code></pre>\n\n<p>Why? Because the bracing style isn't consistent here either: those are Java-style opening braces, C# conventions put the opening brace <code>{</code> on the next line. Also don't try to compact everything, let it breathe!</p>\n\n<pre><code> while (i < j) \n {\n do \n {\n j--;\n } \n while (data[i] < data[j]);\n\n //...\n</code></pre>\n\n<p>This is also a naming opportunity:</p>\n\n<pre><code>int i=left; // i is our bot->top travelling \"pointer\"\nint j=right+1; // j if our top->bot travelling \"pointer\"\n</code></pre>\n\n<p>The comments could be removed if the \"pointers\" had more descriptive names:</p>\n\n<pre><code>int bottomUpIndex = left;\nint topDownIndex = right + 1;\n</code></pre>\n\n<hr>\n\n<p>This is interesting:</p>\n\n<pre><code> // DEBUG: Uncomment to show swap details\n //Console.WriteLine (\"SW {0:00}/{1:00}: {2}\",data[j], \n //data[i],this.ToString());\n</code></pre>\n\n<p>This is going to be WAY overkill for your little exercise, but if you went with a SOLID architecture, you could have an <code>ISwapable</code> interface injected as a dependency to your <code>QuickSort</code> implementation (in the class' constructor):</p>\n\n<pre><code>public interface ISwapable\n{\n void Swap(int[] data, int indexA, int indexB);\n}\n</code></pre>\n\n<p>And then you could have a basic implementation that does the swapping, and a <em>decorator</em> that does the debug output - and you decide which <code>ISwapable</code> implementation you want to <em>inject</em> at start-up:</p>\n\n<pre><code>public class DebugOutputSwapDecorator : ISwapable\n{\n private readonly ISwapable _swapper;\n\n public DebugOutputSwapDecorator(ISwapable swapper)\n {\n _swapper = swapper;\n }\n\n public void Swap(int[] data, int indexA, int indexB)\n {\n _swapper.Swap(data, indexA, indexB);\n DisplaySwappingResult(data, data[indexA], data[indexB]);\n }\n\n private void DisplaySwappingResult(int[] data, int valueA, int valueB)\n {\n StringBuilder builder = new StringBuilder((data.Length * 6) + 1);\n\n for (int i = 0; i < data.Length; i++)\n builder.AppendFormat(\"[{0:00}] \", data[i]);\n\n Console.WriteLine(\"SW {0}/{1}: {2}\", valueA, valueB, builder.ToString());\n }\n}\n</code></pre>\n\n<p>...and by SOLID's principles the <code>QuickSort</code> class would have no clue that its <code>ISwapable</code> dependency is really outputting the values to the console (it's none of its concern), and instead of having to find the lines of code to comment/uncomment to toggle between behaviors, you could just change the <code>ISwapable</code> implementation you're passing to <code>QuickSort</code>'s constructor when you're creating it in your <code>Main</code> method.</p>\n\n<p>Obviously there'd be a little more work needed to keep everything DRY (<code>DisplaySwappingResult</code> does more than it needs to be doing here), but you get the idea.</p>\n\n<hr>\n\n<p>As for the sorting itself, I like how you've split it into small methods. Nothing to add, really.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:48:05.470",
"Id": "85685",
"Score": "0",
"body": "Surprised to see DI even suggested for such a low level operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:51:04.903",
"Id": "85686",
"Score": "0",
"body": "@Frank I know, ...I thought the same thing too. I guess the commenting/uncommenting of debug output tripped something in my abstraction-freak's brain ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T13:24:13.243",
"Id": "86170",
"Score": "2",
"body": "@Frank and Mat, actually I found it quite an interesting idea. Starting off, as I did, in standard ANSI C I would have done this 'the good old days' using #if debug pre-processor directives.\nSo, I was completely unaware of this (quite elegant) way of doing things in a 'proper' OOP language. \nOnce again, thanks guys!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:33:45.020",
"Id": "48787",
"ParentId": "48773",
"Score": "5"
}
},
{
"body": "<p>Today in c# 7 you can write all quicksort in \"one line\"</p>\n\n<pre><code>static IEnumerable<int> QuickSort(IEnumerable<int> list) =>\n list.FirstOrDefault() is var head &&\n list.Skip(1) is var tail &&\n tail.Where(e => e >= head) is var larger &&\n tail.Where(e => e < head) is var smaller &&\n !list.Any()\n ? Enumerable.Empty<int>()\n : QuickSort(smaller).Append(head).Concat(QuickSort(larger));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-15T06:44:31.663",
"Id": "368904",
"Score": "2",
"body": "This is really nice but I consider this as a Code Golf solution that has no place in production code ;-) Btw, you can replace one of the `Concat`s with `Append` and it would be great if you could explain your solution a bit because well, this is Code Review and not Code Golf..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-15T15:05:45.553",
"Id": "368947",
"Score": "0",
"body": "@t3chb0t this isn't code-golf; far too clear, and look at all those gratuitous variable declarations! I do agree some explanation (and perhaps justification!) is in order, however!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-15T15:11:59.167",
"Id": "368949",
"Score": "0",
"body": "@VisualMelon it isn't clear at all ;-) no sane person would ever build such an expression concatenated with ANDs using tricky inline variables. Code-golf it is :-P it's not even functional but it's fun ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-15T15:28:05.433",
"Id": "368951",
"Score": "0",
"body": "@t3chb0t well, we'll have to differ on our definitions; if this was codegolf.SE, the answer might get a down-vote from me for lack of effort ;) a big problem with this asnwer is that it won't work if the pivot appears more than once, and doesn't have the partitioning implemented in the OP, so can't possibility qualify as an answer, let alone a review in it's current form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-11T03:15:12.857",
"Id": "378002",
"Score": "0",
"body": "@t3chb0t yes you are right, with append its better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-11T03:23:33.773",
"Id": "378004",
"Score": "0",
"body": "@t3chb0t The inline var's are a new feature of c# pattern matching, it can be used to declare a variable in an expression like an if or a ternary. the ideia is to represent quicksort in one expression, so i choose to use the var's on the start of the function trying to make de body more readable, with only `qs(smaller) + head + qs(larger)`, it's havelly inspired in a Haskell implementation of it (http://wiki.c2.com/?QuickSortInHaskell)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-11T03:26:59.040",
"Id": "378005",
"Score": "0",
"body": "@VisualMelon I had make a mistake, i forgot to call QuickSort on the `larger` part, i fixed it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-11T06:40:13.617",
"Id": "378021",
"Score": "0",
"body": "I must say that I'm pretty upset that the official documentation about [pattern matching](https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching) does not mention `is var` but some _random_ blog about [Dissecting the pattern matching in C# 7](https://blogs.msdn.microsoft.com/seteplia/2017/10/16/dissecting-the-pattern-matching-in-c-7/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-11T12:31:49.203",
"Id": "378059",
"Score": "1",
"body": "@LucasTeles I'd not actually noticed that... the problem whereto I refer is that any elements in tail which are _equal_ to the pivot will be lost, you need something like `tail.Where(e => e >= head) is var larger &&`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-13T14:52:22.163",
"Id": "378378",
"Score": "0",
"body": "@VisualMelon you are absolutely right, sorry that's was a typo"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-04-15T03:21:53.027",
"Id": "192083",
"ParentId": "48773",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:34:29.177",
"Id": "48773",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"sorting",
"quick-sort"
],
"Title": "Quicksort implementation in C#"
} | 48773 |
<p>We regularly have to convert a bunch of autotask Contracts to a custom CRM entity because we have employees who don't work in Autotask but need those contracts. I wrote the above code to handle this job. this code is supposed to run in a scheduled batch</p>
<ol>
<li>it retrieves all CRM accounts;</li>
<li>it loops over all accounts, doing the following per account:</li>
<li>retrieve the account from autotask using the ID;</li>
<li>loop over all contracts for this account and do the following per contract;</li>
<li>see if the contract already exists in CRM (abonnement, because contracts were already taken);</li>
<li>if the contract already exists, modify it if necessary;</li>
<li>if the contract does not yet exist, calculate the price and create it in CRM.</li>
<li>once all contracts are processed, deactivate those which are expired.</li>
</ol>
<p>I've already done an initial code review with a senior developer, whose changes I've already included in this version, but I'm wondering what other improvements might be made.</p>
<p>Some peculiarities: Autotask saves all fields as a string, but they're returned from the service as objects. Only the id field for an entity is not saved as a string, but as a long.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using AutoTask.Sync.autoTaskWebService;
namespace AutoTask.Sync
{
public static class AutotaskAccountImporter
{
/// <summary>
/// Main method that retrieves and updates.
/// </summary>
private static void Main()
{
//connect to the 2 programs
AutoTaskConnector.ConnectToAutoTask();
Crm.LoginToCrm();
try
{
//get a list of accounts from CRM which are also in AutoTaskConnector
List<Account> crmAccounts = Crm.GetAccountsWithAutotaskId();
Console.WriteLine("{0} Accounts opgehaald uit CRM.", crmAccounts.Count);
//prepare list of abonnementen to insert;
List<acm_abonnement> abonnementen = new List<acm_abonnement>();
int accountCount = 0;
//prepare list of abonnementen to save;
List<acm_abonnement> updatedAbonnements = new List<acm_abonnement>();
//Loop over all accounts;
foreach (Account crmAccount in crmAccounts)
{
ExtractAbonnementenFromCrmAccount(crmAccount, ref updatedAbonnements, ref abonnementen, ref accountCount);
}
//create new abonnementen, update changed existing, deactivate those that have ended.
Console.WriteLine("{0} Abonnementen wegschrijven naar CRM", abonnementen.Count);
Crm.CreateAbonnementen(abonnementen);
Console.WriteLine("{0} Abonnementen Aanpassen in CRM", updatedAbonnements.Count);
Crm.UpdateBestaandeAbonnementen(updatedAbonnements);
Crm.DeactivateVerlopenAbonnementen();
}
catch (FaultException<OrganizationServiceFault> ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
Console.WriteLine("Message: {0}", ex.Detail.Message);
Console.WriteLine("Inner Fault: {0}",
null == ex.Detail.InnerFault ? "No Inner Fault" : ex.Detail.InnerFault.Message);
}
catch (SaveChangesException ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine("Message: {0}", ex.Message);
Console.WriteLine("Inner Fault: {0}",
null == ex.InnerException ? "No Inner Fault" : ex.InnerException.Message);
}
}
private static void ExtractAbonnementenFromCrmAccount(Account crmAccount, ref List<acm_abonnement> updatedAbonnements, ref List<acm_abonnement> abonnementen, ref int accountCount)
{
try
{
//get account from autotask;
autoTaskWebService.Account autotaskAccount = AutoTaskConnector.GetAutotaskAccountForID(crmAccount.slfn_Klantnr.GetValueOrDefault());
//Get all contracts for a certain account from autotask;
IEnumerable<autoTaskWebService.Contract> autotaskContracts = AutoTaskConnector.GetContractsForAccount(autotaskAccount.id);
int accountAbonnementenCount = 0;
//Loop over all contracts
foreach (autoTaskWebService.Contract autotaskContract in autotaskContracts)
{
DateTime? nextInvoiceDateTime = null;
//get all contractserviceUnits
var servicescost = CalculatecostAndNextInvoice(autotaskContract, ref nextInvoiceDateTime);
//Check if the contract already exists in CRM
if (UpdateAbonnementIfNeeded(updatedAbonnements, autotaskContract, nextInvoiceDateTime, servicescost))
{
continue;
}
//create a new abonnement using the correct values;
abonnementen.Add(new acm_abonnement(crmAccount, autotaskAccount, autotaskContract, servicescost, nextInvoiceDateTime));
accountAbonnementenCount++;
}
if (accountAbonnementenCount > 0)
{
Console.WriteLine("{0} abonnementen aangemaakt.", accountAbonnementenCount);
}
accountCount++;
Console.WriteLine("{0} accounts verwerkt.", accountCount);
}
catch (AutotaskCallException autoexception)
{
Console.WriteLine("Foutmelding van Autotask API bij ophalen van {1}: {0}", autoexception.Message, autoexception.AutotaskEntity);
}
}
private static bool UpdateAbonnementIfNeeded(List<acm_abonnement> updatedAbonnements, autoTaskWebService.Contract autotaskContract, DateTime? nextInvoiceDateTime, double servicescost)
{
List<acm_abonnement> bestaandeabonnementen = Crm.GetAbonnementenWithMultiversId(autotaskContract.id.ToString(CultureInfo.InvariantCulture));
if (bestaandeabonnementen.Any())
{
//if it exists, check if the price, invoicedate or SLA have changed.
//if they changed, update them and add them to the updatelist.
acm_abonnement bestaandAbonnement = bestaandeabonnementen.First();
Console.WriteLine("Abonnement bestaat al in CRM, checken of het geupdate moet worden.");
if (bestaandAbonnement.ContractIsAltered(autotaskContract, nextInvoiceDateTime, servicescost))
{
bestaandAbonnement.acm_bedrag = new Money((decimal) servicescost);
bestaandAbonnement.acm_volgendefactuurdatum = nextInvoiceDateTime;
bestaandAbonnement.acm_slapicklist = new OptionSetValue(Convert.ToInt16(autotaskContract.ServiceLevelAgreementID.ToString()));
updatedAbonnements.Add(bestaandAbonnement);
Console.WriteLine("{0} abonnementen dienen aangepast te worden.", updatedAbonnements.Count);
}
return true;
}
return false;
}
private static double CalculatecostAndNextInvoice(autoTaskWebService.Contract autotaskContract, ref DateTime? nextInvoiceDateTime)
{
List<ContractServiceUnit> contractServiceUnits = AutoTaskConnector.GetContractServiceUnitsForContract(autotaskContract.id);
double servicescost = 0;
if (contractServiceUnits.Any())
{
//calculate contract price and invoicedate based on retrieved units
servicescost = contractServiceUnits.Sum(csu => Math.Round(Convert.ToDouble(csu.Price.ToString()), 2, MidpointRounding.AwayFromZero));
nextInvoiceDateTime = DateTime.Parse(contractServiceUnits.First().EndDate.ToString()).AddDays(1);
}
else
{
//if no units found, try with services;
List<ContractService> autotaskContractServices = AutoTaskConnector.GetContractServicesForContract(autotaskContract.id);
if (autotaskContractServices.Any())
{
servicescost = autotaskContractServices.Sum(acs => Convert.ToDouble(acs.AdjustedPrice.ToString()));
}
}
return servicescost;
}
}
/// <summary>
/// Autotask interface
/// </summary>
public static class AutoTaskConnector
{
private static ATWS _oService;
/// <summary>
/// connects to AutoTaskConnector
/// </summary>
public static void ConnectToAutoTask()
{
const string sWebUri = "autotaskurl";
_oService = new ATWS();
NetworkCredential oCred = new NetworkCredential("autotaskusername", "autotaskpassword");
CredentialCache credCache = new CredentialCache { { new Uri(_oService.Url), "Basic", oCred } };
_oService.Url = sWebUri;
_oService.Credentials = credCache;
}
/// <summary>
/// Gets an account with a specific ID.
/// Throws an autotaskException if Autotask returns an error.
/// </summary>
/// <param name="crmId">ID of the entity</param>
/// <returns>A single Autotask Account with that CRM ID.</returns>
public static autoTaskWebService.Account GetAutotaskAccountForID(int crmId)
{
StringBuilder sBuilderAccount = new StringBuilder();
sBuilderAccount.Append(@"<queryxml version=""1.0"">");
sBuilderAccount.Append(@"<entity>Account</entity>");
sBuilderAccount.Append(@"<query>");
sBuilderAccount.Append(@"<condition><field>AccountNumber<expression op=""Equals"">" + crmId +
@"</expression></field></condition>");
sBuilderAccount.Append(@"</query></queryxml>");
ATWSResponse oResponseAccount = _oService.query(sBuilderAccount.ToString());
if (oResponseAccount.Errors.Any())
{
throw new AutotaskCallException(oResponseAccount.Errors[0].Message, "Account");
}
if (!oResponseAccount.EntityResults.Any()) return null;
autoTaskWebService.Account account = (autoTaskWebService.Account)oResponseAccount.EntityResults[0];
return account;
}
/// <summary>
/// Gets all contracts for a specific Account that are active today
/// </summary>
/// <param name="accountId">ID of the account</param>
/// <returns>A list of Autotask Contracts bound to a certain account.</returns>
public static IEnumerable<autoTaskWebService.Contract> GetContractsForAccount(long accountId)
{
string now = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss");
StringBuilder sBuilderContract = new StringBuilder();
sBuilderContract.Append(@"<queryxml version=""1.0"">");
sBuilderContract.Append(@"<entity>Contract</entity>");
sBuilderContract.Append(@"<query>");
sBuilderContract.Append(@"<condition><field>AccountID<expression op=""Equals"">" + accountId +
@"</expression></field></condition>");
sBuilderContract.Append(@"<condition><field>StartDate<expression op=""LessThanorEquals"">" + now +
@"</expression></field></condition>");
sBuilderContract.Append(@"<condition><field>EndDate<expression op=""GreaterThanorEquals"">" + now +
@"</expression></field></condition>");
sBuilderContract.Append(@"</query></queryxml>");
ATWSResponse oResponseContract = _oService.query(sBuilderContract.ToString());
if (oResponseContract.Errors.Any())
{
throw new AutotaskCallException(oResponseContract.Errors[0].Message, "Contract");
}
return oResponseContract.EntityResults.Cast<autoTaskWebService.Contract>().ToList();
}
/// <summary>
/// Gets all services for a contract.
/// Used when ServiceUnits are unavailable for whatever reason.
/// </summary>
/// <param name="contractId"></param>
/// <returns>A list of ContractServices for a specific contract.</returns>
public static List<ContractService> GetContractServicesForContract(long contractId)
{
StringBuilder sBuilderContract = new StringBuilder();
sBuilderContract.Append(@"<queryxml version=""1.0"">");
sBuilderContract.Append(@"<entity>ContractService</entity>");
sBuilderContract.Append(@"<query>");
sBuilderContract.Append(@"<condition><field>ContractID<expression op=""Equals"">" + contractId +
@"</expression></field></condition>");
sBuilderContract.Append(@"</query></queryxml>");
ATWSResponse oResponseContract = _oService.query(sBuilderContract.ToString());
if (oResponseContract.Errors.Any())
{
throw new AutotaskCallException(oResponseContract.Errors[0].Message, "ContractService");
}
return oResponseContract.EntityResults.Cast<ContractService>().ToList();
}
/// <summary>
/// Gets the serviceUnits for a contract.
/// </summary>
/// <param name="contractId"></param>
/// <returns>A list of contractserviceUnits bound to a specific contract.</returns>
public static List<ContractServiceUnit> GetContractServiceUnitsForContract(long contractId)
{
string now = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss");
StringBuilder sBuilderContract = new StringBuilder();
sBuilderContract.Append(@"<queryxml version=""1.0"">");
sBuilderContract.Append(@"<entity>ContractServiceUnit</entity>");
sBuilderContract.Append(@"<query>");
sBuilderContract.Append(@"<condition><field>ContractID<expression op=""Equals"">" + contractId +
@"</expression></field></condition>");
sBuilderContract.Append(@"<condition><field>StartDate<expression op=""LessThanorEquals"">" + now +
@"</expression></field></condition>");
sBuilderContract.Append(@"<condition><field>EndDate<expression op=""GreaterThanorEquals"">" + now +
@"</expression></field></condition>");
sBuilderContract.Append(@"</query></queryxml>");
ATWSResponse oResponseContract = _oService.query(sBuilderContract.ToString());
if (oResponseContract.Errors.Any())
{
throw new AutotaskCallException(oResponseContract.Errors[0].Message, "ContractServiceUnit");
}
return oResponseContract.EntityResults.Cast<ContractServiceUnit>().ToList();
}
}
/// <summary>
/// Custom exception which gets thrown if an autotask API call returns an error.
/// </summary>
public class AutotaskCallException : Exception
{
public readonly string AutotaskEntity;
public AutotaskCallException(string message, string entity)
: base(message)
{
AutotaskEntity = entity;
}
}
/// <summary>
/// CRM interface
/// </summary>
public static class Crm
{
private static IOrganizationService _service;
private static CRMContext _context;
/// <summary>
/// Logs into CRM with specific credentials.
/// </summary>
public static void LoginToCrm()
{
Uri organizationUri = new Uri("crmurl");
var cred = new ClientCredentials();
cred.UserName.UserName = "crmusername";
cred.UserName.Password = "crmpassword";
OrganizationServiceProxy serviceproxy = new OrganizationServiceProxy(organizationUri, null, cred, null);
serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = serviceproxy;
_context = new CRMContext(_service);
}
/// <summary>
/// Get all accounts from CRM which have their autotaskID set.
/// </summary>
/// <returns>A list of all active CRM accounts that have an autotaskID.</returns>
public static List<Account> GetAccountsWithAutotaskId()
{
return (from accounts in _context.AccountSet
where accounts.slfn_Klantnr != null
&& accounts.StateCode == AccountState.Active
select new Account
{
slfn_Klantnr = accounts.slfn_Klantnr,
Name = accounts.Name,
Id = accounts.Id
}).ToList();
}
/// <summary>
/// Creates all abonnementen from a list
/// </summary>
/// <param name="abonnementen">abonnementen to create.</param>
public static void CreateAbonnementen(IEnumerable<acm_abonnement> abonnementen)
{
foreach (acm_abonnement acmAbonnement in abonnementen)
{
_context.AddObject(acmAbonnement);
}
_context.SaveChanges();
}
/// <summary>
/// Checks if there already is an abonnement with a specific multiversID
/// Prevents double creation of an abonnement.
/// </summary>
/// <param name="multiversId"></param>
/// <returns>A list of abonnementen with a specific autotaskID.</returns>
public static List<acm_abonnement> GetAbonnementenWithMultiversId(string multiversId)
{
return (from abon in _context.acm_abonnementSet
where abon.acm_multiversid == multiversId
select new acm_abonnement
{
acm_bedrag = abon.acm_bedrag,
acm_volgendefactuurdatum = abon.acm_volgendefactuurdatum,
acm_slapicklist = abon.acm_slapicklist
}).ToList();
}
/// <summary>
/// Abonnementen which have expired (einddatum is earlier than the execution date) need to be deactivated.
/// </summary>
public static void DeactivateVerlopenAbonnementen()
{
List<acm_abonnement> verlopenAbonnementen = (from abon in _context.acm_abonnementSet
where abon.acm_einddatum <= DateTime.Now.Date
&& abon.statecode != acm_abonnementState.Inactive
select abon).ToList();
foreach (var acmAbonnement in verlopenAbonnementen)
{
SetStateRequest setAbonnementStateRequest = new SetStateRequest { EntityMoniker = new EntityReference(acm_abonnement.EntityLogicalName, acmAbonnement.Id), State = new OptionSetValue((int)acm_abonnementState.Inactive) };
_service.Execute(setAbonnementStateRequest);
}
}
/// <summary>
/// Updates existing abonnementen
/// </summary>
/// <param name="updatedAbonnements">existing abonnementen</param>
public static void UpdateBestaandeAbonnementen(IEnumerable<acm_abonnement> updatedAbonnements)
{
foreach (acm_abonnement updatedAbonnement in updatedAbonnements)
{
_context.UpdateObject(updatedAbonnement);
}
_context.SaveChanges();
}
}
// ReSharper disable once InconsistentNaming
public partial class acm_abonnement
{
/// <summary>
/// Creates an abonnement based on the required CRM and Autotask entities.
/// </summary>
/// <param name="crmAccount"></param>
/// <param name="autotaskAccount"></param>
/// <param name="autotaskContract"></param>
/// <param name="contractPrice"></param>
/// <param name="nextInvoiceDate"></param>
public acm_abonnement(Account crmAccount, autoTaskWebService.Account autotaskAccount, autoTaskWebService.Contract autotaskContract, double contractPrice, DateTime? nextInvoiceDate)
{
LogicalName = EntityLogicalName;
acm_bedrag = new Money(Convert.ToDecimal(contractPrice));
acm_begindatum = DateTime.Parse(autotaskContract.StartDate.ToString());
//Autotask uses letters to indicate how often a contract is billed.
if (autotaskContract.ContractPeriodType != null)
{
switch (autotaskContract.ContractPeriodType.ToString())
{
case "m":
acm_contractperiodtype = new OptionSetValue(100000000);
break;
case "q":
acm_contractperiodtype = new OptionSetValue(100000001);
break;
case "s":
acm_contractperiodtype = new OptionSetValue(100000002);
break;
case "y":
acm_contractperiodtype = new OptionSetValue(100000003);
break;
}
}
if (autotaskContract.ContractType != null)
{
//CRM optionset heeft zelfde waarden als autotask picklist.
acm_contracttypepicklist = new OptionSetValue(Convert.ToInt16(autotaskContract.ContractType.ToString()));
}
acm_einddatum = DateTime.Parse(autotaskContract.EndDate.ToString());
acm_klant = new EntityReference(Account.EntityLogicalName, crmAccount.Id);
acm_multiversid = autotaskContract.id.ToString(CultureInfo.InvariantCulture);
acm_naamklantautotask = autotaskAccount.AccountName.ToString();
acm_name = autotaskContract.ContractName.ToString();
acm_omschrijving = autotaskContract.Description.ToString();
if (autotaskContract.ServiceLevelAgreementID != null)
{
acm_slapicklist = new OptionSetValue(Convert.ToInt16(autotaskContract.ServiceLevelAgreementID.ToString()));
}
acm_volgendefactuurdatum = nextInvoiceDate;
}
/// <summary>
/// Checks if a contract has sufficiently been altered in Autotask.
/// </summary>
/// <param name="autotaskContract"></param>
/// <param name="nextInvoiceDateTime"></param>
/// <param name="servicescost"></param>
/// <returns>true if any of the above field have been altered, false if they're all the same.</returns>
public bool ContractIsAltered(autoTaskWebService.Contract autotaskContract, DateTime? nextInvoiceDateTime, double servicescost)
{
bool bedrag = (acm_bedrag.Value != (Decimal.Truncate((decimal)servicescost)));
bool factuurdatum = false;
if (acm_volgendefactuurdatum != null && nextInvoiceDateTime != null)
{
factuurdatum = (acm_volgendefactuurdatum.Value.ToLocalTime() != nextInvoiceDateTime.Value);
}
bool servicelevelagreement = ((acm_slapicklist ?? new OptionSetValue(1)).Value.ToString(CultureInfo.InvariantCulture) != (autotaskContract.ServiceLevelAgreementID ?? 1).ToString());
return bedrag || factuurdatum || servicelevelagreement;
}
}
}
</code></pre>
| [] | [
{
"body": "<h3>Magic Strings</h3>\n<blockquote>\n<pre><code>string now = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss");\nStringBuilder sBuilderContract = new StringBuilder();\nsBuilderContract.Append(@"<queryxml version=""1.0"">");\nsBuilderContract.Append(@"<entity>Contract</entity>");\nsBuilderContract.Append(@"<query>");\nsBuilderContract.Append(@"<condition><field>AccountID<expression op=""Equals"">" + accountId +\n @"</expression></field></condition>");\nsBuilderContract.Append(@"<condition><field>StartDate<expression op=""LessThanorEquals"">" + now +\n @"</expression></field></condition>");\nsBuilderContract.Append(@"<condition><field>EndDate<expression op=""GreaterThanorEquals"">" + now +\n @"</expression></field></condition>");\nsBuilderContract.Append(@"</query></queryxml>");\n</code></pre>\n</blockquote>\n<p>This code seems to be repeated enough to warrant an abstraction, be it only to get rid of inline XML string building.</p>\n<p>This would require implementing an <code>XmlQueryBuilder</code> class and an <code>XmlQueryOperator</code> enum, but I'd like the query code to read something like this, so as to maximize maintainability and reduce the amount of possible typos and other hard-to-find bugs in the string:</p>\n<pre><code>var xml = new XmlQueryBuilder<Contract>()\n .Where(contract => contract.AccountID, XmlQueryOperator.Equals, accountId)\n .Where(contract => contract.StartDate, XmlQueryOperator.LessThanOrEquals, now)\n .Where(contract => contract.EndDate, XmlQueryOperator.GreaterThanOrEquals, now);\n\nvar result = _service.Query(xml.ToString());\n</code></pre>\n<p>The <code>XmlQueryBuilder<TEntity>.ToString()</code> method could use some Linq-to-Xml to produce the XML string in a strongly-typed way. In two words: <em>avoid magic strings</em> ;)</p>\n<p><sub><em>(I might implement such a class later, and put it up for review ;)</em></sub></p>\n<hr />\n<h3>Naming</h3>\n<p>It's not clear whether your API is French, English or German:</p>\n<blockquote>\n<pre><code>//Loop over all accounts;\nforeach (Account crmAccount in crmAccounts)\n{\n ExtractAbonnementenFromCrmAccount(crmAccount, ref updatedAbonnements, ref abonnementen, ref accountCount);\n}\n</code></pre>\n</blockquote>\n<p><code>crmAccount</code> and <code>accountCount</code> both sound English, <code>updatedAbonnements</code> is <em>Frenglish</em>, <code>abonnementen</code> sounds German, and <code>ExtractAbonnementenFromCrmAccount</code> looks like a mix of English and German, which isn't ideal. I'd try to stick to a single language, as much as possible. It looks like you have to cope with a somewhat multilingual API though.</p>\n<p>The naming conventions aren't clear either. I'd stick to the C# conventions for everything I have control over, and use <em>PascalCase</em> for types and public/exposed members, and <em>camelCase</em> for locals and parameters - <em>alllowercase</em> isn't an option! Also, drop the random single-letter prefixes, like <code>s</code> on <code>sBuilderContract</code> - a typical name for a <code>StringBuilder</code> instance is just <code>builder</code>. <code>oResponseAccount</code> is also not clear about why it needs a "o" prefix (is that for "object?" - <strong>everything</strong> in .NET is an <code>object</code>!)...</p>\n<hr />\n<h3>Static</h3>\n<p>I think there's too much <code>static</code> going on here. It's static that blew up the <a href=\"http://en.wikipedia.org/wiki/Hindenburg_disaster\" rel=\"nofollow noreferrer\">Hindenburg</a> - it's best to avoid <code>static</code> classes and methods, and to instantiate your service instead, so that you can reduce <em>coupling</em> and run unit tests that isolate and control these dependencies, if possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T15:05:31.747",
"Id": "86013",
"Score": "1",
"body": "As a comment on the naming convention: if something is from CRM, that's all lowercase by design: CRM entities and fields have a lowercase and a camelCase or PascalCase way of referring to them depending on the environment (JS and C#), and not having a camelCase or PascalCase somewhat eases development. Whether this is the right call or not is food for thought, but regardless, it's impossible to change these this late in development, since these fields are not changeable in CRM anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T18:17:29.200",
"Id": "86046",
"Score": "0",
"body": "@NateKerkhofs see http://codereview.stackexchange.com/q/49003/23788 for an implementation (pending peer review!) of the *fluent interface* `XmlQueryBuilder` I described."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T14:47:09.290",
"Id": "48987",
"ParentId": "48782",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48987",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:04:25.373",
"Id": "48782",
"Score": "4",
"Tags": [
"c#",
"converting"
],
"Title": "Program for importing autotask contracts into dynamics CRM 2011"
} | 48782 |
<p>I just created the following code and am wondering whether it is logically correct (all other feedback is of course also welcome):</p>
<pre><code>public interface HandView extends View<Hand> {
void onCardAdded(final Card card);
void onCardPlayed(final int cardIndex);
void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
public static HandView merge(final HandView... handViews) {
return new HandView() {
@Override
public void onCardAdded(final Card card) {
Arrays.stream(handViews).forEach(handView -> handView.onCardAdded(card));
}
@Override
public void onCardPlayed(final int cardIndex) {
Arrays.stream(handViews).forEach(handView -> handView.onCardPlayed(cardIndex));
}
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
Arrays.stream(handViews).forEach(handView -> handView.onCardsSwapped(cardIndexOne, cardIndexTwo));
}
};
}
@FunctionalInterface
public static interface OnCardAddedListener extends HandView, Consumer<Card> {
@Override
default void accept(final Card card) {
onCardAdded(card);
}
@Override
void onCardAdded(final Card card);
@Override
default void onCardPlayed(final int cardIndex) { }
@Override
default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
}
@FunctionalInterface
public static interface OnCardPlayedListener extends HandView, IntConsumer {
@Override
default void accept(final int cardIndex) {
onCardPlayed(cardIndex);
}
@Override
default void onCardAdded(final Card card) { }
@Override
void onCardPlayed(final int cardIndex);
@Override
default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
}
@FunctionalInterface
public static interface OnCardsSwappedListener extends HandView {
@Override
default void onCardAdded(final Card card) { }
@Override
default void onCardPlayed(final int cardIndex) { }
@Override
void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
}
}
</code></pre>
<p>And then I used it like this in the following integration test (so you can see the usage):</p>
<pre><code>@Test
public void testRemoveCallbackNotTriggeredAfterRemoval() {
Hand hand = new Hand(5);
AtomicInteger counter = new AtomicInteger(0);
HandView.OnCardAddedListener handView = card -> counter.incrementAndGet();
hand.addViewCallback(handView);
HandView.OnCardAddedListener handView2 = card -> counter.incrementAndGet();
hand.addViewCallback(handView2);
hand.add(new MonsterCard("Test", 7, 7, MonsterModus.HEALING));
assertEquals(2, counter.get());
hand.removeViewCallback(handView2);
hand.add(new MonsterCard("Test Test", 5, 5, MonsterModus.HEALING));
assertEquals(3, counter.get());
hand.removeViewCallback(handView);
hand.add(new MonsterCard("Test Test Test", 3, 3, MonsterModus.HEALING));
assertEquals(3, counter.get());
}
</code></pre>
<p>Where <code>Hand.addViewCallback</code> expects an argument of type <code>HandView</code>.</p>
<p>It seems to be working, the only thing I am left off wondering is:</p>
<ul>
<li>Is it not normal to have <code>HandView extends OnCardAddedListener, OnCardPlayerListener, OnCardsSwappedListener</code>?</li>
</ul>
<p>The caveat then is that I don't think methods accepting an <code>HandView</code> now, would accept those sub-interfaces then.</p>
| [] | [
{
"body": "<p>Honestly, skiwi, you make things more complicated than they need to be.</p>\n\n<p>Please rename <code>View</code> to <code>Listener</code> to avoid confusion. Because that's really what they are, it's a Listener, not a View. It doesn't by itself provide any UI functionality.</p>\n\n<p>Prefixing your interfaces with <code>On</code> is, although understandable why you are doing it, not something I recommend or have seen been done in other places. You're already suffixing <code>Listener</code> to the name (which is what I would recommend, and what I have seen in lots of other code), no need to prefix the interface with <code>On</code>. The method names can be prefixed with <code>on</code>, as they have been already.</p>\n\n<p>Why are you bringing <code>IntConsumer</code> and <code>Consumer<Card></code> into your code? In what way does that help you? In my opinion, it doesn't help you at all. It creates more confusion than brings something good. If you want to \"transform\" an <code>IntConsumer</code> into a <code>CardPlayedListener</code>, use Java 8's method reference style by using something like <code>IntConsumer::accept</code>.</p>\n\n<p>Now, let's see if we can write more or less the same thing of your interface heirarchy but with fewer lines.</p>\n\n<pre><code>public interface HandListener {\n default void onCardAdded(final Card card) {}\n\n default void onCardPlayed(final int cardIndex) {}\n\n default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {}\n\n public static HandListener merge(final HandListener... handViews) {\n return new HandListener() {\n @Override\n public void onCardAdded(final Card card) {\n Arrays.stream(handViews).forEach(handView -> handView.onCardAdded(card));\n }\n\n @Override\n public void onCardPlayed(final int cardIndex) {\n Arrays.stream(handViews).forEach(handView -> handView.onCardPlayed(cardIndex));\n }\n\n @Override\n public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {\n Arrays.stream(handViews).forEach(handView -> handView.onCardsSwapped(cardIndexOne, cardIndexTwo));\n }\n };\n }\n\n @FunctionalInterface\n public static interface CardAddedListener extends HandListener {\n @Override\n void onCardAdded(final Card card);\n }\n\n @FunctionalInterface\n public static interface CardPlayedListener extends HandListener {\n @Override\n void onCardPlayed(final int cardIndex);\n }\n\n @FunctionalInterface\n public static interface CardsSwappedListener extends HandListener {\n @Override\n void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);\n }\n}\n</code></pre>\n\n<p>This way, you can keep having only <code>HandListener</code>s as listeners in your <code>Hand</code>, no need to split it up into three separate listeners. And if you want to easily create a listener that listens only to cards being swapped, you can easily do so. The trick here is that I'm overriding a default method and <em>removing</em> the implementation, thus making it abstract again. While letting the original <code>HandListener</code> interface have default implementations for all the methods.</p>\n\n<ul>\n<li>Original lines of code: <code>72</code></li>\n<li>New lines of code: <code>43</code></li>\n<li>Lines of code reduced by: <code>40%</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:45:45.080",
"Id": "48809",
"ParentId": "48783",
"Score": "5"
}
},
{
"body": "<p>Firstly, as usual, this answer assumes anyone reading this already saw <a href=\"https://codereview.stackexchange.com/a/48809/20251\">Simon's answer</a>.</p>\n\n<h2>MVC Architecture Issues</h2>\n\n<p>The problem with this design: </p>\n\n<pre><code>public interface HandView extends View<Hand> {\n //... some handler methods\n}\n</code></pre>\n\n<p>apart from being just confusing, is that it violates Interface Segregation. By violating this principle, namely that identifiable roles map to corresponding small interfaces, it forces the publisher of these events to depend on <code>HandView</code> and everything else it depends on. As a <em>publisher/generator</em> of some events I do not care if the <em>listeners</em> are views or loggers or statistic aggregators analyzers or just no-ops etc. </p>\n\n<p>Imagine for example, that <em>I want to dim the cards in the hand view when turn passes to the other player</em>. This feature requires that HandView also listens to some <code>onNextTurn()</code>, or <code>onTurnPassed(Player nextPlayer)</code> events. For example I am editing the <code>Hand</code> model class and want to raise some event. If I type <code>handView.</code> the IDE tells me I also have access to <code>onTurnPassed(Player nextPlayer)</code>. This not only means <code>Hand</code> depends on <code>Player</code> unnecessarily, it should not be able to raise such events.</p>\n\n<p>You are trying to do two things at once, which makes it also SRP violation: First it is a design contract for a View Component. It also should be the role contract for any component that listens to Hand Events. We generally need the first kind of interfaces for abstract factories, e.g. <code>HandView handView = createHandView()</code>. I need to make sure <code>HandView</code> interface can fill all roles a Hand View is supposed to fill, if I am to avoid unchecked casts etc non-type-safe operations. </p>\n\n<p>You can refactor it thus:</p>\n\n<pre><code>interface HandView extends HandListener, TurnListener, ..... {\n // Nothing\n // this is a design contract for Hand View component\n // I can use this interface as return type of an abstract factory\n // or to test features (functional test) \n // that involves multiple roles of a Hand View\n // Better still I can just delete this if I'm not doing either\n}\n\ninterface HandListener {\n //... handler methods for hand events\n}\n</code></pre>\n\n<h2>Per-event Repetition</h2>\n\n<p>Another problem point is per-event repetition, but before we go there let's see some other code smells, even though not as prominent, are more easily identifiable, and upon alleviation will help us deal with this problem:</p>\n\n<pre><code>@FunctionalInterface\npublic static interface OnCardPlayedListener extends HandView, IntConsumer {\n // ....\n @Override\n default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }\n</code></pre>\n\n<p>First of all this is a clearly identifiable case of <a href=\"http://sourcemaking.com/refactoring/refused-bequest\" rel=\"nofollow noreferrer\"><strong>Refused Bequest</strong></a>. <code>default</code> methods are supposed to be used for adding new behavior to existing interfaces, but here it is used to refuse some behavior of the super type. As said in the link if a subtype is refusing some behavior it may not be a serious problem but if it is refusing the interface of the extended type it is serious. Any new behavior added to <code>HandView</code> would be a <a href=\"http://sourcemaking.com/refactoring/shotgun-surgery\" rel=\"nofollow noreferrer\"><strong>shotgun surgery</strong></a> to types that extend it. <code>CardPlayedListener extends HandView</code> means a <code>CardPlayedListener</code> <strong>is a</strong> <code>HandView</code>; whereas, in fact it is just the opposite, a View of a Hand is a listener of Card-Played event. This is not, as you call it, '<strong>logically correct</strong>'. </p>\n\n<p>Let's also look at the signatures of the methods: we have a <code>void(Card)</code>, which isn't that bad, but the others are <code>void(int)</code>, <code>void(int, int)</code>. Even if this fact would not be an absolute indication for a refactoring; <strong>any model layer concerns, such as domain events should use domain types as parameters</strong> as much as possible. Suppose you decided to pass the <code>Card</code> played along with <code>the cardIndex</code> to the <code>onCardPlayed</code> methods, you would have to change all the handler code, even though they are working perfectly. With Java 8 adding a new method to an interface need not be a breaking change, but adding a parameter still is.</p>\n\n<p>Let's now look at <code>CardSwapped</code> more closely, <code>void (int cardIndexOne, int cardIndexTwo)</code>. It is clear that <code>cardIndexOne</code>, <code>cardIndexTwo</code> are some kind of <a href=\"http://sourcemaking.com/refactoring/data-clumps\" rel=\"nofollow noreferrer\"><strong>Data Clump</strong></a>. They don't <em>mean</em> anything on their own. They have some rules implicit or explicit that about them which means they are not ordinary integers. For example indexes can't be negative and if hand size is constant should be less than <code>HAND_SIZE</code>. Since a <code>swap cards (n, n)</code> type no-op would not trigger a <code>CardSwapped</code> event in the model, they probably should not be same etc. These kind of observations are indications that they are a part of some domain type.</p>\n\n<p>After all this talk, good news, our job is so easy: In case of domain events those domain types are Domain Events themselves! Just apply <a href=\"http://sourcemaking.com/refactoring/introduce-parameter-object\" rel=\"nofollow noreferrer\"><strong>Introduce Parameter Object</strong></a>, and were done.</p>\n\n<pre><code>class CardAdded {\n Card card;\n}\n\nclass CardPlayed {\n int cardIndex;\n}\n\nclass CardsSwapped {\n int cardIndexOne; \n int cardIndexTwo;\n}\n</code></pre>\n\n<p><code>onCardAdded(CardAdded)</code> is redundant so let's rename them to <code>void on(CardAdded)</code>. now it is more clear that a listener is some kind of <code>consumer</code> for the event.</p>\n\n<pre><code>@FunctionalInterface\ninterface Listener<T> {\n void on(T event);\n}\n</code></pre>\n\n<p>Because of type erasure we cannot say of course <code>HandListener extends Listener<CardAdded>, Listener<CardPlayed>, ...</code>. But think of this interface somewhat like a type-safe marker, a thing pre-generics <code>java.util.EventListener</code> could not be. Also note that <code>HandListener</code> does not listen to Hand Event<strong>s</strong> as a <code>CardAddedListener</code> listener listens to <code>CardAdded</code>. Which is a possibly extensible logical grouping of events, the other is is a single <em>specific</em> event.</p>\n\n<p>Composition-over-inheritence <code>HandListener</code>:</p>\n\n<pre><code>public interface HandListener {\n Listener<CardAdded> onCardAdded();\n\n Listener<CardAdded> onCardPlayed();\n\n Listener<CardAdded> onCardsSwapped();\n}\n</code></pre>\n\n<p><code>onCardAdded()</code> etc are just getters but I did not named them <code>getCardAddedHandler</code>, this way it is less wordy and less framework-y and more domain-y. This also make clear that they are not meant to be called like <code>handListener.onCardAdded().oc(cardAdded)</code>, and instead like <code>hand.onCardAdded().addListener(handView.onCardAdded())</code> in a similar way to Java <code>Observable</code> and .NET <code>event</code>s.</p>\n\n<p>I doubt you would need <code>merge</code> method at this point, but you can use something like this instead to chain generic interfaces, which cannot be used in varargs :</p>\n\n<pre><code> default Listener<T> andThen(Listener<T> otherListener) {\n return event -> {\n this.on(event);\n otherListener.on(event);\n };\n}\n</code></pre>\n\n<h2>Add/Remove Listener</h2>\n\n<p>I refactored the test case as below to make it compile with the changes I suggested:</p>\n\n<pre><code>@Test\npublic void shouldNotTriggerCallbackAfterRemoval() {\n\n // give them names indicating we don't care what they actually are\n MonsterCard someCard = new MonsterCard(\"Test\", 7, 7, MonsterModus.HEALING);\n MonsterCard someOtherCard = new MonsterCard(\"Test\", 5, 5, MonsterModus.HEALING);\n MonsterCard yetAnotherCard = new MonsterCard(\"Test\", 3, 3, MonsterModus.HEALING);\n\n Hand hand = new Hand(5);\n AtomicInteger counterOne = new AtomicInteger(0);\n Listener<CardAdded> listenerOne = cardAdded -> counterOne.incrementAndGet();\n\n AtomicInteger counterTwo = new AtomicInteger(0);\n Listener<CardAdded> listenerTwo = cardAdded -> counterTwo.incrementAndGet();\n\n hand.onCardAdded().addListener(listenerOne);\n hand.onCardAdded().addListener(listenerTwo);\n hand.add(someCard);\n assertEquals(1, counterOne.get());\n assertEquals(1, counterTwo.get());\n\n hand.onCardAdded().removeListener(listenerTwo);\n hand.add(someOtherCard);\n assertEquals(2, counterOne.get());\n assertEquals(1, counterTwo.get());\n\n hand.onCardAdded().removeListener(listenerOne);\n hand.add(yetAnotherCard);\n assertEquals(2, counterOne.get());\n assertEquals(1, counterTwo.get());\n}\n</code></pre>\n\n<p>I split the counters this way because it will makes sure the correct listener is removed.\nIf you only assert on the total number of listener invocations, removing any listener in\n<code>removeListener</code> will make it pass!</p>\n\n<p>Still IDE is complaining I'm not using the event parameter in the handlers and it is right.\nIf I'm calling the listeners with <code>null</code> or any other value regardless of which card is added the test would still pass. If you follow the \"Write just enough code to make the test pass.\" maxim, you will catch this kind of cases. Maybe you could use something like <code>AtomicReference<CardAdded> lastParameterOne</code>, and assert on it.</p>\n\n<p>I added these to make it pass; so names, design etc is just to give you an idea :</p>\n\n<pre><code>interface EventSource<T> {\n void addListener(Listener<T> listener);\n void removeListener(Listener<T> listener);\n}\n\ninterface Notifier<T> {\n void fire(T event);\n}\n\ninterface Publisher<T> extends EventSource<T>, Notifier<T> {\n}\n\nclass SimpleEvent<T> implements Publisher<T> {\n private final List<Listener<T>> listeners = new ArrayList<>();\n\n @Override\n public void fire(T event) {\n listeners.forEach(l -> l.on(event));\n }\n\n @Override\n public void addListener(Listener<T> listener) {\n listeners.add(listener);\n }\n\n @Override\n public void removeListener(Listener<T> listener) {\n listeners.remove(listener);\n }\n}\n\nclass Hand {\n public void addCard(Card card) {\n // ....\n fireCardAdded(card);\n }\n\n private void fireCardAdded(Card card) {\n onCardAdded().fire(new CardAdded(card));\n }\n\n private final Publisher<CardAdded> cardAdded = new SimpleEvent<>();\n public Publisher<CardAdded> onCardAdded() {\n return cardAdded;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T15:08:48.587",
"Id": "86014",
"Score": "0",
"body": "Absolutely brilliant! Your reminded me about why I use domain-specific `Event` classes in my own code. Perhaps I should have said this to skiwi a couple of days ago. Thanks for reminding me! And also thanks for teaching me some more stuff!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T07:09:44.357",
"Id": "86128",
"Score": "1",
"body": "@SimonAndréForsberg Thanks for the kind remarks. \nI'm glad my post has been helpful to you in some way. \nMany good practices become muscle memory for experienced programmers,\nbut I'm keeping things extra-pedantic \nand addressing not the regular users of CR but my past, fresh-out-of-school self."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T14:20:26.290",
"Id": "48985",
"ParentId": "48783",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48985",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:06:28.967",
"Id": "48783",
"Score": "10",
"Tags": [
"java",
"object-oriented",
"interface"
],
"Title": "Functional interface hierarchy in Java 8"
} | 48783 |
<p>JSFiddle: <a href="http://jsfiddle.net/yMSHa/" rel="nofollow">http://jsfiddle.net/yMSHa/</a> (Note: Real code uses JQuery 1.4.1)</p>
<p>HTML:</p>
<pre><code><div data-name="action" data-id="1">Do It A 1</div>
<div data-name="action" data-id="2">Do It A 2</div>
<div data-name="action" data-id="3">Do It A 3</div>
<div data-name="action" data-id="4">Do It A 4</div>
<div data-name="action" data-id="5">Do It A 5</div>
<div style="display:none;">
<div id="DoIt2">Do It B</div>
</div>
</code></pre>
<p>JS:</p>
<pre><code>var RepDiv = $('#DoIt2');
var OldDiv = null;
$('div[data-name="action"]').each(function (i, f) {
var actionid = $(f).attr('data-id');
if (actionid) {
$(f).css('cursor', 'pointer');
var OnClick = function () {
if (OldDiv) {
RepDiv.replaceWith(OldDiv);
OldDiv.click(OnClick);
}
OldDiv = $(this).replaceWith(RepDiv);
};
$(f).click(OnClick);
}
});
</code></pre>
<p>Below is some simple JavaScript which replaces one node at a time when that node is clicked. The idea behind this code is that a user can click on a node for that node to be expanded with more options.</p>
<p>I'm looking for a general review. My main concern is whether this code is written properly in terms of good practices.</p>
| [] | [
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li><p><code>i</code> and <code>f</code>, even for <code>forEach</code> are not very good names, pick something more meaningful.</p></li>\n<li><p>if <code>data-id</code> is the action id, perhaps you could have gotten/set it with <code>$().data('actionId')</code> ?</p></li>\n<li><p>The way your replacement function uses <code>OldDiv</code> and <code>RepDiv</code> smells like global variable abuse</p></li>\n<li><p>Consider using smallCamelCase, <code>actionid</code> -> <code>actionId</code>, <code>OldDiv</code> -> <code>oldDiv</code></p></li>\n<li><p>Consider caching <code>$(f)</code>, since you access it several times ( <code>var $f = $(f);</code> and then only access <code>$f</code> )</p></li>\n<li><p>This : <code>$(f).css('cursor', 'pointer');</code> really belongs in .css file</p></li>\n</ul>\n\n<p>Other than that, your code looks okay to me. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:37:34.660",
"Id": "85708",
"Score": "0",
"body": "I resolved the global variable concerns by wrapping the code in a function (i.e., `var GlobalWrapper = function() {/*My Code*/}();`). Setting `data-id` with `.data()` is a bit more difficult than setting it in an attribute, as divs are generated by an asp.net repeater that looks something like `<div data-id = '<%=Data.ID%>'>`. The interesting thing about `$(f).css('cursor', 'pointer');` is that it means the links don't look clickable until the events are loaded. I'm not sure if that should be considered a good thing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:51:59.160",
"Id": "48810",
"ParentId": "48784",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48810",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:16:58.990",
"Id": "48784",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Is this node replacement code reasonable?"
} | 48784 |
<p>I've got a <code>LoggingMessageHandler</code> that incoming requests on my WebApi application filter through.</p>
<pre><code>public class LoggingMessageHandler : DelegatingHandler
{
public ILogManager LogManager { get; set; } //injected
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var logger = SetupLogger(request);
var correlationId = request.GetCorrelationId().ToString();
var requestInfo = await LogRequest(request, logger, correlationId);
var response = await base.SendAsync(request, cancellationToken);
await LogResponse(response, logger, correlationId, requestInfo);
response.Headers.Add("X-Correlation-Id", correlationId);
return response;
}
private ILogger SetupLogger(HttpRequestMessage request)
{
var loggerName = request.RequestUri.AbsolutePath.Replace("/", "-");
var logger = LogManager.GetLogger(loggerName);
return logger;
}
private async Task<string> LogRequest(HttpRequestMessage request, ILogger logger, string correlationId)
{
var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);
var requestMessage = "";
if (request.Content != null)
requestMessage = await request.Content.ReadAsStringAsync();
await LogMessageAsync(logger, "Request", correlationId, requestInfo, requestMessage);
return requestInfo;
}
private async Task LogResponse(HttpResponseMessage response, ILogger logger, string correlationId, string requestInfo)
{
var responseMessage = string.Empty;
if (response.IsSuccessStatusCode)
{
if (response.Content != null)
responseMessage = await response.Content.ReadAsStringAsync();
}
else
responseMessage = response.ReasonPhrase;
await LogMessageAsync(logger, "Response", correlationId, requestInfo, responseMessage);
}
private async Task LogMessageAsync(ILogger logger, string type, string correlationId, string requestInfo, string body)
{
await Task.Run(() => logger.Info("{0} - {1} - API - {2}: \r\n{3}", correlationId, requestInfo, type, body));
}
}
</code></pre>
<p>When I run ANTS profiler, and test my application, > 70% of the CPU time is spent on this one line:</p>
<pre><code>await Task.Run(() => logger.Info("{0} - {1} - API - {2}: \r\n{3}", correlationId, requestInfo, type, body));
</code></pre>
<p>Is that expected?</p>
<p>Am I doing something wrong?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:09:57.590",
"Id": "85670",
"Score": "0",
"body": "`//injected` - are you using an IoC container?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:12:31.153",
"Id": "85672",
"Score": "1",
"body": "Yes... omitted for brevity (it's Autofac - via property injection)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:15:56.570",
"Id": "85674",
"Score": "0",
"body": "[This](http://stackoverflow.com/questions/7044497/how-do-i-create-an-asyncronous-wrapper-for-log4net) might be of interest. Log4Net has an async *appender* that looks readily available (not familiar with Log4Net)."
}
] | [
{
"body": "<p>I haven't used Autofac, but with Ninject you can use the logging extensions to automagically inject an <code>ILogger</code> into any class' constructor, so you can stick to constructor injection (which is always preferable over all other kinds of dependency injection techniques), with the only drawback that you have a <code>using Ninject.Extensions.Logging;</code> dependency on your module (given that your current code already has dependencies on Log4Net, I don't see it being an issue though).</p>\n\n<p>I haven't used Log4Net either, but <a href=\"https://stackoverflow.com/questions/7044497/how-do-i-create-an-asyncronous-wrapper-for-log4net\">you might be reinventing the wheel</a>.</p>\n\n<p>With NLog <a href=\"https://stackoverflow.com/a/3868618/1188513\">it looks like</a> you simply put an <code>async</code> attribute in your <code>targets</code> configuration and you're set:</p>\n\n\n\n<pre><code><targets async=\"true\">\n</code></pre>\n\n<p>And with the IoC container auto-resolving <code>ILogger</code> for you, all you really need is to constructor-inject an <code>ILogger</code> into whatever class requires logging functionality.</p>\n\n<hr>\n\n<p>I would look into implementing similar functionality with Autofac/Log4Net, or see what I get with Ninject/Log4Net or Ninject/NLog logging extensions, both available through NuGet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-28T19:29:32.313",
"Id": "167144",
"Score": "0",
"body": "This isn't really relevant to the problem. Matt's Mug is asking why log4net is consuming so much CPU."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-28T19:46:25.450",
"Id": "167145",
"Score": "0",
"body": "@AndrewRondeau swapping for a less bugged-up log provider sounds relevant to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-28T20:01:31.607",
"Id": "167148",
"Score": "0",
"body": "@AndrewRondeau problems to be solved should be solved on Stack Overflow. Here, any and all facets of the code are up for review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-28T20:06:15.007",
"Id": "167149",
"Score": "1",
"body": "@RubberDuck not my best answer though. looking at it again, I'm tempted to flag myself."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:28:22.287",
"Id": "48793",
"ParentId": "48788",
"Score": "3"
}
},
{
"body": "<p>Are you using a <code>BufferingForwardingAppender</code>? By default, it makes some very CPU intense calls for every logging statement. This pitfall is not documented.</p>\n\n<p>The short answer is that, when you configure your BufferingForwardingAppender, you need to configure it so it doesn't do expensive things like get a stack trace. (You probably aren't logging the things it's collecting, anyway!)</p>\n\n<p>There's a very good explanation of how to fix this at <a href=\"https://stackoverflow.com/a/11351400\">https://stackoverflow.com/a/11351400</a></p>\n\n<p>Reconfiguring my <code>BufferingForwardingAppender</code> made a major CPU improvement!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-28T19:37:31.910",
"Id": "92085",
"ParentId": "48788",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:07:32.487",
"Id": "48788",
"Score": "0",
"Tags": [
"c#",
"asynchronous",
"dependency-injection",
"logging"
],
"Title": "Async Log4net logging handler - High CPU usage on async call"
} | 48788 |
<p>I am new to Scala and I have written a function which uses pattern matching to filter words based on some conditions. It seems to work correctly but I am suspect that I haven't used the Scala pattern matching in the best way. I think this because each of my cases contain an <code>if</code> statement. I have not seen any examples where people use <code>if</code> statements in pattern matching functions so I'm thinking there might be a better way of doing this. Or maybe this particular usage does not fit well with pattern matching.</p>
<pre><code>def getImportance(token:String,stopWords:Set[String])={
token match{
case t if t.length()==1 => 0
case t if t.length()>15 => 0
case t if t.matches("\\p{Punct}+") => 0
case t if stopWords.contains(t.toLowerCase()) => 0
case _ => 1
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-28T21:05:10.657",
"Id": "89893",
"Score": "0",
"body": "Zero-length words get assigned an Importance of 1. I'm not sure that is correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T14:31:11.443",
"Id": "89980",
"Score": "0",
"body": "'token' is actually the output from a tokenizer which would not output zero-length words, so that case would never occur."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T19:23:32.243",
"Id": "90071",
"Score": "0",
"body": "Hmmm. I've heard that before."
}
] | [
{
"body": "<p>I don't think that using pattern matching is necessary in this case, you only have a few simple conditions that can be better represented with a simple <code>if</code>. See what you think about this solution:</p>\n\n<pre><code>def getImportance(token: String, stopWords: Set[String]) =\n if (token.length() == 1 || token.length() > 15 ||\n token.matches(\"\\\\p{Punct}+\") ||\n stopWords.contains(token.toLowerCase()))\n 0\n else\n 1\n</code></pre>\n\n<p>I believe it is simpler and easier to read. I think using patter matching for these simple cases only hinders the understanding of the code ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:49:16.680",
"Id": "48797",
"ParentId": "48789",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48797",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:15:43.700",
"Id": "48789",
"Score": "1",
"Tags": [
"beginner",
"scala"
],
"Title": "Pattern-matching function"
} | 48789 |
<p>I've written a recursive method for fetching grid neighbours in a symmetrical 2-dimensional grid, the problem is that I've found myself duplicating the code more or less into an overload to prevent my list from re-initializing everytime the method calls on itself.</p>
<p>I'm guessing there are ways to get around this that doesn't involve code duplication. Any help is appreciated.</p>
<pre><code>public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
var neighbours = new List<Cell<int>>();
if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell<int> neighbour;
switch (direction)
{
case Direction.Left:
x = -1;
break;
case Direction.Right:
x = 1;
break;
case Direction.Up:
y = -1;
break;
case Direction.Down:
y = 1;
break;
}
neighbour = cells[cell.Position.Row + y, cell.Position.Column + x];
neighbours.Add(neighbour);
GetNeighbours(neighbour, direction, neighboursToGet - 1, neighbours);
}
return neighbours;
}
public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet, List<Cell<int>> neighbours)
{
if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell<int> neighbour;
switch (direction)
{
case Direction.Left:
x = -1;
break;
case Direction.Right:
x = 1;
break;
case Direction.Up:
y = -1;
break;
case Direction.Down:
y = 1;
break;
}
neighbour = cells[cell.Position.Row + y, cell.Position.Column + x];
neighbours.Add(neighbour);
GetNeighbours(neighbour, direction, neighboursToGet - 1, neighbours);
}
return neighbours;
}
</code></pre>
| [] | [
{
"body": "<p>It seems to me that most of the body of the first GetNeighbours is extraneous. Wouldn't this be enough ?</p>\n\n<pre><code>public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)\n{\n var neighbours = new List<Cell<int>>();\n\n GetNeighbours(cell, direction, neighboursToGet, neighbours);\n\n return neighbours;\n}\n</code></pre>\n\n<p>Also, it is redundant to accept neighbours as a read/write parameter <em>and</em> to return it. However, if you are going to do it, you could as well write:</p>\n\n<pre><code>public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)\n{\n return GetNeighbours(cell, direction, neighboursToGet, new List<Cell<int>>());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:43:01.413",
"Id": "85676",
"Score": "0",
"body": "Good god.. You're absolutely right, I feel so dumbfounded right now :D .."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:31:31.203",
"Id": "48794",
"ParentId": "48790",
"Score": "6"
}
},
{
"body": "<p>As a first step, I'd change this implementation:</p>\n\n<pre><code>public List<Cell<int>> GetNeighbours(Cell<int> cell, \n Direction direction, \n int neighboursToGet)\n</code></pre>\n\n<p>To call into this one:</p>\n\n<pre><code>public List<Cell<int>> GetNeighbours(Cell<int> cell, \n Direction direction, \n int neighboursToGet, \n List<Cell<int>> neighbours)\n</code></pre>\n\n<p>But @Zoyd was faster to spot it ;)</p>\n\n<p>Bottom line is, when you find yourself hitting <kbd>Ctrl</kbd>+<kbd>C</kbd>, a big shiny red flag should be automatically raised in your mind before you even have time to hit <kbd>Ctrl</kbd>+<kbd>V</kbd> - if you're copying code, <em>you're doing it wrong</em>.</p>\n\n<hr>\n\n<p>I like that you're using an <code>enum</code> for your <code>Direction</code>. However you could also tackle the <code>switch</code> like this:</p>\n\n<pre><code>var directionalOffsets = new Dictionary<Direction, Func<Point, Point>>\n {\n { Direction.Left, point => new Point(point.X - 1, point.Y) },\n { Direction.Right, point => new Point(point.X + 1, point.Y) },\n { Direction.Up, point => new Point(point.X, point.Y - 1) },\n { Direction.Down, point => new Point(point.X, point.Y + 1) }\n };\n</code></pre>\n\n<p>Which, assuming <code>cell.Position</code> can be refactored into a <code>Point</code>, means <code>if (neighboursToget > 0)</code>...</p>\n\n<pre><code>var position = directionalOffsets[direction](cell.Position);\n</code></pre>\n\n<p>Then <code>neighbour</code> could be retrieved like this:</p>\n\n<pre><code>var neighbour = cells[position.Y, position.X];\n</code></pre>\n\n<p>Now it looks like <code>cells</code> has its dimensions reversed. I'd be more instinctively expecting this:</p>\n\n<pre><code>var neighbour = cells[position.X, position.Y];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:51:54.247",
"Id": "48798",
"ParentId": "48790",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:23:38.360",
"Id": "48790",
"Score": "5",
"Tags": [
"c#",
"recursion"
],
"Title": "Can I simplify this recursive grid search?"
} | 48790 |
<p>So my problem is this, I need to create a grid that in each cell there should be a 0 or a 1. These cells when clicked should toggle between 0 and 1. When hovered It should show the coordinates (ex: 1,5). Now the only way I got this to work was by creating three divs. One for the cell (which contains the number), one for the coordinates (this one is added dynamically) and another div (wrapper) that will on top of the other two and this one will have the event listeners. So basically I'm creating three divs for cell, now this work perfectly if its for a 10x10 grid, but when It gets to a more large (64x64) the browser starts to freeze.</p>
<p>This is how the HTML looks for a cell of the grid:</p>
<pre><code><div class="cell cellUnselected" id="cell_1_1" style="left: 0px; top: 0px;">0</div>
<div class="cellCoordinates cellCoordText" id="cell_1_1_coord" style="left: 0px; top: 0px;"></div>
<div class="cellWrapper" id="cell_1_1_wrapper" style="left: 0px; top: 0px;"></div>
</code></pre>
<p>I created a working fiddle please take a look:</p>
<p><a href="http://jsfiddle.net/vicgonzalez25/Tfs2M/">http://jsfiddle.net/vicgonzalez25/Tfs2M/</a></p>
<p>The problem: Once the grid start getting to a bigger size (ex: 64x64) by creating these three divs the browser starts to freeze.</p>
<p>My question is: is there a more efficient way of doing this grid ? Maybe using a table ? Thanks</p>
<p>In order to reproduce:</p>
<p>HTML:</p>
<pre><code><div id="gridLayout" class="gridLayout">
<div id="gridHeader">
<h2>Aperture Configuration:</h2>
Grid Size:
<input id="rows" type="number" min="1" max="50" value="10" width="40" size="3" onChange="GRASP.start();">
x
<input id="cols" type="number" min="1" max="50" value="10" width="40" size="3" onChange="GRASP.start();">
</div>
<div id="grid" class="gridContainer"></div>
<div id="matrixHeader" style="position:absolute">
<h2>Auto Correlation:</h2>
</div>
<div id="matrix" class="autocorrMatrixContainer"></div>
</div>
</code></pre>
<p>Javascript:</p>
<pre><code>(function(GRASP, $){
var GRID_ROWS,
GRID_COLS,
GRID_ELEMENT,
MATRIX_ROWS,
MATRIX_COLS,
MATRIXHEADER_ELEMENT,
MATRIX_ELEMENT,
A,C;
GRASP.config = {
gridContainer: "grid",
matrixContainer: "matrix",
matrixHeader: "matrixHeader"
};
GRASP.start = function(){
GRID_ROWS = $("#rows").val();
GRID_COLS = $("#cols").val();
MATRIX_ROWS = GRID_ROWS * 2 - 1;
MATRIX_COLS = GRID_COLS * 2 - 1;
createGrid();
createAutocorrelationMatrix();
};
function createGrid()
{
GRID_ELEMENT = $("#"+GRASP.config.gridContainer);
GRID_ELEMENT.html(""); // Clear Grid ;)
var coord;
var cell; // Contains the 1 or 0 based upon the cell selection
for(var i=1; i<=GRID_ROWS; i++){
for(var j=1; j<=GRID_COLS; j++){
coord = "" + i + "," + j;
$(document.createElement("div"))
.addClass("cellWrapper")
.attr("alt", coord)
.css("left", parseInt((j-1) * 36, 10) + "px")
.css("top", parseInt((i-1) * 36, 10) + "px")
.width(36).height(36)
.data("row", i).data("col", j)
.appendTo("#"+GRASP.config.gridContainer)
.on("click", cellClick)
.on("mouseenter", {isMatrix: false}, cellMouseEnter)
.on("mouseleave", cellMouseLeave);
$(document.createElement("div"))
.addClass("cell cellUnselected")
.attr("alt", coord)
.css("left", parseInt((j-1) * 36, 10) + "px")
.css("top", parseInt((i-1) * 36, 10) + "px")
.text("0")
.appendTo("#"+GRASP.config.gridContainer);
}
}
GRID_ELEMENT.height(36 * GRID_ROWS);
GRID_ELEMENT.width(36 * GRID_COLS);
}
function createAutocorrelationMatrix() {
MATRIXHEADER_ELEMENT = $("#" + GRASP.config.matrixHeader);
MATRIX_ELEMENT = $("#" + GRASP.config.matrixContainer);
MATRIX_ELEMENT.html("");
MATRIXHEADER_ELEMENT.css("top", parseInt(GRID_ELEMENT.offset().top + (GRID_ROWS * 36)) + "px");
MATRIX_ELEMENT.css("top", parseInt(MATRIXHEADER_ELEMENT.offset().top + MATRIXHEADER_ELEMENT.height()) + "px");
var cellSize = Math.ceil((GRID_ROWS * 36) / MATRIX_ROWS);
var coord;
for (var i=1;i<=MATRIX_ROWS;i++){
for (var j=1;j<=MATRIX_COLS;j++){
coord = "" + i + "," + j;
$(document.createElement("div"))
.addClass("autocorrMatrixCellWrapper")
.attr("alt", coord)
.css("left", parseInt((j-1) * cellSize, 10) + "px")
.css("top", parseInt((i-1) * cellSize, 10) + "px")
.data("row", i).data("col", j)
.appendTo("#"+GRASP.config.matrixContainer)
.on("mouseenter", {isMatrix: true}, cellMouseEnter)
.on("mouseleave", cellMouseLeave);
$(document.createElement("div"))
.addClass("autocorrMatrixCell autocorrMatrixCellUnselected")
.attr("alt", coord)
.css("left", parseInt((j-1) * cellSize, 10) + "px")
.css("top", parseInt((i-1) * cellSize, 10) + "px")
.appendTo("#"+GRASP.config.matrixContainer);
}
}
MATRIX_ELEMENT.height(36 * GRID_ROWS);
MATRIX_ELEMENT.width(36 * GRID_COLS);
}
function cellClick(){
var cell = $(this).next();
if(cell.text() == "0"){
cell.text("1");
} else {
cell.text("0");
}
}
function cellMouseEnter(e){
var i = $(this).data("row");
var j = $(this).data("col");
var x = e.data.isMatrix ? Math.ceil((GRID_ROWS * 36) / MATRIX_ROWS) : 36;
var div = $(document.createElement("div"))
.addClass("cellCoordinates cellCoordText")
.css("left", parseInt((j-1) * x, 10) + "px")
.css("top", parseInt((i-1) * x, 10) + "px")
.text(i + ", " + j);
$(this).before(div);
}
function cellMouseLeave(){
$(this).prev().remove();
}
}(window.GRASP = window.GRASP || {}, jQuery));
$(document).ready(function(){
GRASP.start();
});
</code></pre>
<p>CSS:</p>
<pre><code>.gridContainer {
/* width: inherit; */
/* float: left; */
position: relative;
top: 10px;
padding: 0 0 0 0;
display: block;
background: none;
font-family: Arial, Helvetica, Verdana, sans-serif;
}
.cell {
width: 36px;
height: 36px;
position: absolute;
z-index: 0;
/*
font-size: 16pt;
*/
font-size: x-large;
font-weight: normal;
font-style: normal;
color: #888888;
text-align: center;
display: table-cell;
vertical-align: middle;
line-height: 2em;
/* padding-top: 0.25em; */
}
.cellSelected {
background: #00CCFF;
}
.cellUnselected {
background: none;
}
.cellCoordinates {
width: 36px;
height: 36px;
position: absolute;
background: none;
z-index: 1;
}
.autocorrMatrixContainer {
position: absolute;
/* float: left; */
/* bottom: 0px; */
display: block;
background: none;
font-family: Arial, Helvetica, Verdana, sans-serif;
}
.autocorrMatrixCell {
width: 16px;
height: 16px;
position: absolute;
z-index: 0;
font-size: xx-small;
font-weight: normal;
font-style: normal;
color: #FFFFFF;
text-align: center;
display: table-cell;
vertical-align: middle;
line-height: 2em;
/* padding-top: 0.25em; */
}
.autocorrMatrixCellWrapper {
width: 16px;
height: 16px;
position: absolute;
background: none;
z-index: 2;
border-style: solid outset;
border-width: 1px;
border-color: black;
font-size: x-small;
}
.autocorrMatrixCellCoordText {
font-size: xx-small;
font-weight: normal;
font-style: normal;
padding-top: 2px;
padding-left: 3px;
color: #444444;
text-align: left;
vertical-align: top;
}
.cellWrapper {
width: 36px;
height: 36px;
position: absolute;
background: none;
z-index: 2;
border-style: solid outset;
border-width: 1px;
border-color: black;
font-size: normal;
}
.cellCoordText {
font-size: x-small;
font-weight: normal;
font-style: normal;
padding-top: 2px;
padding-left: 3px;
color: #444444;
text-align: left;
vertical-align: top;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:52:38.703",
"Id": "85677",
"Score": "0",
"body": "if you used XHTML you could create a single element and give it specific attributes for each of the three things, and then accompany all the differences with different CSS classes using Javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:53:00.147",
"Id": "85698",
"Score": "2",
"body": "@Malachi you can do the same in HTML5, using `data` attributes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:34:44.033",
"Id": "85706",
"Score": "0",
"body": "Please add your JS to this question, it is review worthy!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:36:07.290",
"Id": "85707",
"Score": "0",
"body": "Yes I was adding it ;) I added everything to reproduce.."
}
] | [
{
"body": "<p>Most interesting, a few pointers with 64 by 64 in mind.</p>\n\n<ul>\n<li><p><code>.appendTo(\"#\"+GRASP.config.gridContainer)</code> <- That has got to be really slow. You access a property of an object/property of an object, concatenate and then use jQuery to do document.getElementById. Cache that jQuery result and go for that.</p></li>\n<li><p>Except, every time you add an element, the browser rejiggles everything, which takes a surprising amount of calculations.. I would create a new <code>div</code> from scratch , attach all the elements under it and then add it to the document. This should speed up things tremendously.</p></li>\n<li><p>I love how you actually already have that jQuery result cached ;) <br><code>GRID_ELEMENT = $(\"#\"+GRASP.config.gridContainer);</code></p></li>\n</ul>\n\n<p>Not related to speed, but</p>\n\n<ul>\n<li><p>I would rather go for <code>$MATRIXHEADER</code> then <code>MATRIXHEADER_ELEMENT</code></p></li>\n<li><p>There is a bit of copy pastage going on between <code>createAutocorrelationMatrix</code> and <code>createGrid</code> (the <code>createElement</code> part), you should resolve that into a common helper function</p></li>\n<li><p>This:</p>\n\n<pre><code>function cellClick(){\n var cell = $(this).next();\n\n if(cell.text() == \"0\"){\n cell.text(\"1\");\n } else {\n cell.text(\"0\");\n }\n}\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>function cellClick(){\n var cell = $(this).next();\n cell.text( cell.text() == '0' ? '1' : '0');\n}\n</code></pre></li>\n</ul>\n\n<p>All in all, very readable code, I would not mind maintaining this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T20:09:25.690",
"Id": "85712",
"Score": "0",
"body": "Yeah for bullet 3 I was like, didn't I stored that in a variable ?? lol"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:01:51.113",
"Id": "48811",
"ParentId": "48792",
"Score": "5"
}
},
{
"body": "<p>I came up with quite a few changes, that I think may improve your speed quite dramatically.</p>\n\n<p>Do note that I removed everything related to your Auto Correlation Matrix. I was not sure what it was for, and I wanted to keep my example short and clear. The changes I made for the grid should be easily applicable to that matrix as well however.</p>\n\n<ul>\n<li><p>I don't understand why you need the 3 divs per cell. One div should be just fine! That is already 66% less DOM elements, and that should help...</p>\n\n<ul>\n<li>In my version the coordinates are stored in a data attribute, and shown trough a css <code>:before</code> pseudo element on <code>:hover</code>. That eliminates 2 event listeners per cell and means you can use the much better css hover.</li>\n<li>The value (0,1) is now stored in that one .cell div</li>\n<li>The click handler is attached to that same div</li>\n<li>Other advantages are that you don't need to use z-indexing and require a lot less css to display things correctly (that needs to be rendered for each cell)</li>\n</ul></li>\n<li><p>The suggestion of mr. Rabbit to insert all your html at once, in stead of cell by cell, was a very good one, as it drastically reduces the number of reflows. So I went ahead and implemented that one.</p></li>\n<li>I no longer position the cells <code>absolute</code>. You set the width and height of the wrapper, so just making them float left makes them automatically move into their correct position (just make sure to take the border width into account). This eliminates the need for all the position calculations that must take quite some time. If you want to keep the positions absolute, you should figure out some way of caching your coordinates. The y position is the same for all cells in row 1, the x postion is the same for all cells in column 1. Store the coordinates in some array map, and store them there the first time you calculate them and reuse them afterwards, or something in that order.</li>\n<li>I tried to put as little code as possible inside the inner for loop, as it gets executed a lot of times. I create the cell in a single step and don't use the <code>coord</code> variable anymore as it would only get used once.</li>\n<li>a little sidenote, why do you give your variables names in all caps? Isn't that only meant for constants? I kept them, as not relevant to the question, but find it very confusing...</li>\n</ul>\n\n<p>Enough said, time for some code:</p>\n\n<pre><code>(function (GRASP, $) {\n var GRID_ROWS,\n GRID_COLS,\n GRID_ELEMENT;\n\n GRASP.config = {\n gridContainer: \"grid\",\n matrixContainer: \"matrix\",\n matrixHeader: \"matrixHeader\"\n };\n\n GRASP.start = function () {\n GRID_ROWS = $(\"#rows\").val();\n GRID_COLS = $(\"#cols\").val();\n createGrid();\n };\n\n function createGrid() {\n GRID_ELEMENT = $(\"#\" + GRASP.config.gridContainer);\n var cell; // Contains the 1 or 0 based upon the cell selection\n var newGrid = $('<div id=\"grid\" class=\"gridContainer\" ></div>');\n\n\n for (var i = 1; i <= GRID_ROWS; i++) {\n for (var j = 1; j <= GRID_COLS; j++) {\n $(\"<div class='cell' data-hover-text='\"+i+\",\"+j+\"'>0</div>\")\n .appendTo(newGrid)\n .on(\"click\", cellClick);\n }\n }\n\n newGrid.height(38 * GRID_ROWS);\n newGrid.width(38 * GRID_COLS);\n\n GRID_ELEMENT.replaceWith(newGrid);\n }\n\n function cellClick() {\n $(this).text($(this).text() == \"0\" ? \"1\" : \"0\");\n }\n\n\n}(window.GRASP = window.GRASP || {}, jQuery));\n\n$(document).ready(function () {\n GRASP.start();\n});\n</code></pre>\n\n<p>And the updated fiddle (that contains the css for the coordinates on hover):\n<a href=\"http://jsfiddle.net/Tfs2M/2/\" rel=\"nofollow\">http://jsfiddle.net/Tfs2M/2/</a></p>\n\n<p>I did not do any benchmarks, but I am quite confident that this version is faster and more efficient. Anyway, I hope I gave you some good ideas and pointed in the right direction. Happy coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T23:36:11.010",
"Id": "49445",
"ParentId": "48792",
"Score": "1"
}
},
{
"body": "<p>In addition to the other suggestions, this is a <em>perfect</em> use case for delegation. Rather than using <code>on</code> on each element (so remove this line):</p>\n\n<pre><code>.on(\"click\", cellClick)\n</code></pre>\n\n<p>Use <code>on</code> on <code>newGrid</code>, giving it a selector:</p>\n\n<pre><code>newGrid.on('click', '.cell', cellClick);\n</code></pre>\n\n<p>This only needs to be done once, and reduces however many event listeners you'd have had before to just one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T23:43:45.607",
"Id": "49446",
"ParentId": "48792",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:27:49.180",
"Id": "48792",
"Score": "7",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Most efficient way of creating a grid in HTML with CSS?"
} | 48792 |
<p>I'm serializing instances of a lot of classes (in C# 3.0), and I've found myself writing this:</p>
<pre><code>[DataContract]
public class ModelClass
{
public static Guid GetID(ModelClass instance) { ... }
public static T FromID<T>(Guid value) where T : ModelClass { }
[DataMember] public Guid m_id { get; set; }
}
[DataContract]
public class ConcreteModel: ModelClass
{
[DataMember]
public string m_name;
// Stuff we don't serialize
public Sector m_sector;
public Theater m_theater;
public Weather m_weather;
public TerrainType m_terrainType;
// Link serialized ids to real objects through GetID & FromID
[DataMember] private Guid m_sectorID
{
get { return GetID(m_sector); }
set { m_sector = FromID<Sector>(value); }
}
[DataMember] private Guid m_theaterID
{
get { return GetID(m_theater); }
set { m_theater = FromID<Theater>(value); }
}
[DataMember] private Guid m_weatherID
{
get { return GetID(m_weather); }
set { m_weather = FromID<Weather>(value); }
}
[DataMember] private Guid m_terrainTypeID
{
get { return GetID(m_terrainType); }
set { m_terrainType = FromID<TerrainType>(value); }
}
}
</code></pre>
<p><code>ConcreteModel</code> is just one of many (~100) classes that will have some objects that are going to be saved using IDs, but not the whole objects, so we'll have to write that kind of properties a lot of times.</p>
<p>Is there any way of avoiding this? In C++ I'd be using macros, but not in C#...</p>
<p>My main concern here is not writing those properties all over again like 500 times or more. Any idea on how could I avoid that?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:39:14.937",
"Id": "85684",
"Score": "2",
"body": "You're pretty much stuck here, unless you generate the code with a `.tt` or use Nemerle or F# (which could actually make sense: they certainly do have macros). This is mostly because you're declaring methods for each property. Roslyn may help eventually. Additionally, since this is CodeReview, I have to comment on the horror of your hungarian notation. I'm fine with your alignment though, assuming you're using elastic tabstops and not spaces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T16:22:54.250",
"Id": "85784",
"Score": "0",
"body": "@Magus AFAIK, F# doesn't have macros."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T14:12:35.033",
"Id": "86003",
"Score": "0",
"body": "Ah, I overestimated the team's cleverness, then."
}
] | [
{
"body": "<p>As @Magus <a href=\"https://codereview.stackexchange.com/questions/48801/how-could-i-reduce-repetition-with-properties-methods#comment85684_48801\">commented</a>, this is as good as it gets.</p>\n\n<p>...almost.</p>\n\n<pre><code>[DataContract]\npublic class ConcreteModel: ModelClass\n</code></pre>\n\n\n\n<pre><code>[DataMember] public Guid m_id { get; set; }\n</code></pre>\n\n\n\n<pre><code>[DataMember]\npublic string m_name;\n</code></pre>\n\n<p>You're not consistent with how you're placing your <code>DataMemberAttribute</code> attributes; sometimes they're sitting on top of the decorated member, other times they're stuck in front, on the same line. I'd stick to consistently having them on top.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// Stuff we don't serialize\npublic Sector m_sector;\npublic Theater m_theater;\npublic Weather m_weather;\npublic TerrainType m_terrainType;\n</code></pre>\n</blockquote>\n\n<p>Why are these fields <code>public</code> in the first place? You are breaking encapsulation!</p>\n\n<blockquote>\n<pre><code>[DataMember] private Guid m_sectorID\n{\n get { return GetID(m_sector); }\n set { m_sector = FromID<Sector>(value); }\n}\n</code></pre>\n</blockquote>\n\n<p>I'm not familiar with serialization using <code>[DataMemberAttribute]</code>, but it's rather odd that you expose public fields and declare private serializable properties. Since the fields are exposed anyway, why not just do this?</p>\n\n<pre><code>private Sector m_sector;\n\n[DataMember]\npublic Guid m_sectorID\n{\n get { return GetID(m_sector); }\n set { m_sector = FromID<Sector>(value); }\n}\n</code></pre>\n\n<hr>\n\n<p>The naming is, as @Magus commented already, breaking all C# naming conventions. Drop the <code>m_</code> prefix, and use <em>PascalCase</em> for public members:</p>\n\n<pre><code>private Sector _sector; // or just \"sector\"\n\n[DataMember]\npublic Guid SectorId\n{\n get { return GetId(_sector); }\n set { _sector = FromId<Sector>(value); }\n}\n</code></pre>\n\n<hr>\n\n<p>If <code>ModelClass</code> isn't intended to be instantiated and only serve as a base class, you should make it <code>abstract</code> - also \"Class\" at the end of a class name is rather useless. How about this?</p>\n\n<pre><code>public abstract class ModelBase\n</code></pre>\n\n<p>The <code>public static</code> members could made non-static, and be <code>protected</code> so as to only be exposed to the derived types.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:03:14.100",
"Id": "85699",
"Score": "1",
"body": "I think I'd also rename `ModelClass`, but to something slightly different: `YourProgramModel`, `DataModel` or something similar. `Base` can sometimes be a nice suffix to avoid confusion, but it only conveys how it was implemented rather than what it's for, and `Model` is a very generic word which can mean different things in different contexts."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T17:53:04.357",
"Id": "48806",
"ParentId": "48801",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:10:42.287",
"Id": "48801",
"Score": "4",
"Tags": [
"c#",
".net",
"serialization"
],
"Title": "How could I reduce repetition with properties/methods?"
} | 48801 |
<p>Here is my entry for the Code Jam problem <a href="https://code.google.com/codejam/contest/2984486/dashboard#s=p1" rel="nofollow">Full Binary Tree</a> (I didn't compete but tackled the problem afterwards). It does solve the provided inputs, so I suppose it is correct. I am looking for any suggestions regarding the code. One thing I don't like is the fact that the Node constructor clears the array that it receives as a parameter, do you see a clean way to fix this ? Is it possible without declaring an extra class wrapping Node ?</p>
<pre><code>import java.util.*;
class Node {
static NodeComparator cmp = new NodeComparator();
private ArrayList<Node> children = new ArrayList<>();
private int nDescendants = 0; // descendants = number of children and, recursively, children of children, etc.
public int getNDescendants() {
return nDescendants;
}
// turns the tree into a full binary tree by removing as few nodes as possible
public void makeFullBinary() {
// first, recursively make all the children into full binary trees
for (Node n : children) {
n.makeFullBinary();
}
// sort the children from least to most number of descendants
Collections.sort(children, cmp);
// remove descendants as needed to end up with 0 or 2
while ((children.size() != 0) && (children.size() != 2)) {
children.remove(0);
}
// recompute the number of descendants
nDescendants = 0;
for (Node c : children) {
nDescendants += 1 + c.getNDescendants();
}
}
// builds a tree from an array of booleans (adjacency matrix)
// edges is destroyed after the constructor is called
public Node(boolean[][] edges, int root) {
for (int i = 0; i < edges.length; i++) {
if (edges[root][i]) {
edges[root][i] = false;
edges[i][root] = false;
children.add(new Node(edges, i));
}
}
for (Node c : children) {
nDescendants += 1 + c.getNDescendants();
}
}
}
// comparator for sorting only
class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node n0, Node n1) {
return n0.getNDescendants() - n1.getNDescendants();
}
}
public class Program {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nCases = in.nextInt();
in.nextLine();
for (int caseNumber = 1; caseNumber <= nCases; caseNumber++) {
int nNodes = in.nextInt();
in.nextLine();
boolean[][] edges = new boolean[nNodes][nNodes];
for (int i = 0; i < nNodes-1; i++) {
String[] s = in.nextLine().split(" ");
int x = Integer.parseInt(s[0])-1;
int y = Integer.parseInt(s[1])-1;
edges[x][y] = true;
edges[y][x] = true;
}
int maxDescendants = 0;
boolean [][] e = new boolean[nNodes][nNodes];
for (int i = 0; i < nNodes; i++) {
for (int a = 0; a < nNodes; a++) {
for (int b = 0; b < nNodes; b++) {
e[a][b] = edges[a][b];
}
}
Node tree = new Node(e, i);
tree.makeFullBinary();
maxDescendants = Math.max(maxDescendants, tree.getNDescendants());
}
System.out.print("Case #");
System.out.print(caseNumber);
System.out.print(": ");
System.out.println(nNodes - maxDescendants - 1);
}
in.close();
}
}
</code></pre>
| [] | [
{
"body": "<p>Oke I'm going to have with this review the point of <b>javadoc, namings and methods.</b></p>\n\n<h2>First :</h2>\n\n<p>You make comment, what is actually good but try to make javadoc in stead of commenting everything.</p>\n\n<pre><code>// comparator for sorting only\nclass NodeComparator implements Comparator<Node> {\n @Override\n public int compare(Node n0, Node n1) {\n return n0.getNDescendants() - n1.getNDescendants();\n } \n}\n</code></pre>\n\n<p>should be :</p>\n\n<pre><code>/**\n* Comparator for sorting on descendants\n*/\nclass NodeComparatorNDescendants implements Comparator<Node> {\n @Override\n public int compare(Node n0, Node n1) {\n return n0.getNDescendants() - n1.getNDescendants();\n } \n}\n</code></pre>\n\n<p><b>Why :</b><br/><br/>\nThis cause you no more effort than commenting, but you can generate a complete javadoc what other persons can look into.<br/>\nAlso see that I added the on what you are sorting there.<br/>\nAt last I changed also the class name.<br/> Now you will already see without the javadoc on what you will compare.<br/>\n<b>Note :</b> Effective class name helps you later also, take this code after a year not seen and you will need to see the implementation of the comparator if you want to know on what it compares.</p>\n\n<h2>Second :</h2>\n\n<p>Like I already said in the first point, naming is everything. <br/>\n<code>Node n</code> => why just not <code>Node node</code>.\nOther example : <code>NodeComparator cmp</code> => <code>NodeComparator nodeComparator</code><br/>\nThis will not take more memory from your program if you have fear for that :), and if you use autocomplete this will not lose time to program.<br/></p>\n\n<h2>Thirth :</h2>\n\n<p>Small effective methods are better than big ones that do a lot.<br/>\nHow less code in a method => the sooner you find the bug because your method complexity is lower.</p>\n\n<p><b>Example :</b></p>\n\n<pre><code>// turns the tree into a full binary tree by removing as few nodes as possible\npublic void makeFullBinary() {\n // first, recursively make all the children into full binary trees\n for (Node n : children) {\n n.makeFullBinary(); \n }\n // sort the children from least to most number of descendants\n Collections.sort(children, cmp);\n // remove descendants as needed to end up with 0 or 2\n while ((children.size() != 0) && (children.size() != 2)) {\n children.remove(0);\n }\n // recompute the number of descendants\n nDescendants = 0;\n for (Node c : children) {\n nDescendants += 1 + c.getNDescendants();\n }\n}\n</code></pre>\n\n<p>should be :</p>\n\n<pre><code>// turns the tree into a full binary tree by removing as few nodes as possible\npublic void makeFullBinary() {\n\n createBinaryTree();\n Collections.sort(children, cmp);\n adjustBinaryTree();\n recalculateDescendants();\n}\n\nprivate void createBinaryTree () {\n for (Node n : children) {\n n.makeFullBinary();\n }\n}\n\nprivate void adjustBinaryTree () {\n while ((children.size() != 0) && (children.size() != 2)) {\n children.remove(0);\n }\n}\n\nprivate void recalculateDescendants () {\n nDescendants = 0;\n for (Node c : children) {\n nDescendants += 1 + c.getNDescendants();\n }\n}\n</code></pre>\n\n<p><b>Why :</b><br/><br/>\nEach method is shorter then the whole method.<br/>\nIt's easier to read and to comprehent the actual doing of the method.<br/>\nNow there is just one thing what bothers me, but it is an discussion amoung programmers, that's the reason I didn't changed it but still going to say<br/>\n<code>nDescendants</code> is a calculated field.<br/>\nFor more rightness you should remove the int and set the <code>recalculateDescendants</code> code in the <code>getNDescendants()</code>.<br/>\nYes you lose performance and you gain an always correctness of the getter.<br/>\nNow you see directly why there are always discussions about that.</p>\n\n<p>Hope this helps you already to improve yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:46:20.670",
"Id": "85724",
"Score": "0",
"body": "Thanks for the review. It is true that I should definitely use Javadoc. In this particular case, it was important for nDescendants to be fast because it was called very often and time was limited, so it had to be stored. Also, I would very much want the correctness of nDescendants to be an invariant, and it is not true if makeFullBinary is split into three smaller methods, so I would think twice before doing that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:23:50.437",
"Id": "48808",
"ParentId": "48803",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T17:26:39.187",
"Id": "48803",
"Score": "4",
"Tags": [
"java",
"tree",
"programming-challenge"
],
"Title": "Google Code Jam 2014: Full Binary Tree"
} | 48803 |
<p>Because the TPL backport not only contains Parallel.* but also PLINQ, concurrent collections, etc, I will try to use this one.</p>
<p>Just for fun, I profiled both the TPL implementation and my own, in the very basic and naive test, mine was actually a little bit faster.</p>
<p><strong>Microsoft TPL backport:</strong> 00:00:17.0673098<br>
<strong>My Implementation:</strong> 00:00:16.9210535<br>
Intel Q6600 (quad-core), 4GB of RAM, Win8.1(x64), VS2013 targetting .NET 3.5</p>
<p>The code is <a href="https://gist.github.com/0x53A/30f9c3005932db2c74b9" rel="noreferrer">here (github gist)</a>, the colorful output of the Concurrency Visualizer is below:</p>
<p><img src="https://i.stack.imgur.com/GkpnQ.png" alt="enter image description here"></p>
<p>This negligeable performance difference (in the best case) gets outweight by the many optimisations the .NET team put in for special cases.</p>
<p><strong>Question:</strong></p>
<p>To ease working with multithreaded code, I wanted to implement a version of <code>Parallel.ForEach</code> for .NET 3.5.</p>
<p>We are for the moment stuck with 3.5 and cannot upgrade. We cannot use external libraries like TPL.</p>
<p>I found <a href="http://www.codeproject.com/Articles/33084/Poor-Man-s-Parallel-ForEach-Iterator" rel="noreferrer">this</a> via Google, but this threw sporadic exceptions during runtime, and because I couldn't find another Version I decided to roll my own.</p>
<p>I did of course test it, but i am always a bit cautious with multithreaded code.</p>
<pre><code>public class Parallel
{
public static void ForEach<T>(IEnumerable<T> items, Action<T> action)
{
if (items == null)
throw new ArgumentNullException("enumerable");
if (action == null)
throw new ArgumentNullException("action");
var resetEvents = new List<ManualResetEvent>();
foreach (var item in items)
{
var evt = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem((i) =>
{
action((T)i);
evt.Set();
}, item);
resetEvents.Add(evt);
}
foreach (var re in resetEvents)
re.WaitOne();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T17:53:06.200",
"Id": "85689",
"Score": "0",
"body": "You could replace the foreach on resetEvents with `WaitHandle.WaitAll(resetEvents.ToArray())`. See [WaitHandle.WaitAll](http://msdn.microsoft.com/en-us/library/System.Threading.WaitHandle.WaitAll(v=vs.110).aspx). It even lets you provide a timeout if you need to support actions which could never terminate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:00:16.260",
"Id": "85690",
"Score": "0",
"body": "Unfortunately, WaitHandle.WaitAll only supports up to 64 items AND throws an Exception on a STA Thread..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:23:37.047",
"Id": "85691",
"Score": "1",
"body": "Your wish is granted: https://www.nuget.org/packages/TaskParallelLibrary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:42:42.123",
"Id": "85695",
"Score": "1",
"body": "unfortunately, i cannot use external libraries (i could, but it would be a big hassle)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T20:57:48.020",
"Id": "85717",
"Score": "2",
"body": "The package Task Parallel Library for .NET 3.5 1.0.2856 that Jessie referred to is published by Microsoft. From the nuget page: \"This backport was shipped with the Reactive Extensions (Rx) library up until v1.0.2856.0. It can be downloaded from http://www.microsoft.com/download/en/details.aspx?id=24940\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:06:24.150",
"Id": "85719",
"Score": "2",
"body": "The NuGet package contains one assembly, System.Threading.dll, which is signed by Microsoft and has a PublicKeyToken=31bf3856ad364e35 (same as System.Workflow.Activities). I guess you need to evaluate if the hassle of getting permission to use this 'external' library out weighs the hassle of writing your own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T01:21:07.117",
"Id": "85733",
"Score": "0",
"body": "Does the other version of `Parallel.ForEach` also wait until all tasks complete?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T10:31:33.167",
"Id": "85800",
"Score": "0",
"body": "[This Microsoft guide](http://www.microsoft.com/en-us/download/details.aspx?id=19222) has a very good implementation of Parallel.ForEach"
}
] | [
{
"body": "<blockquote>\n<pre><code> if (items == null)\n throw new ArgumentNullException(\"enumerable\");\n</code></pre>\n</blockquote>\n\n<p>In the execution path where this exception is thrown, the reported argument name will not match the <em>actual</em> argument name. If this is the result of a <em>rename refactoring</em> (i.e. it's <em>the parameter formerly known as \"enumerable\"</em>), it's unfortunate, the string literal wasn't taken care of. That doesn't happen with ReShaper performing the refactoring, but if you're using the refactoring built into VS, I'm not sure it handles string literals; if you've <em>manually</em> \"renamed\" the argument, ...<em>next time, use refactor/rename</em>! ;)</p>\n\n<p>Your implementation queues a work item for each item in <code>items</code>.</p>\n\n<blockquote>\n <h3><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx\" rel=\"nofollow noreferrer\">ThreadPool.QueueUserWorkItem</a></h3>\n \n <p><em>Queues a method for execution. The method executes when a thread pool thread becomes available.</em></p>\n</blockquote>\n\n<p>The interesting bit is about its <em>return value</em>:</p>\n\n<blockquote>\n <p><strong>Return Value</strong></p>\n \n <p><strong>Type</strong>: <code>System.Boolean</code></p>\n \n <p><strong>true</strong> if the method is successfully\n queued; <code>NotSupportedException</code> is thrown if the work item could not be\n queued.</p>\n</blockquote>\n\n<p>There's the slight possibility that thread pooling might not be supported on the platform code is running on (from what I gathered of reasons for this exception to be thrown), in which case the first iteration will throw a <code>NotSupportedException</code> that the <code>ForEach</code> code might not be expecting at all... but letting it bubble up might just be the best thing to do in this case.</p>\n\n<hr>\n\n<p>If I correctly understand what's going on, you're essentially spawning a thread to run an <code>action</code>, for <strong>each</strong> <code>item</code> in <code>items</code>. This might not be as efficient as you'd think it is: there's only so many concurrent operations that can happen on a quad-core processor, and then there's overhead too; sometimes it's more efficient to simply run the tasks sequentially.</p>\n\n<p>And that's what <code>Parallel.ForEach</code> does:</p>\n\n<blockquote>\n <h3><a href=\"http://msdn.microsoft.com/en-us/library/dd992001(v=vs.110).aspx\" rel=\"nofollow noreferrer\">Parallel.ForEach</a></h3>\n \n <p><em>Executes a foreach operation on an <code>IEnumerable</code> in which iterations <strong>may</strong> run in parallel.</em></p>\n</blockquote>\n\n<p>Thus, I'd use your implementation with care, and perhaps use a profiler and benchmark against a \"normal\" <code>foreach</code> for a given number of iterations, but then your dev environment <em>might</em> have different computing power than your test and/or production environments, so careful with benchmarks, too.</p>\n\n<p>It might be simpler to use the Microsoft NuGet package <a href=\"https://codereview.stackexchange.com/questions/48804/implementation-of-parallel-foreach/48834#comment85691_48804\">@JesseC.Slicer</a> and <a href=\"https://codereview.stackexchange.com/questions/48804/implementation-of-parallel-foreach#comment85719_48804\">@PhilBolduc</a> mentioned in the comments...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T00:18:54.717",
"Id": "85730",
"Score": "1",
"body": "Credit for point out the TaskParallelLibrary package goes to @Jesse C. Slicer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T16:27:23.607",
"Id": "85785",
"Score": "3",
"body": "The point of `ThreadPool` is that it *doesn't* spawn a new thread for each operation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T23:43:53.550",
"Id": "48834",
"ParentId": "48804",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48834",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T17:43:05.330",
"Id": "48804",
"Score": "12",
"Tags": [
"c#",
".net",
"multithreading"
],
"Title": "Implementation of Parallel.ForEach for .NET 3.5"
} | 48804 |
<p>This seems like an awful lot of code and I'm guessing can be condensed and made more efficient somehow. Can anyone suggest this to me at all?</p>
<pre><code>// Add the active class to the first element
$('.indexWorkDetailsInner:first').addClass('active');
// Next Button Click
$('.indexWorkRight').click(function() {
// Move all except the active element to the left
$('.indexWorkDetailsInner').each(function() {
if($(this).hasClass('active')) { }
else {
$(this).css({'left':'-450px'});
}
});
// Animate the active element off the screen
$('.indexWorkDetailsInner.active').stop().animate({'left' : '450px'}, 1000, function () {
$(this).removeClass('active').css({'left':'-450px'}); // Remove the active class, and move element back to the left
$(this).next('.indexWorkDetailsInner').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
$('.indexWorkDetailsInner:last').after($('.indexWorkDetailsInner:first')); // Move the last element to after the first
});
});
// Previous Button Click
$('.indexWorkLeft').click(function() {
// Move all except the active element to the right
$('.indexWorkDetailsInner').each(function() {
if($(this).hasClass('active')) { }
else {
$(this).css({'left':'450px'});
}
});
// Animate the active element off the screen
$('.indexWorkDetailsInner.active').stop().animate({'left' : '-450px'}, 1000, function () {
$(this).removeClass('active').css({'left':'450px'}); // Remove the active class, and move element back to the right
$('.indexWorkDetailsInner:first').before($('.indexWorkDetailsInner:last')); // Move the first element before the last item
$(this).prev('.indexWorkDetailsInner').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the previous element in to view
});
});
// Add the active class to the first element
$('.indexMonitorWork img:first').addClass('active');
// Next Button Click
$('.indexWorkRight').click(function() {
// Move all except the active element to the left
$('.indexMonitorWork img').each(function() {
if($(this).hasClass('active')) { }
else {
$(this).css({'left':'-370px'});
}
});
// Animate the active element off the screen
$('.indexMonitorWork img.active').stop().animate({'left' : '370px'}, 1000, function () {
$(this).removeClass('active').css({'left':'-370px'}); // Remove the active class, and move element back to the left
$(this).next('.indexMonitorWork img').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view
$('.indexMonitorWork img:last').after($('.indexMonitorWork img:first')); // Move the last element to after the first
});
});
// Previous Button Click
$('.indexWorkLeft').click(function() {
// Move all except the active element to the right
$('.indexMonitorWork img').each(function() {
if($(this).hasClass('active')) { }
else {
$(this).css({'left':'370px'});
}
});
// Animate the active element off the screen
$('.indexMonitorWork img.active').stop().animate({'left' : '-370px'}, 1000, function () {
$(this).removeClass('active').css({'left':'370px'}); // Remove the active class, and move element back to the right
$('.indexMonitorWork img:first').before($('.indexMonitorWork img:last')); // Move the first element before the last item
$(this).prev('.indexMonitorWork img').animate({'left' : '0px'}, 1000).addClass('active'); // Animate the previous element in to view
});
});
</code></pre>
<p>It is code for a work carousel. The first two functions move the text left and right. The bottom function moves the image screenshot.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:34:17.803",
"Id": "85693",
"Score": "0",
"body": "Instead of looping, you can just select on both classes at the same time: `$('.indexWorkDetailsInner.active')`. Also, avoid empty blocks (you can negate conditions, you know). Also, looks like you are duplicating the entire thing – do it once, but make it configurable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:39:17.400",
"Id": "85694",
"Score": "0",
"body": "It is duplicated because the top half moves the text, the bottom half moves the image. I know calling `$('.indexWorkDetailsInner')` all the time is not good and it should be a variable. If I do this, is there a way to then call `:first`, `:last` and also do the part `.active` with that variable?\n\nFor example:\n\n`var innerWork = $('.indexWorkDetailsInner');`\n\nIs there a way to then do something like `(innerWork)+('.active')` to be the same as `$('.indexWorkDetailsInner.active')` and again `(innerWork:first)` to be the same as `$('.indexWorkDetailsInner:first')`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:31:14.837",
"Id": "85705",
"Score": "1",
"body": "[Yes](http://api.jquery.com/filter/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:43:46.720",
"Id": "85709",
"Score": "0",
"body": "Excellent. Got it working perfectly now :)"
}
] | [
{
"body": "<p>With help from @Ingo I got it down to the following, which I think is better.</p>\n\n<pre><code>var innerWork = $('div.indexWorkDetailsInner');\nvar innerImg = $('div.indexMonitorWork img');\n\n// Add the active class to the first element\ninnerWork.first().addClass('active');\ninnerImg.first().addClass('active');\n\nfunction workAnimate(direction){\n\n var signOne, signTwo;\n\n if(direction === \"right\" ) { signOne = '-'; signTwo = ''; }\n if(direction === \"left\" ) { signOne = ''; signTwo = '-'; }\n\n innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left\n innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left\n\n // Animate the active element off the screen\n innerWork.filter('.active').stop().animate({'left' : signTwo + '450px'}, 1000, function () {\n\n $(this).removeClass('active').css({'left': signOne + '450px'}); // Remove the active class, and move element back to the left\n if(direction === \"right\" ) {\n $(this).next(innerWork).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view\n innerWork.filter(':last').after(innerWork.filter(':first')); // Move the last element to after the first\n } else {\n innerWork.filter(':first').before(innerWork.filter(':last')); // Move the first element before the last item\n $(this).prev(innerWork).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view\n }\n });\n\n // Animate the active element off the screen\n innerImg.filter('.active').stop().animate({'left' : signTwo + '370px'}, 1000, function () {\n\n $(this).removeClass('active').css({'left': signOne + '370px'}); // Remove the active class, and move element back to the left\n if(direction === \"right\" ) {\n $(this).next(innerImg).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the next element in to view\n innerImg.filter(':last').after(innerImg.filter(':first')); // Move the last element to after the first\n } else {\n innerImg.filter(':first').before(innerImg.filter(':last')); // Move the first element before the last item\n $(this).prev(innerImg).animate({'left' : '0px'}, 1000).addClass('active'); // Animate the previous element in to view\n }\n });\n}\n\n// Next Button Click\n$('div#indexWorkRight').on('click', function() {\n workAnimate('right');\n});\n\n// Previous Button Click\n$('div#indexWorkLeft').on('click', function() {\n workAnimate('left');\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T19:44:36.463",
"Id": "48814",
"ParentId": "48807",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T18:14:50.303",
"Id": "48807",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Work carousel efficiency"
} | 48807 |
<p>I have a database that, among other things, stores publications and publication tags. There is a many-to-many relationship between publications and publication tags. Simply put, I query the database for all the publication tags and the corresponding id. While looping through that query, I have a nested query to count the number of times each tag is used. Once I have all the information, I then loop through all results to display the tags. That seems inefficient, but I can't think of a better way. Thoughts?</p>
<pre><code>//get the tag id and tag names
try {
$stmt = $pdo->prepare('SELECT publicationTagId, tagName FROM publicationTags WHERE EXISTS (SELECT publicationTags_publicationTagId FROM publications_have_publicationTags WHERE publicationTags_publicationTagId = publicationTagId)ORDER BY tagName');
$stmt->execute();
} catch(PDOException $e) {
echo "<p>Oops!</p>";
}
$tags = $stmt->fetchAll();
$tagCount = array();
//iterate through the tags and get usage counts
foreach($tags as $tag) {
try {
$stmt = $pdo->prepare('SELECT count(publicationTags_publicationTagId) FROM publications_have_publicationTags WHERE publicationTags_publicationTagId = :pubId');
$stmt->execute(array(':pubId'=>$tag[0]));
while($tagCounter = $stmt->fetch()) {
$tagCount[] = $tagCounter[0];
}
} catch(PDOException $e) {
echo "<p>Oops!</p>";
}
}
//get the min and max usages
$minUse = min($tagCount);
$maxUse = max($tagCount);
//max and min font size
$maxPercent = 150;
$minPercent = 100;
//prevent divide by zero
$divisor = ($maxUse == $minUse) ? 1 : $maxUse - $minUse;
//multiplier
$multiplier = ($maxPercent - $minPercent) / $divisor;
//set up list
echo "<ul class='tagCloudList'>";
$counter = 0;
//loop through tags
foreach($tags as $tag) {
$size = $minPercent + ($tagCount[$counter][0]-$minUse)*$multiplier;
echo "<li><a href='?pubTag=$tag[1]' style='font-size:$size%'>$tag[1]</a></li>";
$counter++;
}
//reset link
echo "<li><a href='publications.php'>View All</a></li>";
//close the list
echo "</ul>";
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p><em>Note:</em> Your table and especially column names are quite verbose. I would remove the table name from each column as a first start and be more consistent with the names. I'll use better names below. You'll have to map it out yourself.</p>\n</blockquote>\n\n<p>You can get the used tags with their counts in a single query with this statement:</p>\n\n<pre><code>select\n tag_id, \n tag_name, \n count(publication_id)\nfrom\n tag join publication_tag using (tag_id) \ngroup by\n tag_id\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T03:38:29.173",
"Id": "85739",
"Score": "0",
"body": "I agree on the table names. It's my punishment for being lazy and using mysql workbench. It's a little late in the game to rework the database, but I'll consolidate the query. If it checks out I'll accept. Until then, +1...thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T04:50:42.547",
"Id": "85740",
"Score": "0",
"body": "@MatthewJohnson I agree with you on MySQL WorkBench. I took the time to fix all the names as I built the model, but it's a shame it can't be configured with naming styles."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T01:40:10.920",
"Id": "48838",
"ParentId": "48818",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:15:10.927",
"Id": "48818",
"Score": "1",
"Tags": [
"php",
"performance",
"mysql",
"pdo"
],
"Title": "Tag Cloud using 2 queries (one nested), and a foreach loop: Is there a better way?"
} | 48818 |
<p>This PHP script will translate shots on 18 holes to a total under par or E which is 0.</p>
<pre><code>$course = array(0, 4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);
if ($totalpar == 0) {
$score = 'E';
$played = 0;
} else {
if(!empty($h1)) {
$h1score = $course[1] - $h1;
} else {
$h1score = 0;
}
if (!empty($h2)) {
$h2score = $course[2]- $h2;
} else {
$h2score = 0;
}
if (!empty($h3)) {
$h3score = $course[3] - $h3;
} else {
$h3score = 0;
}
if (!empty($h4)) {
$h4score = $course[4] - $h4;
} else {
$h4score = 0;
}
if (!empty($h5)) {
$h5score = $course[5] - $h5;
} else {
$h5score = 0;
}
if (!empty($h6)) {
$h6score = $course[6] - $h6;
} else {
$h6score = 0;
}
if (!empty($h7)) {
$h7score = $course[7] - $h7;
} else {
$h7score = 0;
}
if (!empty($h8)) {
$h8score = $course[8] - $h8;
} else {
$h8score = 0;
}
if (!empty($h9)) {
$h9score = $course[9] - $h9;
} else {
$h9score = 0;
}
if (!empty($h10)) {
$h10score = $course[10] - $h10;
} else {
$h10score = 0;
}
if (!empty($h11)) {
$h11score = $course[11] - $h11;
} else {
$h11score = 0;
}
if (!empty($h12)) {
$h12score = $course[12] - $h12;
} else {
$h12score = 0;
}
if(!empty($h13)) {
$h13score = $course[13] - $h13;
} else {
$h13score = 0;
}
if(!empty($h14)) {
$h14score = $course[14] - $h14;
} else {
$h14score = 0;
}
if (!empty($h15)) {
$h15score = $course[15] - $h15;
} else {
$h15score = 0;
}
if(!empty($h16)) {
$h16score = $course[16] - $h16;
}else {
$h16score = 0;
}
if(!empty($h17)) {
$h17score = $course[17] - $h17;
}else {
$h17score = 0;
}
if(!empty($h18)) {
$h18score = $course[18] - $h18;
}else {
$h18score = 0;
}
}
$scoresum = ($h1score + $h2score + $h3score + $h4score + $h5score + $h6score + $h7score + $h8score + $h9score + $h10score + $h11score + $h12score + $h13score + $h14score + $h15score + $h16score + $h17score + $h18score) * -1;
if ($scoresum != 0) {
$score = $scoresum;
}
else {
$score = 'E';
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:35:40.007",
"Id": "85721",
"Score": "1",
"body": "use an array to store scores as well?"
}
] | [
{
"body": "<p>Instead of having 18 variables $h1 ... $h18 and $h1score ... $h18score, you should have arrays and do the calculation in loops.</p>\n\n<p>Also, what is $played ? It is mentioned once, and seems to have no purpose.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:38:58.693",
"Id": "48824",
"ParentId": "48819",
"Score": "1"
}
},
{
"body": "<p>The big thing worth mentioning here is: <strong>Use an array for your scores.</strong></p>\n\n<p>The instant you do that, the code size shrinks dramatically.</p>\n\n<pre><code>$course = array(0, 4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);\n$scores = array();\n\n// $shots is your array of scores. $shots[1] is the first hole, $shots[2] the second,\n// etc. If you remove the 0 at the beginning of `$course`, then $scores[0] will be\n// the first, $scores[1] the second, etc, which is how arrays often look. But with\n// the zero, you can use the hole number as array index -- which might be more useful\n// if these numbers are coming from an HTML form.\n\nforeach ($course as $hole => $par) {\n if (!empty($shots[$hole])) {\n $scores[$hole] = $par - $shots[$hole];\n }\n}\n\n$scoresum = array_sum($scores);\n\nif ($scoresum != 0) {\n $score = $scoresum;\n}\nelse {\n $score = 'E';\n}\n</code></pre>\n\n<p>But you could do even better than that, if you don't need those intermediate scores.</p>\n\n<pre><code>$course = array(0, 4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);\n$score = 0;\n\nforeach ($shots as $hole => $total) {\n if (!empty($total)) {\n $score += $course[$hole] - $total;\n }\n}\n\nif (empty($score)) $score = 'E';\n</code></pre>\n\n<hr>\n\n<p>And because this seems uncommon knowledge, and will simplify your life if these values are indeed from a form, you can get PHP to build your array for you by giving your inputs arrayish names. Like so:</p>\n\n<pre><code><form>\n <input type=\"text\" name=\"shots[1]\">\n <input type=\"text\" name=\"shots[2]\">\n <input type=\"text\" name=\"shots[3]\">\n <input type=\"text\" name=\"shots[4]\">\n <input type=\"text\" name=\"shots[5]\">\n </form>\n</code></pre>\n\n<p>(You can even leave out the index, if you don't mind the auto-number indexes PHP does.)</p>\n\n<p>When this form is submitted, <code>$_POST['shots']</code> will be an array of all the inputs. Do something like:</p>\n\n<pre><code>$shots = array_map('intval', $_POST['shots']);\n</code></pre>\n\n<p>and you have an array containing the score entered for each hole (or 0 if the entered value didn't make sense as a number).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:45:07.770",
"Id": "48825",
"ParentId": "48819",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48825",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:23:22.927",
"Id": "48819",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "Calculating golf score against course par"
} | 48819 |
<p><strong>Background</strong></p>
<p>I've just started using VIM and have become comfortable with navigation. I'm attempting to reduce repetitive tasks and thought I would take a crack at mapping. I was able to accomplish my task below with a map command, but would like to know what the best way is to do what I am doing.</p>
<p><strong>Task</strong></p>
<p>I frequently write up text files with commands I use. In order to help navigate the files, I like to put a descriptive header above each command or step. For instance:</p>
<pre><code>Randomly Generate Statsd Counters
</code></pre>
<p>should be formatted to look like this</p>
<pre><code>***************************************
** Randomly Generate Statsd Counters **
***************************************
</code></pre>
<p><strong>Solution</strong></p>
<p>I probably spent way too much time on this, but came up with this map command in VIM. I should be able to navigate to any point on the Header line and hit a g key (The key doesn't matter), and be able to wrap the text with the header format. Here is the map:</p>
<pre><code>nnoremap <buffer> g ^i**<space><esc>$a<space>**<esc>:let linelength = virtcol('.')<CR>O<esc>:exec "normal! " . linelength . "i*"<CR><esc><esc>jo<esc>:exec "normal! " . linelength . "i*"<cr><esc><esc>
</code></pre>
<p><strong>Question</strong></p>
<p>I'm sure there is a better way to do this and I thought this would be a good opportunity to first attempt and then have my solution critiqued.</p>
| [] | [
{
"body": "<p>Your solution is interesting because it uses a heavy mix of normal mode commands, Ex commands and vimscript functions but yeah, it's way too long and complicated. </p>\n\n<p>You are definitely right that there are (many) other ways.</p>\n\n<p>Here is one that uses only normal mode commands:</p>\n\n<pre><code>nnoremap g I** <Esc>A **<Esc>yyPv$r*yyjp\n</code></pre>\n\n<p>Here is a variant:</p>\n\n<pre><code>nnoremap g ^c$** <C-r>\" **<Esc>yyPv$r*yyjp\n</code></pre>\n\n<p>Here is one with Ex commands only:</p>\n\n<pre><code>nnoremap g :s/.*/** \\0 **/\\|t-1\\|s/./*/\\|t+1\n</code></pre>\n\n<p>Here is another one that calls a function:</p>\n\n<pre><code>nnoremap g :call MyBannerMaker()<CR>\n\nfunction! MyBannerMaker()\n call setline('.', '** ' . getline('.') . ' **')\n put!=substitute(getline('.'), '.', '*', 'g')\n +put=substitute(getline('.'), '.', '*', 'g')\nendfunction\n</code></pre>\n\n<p>I'd suggest you look for readability, maintainability and extensibility first. Vim will execute the three mappings above instaneously despite their difference in length and apparent complexity so efficiency is kind of hard to measure, here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T22:15:44.963",
"Id": "85726",
"Score": "1",
"body": "Wonderful. Going through these examples and truly understanding them will help me immensely. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T22:09:59.160",
"Id": "48826",
"ParentId": "48823",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "48826",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T21:38:01.393",
"Id": "48823",
"Score": "8",
"Tags": [
"vimscript"
],
"Title": "Map command in VIM"
} | 48823 |
<p>This has been asked a few times here, but I was wondering what I could do to improve the efficiency and readability of my code. My programming skill has gotten rusty, so I would like to elicit all constructive criticism that can make me write code better. </p>
<p><strong>init:</strong></p>
<pre><code>#include <iostream>
using namespace std;
</code></pre>
<p><strong>merge()</strong></p>
<pre><code>//The merge function
void merge(int a[], int startIndex, int endIndex)
{
int size = (endIndex - startIndex) + 1;
int *b = new int [size]();
int i = startIndex;
int mid = (startIndex + endIndex)/2;
int k = 0;
int j = mid + 1;
while (k < size)
{
if((i<=mid) && (a[i] < a[j]))
{
b[k++] = a[i++];
}
else
{
b[k++] = a[j++];
}
}
for(k=0; k < size; k++)
{
a[startIndex+k] = b[k];
}
delete []b;
}
</code></pre>
<p><strong>merge_sort()</strong></p>
<pre><code>//The recursive merge sort function
void merge_sort(int iArray[], int startIndex, int endIndex)
{
int midIndex;
//Check for base case
if (startIndex >= endIndex)
{
return;
}
//First, divide in half
midIndex = (startIndex + endIndex)/2;
//First recursive call
merge_sort(iArray, startIndex, midIndex);
//Second recursive call
merge_sort(iArray, midIndex+1, endIndex);
//The merge function
merge(iArray, startIndex, endIndex);
}
</code></pre>
<p><strong>main()</strong></p>
<pre><code>//The main function
int main(int argc, char *argv[])
{
int iArray[10] = {2,5,6,4,7,2,8,3,9,10};
merge_sort(iArray, 0, 9);
//Print the sorted array
for(int i=0; i < 10; i++)
{
cout << iArray[i] << endl;
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T00:11:16.430",
"Id": "85729",
"Score": "1",
"body": "Fixed indentation as it was imposable to read without it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T00:27:13.247",
"Id": "85731",
"Score": "1",
"body": "@LokiAstari: As much as I dislike the indentation issue as well, it is not from tabs and I have already reviewed it. You may keep a better version for yourself if you're going to review it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-08T19:07:36.640",
"Id": "215835",
"Score": "0",
"body": "your code could be improved further but i think its an really good [merge sorting c++](http://www.hellgeeks.com/merge-sort/) code"
}
] | [
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</p></li>\n<li><p>Code within a function should be indented as well. You already do this with other code blocks, and the same applies to functions.</p></li>\n<li><p>Just avoid Hungarian notation:</p>\n\n<pre><code>int iArray;\n</code></pre>\n\n<p>We already know it's an <code>int</code> array.</p></li>\n<li><p>Prefer not to pass C arrays to functions in C++. This causes them to decay to a pointer; it does not actually pass the array itself.</p>\n\n<p>Instead, pass in a storage container, such as an <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>. Storage containers will <em>not</em> decay to a pointer, and they're more idiomatic C++.</p>\n\n<p>If you have C++11, initialize the vector using <a href=\"http://en.cppreference.com/w/cpp/language/list_initialization\" rel=\"nofollow noreferrer\">list initialization</a>:</p>\n\n<pre><code>std::vector<int> values { 2, 5, 6, 4, 7, 2, 8, 3, 9, 10 };\n</code></pre>\n\n<p>If you don't have C++11, declare it and call <code>push_back()</code> for each value:</p>\n\n<pre><code>std::vector<int> values;\n\nvalues.push_back(2);\nvalues.push_back(5);\n// ...\n</code></pre>\n\n<p>Pass it to a function with such parameters:</p>\n\n<pre><code>void merge_sort(std::vector<int> values, int startIndex, int endIndex) {}\n</code></pre>\n\n<p>As its implementation is that of an array, you can still access its elements with <code>[]</code>. You can also use its iterators (more preferred).</p>\n\n<p>Storage containers do the memory allocation for you, so you will not need <code>new</code>/<code>delete</code>. It's best to do as little manual memory allocation as possible in C++.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T23:06:25.373",
"Id": "48831",
"ParentId": "48828",
"Score": "4"
}
},
{
"body": "<p>Everything Jamal said (so I will not repeat)</p>\n\n<p>Plus:</p>\n\n<p>The normal idium in C++ for passing ranges is <code>[beg, end)</code>.<br>\nFor those not mathematically inclined end is specified one past the end.</p>\n\n<p>If you follow the C++ convention you make it easier for other C++ devs to keep track without having to think to hard about what you are up to. Personally I think it also makes writting merge sort easier.</p>\n\n<pre><code> merge_sort(iArray, 0, 10);\n</code></pre>\n\n<p>Then in merge()</p>\n\n<pre><code> midIndex = (startIndex + endIndex)/2; // The start of the second half\n // Is one past the end of the first half.\n merge_sort(iArray, startIndex, midIndex);\n merge_sort(iArray, midIndex, endIndex);\n</code></pre>\n\n<p>Slight optimization here:</p>\n\n<pre><code>//Check for base case\nif (startIndex >= endIndex)\n{\n return;\n}\n</code></pre>\n\n<p>You can return if the size is 1. A vector of 1 is already sorted. Since <code>end</code> is one past the end the size is <code>end-start</code>.</p>\n\n<pre><code>if ((endIndex - startIndex) <= 1)\n{\n return;\n}\n</code></pre>\n\n<p>Don't do manually memory management in your code.</p>\n\n<pre><code>int *b = new int [size](); // Also initialization costs.\n // So why do that if you don't need to!\n\n// PS in C++ (unlike C)\n// It is more common to put '*' by the type.\n// That's becuase the type is `pointer to int`\n</code></pre>\n\n<p>Better alternative:</p>\n\n<pre><code>std::vector<int> b(size); // Memory management handled for you.\n // Its exception safe (so you will never leak).\n // Overhead is insignificant.\n</code></pre>\n\n<p>A conditional in the middle of a loop is expensive.</p>\n\n<pre><code>while (k < size)\n{\n if((i<=mid) && (a[i] < a[j]))\n {...} else {...}\n}\n</code></pre>\n\n<p>Once one side is used up break out of the loop and just copy the other one.</p>\n\n<pre><code>while (i <= mid && j <= endIndex)\n{ b[k++] = (a[i] < a[j]) ? a[i++] : a[j++];\n}\n// Note: Only one of these two loop will execute.\nwhile(i <= mid)\n{ b[k++] = a[i++];\n}\nwhile(j <= endIndex)\n{ b[k++] = a[j++];\n}\n</code></pre>\n\n<p>Rather than calculating the mid point both in <code>merge()</code> and in <code>merge_sort</code>, it may be worth just passing the value as a parameter.</p>\n\n<p>Learn to do the inplace merge so you don't have to copy the values back after the merge.</p>\n\n<pre><code> midIndex = (startIndex + endIndex)/2;\n merge_sort(iArray, startIndex, midIndex);\n merge_sort(iArray, midIndex, endIndex);\n merge(iArray, startIndex, midIndex, endIndex);\n // ^^^^^^^^ pass midIndex so you don't need to re-calc\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T00:29:11.767",
"Id": "48837",
"ParentId": "48828",
"Score": "4"
}
},
{
"body": "<p>Most of the interesting points has been covered already. The missing one:</p>\n\n<p><code>merge</code> is an important algorithm of its own. As implemented, it imposes very harsh and non-obvious preconditions. Relax them:</p>\n\n<pre><code>void merge(int b[], int a0[], int size0, int a1[], int size1);\n</code></pre>\n\n<p>and let the caller decide how to allocate/delete/reuse the <code>b</code> array. Notice that in the context of <code>mergesort</code> the caller is <em>you</em>, so the caller of <code>mergesort</code> wouldn't see the difference.</p>\n\n<p>PS: a <em>no raw loops</em> rule is also perfectly applicable. A loop:</p>\n\n<pre><code>for(k=0; k < size; k++)\n{\n a[startIndex+k] = b[k];\n}\n</code></pre>\n\n<p>in fact implements an important algorithm known as <code>copy(int * a, int * b, int size)</code>, and is better be factored out as such.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T04:11:51.083",
"Id": "85852",
"Score": "0",
"body": "Thank you! I wasn't aware of this. Read about the no raw loops rule just now, and it makes sense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T05:12:05.883",
"Id": "48846",
"ParentId": "48828",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48837",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T22:48:02.380",
"Id": "48828",
"Score": "4",
"Tags": [
"c++",
"sorting",
"mergesort"
],
"Title": "Implementing the merge sort with only arrays, out of place"
} | 48828 |
<p>I am trying to teach myself OOP in Python. I am picking up some projects from GitHub and trying it out on my own. I wrote a Airline/Hotel Reservation System, where I want to maintain the customer name, ID and maintain a record for Airline or Hotel or Both. I am not sure if my design is correct. I want some input on how to improve the design for my code.</p>
<pre><code>class Reservation:
def __init__(self,passenger_id,passenger_fname,passenger_lname):
self.passenger_id = passenger_id
self.passenger_fname = passenger_fname
self.passenger_lname = passenger_lname
self.cost = 0
self.reservation_id = []
self.passenger_record = {'p_name' : self.passenger_fname + self.passenger_lname,
'p_id' : self.passenger_id,
'p_wallet': self.cost,
'p_reservation_id': self.reservation_id,
}
self.airline_seats = { 'Business Class' : 50,
'First Class' : 50,
'Premium Economy': 100,
'Regular Economy': 150 }
self.airline_price = { 'Business Class' : 2500,
'First Class' : 2000,
'Premium Economy': 1800,
'Regular Economy': 1500 }
self.hotel_room = {'Penthouse' : 10,
'King Deluxe Bedroom' : 20,
'Queen Deluxe Bedroom' : 20,
'Kind Standard Bedroom' : 30,
'Queen Standard Bedroom': 50 }
self.hotel_price = {'Penthouse' : 1000,
'King Deluxe Bedroom' : 700,
'Queen Deluxe Bedroom' : 600,
'Kind Standard Bedroom' : 450,
'Queen Standard Bedroom': 350 }
def currentStatus(self,option):
if option == "Airline":
for key, value in self.airline_seats.items():
print key, value
elif option == "Hotel":
for key,value in self.hotel_room.items():
print key, value
def Total(self):
print self.passenger_record['p_wallet']
class Airline(Reservation):
def __init__(self,passenger_id,passenger_fname,passenger_lname,airline_seat_section,
airline_departure_date):
Reservation.__init__(self,passenger_id,passenger_fname,passenger_lname)
self.airline_seat_section = airline_seat_section
self.airline_departure_date = airline_departure_date
def CheckAvailability(self):
if (self.airline_seats.get(self.airline_seat_section) != 0):
self.airline_seats[self.airline_seat_section] -= 1
self.passenger_record['p_wallet'] += self.airline_price[self.airline_seat_section]
print "\n\nReserved Airline Ticket\n\n"
class Hotel(Reservation):
def __init__(self,passenger_id,passenger_fname,passenger_lname,hotel_room_selection,
hotel_check_in_date,hotel_check_out_date):
Reservation.__init__(self,passenger_id,passenger_fname,passenger_lname)
self.hotel_room_selection = hotel_room_selection
self.hotel_check_in_date = hotel_check_in_date
self.hotel_check_out_date = hotel_check_out_date
def CheckAvailability(self):
if (self.hotel_room.get(self.hotel_room_selection) != 0):
self.hotel_room[self.hotel_room_selection] -= 1
self.passenger_record['p_wallet'] += self.hotel_price[self.hotel_room_selection]
print "\n\nReserved Hotel Room\n\n"
A1 = Airline("1","Arun","Raman","Business Class","07-07-2014")
A1.CheckAvailability()
A1.currentStatus("Airline")
H1 = Hotel("1","Arun","Raman","Penthouse","07-07-2014","07-10-2014")
H1.CheckAvailability()
H1.currentStatus("Hotel")
</code></pre>
| [] | [
{
"body": "<p>One obvious issue is that all of the data for hotels and airlines is stored in the base <code>Reservation</code> class. You should move it to the relevant sub-classes, and I would store it as <em>class attributes</em> (shared by all instances) rather than <em>instance attributes</em> (unique to each instance), otherwise you won't be tracking the correct numbers of free rooms:</p>\n\n<pre><code>class Hotel(Reservation):\n\n HOTEL_ROOM = {'Penthouse': 10,\n 'King Deluxe Bedroom': 20,\n 'Queen Deluxe Bedroom': 20,\n 'King Standard Bedroom': 30,\n 'Queen Standard Bedroom': 50}\n</code></pre>\n\n<p>Also, as it stands, your code effectively makes the booking before it checks the availability. If you try to book something when it's already booked up, you should be raising an error. The customer is too closely tied to e.g. the <code>Hotel</code> - think about it in real terms, do you have the names of all of the customers when you build a new hotel?</p>\n\n<p>A better option would be to create a new class structure:</p>\n\n<ul>\n<li><code>Reservation</code>\n<ul>\n<li><code>HotelReservation</code></li>\n<li><code>AirlineReservation</code></li>\n</ul></li>\n<li><code>Bookable</code>\n<ul>\n<li><code>Hotel</code></li>\n<li><code>Airline</code></li>\n</ul></li>\n<li><code>Customer</code></li>\n</ul>\n\n<p>All <code>Bookable</code>s (which you could extend to e.g. <code>CarHire</code> in the future) would implement <code>check_availability</code> and <code>make_reservation</code>. To make it clear that the sub-classes should implement these, you can put a stub in the parent:</p>\n\n<pre><code>class Bookable(object):\n\n def check_availability(self, *details):\n raise NotImplementedError\n\n def make_reservation(self, *details):\n raise NotImplementedError\n</code></pre>\n\n<p>The sub-classes would then have information specific to that type (e.g. a <code>Hotel</code> would have rooms, an <code>Airline</code> seats, etc.) and their implementations of those methods would reflect that.</p>\n\n<p>The <code>Reservation</code> would then connect the <code>Customer</code> to a <code>Bookable</code> (you might even find you don't need the sub-classes there - what's the difference between an airline reservation and a hotel reservation?) This would go both ways - a <code>Hotel</code> needs to know when to expect whom, and a <code>Customer</code> needs to know what they have booked.</p>\n\n<p>Your code might now look like:</p>\n\n<pre><code>a1 = Airline(\"Qantas\")\nh1 = Hotel(\"Mayfair\")\nc1 = Customer(\"Arun\", \"Raman\")\n\nif a1.check_availability(\"Business Class\", \"07-07-2014\"):\n r1 = a1.make_reservation(c1, \"Business Class\", \"07-07-2014\")\n\nif h1.check_availability(\"Penthouse\", \"07-07-2014\", \"07-10-2014\"):\n r2 = h1.make_reservation(c1, \"Penthouse\", \"07-07-2014\", \"07-10-2014\")\n\nprint(c1.bookings)\n</code></pre>\n\n<p>Looking at that, I'm thinking:</p>\n\n<ol>\n<li>Could we cut the repetition of booking details? Perhaps introduce a <code>Booking</code> class? (e.g. <code>b1 = Booking(c1, details)</code> then <code>for h in hotels: if h.check_availability(b1): h.make_reservation(b1)</code>)</li>\n<li>Make the dates actual <code>datetime</code> objects, not strings.</li>\n</ol>\n\n<p>But I will leave it there for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T00:55:00.830",
"Id": "86107",
"Score": "0",
"body": "so the checkavailability and makeReservation showuld be part of the Booking class? if so how will the checkAvailability can see the information like Airline seats and Airline price, that are defined in the child class. Sorry if question is novice, coming from a C background, i can relate it to a function call !! Not able see in object point of view. I can see we are calling A1.checkAvailability(). So the object is for the airline class. but am not able to see how i would write this in Booking class !!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T09:24:22.933",
"Id": "86142",
"Score": "0",
"body": "They should be implemented in the child classes of `Booking`; I have updated my answer to show what should be in `Booking` itself to reflect that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T10:09:16.173",
"Id": "48917",
"ParentId": "48829",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T23:02:38.590",
"Id": "48829",
"Score": "7",
"Tags": [
"python",
"object-oriented"
],
"Title": "Airline/Hotel reservation system in Python"
} | 48829 |
<p>Let me start by saying that I am very happy with this code. I want to share it with other people because I think they will find it helpful, but I want to make sure I did everything in good form before I do so.</p>
<p>The code allows users to easily manage their image memory. The class handles all of your images, which means no image will be unnecessarily created twice. Each time a new class is created the user can just call <code>recycle()</code> to recycle all the images that were used in the previous class and load all the images needed in the class. Images can be added to this custom class by calling <code>loadImages()</code> and the user can redefine and remove items by calling <code>recycle()</code> with only the images they want to keep (they can also add image here). They can also define images to be scaled custom.</p>
<p>All of that can be done by properly using the <code>onResume</code> and <code>OnPause</code> methods, but this class greatly simplifies it and neatens the code in my opinion. BUT this class can do something that can't be done with the <code>onPause</code> and <code>onResume</code> methods. When loading a new classes images, the images used in the previous classes don't need to be reloaded. Depending on the application the time this saves varies. In my application it saves a visible amount of time due to the large number of duplicate images used in different classes.</p>
<p>What do you think? How could this be improve? Is it worth sharing? </p>
<pre><code>import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
public class Images {
// Image Holder
private ArrayList<Bitmap> images;
// Image Names
private ArrayList<String> imageNames;
// Images that need custom scaling
private ArrayList<String> customScale;
// Options, used for proper scaling
BitmapFactory.Options options;
private Images() {
// init
images = new ArrayList<Bitmap>();
imageNames = new ArrayList<String>();
options = new BitmapFactory.Options();
customScale = new ArrayList<String>();
// Assigns image names
nameImages();
// Set which images should be custom scaled
setCustomScales();
// by default images are null
for (int i = 0; i < imageNames.size(); i++)
images.add(null);
}
//singleton stuff
private static class Holder {
static final Images INSTANCE = new Images();
}
public static Images getInstance() {
return Holder.INSTANCE;
}
// recycle all images not in use
public void recycle(ArrayList<String> imagesInUse, View sv, double scale, DisplayMetrics dm) {
for (int i = 0; i < imageNames.size(); i++)
if (!imagesInUse.contains(imageNames.get(i)))
images.get(i).recycle();
loadImages(imagesInUse, sv, scale, dm);
}
// load all needed images
public void loadImages(ArrayList<String> imageName, View sv, double scale, DisplayMetrics dm) {
Context context = sv.getContext();
for (int ii = 0; ii < imageName.size(); ii++) {
for (int i = 0; i < imageNames.size(); i++) {
if (imageNames.get(i).equals(imageName.get(ii))) {
int resID = sv.getResources().getIdentifier(imageName.get(ii), "drawable", context.getPackageName());
if (customScale.contains(imageName.get(ii))) {
images.set(i, BitmapFactory.decodeResource(sv.getResources(), resID));
images.set(i, customScaleImage(imageName.get(ii), i, dm));
}
else {
if (scale < .5) {
options.inSampleSize = 2;
images.set(i, BitmapFactory.decodeResource(sv.getResources(), resID, options));
if (scale != .5)
images.set(i, Bitmap.createScaledBitmap(images.get(i), (int) (images.get(i).getWidth() * 2 * scale + .5), (int) (images.get(i).getHeight() * 2 * scale + .5), true));
} else {
images.set(i, BitmapFactory.decodeResource(sv.getResources(), resID));
images.set(i, Bitmap.createScaledBitmap(images.get(i), (int) (images.get(i).getWidth() * scale + .5), (int) (images.get(i).getHeight() * scale + .5), true));
}
}
}
}
}
}
// returns bitmap with name of 'imageName'
public Bitmap getImage(String imageName) {
for (int i = 0; i < imageNames.size(); i++) {
if (imageNames.get(i).equals(imageName))
return images.get(i);
}
System.err.println("NO IMAGE OF NAME '" + imageName + "' FOUND!");
return null;
}
// set how you want to custom scale your custom scale images
private Bitmap customScaleImage(String nameOfImage, int index, DisplayMetrics dm) {
if (nameOfImage.equals("example"))
return Bitmap.createScaledBitmap(images.get(index), dm.widthPixels, dm.heightPixels, true);
System.err.println("CUSTOM SCALE NOT SET FOR " + nameOfImage);
return null;
}
// name all images
private void nameImages() {
imageNames.add("example");
}
// Add all custom scale images
private void setCustomScales(){
customScale.add("example");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T01:44:51.483",
"Id": "85735",
"Score": "0",
"body": "can you get away with 2 for loops as that makes the runtime complexity to o(n square)"
}
] | [
{
"body": "<p>Glad to hear that you're looking for a review before publishing it! Let's get right to it. </p>\n\n<h1>Class naming</h1>\n\n<p>Your class is named <code>Images</code> but that doesn't convey a meaning to me. In fact, it's a plural so I would never use this for a class name (how would you describe multiple instances of this class?). </p>\n\n<p><code>Image</code> by itself is obviously not a good name either, since the class does not represent that. I have only vaguely looked through the actual class and its purpose yet but something like <code>ImageManager</code> seems like a good fit here.</p>\n\n<p>Note that the use of <code>*Manager</code> is usually a sign of <a href=\"http://www.martinfowler.com/bliki/AnemicDomainModel.html\" rel=\"nofollow noreferrer\">the anemic domain model</a> but this is one of the cases where that doesn't apply: you actually are managing a collection of images, things that can't be done by the images themselves. You can work with the context for a different name (for example <code>ImageLibrary</code>), but that depends on how you want this to be viewed, really.</p>\n\n<h1>Comments</h1>\n\n<p>Comments should explain <em>why</em> you do something, not <em>what</em> you do. The latter should be done through good naming and adhering to conventions for readability.</p>\n\n<p>Concretely this means that this is redundant:</p>\n\n<pre><code>// Image Holder\nprivate ArrayList<Bitmap> images;\n</code></pre>\n\n<p>I already know it stores images in a collection, I can see that by reading the code (which is what I read before I read comments).</p>\n\n<p>Likewise here (and many other places, these are just a few examples:</p>\n\n<pre><code>// Assigns image names\nnameImages();\n</code></pre>\n\n<h1>Working towards an interface</h1>\n\n<p>I will refer you to <a href=\"https://stackoverflow.com/questions/2697783/what-does-program-to-interfaces-not-implementations-mean\">this SO post</a> on this subject. </p>\n\n<p>What this exactly means for you is that you should define your fields as </p>\n\n<pre><code>List<String>\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>ArrayList<String>\n</code></pre>\n\n<p>Doing so will allow you to change it up to a <code>LinkedList</code> (if you'd want to) without breaking any contracts in your code.</p>\n\n<h1>Diamond operator</h1>\n\n<p>Since Java 7 there is the so called <em>diamond operator</em> available to us. This allows us to omit the type parameter in a generic instantiation.</p>\n\n<p>This would turn</p>\n\n<pre><code>new ArrayList<Bitmap>();\n</code></pre>\n\n<p>into </p>\n\n<pre><code>new ArrayList<>();\n</code></pre>\n\n<h1>Brackets</h1>\n\n<p><em>Always</em> add brackets to your <code>if</code>, <code>for</code>, <code>while</code>, etc statements. If you don't, you will undoubtedly run into a logical error eventually when you decide you want your <code>if</code> statement to perform 2 actions instead of just that 1.</p>\n\n<h1>Indentation</h1>\n\n<p>Right now your method bodies are indented with 2 tabs, conventions state that one tab should be used consisting of 4 spaces (half you have right now). Which makes sense because reading your code definitely makes me noticed the whitespace. Nested blocks will also fill up your screen very quickly like this.</p>\n\n<h1>Descriptive names</h1>\n\n<p>For a single loop I'll usually use <code>i</code> as variable as well but when you have deeply nested loops like <code>loadImages</code> then you should really use a name with more meaning. The code is filled with references to <code>i</code> and <code>ii</code> and I have no idea what they resemble.</p>\n\n<p>Likewise you should make the names say as much as they can on their own: <code>dm</code> and <code>resID</code> are unnecessary abbreviations, <code>displayMetrics</code> and <code>resourceID</code> are much more pleasant to read.</p>\n\n<h1>Intermediate values</h1>\n\n<p>In this same loop you have the following expression:</p>\n\n<pre><code>images.set(i, Bitmap.createScaledBitmap(images.get(i), (int) (images.get(i).getWidth() * scale + .5), (int) (images.get(i).getHeight() * scale + .5), true));\n</code></pre>\n\n<p>To me, it is very hard to take away what this is about. If you would instead use intermediate variables it would be a lot more readable (and easier to debug if something is wrong!). This could become:</p>\n\n<pre><code>Bitmap sourceImage = images.get(i);\nint newWidth = (int) (images.get(i).getWidth() * scale + .5);\nint newHeight = (int) (images.get(i).getHeight() * scale + .5);\nboolean filter = true;\n\nimages.set(i, Bitmap.createScaledBitmap(sourceImage, newWidth, newHeight, filter);\n</code></pre>\n\n<h1>Error handling</h1>\n\n<p>It is very important that your methods do the thing they're described to do and nothing more. Looking at the <code>getImage</code> method I see a call to <code>System.err.println</code>, which I could never have guessed from the method's name. </p>\n\n<p>Instead use proper error handling by providing an actual response. This response can manifest itself as a return value or an exception. Returning <code>null</code> (for reference type return values) has had <a href=\"https://stackoverflow.com/questions/1274792/is-returning-null-bad-design\">its fair share of discussion</a> so I'll let you read through it.</p>\n\n<p>Generally I will always try to avoid <code>null</code> as a return value but that doesn't mean it is always inappropriate to use. For collections it's easy: return an empty collection. For a single object there is more room for preference.</p>\n\n<p>Here I would use an exception though, <code>InvalidArgumentException</code> is the most appropriate. Attempting to retrieve a non-existing image is probably a truly exceptional action and should thus be treated as one.</p>\n\n<h1>Method naming</h1>\n\n<p>Methods should describe <em>actions</em>. When I see a method <code>customScaleImage</code> I have no idea what it will do. Looking at the implementation tells me it will only return something so <code>getCustomScaleImage</code> is appropriate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:48:37.367",
"Id": "85754",
"Score": "0",
"body": "+1 for everything except Diamond operator. Only API 14+ (if I remember correctly) allows Java 7. Unless you use a plugin like [retrolambda](https://github.com/evant/gradle-retrolambda)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T02:15:19.233",
"Id": "48840",
"ParentId": "48830",
"Score": "11"
}
},
{
"body": "<h1>Final</h1>\n\n<pre><code>private ArrayList<Bitmap> images;\n</code></pre>\n\n<p>--></p>\n\n<pre><code>private final List<Bitmap> images;\n</code></pre>\n\n<p>Whenever you have a variable that doesn't change, mark it as final. In this case the List reference itself doesn't change, so it can be marked as final. All class variables that can be marked as final, <a href=\"https://stackoverflow.com/questions/154314/when-should-one-use-final\">should be marked as final</a>.</p>\n\n<h1>JavaDoc</h1>\n\n<p>You say that this is intended to be used by others, as a Library. However, regular users are used to seeing classes documented with JavaDoc. Please learn <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\" rel=\"nofollow noreferrer\">how to write JavaDoc</a>.</p>\n\n<h1>Math.round</h1>\n\n<pre><code>(int) (images.get(i).getWidth() * scale + .5);\n</code></pre>\n\n<p>What you're doing here is to round the double value to the nearest integer. Use <code>Math.round</code> for that, which would make your intent more clear, instead of adding a seemingly random <code>0.5</code> at the end.</p>\n\n<h1>Private</h1>\n\n<p>Most of your variables are declared as <code>private</code>, which is good, but this is not:</p>\n\n<pre><code>BitmapFactory.Options options;\n</code></pre>\n\n<p>As far as I can see, that variable can be - and therefore should be - <code>private final</code>.</p>\n\n<h1>Android Logging</h1>\n\n<pre><code>System.err.println(\"NO IMAGE OF NAME '\" + imageName + \"' FOUND!\");\n</code></pre>\n\n<p>The better practice of logging in Android is to use the static methods in the <code>Log</code> class</p>\n\n<pre><code>Log.e(\"YOUR_TAG\", \"NO IMAGE OF NAME '\" + imageName + \"' FOUND!\");\n</code></pre>\n\n<p>This allows users of Logcat to filter on your tag, which greatly simplifies scanning through the endless logging that Android produces.</p>\n\n<h1>\"example\"</h1>\n\n<p>I'm sorry but I just cannot see what good these methods do. Why are they there? What's so special about this \"example\"? Remove it, or come up with a very good reason for why you have it.</p>\n\n<pre><code>// name all images\nprivate void nameImages() {\n imageNames.add(\"example\");\n}\n\n// Add all custom scale images\nprivate void setCustomScales(){\n customScale.add(\"example\");\n}\n</code></pre>\n\n<h1>List, or Set?</h1>\n\n<p>In your <code>recycle</code> method you have this parameter:</p>\n\n<pre><code>ArrayList<String> imagesInUse\n</code></pre>\n\n<p>By now you of course know that it should be declared as <code>List</code> rather than <code>ArrayList</code>, but that's not the point here. Let me ask you a question about this variable:</p>\n\n<p><strong>Does the order of the elements matter?</strong></p>\n\n<p>No? Good. Then use <code>Set<String></code> instead. The <code>.contains</code> method is much more effective on a set than on a <code>List</code>. For more information, see <a href=\"https://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list\">What is the difference between set and list?</a></p>\n\n<p>You should ask yourself this question for <strong>all</strong> the times you use a <code>List</code> or a <code>Set</code>. Remember the question: <strong>Does the order of the elements matter?</strong></p>\n\n<h1>Recycling</h1>\n\n<p>What would happen if you'd try to get an image that you have already recycled?</p>\n\n<p>In your <code>recycle</code> method, you don't remove the image from the <code>images</code> list or the <code>imageNames</code> list. I think this will result in unexpected behavior.</p>\n\n<h1>Map</h1>\n\n<p>In your <code>getImage</code> method you loop through one list to find a matching string, to then return the same index in another list. Rather than doing that, learn how to use a <code>Map<String, Bitmap></code>. A <code>Map</code> has a lookup time of \\$O(1)\\$ rather than \\$O(n)\\$ which you get by looping through the list.</p>\n\n<p>This line should get you started:</p>\n\n<pre><code>Map<String, Bitmap> map = new HashMap<String, Bitmap>();\n</code></pre>\n\n<p>Look especially on the <code>put</code>, <code>get</code>, <code>containsKey</code> methods in the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\">JavaDoc for the Map interface</a>.</p>\n\n<h1>Singleton</h1>\n\n<p>First of all I'd question if your class really <em>needs</em> to be a singleton. Even if you would decide that Yes, it should be a singleton, then there's a \"better\" way of doing it.</p>\n\n<pre><code>public enum SingletonInstance {\n INSTANCE;\n\n private SingletonObject instance;\n\n private SingletonInstance() {\n this.instance = new SingletonObject();\n }\n}\n</code></pre>\n\n<h1>Usefulness</h1>\n\n<p>I'm sorry, but I personally would not use - or recommend - this class to handle images. I feel that it is easier to do handle images directly in my application rather than use your library. In my opinion, your library does not provide functionality, it seems to <em>remove</em> functionality. For example, let's say I'd want to load my image referenced by the id <code>R.drawable.myimage</code>. The way to do that in your library would be to provide it with the <em>string</em> <code>\"myimage\"</code>. If I would rename that image to <code>newimage</code>, your library would not recognize that I have changed the name and therefore cause a problem in runtime, while by using <code>R.drawable.myimage</code> it would either rename itself when I rename the image or I would get a compiler error (which is better than a runtime error).</p>\n\n<p>Don't feel bad about that though, I've coded lots of things that ended up being unneeded. That's how you learn. And besides, that's just my opinion. If you want to use this library yourself, then you've already gained a (hopefully happy) customer.</p>\n\n<p>Keep on coding. And remember that if you want to (which I'd recommend, I hope to be more positive next time), you can <a href=\"https://codereview.meta.stackexchange.com/questions/1065/how-to-post-a-follow-up-question\">ask a follow-up question</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:29:50.817",
"Id": "85772",
"Score": "0",
"body": "Thanks for the reply. I'm going to fix the nameImage() method so that it adds the image names programmatically rather than having to name them manually. Though I can see that changing an image name would be annoying."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:46:47.907",
"Id": "48853",
"ParentId": "48830",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T23:02:52.483",
"Id": "48830",
"Score": "10",
"Tags": [
"java",
"android",
"memory-management",
"image"
],
"Title": "Image handling class"
} | 48830 |
<p>I made a navigation bar on the left side of my site. It works perfectly, the only problem is I'm new to jQuery and I think I'm repeating too much code. Is this the case? If it is please help me out.</p>
<p><strong>HTML</strong></p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DopEYEmine</title>
<!--Favicon-->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!--Fonts-->
<link href='http://fonts.googleapis.com/css?family=Special+Elite' rel='stylesheet' type='text/css'>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div id="sidebar">
<ul>
<li><img class="logo" src="img/whitelogo.svg"><img class="logotwo" src="img/whitelonglogo.svg"></li>
<li><img class="nav_icons" src="img/about.svg"><a class="about_btn" href="#">ABOUT</a></li>
<li><img class="nav_icons" src="img/submit.svg"><a class="submit_btn" href="#">SUBMIT</a></li>
<li><img class="nav_icons" src="img/contact.svg"><a class="contact_btn" href="#">CONTACT</a></li>
</ul>
</div>
<div id="about">
<div class="menucontent">
<div class="aboutclose closer">CLOSE</div>
<div>
<img src="img/logo.png">
</div>
<p>"Dopamine: the molecule behind all our most sinful behaviors and secret cravings."</p>
<p></p>
</div>
</div>
<div id="submit">
<div class="menucontent">
<div class="submitclose closer">CLOSE</div>
<form action="submitform.php" method="post" enctype="multipart/form-data">
<input type="text" name="name" placeholder="NAME" />
<input type="text" name="email" placeholder="E-MAIL">
</form>
</div>
</div>
<div id="contact">
<div class="menucontent">
<div class="contactclose closer">CLOSE</div>
</div>
</div>
<div id="mainarea">
</div>
<!--Javascript-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/browser_hack.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>html, body {
height: 100%;
width: 100%;
overflow: hidden;
}
a{
text-decoration: none;
}
/*Side Bar Nav----------------------------------*/
.logo {
position: absolute;
top: 30px;
left: 10px;
width: 75px;
margin: 0px;
}
.logotwo {
position: absolute;
top: 34px;
left: 110px;
width: 150px;
display: none;
}
#sidebar {
float: left;
z-index: 10;
position: relative;
top: 0;
left: 0;
height: 100%;
width: 95px;
background: #555;
overflow: hidden;
border-right: solid 3px #444;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
#sidebar:hover {
width: 285px;
background: #000;
border-right: none;
}
.nav_icons {
width: 40px;
height: 40px;
}
#sidebar li {
display: block;
font-family: 'Special Elite', cursive;
}
#sidebar ul li:nth-child(2) {
position: absolute;
top: 88px;
left: 27px;
}
#sidebar ul li:nth-child(3) {
position: absolute;
top: 148px;
left: 27px;
}
#sidebar ul li:nth-child(4) {
position: absolute;
top: 208px;
left: 27px;
}
.about_btn,
.submit_btn,
.contact_btn {
position: relative;
top: -25px;
left: 80px;
color: #fff;
display: none;
padding: 10px 200px 5px 5px;
}
.gecko .about_btn,
.gecko .submit_btn,
.gecko .contact_btn {
top: -35px;
}
#sidebar a:hover {
background-color: #fff;
color: #000;
}
/*Panel------------------------------------*/
.closer {
float: right;
font-weight: 900;
font-size: .7em;
padding: 5px;
cursor: pointer;
}
.closer:hover {
font-size: .75em;
}
.menucontent {
width: 500px;
}
/*About------------------------------------*/
#about {
float: left;
z-index: 10;
height: 100%;
width: 500px;
background-color: #fff;
box-shadow: 3px 0px 2px #555;
opacity: .7;
display: none;
}
#about p {
width: 400px;
margin: 0 auto;
text-align: left;
font-family: 'Special Elite', cursive;
}
#about img {
position: relative;
top: 25px;
left: 50px;
display: block;
width: 400px;
}
/*Contact------------------------------------*/
#contact {
float: left;
z-index: 10;
height: 100%;
width: 500px;
background-color: #fff;
box-shadow: 3px 0px 2px #555;
opacity: .7;
display: none;
}
/*Submit------------------------------------*/
#submit {
float: left;
z-index: 10;
height: 100%;
width: 500px;
background-color: #fff;
box-shadow: 3px 0px 2px #555;
opacity: .7;
display: none;
}
/*Main Area--------------------------------*/
#mainarea {
float:left;
display:block;
position:relative;
top: 0;
right: 0;
z-index: 1;
height: 100%;
width: 100%;
padding-left: 100px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-0-box-sizing: border-box;
box-sizing: border-box;
}
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$(document).ready(function(){
//SIDEBAR-------------------------------------------------------
$('#sidebar').hover(function(){
$(".about_btn, .submit_btn, .contact_btn").delay(100).fadeIn(1000);
$(".logotwo").delay(100).fadeIn(1000);
},function(){
$(".about_btn, .submit_btn, .contact_btn").fadeOut(10);
$(".logotwo").fadeOut(10);
});
//ABOUT PANEL---------------------------------------------------
var fadeInAbout = function() {
$('#about').animate({width: 'toggle'});
};
$(".about_btn").click(function () {
if($('#submit').css("display") == "block") {
$('#submit').fadeOut(10);
fadeInAbout();
} else if($('#contact').css("display") == "block") {
$('#contact').fadeOut(10);
fadeInAbout();
} else {
fadeInAbout();
}
});
$(".aboutclose").click(function () {
fadeInAbout();
});
//SUBMIT PANEL---------------------------------------------------
var fadeInSubmit = function() {
$('#submit').animate({width: 'toggle'});
};
$(".submit_btn").click(function () {
if($('#about').css("display") == "block") {
$('#about').fadeOut(10);
fadeInSubmit();
} else if($('#contact').css("display") == "block") {
$('#contact').fadeOut(10);
fadeInSubmit();
} else {
fadeInSubmit();
}
});
$(".submitclose").click(function () {
fadeInSubmit();
});
//CONTACT PANEL---------------------------------------------------
var fadeInContact = function() {
$('#contact').animate({width: 'toggle'});
};
$(".contact_btn").click(function () {
if($('#about').css("display") == "block") {
$('#about').fadeOut(10);
fadeInContact();
} else if($('#submit').css("display") == "block") {
$('#submit').fadeOut(10);
fadeInContact();
} else {
fadeInContact();
}
});
$(".contactclose").click(function () {
fadeInContact();
});
//---------------------------------------------------------------
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T02:09:01.857",
"Id": "85737",
"Score": "0",
"body": "try and separate code that is similar and see if you can combine it into one function instead of 2+"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:18:57.767",
"Id": "85757",
"Score": "0",
"body": "@Geo show him, and you have a full-fledged CR-answer..."
}
] | [
{
"body": "<p>I have a few suggestions.</p>\n\n<p><strong>1. Always cache your jquery objects if you are going to select the same thing more than once.</strong></p>\n\n<p>For example: </p>\n\n<pre><code>if($('#submit').css(\"display\") == \"block\") {\n $('#submit').fadeOut(10);\n</code></pre>\n\n<p>Here you are querying the DOM twice to find the <code>#submit</code> element. Instead, save it to a variable and use that variable in both places:</p>\n\n<pre><code>var $submit = $('#submit');\n\nif($submit.css(\"display\") == \"block\") {\n $submit.fadeOut(10);\n</code></pre>\n\n<p>In fact, assuming the elements in question are not dynamically created/removed, you can add this variable assignment at the very top of your code (inside your document.ready) and use it throughout your code. This is only 1 single query instead of multiple with every click.</p>\n\n<p><strong>2. For code readability use <code>.is(\":visible\")</code> to check if an element is visible.</strong> </p>\n\n<p>Instead of <code>$submit.css(\"display\") == \"block\"</code>, which I am assuming you are using to check to see if the element is <code>display: none</code> (hidden) vs <code>display: block</code> (visible), you can use <code>$submit.is(\":visible\")</code>. This is slightly more concise but more importantly better conveys what the code is doing.</p>\n\n<p><strong>3. If a function is called in all possible execution paths, call it after the <code>if</code></strong></p>\n\n<p>In the following code (and other similar code), the function (fadeInContact in this case) is called in every possible execution path:</p>\n\n<pre><code>if($('#about').css(\"display\") == \"block\") {\n $('#about').fadeOut(10);\n fadeInContact();\n} else if($('#submit').css(\"display\") == \"block\") {\n $('#submit').fadeOut(10);\n fadeInContact();\n} else {\n fadeInContact();\n}\n</code></pre>\n\n<p>In this case, the following is functionally equivalent and doesn't require you to put the function into every if/else branch:</p>\n\n<pre><code>if($('#about').css(\"display\") == \"block\") {\n $('#about').fadeOut(10);\n} else if($('#submit').css(\"display\") == \"block\") {\n $('#submit').fadeOut(10);\n}\n\nfadeInContact();\n</code></pre>\n\n<p><strong>4. Replace all <code>fadeIn</code> functions with just one.</strong></p>\n\n<p>You have three different functions which are identical with exception of the <code>id</code> of the element. One example:</p>\n\n<pre><code>var fadeInContact = function() {\n $('#contact').animate({width: 'toggle'});\n};\n</code></pre>\n\n<p>All 3 of these could be replace by one with a parameter for the <code>id</code>:</p>\n\n<pre><code>var fadeInElement = function(id) {\n $('#' + id).animate({width: 'toggle'});\n};\n</code></pre>\n\n<p>Then it would be called like this:</p>\n\n<pre><code>fadeInElement(\"contact\");\n</code></pre>\n\n<p><strong>5. Use chaining and filters to consolidate code.</strong></p>\n\n<p>While not 100% equivalent, making the assumption that only one of your elements is visible at a time, you can replace the following:</p>\n\n<pre><code>if($('#about').css(\"display\") == \"block\") {\n $('#about').fadeOut(10);\n} else if($('#submit').css(\"display\") == \"block\") {\n $('#submit').fadeOut(10);\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>$(\"#about, #submit\").filter(\":visible\").fadeOut(10);\n</code></pre>\n\n<p>In fact, <code>fadeOut</code> will implicitly do a check for visibility and only fade out if the element is visible. As a result, the <code>filter</code> can be excluded making it simply:</p>\n\n<pre><code>$(\"#about, #submit\").fadeOut(10);\n</code></pre>\n\n<hr>\n\n<p>With all changes above incorporated, the following:</p>\n\n<pre><code>$(\".about_btn\").click(function () {\n if($('#submit').css(\"display\") == \"block\") {\n $('#submit').fadeOut(10);\n fadeInAbout();\n } else if($('#contact').css(\"display\") == \"block\") {\n $('#contact').fadeOut(10);\n fadeInAbout();\n } else {\n fadeInAbout();\n }\n}); \n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>$(\".about_btn\").click(function () {\n $(\"#contact, #submit\").fadeOut(10);\n\n fadeInElement(\"about\");\n}); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T19:58:00.090",
"Id": "51335",
"ParentId": "48839",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "51335",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T02:03:24.380",
"Id": "48839",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"jquery",
"performance"
],
"Title": "Navigation bar implementation"
} | 48839 |
<p>I was doing writing some various things in JavaScript and ending up writing 2 scripts that proved useful in quite a lot of my other programs and I was wondering if there was anything that I could do better because I'm fairly new to JavaScript and jQuery after a fairly long history of Java/C++.</p>
<p>Both programs have <code>__</code> passed to them as I have used this as my global variable to prevent cluttering of the actual global namespace (if that is what you call it) and from what I can tell objects that get passed get passed as pointers but values do not, which I still find hard to fully understand in a weakly typed language like JS. The reason they are actually in the functions in the first place is to prevent it from cluttering the global namespace if one of you wants to use it and has underscore.js or simply use <code>__</code> somewhere else.</p>
<p>The first one basically manages inline consoles that look better in my pages while debugging and creates an assert function. <code>log</code> assigns classes based on the second parameter, and these classes are listed in <em>every</em> style sheet I make which is fairly annoying, but I have yet to find a better way to do this. I could maybe assign them CSS styles directly, but that would assign it to every object separately and waste memory.</p>
<h2>console.js</h2>
<pre><code>var log,assert;
!function(__){
__.hasConsole = true;
const ilconsole = $("#console-log");
log = function(text,level){
if (!ilconsole[0]) return false;
level = "log-" + (level || "log"); //log-log for best log 2012
ilconsole.append('<span class = "'+level+'">'+text+'</span></br>');
return true;
};
assert = function(a){
if(!a){
var n = new Error("Assertion failed");
log(n.stack,"fatal"); //I love stacks, but I hate the way this looks ;c
throw (n);
//mabye could replace all this with 'throw new Error("Assertion failed");' or even 'throw "assertion failed";'
}
};
$(document).ready(function(){
if (!log("Inline console found","important")){
log = function(f){console.log(f);}; //Prevents the second paramater interfering with default consoles that take a second paramater
log("No inline console found, defaulting to browser console. Add an object with id 'console-log' into the document to enable inline console.");
__.hasConsole = false;
}
});
}(__ || !function(){throw new Error("Global namespace (__) must be set to an object!");}()); //I don't know if this is bad practice but it stops it from running
</code></pre>
<p>The second one is a way to add inputs that have the text disappear when you focus them and have a button linked if you press enter while focused. The difference between this and <code>$(this)</code> are obvious in the object properties but I don't know how to speeds compare, so I went with the basic JavaScript for what I could as I assumed it was faster. This may cause cache-misses but I don't think those are important in JavaScript in general because this isn't being called 120 times a second like things in C++.</p>
<h2>jbase.js</h2>
<pre><code>!function(__){$(document).ready(function(){
__.hasjbase = true;
$(".jtext")
.text(function(){this.value = $(this).attr("jvalue");})
.focus(function(){
const $this = $(this);
if(this.value == $this.attr("jvalue"))
$this.val("");
})
.blur(function(){
const $this = $(this);
if(this.value === "") // I dont know if this is right (what if they type 'false' or '0' or 'undefined')
$this.val($this.attr("jvalue"));
});
$(".jlink")
.keyup(function(e){
if (e.which != 13) return;//return key
const $this = $(this);
const $that = $("#" + $this.attr("jlink"));
assert($that[0]);
$this.blur(); //unneeded?
$that.focus();
$that.click();
});
});}(__ || /*!function(){throw new Error("Global namespace (__) must be set to an object!");}()*/ {});//throw is commented because the __ isnt used importantly this script
//Example usage
/*
Input that changes to blank when focused, and activates foo when enter is hit
<input type = "text" class = "wow so fresh jtext jlink" jvalue = "cool input!" jlink = "foo"></input>
<input type = "button" id = "foo"></input>
Input that changes to blank when focused
<input type = "text" class = "wow so fresh jtext" jvalue = "cool input!"></input>
*/
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T03:26:36.610",
"Id": "85738",
"Score": "2",
"body": "`x === \"\"` will not false-positively on `0, null, false, undefined, whitespace, etc` it will work as you want, **edit:** unless you want to be false when they type 0, etc"
}
] | [
{
"body": "<h1>console.js</h1>\n\n<pre><code>;(function (__) {\n\n // As far as I know, there are no \"const\" in JS.\n var ilconsole = $(\"#console-log\");\n\n // Like C, 0 is false, non-0 is true. jQuery objects have length, a count of the elements in the set\n __.hasConsole = ilconsole.length;\n\n\n function log(text, level) {\n if (__.hasConsole) {\n level = \"log-\" + (level || \"log\");\n\n // Using div for a natural \"new-line\", no <br>\n // Also using a chained approach, more readable\n $('<div>', {\n class: level\n }).text(text).appendTo(ilconsole);\n } else {\n\n // default to console.log()\n console.log(text);\n }\n };\n\n function assert(a) {\n // early return pattern avoids further indentation\n if (a) return;\n // The only standard properties of Error is name and message.\n // You could subclass Error to create custom errors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\n throw (new Error(\"Assertion failed\"));\n };\n\n $(function () {\n if (__.hasConsole) log(\"Inline console found\", \"important\");\n else log(\"No inline console found, defaulting to browser console. Add an object with id 'console-log' into the document to enable inline console.\");\n });\n\n // If they needed to be global, expose them as global\n window.log = log;\n window.assert = assert;\n\n// Use the existing __ or create one on the fly. No need for declaring __ beforehand\n}(this.__ = this.__ || {}));\n</code></pre>\n\n<h1>jbase.js</h1>\n\n<pre><code>;(function (__) {\n $(function () {\n\n __.hasjbase = true;\n\n // What I think you need here is the placeholder attribute\n // <input type=\"text\" placeholder=\"some value\" />\n\n\n // If you go for the JS route, then there's no issue with using native\n // but I highly suggest using data-* attributes so that the HTML will be valid\n $(\".jtext\")\n .val(function () {\n return this.jvalue;\n })\n .focus(function () {\n if (this.value == this.jvalue) this.value = '';\n })\n .blur(function () {\n if (this.value === \"\") this.value = this.jvalue;\n });\n\n $(\".jlink\").keyup(function (e) {\n if (e.which !== 13) return; //return key\n var $this = $(this);\n var $that = $(\"#\" + this.jlink);\n assert($that[0]);\n // Gain focus on one element will lose focus on the other.\n $that.focus();\n $that.click();\n });\n });\n}(this.__ = this.__ || {}));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T21:49:40.327",
"Id": "85918",
"Score": "0",
"body": "in jbase, I didnt realize what I did with the `.val` under `$(\".jtext\")`, (probably some result of me copypasting `.focus` and `.blur`), but you kept it as a function that returns the value `this.jvalue`. Couldnt you just make it into `.val(this.jvalue)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T22:04:07.777",
"Id": "85919",
"Score": "0",
"body": "@user1114214 The `this` when doing `.val(this.jvalue)` is not `.jtext`. The reason I placed it in a function is because inside that function, the `this` is `.jtext`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:15:13.423",
"Id": "48874",
"ParentId": "48843",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48874",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T03:22:19.243",
"Id": "48843",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"beginner",
"html",
"plugin"
],
"Title": "JavaScript scrippits"
} | 48843 |
<p>As I am relativistically new to programming and lack any sort of formal experience in the matter, I was wondering if any of you with a bit more knowledge in the subject would be willing to tell me if the following code is an acceptable way to accomplish a function binding event handler in Java 8.</p>
<p>I admit that the naming conventions in the following code may be slightly off-par, however, it makes sense to me as a free-spirited beginner who cares not for package.thousand_sub-packages.overly_long_class_name_and_full_essay.java.</p>
<p>Again, the purpose of this question is to ascertain if my solution is an acceptable one, and if it is not, what a proper one would be.</p>
<p>First the main class:</p>
<pre><code>package TestingApp;
import JGameEngineX.JGameEngineX;
import Modes.Main_Game;
import Modes.Main_Menu;
import java.util.Random;
/**
* @author RlonRyan
* @name JBasicX_TestingApp
* @version 1.0.0
* @date Jan 9, 2012
* @info Powered by JBasicX
*
*/
public class JBasicX_TestingApp {
public static JGameEngineX instance;
public static final String[] options = {"Lambda Style!", "Javaaa!", "Spaaaaaace!", "Generic!", "Automated!", "Title goes here."};
public static void main(String args[]) {
if (instance != null) {
return;
}
String mode = args.length >= 1 ? args[0] : "windowed";
int fps = args.length >= 3 ? Integer.parseInt(args[2]) : 100;
int width = args.length >= 4 ? Integer.parseInt(args[3]) : 640;
int height = args.length >= 5 ? Integer.parseInt(args[4]) : 480;
instance = new JGameEngineX("JBasicX Testing Application: " + options[new Random().nextInt(options.length)], mode, fps, width, height);
instance.registerGameMode(new Main_Menu(instance));
instance.registerGameMode(new Main_Game(instance));
instance.init();
instance.start("main_menu");
}
}
</code></pre>
<p>Next the menu mode class:</p>
<pre><code>package Modes;
import JGameEngineX.JGameEngineX;
import JGameEngineX.JGameModeX.JGameModeX;
import JIOX.JMenuX.JMenuElementX.JMenuTextElementX;
import JIOX.JMenuX.JMenuX;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.util.Random;
/**
*
* @author RlonRyan
*/
public class Main_Menu extends JGameModeX {
private JMenuX menu;
public Main_Menu(JGameEngineX holder) {
super("Main_Menu", holder);
}
@Override
public void init() {
menu = new JMenuX("Main Menu", 160, 120, 320, 240);
menu.addMenuElement(new JMenuTextElementX("Start", () -> (holder.setGameMode("main_game"))));
menu.addMenuElement(new JMenuTextElementX("Toggle Game Data", () -> (holder.toggleGameDataVisable())));
menu.addMenuElement(new JMenuTextElementX("Randomize!", () -> (holder.setBackgroundColor(new Color(new Random().nextInt(256),new Random().nextInt(256),new Random().nextInt(256))))));
menu.addMenuElement(new JMenuTextElementX("Reset!", () -> (holder.setBackgroundColor(Color.BLACK))));
menu.addMenuElement(new JMenuTextElementX("Quit", () -> (System.exit(0))));
}
@Override
public void registerBindings() {
bindings.bind(KeyEvent.KEY_PRESSED, KeyEvent.VK_DOWN, (e) -> (menu.incrementHighlight()));
bindings.bind(KeyEvent.KEY_PRESSED, KeyEvent.VK_UP, (e) -> (menu.deincrementHighlight()));
bindings.bind(KeyEvent.KEY_PRESSED, KeyEvent.VK_ENTER, (e) -> (menu.selectMenuElement()));
bindings.bind(KeyEvent.KEY_PRESSED, KeyEvent.VK_ESCAPE, (e) -> (System.exit(0)));
bindings.bind(KeyEvent.KEY_PRESSED, (e) -> (System.out.println("Keypress: " + ((KeyEvent) e).getKeyChar() + " detected with lambda!")));
}
@Override
public void start() {
menu.open();
}
@Override
public void update() {
// Update...
}
@Override
public void pause() {
// Do nothing
}
@Override
public void stop() {
menu.close();
}
@Override
public void paint(Graphics2D g2d) {
menu.paint(g2d);
}
}
</code></pre>
<p>Finally the binding class:</p>
<pre><code>package JEventX;
import java.awt.AWTEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.function.Consumer;
import javafx.util.Pair;
/**
*
* @author RlonRyan
*/
public class JEventBinderX {
private final HashMap<Pair<Integer, Integer>, ArrayList<Consumer<AWTEvent>>> bindings;
public JEventBinderX() {
bindings = new HashMap<>();
}
public final void bind(int trigger, Consumer<AWTEvent> method) {
bind(new Pair<>(trigger, 0), method);
}
public final void bind(int trigger, int subtrigger, Consumer<AWTEvent> method) {
bind(new Pair<>(trigger, subtrigger), method);
}
public final void bind(Pair<Integer, Integer> trigger, Consumer<AWTEvent> method) {
if (!this.bindings.containsKey(trigger)) {
this.bindings.put(trigger, new ArrayList<>());
}
this.bindings.get(trigger).add(method);
}
public final void release(int trigger) {
release(new Pair<>(trigger, 0));
}
public final void release(Pair<Integer, Integer> trigger) {
if (this.bindings.containsKey(trigger)) {
this.bindings.remove(trigger);
}
}
public final void release(int trigger, Consumer<AWTEvent> method) {
release(new Pair<>(trigger, 0), method);
}
public final void release(Pair<Integer, Integer> trigger, Consumer<AWTEvent> method) {
if (this.bindings.containsKey(trigger)) {
this.bindings.get(trigger).remove(method);
}
}
public final void fireEvent(AWTEvent e) {
Pair<Integer, Integer> id = null;
if(e instanceof MouseEvent) {
id = new Pair<>(e.getID(), ((MouseEvent)e).getButton());
}
else if(e instanceof KeyEvent) {
id = new Pair<>(e.getID(), ((KeyEvent)e).getKeyCode());
}
if(id != null && this.bindings.containsKey(id)){
bindings.get(id).stream().forEach((c) -> c.accept(e));
}
id = new Pair<>(e.getID(), 0);
if(this.bindings.containsKey(id)) {
bindings.get(id).stream().forEach((c) -> c.accept(e));
}
}
public final void fireEvent(AWTEvent e, int subid) {
Pair<Integer, Integer> id = new Pair<>(e.getID(), subid);
if(this.bindings.containsKey(id)){
bindings.get(id).stream().forEach((c) -> c.accept(e));
}
}
}
</code></pre>
<p>[Edit] And the JGameModeX class</p>
<pre><code>package JGameEngineX.JGameModeX;
import JEventX.JEventBinderX;
import JGameEngineX.JGameEngineX;
import java.awt.Graphics2D;
/*
* public static enum GAME_STATUS {
*
* GAME_STOPPED,
* GAME_INTIALIZING,
* GAME_STARTING,
* GAME_MENU,
* GAME_RUNNING,
* GAME_PAUSED;
* }
*/
/**
*
* @author RlonRyan
*/
public abstract class JGameModeX {
public final String name;
public final JEventBinderX bindings;
public final JGameEngineX holder;
public JGameModeX(String name, JGameEngineX holder) {
this.name = name.toLowerCase();
this.bindings = new JEventBinderX();
this.holder = holder;
}
public abstract void init();
public abstract void registerBindings();
public abstract void start();
public abstract void update();
public abstract void paint(Graphics2D g2d);
public abstract void pause();
public abstract void stop();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:36:36.970",
"Id": "85774",
"Score": "0",
"body": "This code really needs `JGameModeX` in order for some of the code to make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:58:50.980",
"Id": "85798",
"Score": "0",
"body": "That would help, I suppose..."
}
] | [
{
"body": "<p>Looks completely acceptable to me. If there is no reason to hold on to the lambdas in some other way, e.g. to flush or remove them, and they're not too big or complicated to distract from the current context, then I see this as much the preferred way to do it.</p>\n\n<p>Short answer but, yeah, good question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T13:39:38.277",
"Id": "49146",
"ParentId": "48845",
"Score": "3"
}
},
{
"body": "<p>Why do you have this piece of code ? </p>\n\n<blockquote>\n<pre><code>if (instance != null) {\n return; \n}\n</code></pre>\n</blockquote>\n\n<p>In fact, why is <code>public static JGameEngineX instance;</code> public at all? Do you really need to expose it ? The code I was asking earlier seems to verify that <code>instance</code> has not been initialized by anything else but this class. If <code>instance</code> was private you would not need to check if it was created elsewhere since you have control over it. If you don't need the public visibility don't use it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T03:34:25.357",
"Id": "86672",
"Score": "0",
"body": "Oh, yeah, that is a bit dumb... I think I was thinking about trying to prevent multiple concurrent runs, but never got around to it, so I wound up with that. I'll make a note to remove it, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T14:07:09.517",
"Id": "49147",
"ParentId": "48845",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T05:09:22.660",
"Id": "48845",
"Score": "10",
"Tags": [
"java",
"beginner"
],
"Title": "\"Event Binding\" in Java employing Lambda"
} | 48845 |
<p>This program calculates the square root of an unsigned 32-bit number with some bit fiddling to get a very close approximation, then one iteration of the <a href="http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method" rel="nofollow">Babylonian method</a> to get an exact value. I don't know if this could be faster, but hope it can.</p>
<p>I have trouble with clearly commenting my code, so I will gladly explain unclear portions of code.</p>
<pre><code>[global sqrti]
sqrti:
mov eax, [esp+4]
xor ecx, ecx ; clear register to put our approximation in
; make the lower 16 bits of CX equal the even-numbered bits of EAX
shr eax, 3
rcr cx, 1
%rep 14
shr eax, 2
rcr cx, 1
%endrep
; do one iteration of the Babylonian method
or ecx, 1 ; prevent a division by zero
mov eax, [esp+4]
xor edx, edx ; clear top half of DIV's implied operand
div ecx
add eax, ecx
shr eax, 1
ret
</code></pre>
| [] | [
{
"body": "<p>The first thing which strikes me as odd is how you calculate your initial estimation. If you only take every 2nd bit into account that means a value like <code>0b10101010101010</code> would yield a <code>0</code> as your initial estimation (or <code>1</code> after the <code>or ecx, 1</code> adjustment) - not very good. Also it's not clear to me why you skip the first 3 bits, that makes even your best estimates off by a factor of 2.</p>\n\n<p>But I can see what you try to do: just take the \"half\" of the bits of the initial value. I think you can fix that by first or-ing the even with the uneven bits together and then apply the shifting and roring:</p>\n\n<pre><code> mov eax, [esp+4]\n test eax, eax,\n jnz positive\n ret ; Return immediately when input is 0\npositive:\n mov ecx, eax\n shl ecx\n or eax, ecx\n bsr ecx, eax ; Get highest bit for later adjustment\n xor edx, edx\nloop:\n shr eax, 2\n rcr dx\n jnz loop\n shr cl ; Adjust for skipped bits\n inc cl\n rol dx, cl\n mov ecx, edx ; Use ecx to store estimation\n</code></pre>\n\n<p>Note that <code>shr</code> modifies the zero flag, but <code>rcr</code> doesn't so you can jump out of the loop as soon as <code>eax</code> turns out to be 0.</p>\n\n<p>Furthermore note that <code>1</code> is an implied parameter for shifting operations if none is given. So you can safe a byte each time you leave it out (and possibly a cycle).</p>\n\n<p>The other thing which is strange is that you only do one iteration. You should repeat it till your estimated value varies only by 0 or 1 between iterations, otherwise it's hard to see how your sqrti function will be useful.</p>\n\n<p>And I don't think you need the <code>or ecx, 1</code> statement. Just make sure to return immediately if <code>[esp+4]</code> turns out to be 0. And if its positive your <code>ecx</code> register should never become 0 if you get the initial estimation right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:30:32.403",
"Id": "85792",
"Score": "0",
"body": "Thanks for your answer, David. Looking back, it does seem extremely odd for me to initially shift EAX right by 3. Looking at that number you've given, that could be very bad. Another possibility could be an AND with 0x55555555, shifting that right, and adding it to the original value.\n\nI only did one iteration because, in my trials, the estimate was usually off by only a few bits in the last place. In retrospect, I should probably check better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:34:30.837",
"Id": "85808",
"Score": "0",
"body": "I don't think adding would be good, because that might also zero out the even bits. I noticed however that my solution also has problems, because by short cutting the loop the inital cx value might be too high... Maybe you have to use the fixed rep after all, but I'm thinking about a better solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:24:43.327",
"Id": "85819",
"Score": "0",
"body": "Ok, I think I found a solution: `bsf` to the rescue (that finds the highest set bit and is available since 386). You can use that to adjust the final estimation. I edited my answer accordingly.\n\nNote that I had to replace `ecx` with `edx` in the loop, because shift operations only allow `cl` as a register parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T22:52:09.187",
"Id": "85839",
"Score": "1",
"body": "@DavidOngaro: I believe you want `bsr`. `bsf` finds the *least* significant bit that's set, not the most significant bit."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:31:12.287",
"Id": "48851",
"ParentId": "48847",
"Score": "7"
}
},
{
"body": "<p>I made a few experiments and tested them by timing one billion calculations of sqrt(400000000). With your implementation, it takes <strong>12 seconds</strong> on my PC.</p>\n\n<p>I had a few ideas, but none of the simple ones improves the run time.</p>\n\n<p>It would be possible to avoid loading the parameter from memory twice (mov eax, [esp+4]) by storing it into ebx, but this doesn't change anything.</p>\n\n<p>Another attempt I made was to split the bits extraction part into two: copy eax into ebx, shift ebx by 2, and then, extract one bit from eax, shift by 4, extract one bit from ebx, shift by 4, etc. %rep 14 becomes %rep 7, of course. I thought this might make room for some parallel execution of the two halves, but somehow, it didn't (maybe because of the contention on cx ?).</p>\n\n<p>Now, for something that actually works :-) Are you open to the modern additions to the x86 instruction set ? Haswell processors support the BMI2 instruction set, part of AVX2, which contains a neat new instruction named PEXT, for parallel extract. This has been available for some time on MMX registers via SSE4 (introduced on Nehalem), now it has come to regular registers.</p>\n\n<p><strong>PEXT dest, src, mask</strong> extracts bits from <strong>src</strong>, keeping those that are set in <strong>mask</strong>, and puts the result in <strong>dest</strong>. In the present case, this part:</p>\n\n<pre><code>; make the lower 16 bits of CX equal the even-numbered bits of EAX\n shr eax, 3\n rcr cx, 1\n%rep 14\n shr eax, 2\n rcr cx, 1\n%endrep\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>mov edx, 0x55555555 ; odd-numbered bits = 0, even-numbered bits = 1\npext ecx, eax, edx ; extract the even-numbered bits of eax into ecx\n</code></pre>\n\n<p>So, what does it change ? Now, the billion calculations take <strong>4,7 seconds</strong>, so I guess this speaks for itself. Of course, the program now requires a Haswell processor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:42:41.400",
"Id": "85793",
"Score": "0",
"body": "My processor isn't a Haswell, so I couldn't try the PEXT instruction. However, I found the SSE4 instruction you were talking about: EXTRQ. It does the same thing, but with an XMM register. I'll see if I can use that instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T09:45:28.913",
"Id": "48852",
"ParentId": "48847",
"Score": "2"
}
},
{
"body": "<p>I suppose the first question to consider here is how accurate of an estimate of the square root you need/want. As it stands right now, your routine is quite fast, but accuracy is <em>quite</em> poor.</p>\n\n<p>I did a quick test summing the computed square roots of a sample of numbers and compared the result against that from the <code>sqrt</code> in the standard library:</p>\n\n<pre><code>for (int i = 0; i < 0x2fffff; i += 13)\n sum += f(i);\n</code></pre>\n\n<p>The results I got were:</p>\n\n<pre><code>fsqrt: 285997356\nsqrti: 3567533576\n</code></pre>\n\n<p>Your result is wrong by factor of about 12. Since this is the sum, your individual results may even be further off than that.</p>\n\n<p>I have a difficult time imagining an application for which this level of (in)accuracy would be acceptable, but if it's even close to acceptable, I'd use an even (much) simpler approximation:</p>\n\n<pre><code>approx proc num:dword\n mov eax, num\n bsr ecx, eax\n mov eax, 1\n shr ecx, 1\n shl eax, cl\n ret\napprox endp\n</code></pre>\n\n<p>This produces a result <em>very</em> quickly, and it's at least sort of in the right general range, anyway:</p>\n\n<pre><code>fsqrt: 285997356\napprox: 200588695\n</code></pre>\n\n<p>That's obviously still not very accurate, but at least it's sort of close. If we want to improve that a little, we can add one more iteration of the same basic idea: remove the MSB that's set in the input, approximate the square root of what's left, and add that to our result:</p>\n\n<pre><code>approx proc num:dword\n mov eax, num\n bsr ecx, eax\n mov ebx, 1\n push ecx\n shr ecx, 1\n shl ebx, cl\n\n mov esi, 1\n pop ecx\n shl esi, cl\n\n sub eax, esi\n bsr ecx, eax\n shr ecx, 1\n mov edi, 1\n shl edi, cl\n or ebx, edi\n mov eax, ebx\n ret\napprox endp\n</code></pre>\n\n<p>For the test run, the result now looks like this:</p>\n\n<pre><code>fsqrt: 285997356\napprox: 281530962\n</code></pre>\n\n<p>This obviously isn't <em>very</em> accurate yet, but at least I can imagine cases where it might easily be accurate enough, and it is pretty fast. If it's <em>not</em> accurate enough for your purposes, the next step is probably to just use <code>fsqrt</code>. Although (at least by my timing) this routine is faster than <code>fsqrt</code>, it already takes about two thirds the time that fsqrt does, so adding even one more iteration would put it about even with <code>fsqrt</code>.</p>\n\n<p>If you want a routine that's accurate and <em>nearly</em> competitive with fsqrt, you might consider the binary reducing algorithm instead:</p>\n\n<pre><code>isqrt proc num:dword\n mov eax, num\n xor ebx, ebx\n bsr ecx, eax\n and cl, 0feh\n mov edx, 1\n shl edx, cl\nrefine:\n mov esi, ebx\n add esi, edx\n cmp esi, eax\n ja @f\n sub eax, esi\n shr ebx, 1\n add ebx, edx\n jmp next\n@@:\n shr ebx, 1\nnext :\n shr edx, 2\n jnz refine\n mov eax, ebx\n ret\nisqrt endp\n</code></pre>\n\n<p>Depending upon circumstances, calling conventions, etc., this <em>can</em> be marginally faster than the <code>sqrt</code> in the C standard library (but it's often a little slower), and at least in my testing it produces <em>identical</em> results:</p>\n\n<pre><code>fsqrt: 285997356\nisqrt: 285997356\n</code></pre>\n\n<p>If you want to improve speed and can tolerate some inaccuracy, you could probably do a bit to loosen the exit condition from that, and come up with something that produced reasonably accurate results a little more quickly. I'll leave that as the dreaded \"exercise for the reader.\"</p>\n\n<p>Rereading, I notice what I've written above isn't quite accurate: the references to <code>fsqrt</code> aren't actually comparing to using the <code>fsqrt</code> instruction directly--they're to calling the <code>sqrt</code> in the C standard library. I haven't looked though--it's possible the compiler is generating code for that inline, so the comparison really is to the <code>fsqrt</code> instruction without little (or nothing) else involved.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T23:59:04.300",
"Id": "48891",
"ParentId": "48847",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T05:39:48.387",
"Id": "48847",
"Score": "9",
"Tags": [
"algorithm",
"beginner",
"mathematics",
"assembly",
"bitwise"
],
"Title": "Integer square root in x86 assembly (NASM)"
} | 48847 |
<p>My concern with this code is the excessive use of <code>.encode('utf-8')</code>. Any advice on refining these functions would be very helpful.</p>
<p><a href="https://github.com/Ricky-Wilson/rss2html/blob/master/setup.py" rel="nofollow">rss2html GitHub repo</a></p>
<pre><code>#!/usr/bin/env python
""" Simple rss to html converter """
__version__ = "0.0.1"
__author__ = "Ricky L Wilson"
from feedparser import parse as parsefeed
import StringIO
def entry2html(**kwargs):
""" Format feedparser entry """
title = kwargs['title'].encode('utf-8')
link = kwargs['link'].encode('utf-8')
description = kwargs['description'].encode('utf-8')
template = """
<h2 class='title'>{title}</h2>
<a class='link' href='{link}'>{title}</a>
<span class='description'>{description}</span>
"""
return template.format(title=title, link=link, description=description)
def convert_feed(**kwargs):
""" Main loop """
out = StringIO.StringIO("")
for entry in parsefeed(kwargs['url']).entries:
title = entry['title']
link = entry['link']
description = entry['description']
print >>out, entry2html(title=title, link=link,
description=description)
return out.getvalue()
print convert_feed(url='http://stackoverflow.com/feeds')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:04:23.877",
"Id": "85874",
"Score": "1",
"body": "I've removed your new version of the code, since it [adds confusion to the question](http://meta.codereview.stackexchange.com/q/1763/9357). If you would like further advice, feel free to ask another question."
}
] | [
{
"body": "<p>Work in Unicode and encode at the last moment:</p>\n\n<pre><code>def entry2html(**kwargs):\n \"\"\" Format feedparser entry \"\"\"\n template = u\"\"\"\n <h2 class='title'>{title}</h2>\n <a class='link' href='{link}'>{title}</a>\n <span class='description'>{description}</span>\n \"\"\"\n return template.format(**kwargs)\n\ndef convert_feed(**kwargs):\n \"\"\" Main loop \"\"\"\n out = u'\\n'.join(entry2html(**entry) \n for entry in parsefeed(kwargs['url']).entries)\n return out.encode('utf-8')\n</code></pre>\n\n<p>You can pass <code>entry</code> directly as <code>format</code> does not mind extra keyword arguments. <code>StringIO</code> is not necessary for simple concatenation of strings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T07:49:05.237",
"Id": "48849",
"ParentId": "48848",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48849",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T06:48:56.730",
"Id": "48848",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"utf-8",
"rss"
],
"Title": "Avoiding use of .encode() in rss2html"
} | 48848 |
<p>This question originates from <a href="https://stackoverflow.com/questions/23433442/sort-3x3-grid-by-rotating-2x2-subgrids">this post</a>.</p>
<p>Anyway, I'm trying to solve the following problem:</p>
<p>Given a 3x3 grid with numbers 1-9, for example:</p>
<pre><code>2 8 3
1 4 5
7 9 6
</code></pre>
<p>I have to sort the grid by rotating a 2x2 subgrid clockwise or counter-clockwise. The above example could be solved like this:</p>
<p>Rotate the top left piece clockwise:</p>
<pre><code>2 8 3 1 2 3
1 4 5 => 4 8 5
7 9 6 7 9 6
</code></pre>
<p>Rotate the bottom right piece counter-clockwise:</p>
<pre><code>1 2 3 1 2 3
4 8 5 => 4 5 6
7 9 6 7 8 9
</code></pre>
<p>The grid is now 'sorted'.</p>
<p>I have to find the number of least possible moves to get from situation B to situation A (sorted)</p>
<p>My current implementation consists of creating a look-up table for all the possible permutations of the grid (idea from the original thread by user Sirko). The look-up table is a HashMap. I reduce the grids to strings like this:</p>
<pre><code>1 2 3
4 5 6 => "123456789"
7 8 9
</code></pre>
<p>My current implementation (in Java):</p>
<pre><code>import java.util.*;
public class Kiertopeli {
// initialize the look-up table
public static Map<String, Integer> lookUp = createLookup();
public static int etsiLyhin(int[][] grid) {
String finale = "";
for(int[] row : grid)
for(int num : row)
finale += Integer.toString(num);
// fetch the wanted situation from the look-up table
return lookUp.get(finale);
}
public static Map<String, Integer> createLookup() {
// will hold the list of permutations we have already visited.
Map<String, Integer> visited = new HashMap<String, Integer>();
Queue q = new ArrayDeque<Object[]>();
q.add(new Object[] { "123456789", 0 });
// just for counting. should always result in 362880.
int permutations = 0;
Object[] str;
creation:
while(!q.isEmpty())
{
str = (Object[])q.poll();
// pick the next non-visited permutation.
while(visited.containsKey((String)str[0])) {
if(q.isEmpty()) break creation;
str = (Object[])q.poll();
}
// mark the permutation as visited.
visited.put((String)str[0], (Integer)str[1]);
// loop through all the rotations.
for(int i = 0; i < 4; i++) {
// get a String array with arr[0] being the permutation with clockwise rotation,
// and arr[1] with counter-clockwise rotation.
String[] rotated = rotate((String)str[0], i);
// if the generated permutations haven't been created before, add them to the queue.
if(!visited.containsKey(rotated[0])) q.add(new Object[] { rotated[0], (Integer)str[1]+1 });
if(!visited.containsKey(rotated[1])) q.add(new Object[] { rotated[1], (Integer)str[1]+1 });
}
permutations++;
}
System.out.println(permutations);
return visited;
}
public static String[] rotate(String string, int place) {
StringBuilder str1 = new StringBuilder(string);
StringBuilder str2 = new StringBuilder(string);
if(place == 0) { // top left piece
str1.setCharAt(0, string.charAt(3));
str1.setCharAt(1, string.charAt(0)); // clockwise rotation
str1.setCharAt(4, string.charAt(1)); //
str1.setCharAt(3, string.charAt(4));
str2.setCharAt(3, string.charAt(0));
str2.setCharAt(0, string.charAt(1)); // counter-clockwise
str2.setCharAt(1, string.charAt(4)); //
str2.setCharAt(4, string.charAt(3));
}
if(place == 1) { // top right
str1.setCharAt(1, string.charAt(4));
str1.setCharAt(2, string.charAt(1));
str1.setCharAt(5, string.charAt(2));
str1.setCharAt(4, string.charAt(5));
str2.setCharAt(4, string.charAt(1));
str2.setCharAt(1, string.charAt(2));
str2.setCharAt(2, string.charAt(5));
str2.setCharAt(5, string.charAt(4));
}
if(place == 2) { // bottom left
str1.setCharAt(3, string.charAt(6));
str1.setCharAt(4, string.charAt(3));
str1.setCharAt(7, string.charAt(4));
str1.setCharAt(6, string.charAt(7));
str2.setCharAt(6, string.charAt(3));
str2.setCharAt(3, string.charAt(4));
str2.setCharAt(4, string.charAt(7));
str2.setCharAt(7, string.charAt(6));
}
if(place == 3) { // bottom left
str1.setCharAt(4, string.charAt(7));
str1.setCharAt(5, string.charAt(4));
str1.setCharAt(8, string.charAt(5));
str1.setCharAt(7, string.charAt(8));
str2.setCharAt(7, string.charAt(4));
str2.setCharAt(4, string.charAt(5));
str2.setCharAt(5, string.charAt(8));
str2.setCharAt(8, string.charAt(7));
}
return new String[] { str1.toString(), str2.toString() };
}
public static void main(String[] args) {
String grids = "2 8 3 1 4 5 7 9 6 "
+ "1 6 5 8 7 2 3 4 9 "
+ "1 6 5 8 7 2 3 4 9 "
+ "1 7 6 8 2 5 3 4 9 "
+ "8 1 5 7 4 6 3 9 2 "
+ "9 8 7 6 5 4 3 2 1 ";
Scanner reader = new Scanner(grids);
System.out.println();
while (reader.hasNext()) {
System.out.println("Enter grid:");
int[][] grid = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
grid[i][j] = reader.nextInt();
}
}
System.out.println(" Smallest: " + etsiLyhin(grid));
}
}
}
</code></pre>
<p>The problem is, this runs for too long. Well, to clarify, on the server this code is tested on it runs for more than 2000ms (maximum allowed), but on my machine it runs for 1500-1600ms. Is there any optimization I could do here?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T21:19:54.120",
"Id": "85833",
"Score": "1",
"body": "Please do not modify the code in the question after it has been answered, or add your solution to the question. See our [new guidelines](http://meta.codereview.stackexchange.com/questions/1763) for sharing your revisions. I've rolled back Rev 3 to Rev 1."
}
] | [
{
"body": "<p>I guess you could get quite some performance from changing your main data type from <code>String</code> to an <code>byte</code> or <code>integer</code> array like, e.g.:</p>\n\n<pre><code>byte[] sorted = new byte[]() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n</code></pre>\n\n<p>Then you could easily change the identifying code for each permutation to an <code>integer</code> as well. Which could be computed out of the above array like this:</p>\n\n<pre><code>int code = sorted[8] * 1 +\n sorted[7] * 10 +\n sorted[6] * 100 +\n sorted[5] * 1000 +\n sorted[4] * 10000 +\n sorted[3] * 100000 +\n sorted[2] * 1000000 +\n sorted[1] * 10000000 +\n sorted[0] * 100000000;\n</code></pre>\n\n<p>This would keep you from using <code>String</code> comparisons inside the <code>Map visited</code>. Generally <code>int</code> operations are faster than the equivalent <code>String</code> operations.</p>\n\n<p>As I already mentioned in my answer to the original question, another improvement would be to look, if a permutation was already added to the queue before. If so, we don't have to do this again as it will yield no new information. This will reduce the <code>put()</code>/<code>poll()</code> operations on the queue by a lot.</p>\n\n<p>You could do this, by introducing a new <code>Set</code> and using this to verify, if a specific permutation has been added to the queue before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:39:16.147",
"Id": "85761",
"Score": "0",
"body": "Am I not checking if a permutation was already added to the queue in the for loop? But using integer arrays instead of strings make a lot of sense. Thanks! Will do this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:41:15.520",
"Id": "85762",
"Score": "0",
"body": "You are checking, if you already have added a permutation to the result, but not to the queue. This is a difference as there will be multiple entries for a single permutation in the queue as long as none has been added to `visited`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T13:02:08.700",
"Id": "85763",
"Score": "0",
"body": "Alllllright! I was able to cut the time down to 1 second by checking if a permutation had been queued. I'll do the int array now as well. Thanks a lot!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:35:25.617",
"Id": "48859",
"ParentId": "48855",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48859",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T10:48:50.283",
"Id": "48855",
"Score": "3",
"Tags": [
"java",
"algorithm",
"sorting",
"matrix"
],
"Title": "Sort 3x3 grid by rotating 2x2 subgrids"
} | 48855 |
<p><img src="https://i.stack.imgur.com/gOup9.jpg" alt="enter image description here"></p>
<p><a href="http://rgcsm.info/blog/guess-number-game-project-source-code-java-swing/" rel="nofollow noreferrer">Also posted at rgcsm.info/blog</a></p>
<pre><code>//Number Guessing Game in Java Swing
//Also posted at
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Guess extends JFrame
{
JTextField t1, t2, t3, t4;
JLabel j4;
ButtonListener bl1;
ButtonListener2 bl2;
ButtonListener3 bl3;
//setting random number in rand variable
int rand=(int) (Math.random()*100);
int count=0;
public Guess()
{
//Get the container
Container c = getContentPane();
//Set absolute layout
c.setLayout(null);
//Set Background Color
c.setBackground(Color.WHITE);
//Creating image
JLabel lblpic = new JLabel("");
lblpic.setIcon(new ImageIcon("images.png"));
lblpic.setBounds(0,0,500,350);
//Creating label Guess my number text
JLabel j=new JLabel("Guess my number game");
j.setForeground(Color.RED);
j.setFont(new Font("tunga",Font.BOLD,24));
j.setSize(270,20);
j.setLocation(300,35);
//Creating label Enter a number.....
JLabel j1=new JLabel("Enter a number b/w 1-100");
j1.setFont(new Font("tunga",Font.PLAIN,17));
j1.setSize(270,20);
j1.setLocation(300,60);
//Creating TextField for input guess
t1=new JTextField(10);
t1.setSize(50,30);
t1.setLocation(350,80);
//Creating Label for Display message
j4=new JLabel("Try and guess my number");
j4.setFont(new Font("tunga",Font.PLAIN,17));
j4.setSize(270,20);
j4.setLocation(290,130);
//Creating Text field for best score
t2=new JTextField(10);
t2.setSize(40,20);
t2.setLocation(10,10);
//Creating Label for best score
JLabel j5=new JLabel("Best Score");
j5.setFont(new Font("tunga",Font.PLAIN,17));
j5.setSize(270,20);
j5.setLocation(60,10);
//Creating guess text field
t3=new JTextField(10);
t3.setSize(40,20);
t3.setLocation(160,10);
//Creating guess Label
JLabel j6=new JLabel("Guesses");
j6.setFont(new Font("tunga",Font.PLAIN,17));
j6.setSize(270,20);
j6.setLocation(210,10);
//creating 3 buttons
JButton b1=new JButton("Guess");
b1.setSize(150,40);
b1.setLocation(260,250);
bl1=new ButtonListener();
b1.addActionListener(bl1);
JButton b2=new JButton("Give up!");
b2.setSize(100,30);
b2.setLocation(180,200);
bl2=new ButtonListener2();
b2.addActionListener(bl2);
JButton b3=new JButton("Play Again");
b3.setSize(120,30);
b3.setLocation(330,200);
bl3=new ButtonListener3();
b3.addActionListener(bl3);
//Place the components in the pane
c.add(j5);
c.add(j4);
c.add(lblpic);
c.add(j);
c.add(j1);
c.add(t1);
c.add(t2);
c.add(t3);
c.add(b1);
c.add(b2);
c.add(b3);
c.add(j6);
//Changing TextFields to UnEditable
t2.setEditable(false);
t3.setEditable(false);
//Set the title of the window
setTitle("GUESS MY NUMBER");
//Set the size of the window and display it
setSize(550,350);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class ButtonListener implements ActionListener
{
int bestScore=100;
public void actionPerformed(ActionEvent e)
{
int a = Integer.parseInt(t1.getText());
count=count+1;
if(a<rand)
{
j4.setText(a+" is too low, try again!!");
}
else if(a>rand)
{
j4.setText(a+" is too high, try again!!");
}
else
{
j4.setText("CORRECT, YOU WIN!!!!");
if(count<bestScore)
{
bestScore=count;
t2.setText(bestScore+"");
}
else
t2.setText(""+bestScore);
t1.setEditable(false);
}
//setting focus to input guess text field
t1.requestFocus();
t1.selectAll();
t3.setText(count+"");
}
}
private class ButtonListener2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
t3.setText("");
j4.setText(rand+" is the answer!");
t1.setText("");
t1.setEditable(false);
}
}
private class ButtonListener3 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
rand=(int) (Math.random()*100);
t1.setText("");
t3.setText("");
j4.setText("Try and guess my number");
t3.setText("");
count=0;
t1.setEditable(true);
t1.requestFocus();
}
}
public static void main(String[] args)
{
new Guess();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:31:12.160",
"Id": "85760",
"Score": "0",
"body": "Welcome to Code Review! Because links tend to go away over time, please also copy the description from your blog to this post itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:07:20.737",
"Id": "85802",
"Score": "0",
"body": "Seems like someone needs to read about the [EDT](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html). Your code create and mutates Swing components off of the EDT, this is in complete violation of Swings threading policy."
}
] | [
{
"body": "<h3>Naming:</h3>\n<p>You're naming your things terribly:</p>\n<blockquote>\n<pre><code>JTextField t1, t2, t3, t4;\nJLabel j4;\nButtonListener bl1;\nButtonListener2 bl2;\nButtonListener3 bl3;\n</code></pre>\n</blockquote>\n<p>Better would definitely be:</p>\n<pre><code>JTextField guessInput, bestScore, guessText; \n</code></pre>\n<p>You should already be able to see: <code>t4</code> was unused, guessInput (taken from the comments at initialization) and guessText (also take from the comment at init) are somewhat doubled.</p>\n<blockquote>\n<pre><code>ButtonListener, ButtonListener2, ButtonListener3\n</code></pre>\n</blockquote>\n<p>Wait what??? you have 3 different action listeners and call them ButtonListener 1, 2 and 3?<br />\nShame on you. Better names would be:</p>\n<pre><code>GuessSubmittedListener\nSurrenderListener\nNewGameListener\n</code></pre>\n<p>Move this thorough your whole code.</p>\n<h3>Starting the game:</h3>\n<blockquote>\n<pre><code>public static void main(String[] args)\n{\n new Guess();\n}\n</code></pre>\n</blockquote>\n<p>Conventionally you'd have something like the following instead:</p>\n<pre><code>public static void main(String[] args){\n Guess game = new Guess();\n game.start(); // game.run(); game.begin(); game.whatever();\n}\n</code></pre>\n<p>The constructor of game is supposed to initialize it. But it <strong>never</strong> should be responsible for starting the game.</p>\n<h3>Braces:</h3>\n<p>The convention for Java is "egyptian braces". The opening curly brace is on the line with the block expression, the closing brace is separate. You are using the C# conventions...</p>\n<h3>Magic Numbers:</h3>\n<p>Your whole code is littered with magic numbers, numbers that have no explanation whatsoever. Move these numbers to constants:</p>\n<blockquote>\n<pre><code>int rand = (int) (Math.random()*100);\n</code></pre>\n</blockquote>\n<p>Nonononon...</p>\n<pre><code>private static final int RANDOM_BORDER = 101;\n\nRandom rnd = new Random();\nint randNumber = rnd.nextInt(MAX_NUMBER);\n</code></pre>\n<p>Same goes for the whole initialization stuff... There's so many magic numbers there I'm almost having a breakdown right now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:28:12.210",
"Id": "85759",
"Score": "1",
"body": "`(int) (Math.random()*100);` does not do the same as `rnd.nextInt(101);`. The first does not include the possibility for the number 100, the second does. Other than that, +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:06:14.647",
"Id": "85801",
"Score": "0",
"body": "You don't mention that lack of Swing threading. This is the **biggest issue**. The game runs itself on the main thread. This is a **massive bug** waiting to happen. Otherwise +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T12:08:48.143",
"Id": "48858",
"ParentId": "48856",
"Score": "7"
}
},
{
"body": "<h1>Layoutmanagers</h1>\n\n<p>You're using absolute positioning for all your elements which won't scale well when you enlarge or shrink the application. For this reason you should use a layoutmanager that will handle the resizing for you (and it's a lot easier to extend your application with new elements).</p>\n\n<p>For more information I'll refer you to <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html\">the documentation</a>.</p>\n\n<h1>Comments</h1>\n\n<pre><code>//Set the title of the window\nsetTitle(\"GUESS MY NUMBER\"); \n</code></pre>\n\n<p>The comment doesn't tell me anything I don't know yet. Comments should explain <em>why</em> I do something, not <em>what</em> I'm doing.</p>\n\n<h1>Naming</h1>\n\n<p>Your class is named <code>Guess</code>, which isn't very descriptive of what it means. <code>GuessingGame</code> would be a lot better and clarifies that it is a game we're talking about.</p>\n\n<h1>Spacing</h1>\n\n<p>Add a space before and after your binary operators like <code>*</code>, <code>&&</code>, <code>=</code>, etc. Right now the code gives a very compressed feeling.</p>\n\n<h1>Braces</h1>\n\n<p>I see this line of code:</p>\n\n<pre><code>else\n t2.setText(\"\"+bestScore);\nt1.setEditable(false);\n</code></pre>\n\n<p><em>Always</em> use braces so I can distinguish easily between what should be inside that <em>if</em> statement. Right now I can't tell for sure if that is intended or if it is a logical error. It will also prevent you from introducing errors when you add an expression to your <code>else</code> body without thinking about the braces.</p>\n\n<p>If anything, it's also a matter of staying consistent.</p>\n\n<h1>Main</h1>\n\n<p>I prefer to put my <code>main</code> method in a separate class so I always have instant knowledge of where my application starts without having to dig into my separate classes. It's also more comfortable to work with when you have to setup certain things like the \"Look and Feel\" or logging.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T21:06:17.097",
"Id": "85831",
"Score": "0",
"body": "Man, I had to scroll all the way down to find an answer mentioning the absolute positioning. As someone who has to maintain several legacy GUIs with enormous complexity, this is one of *the* most terrible things I have to deal with and I find myself rewriting one class after another to get rid of it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:07:26.070",
"Id": "48862",
"ParentId": "48856",
"Score": "7"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/48858/40788\">Vogel612's answer already covered naming</a>. I'd like to highlight some other things: some because of how Swing works, and some about initialisation.</p>\n\n<h1>Initialisation</h1>\n\n<p>Initialisation and reset take mostly the same actions but are in two different places: <code>ButtonListener3.actionPerformed</code> and <code>Guess.<init></code>. Try taking these actions out and creating methods that clarify their intent:</p>\n\n<pre><code>private static final int MAX_NUMBER = 100;\npublic void start() {\n rand = (int) (Math.random() * MAX_NUMBER) + 1;\n count = 0;\n // set labels here\n}\n\npublic void restart() {\n // any cleanup goes here\n start();\n}\n</code></pre>\n\n<hr>\n\n<h1>Keep it on the EDT</h1>\n\n<p>Swing is a multi-threaded environment, and any manipulation of GUI elements should happen on the Event Dispatch Thread (EDT). For most of an application's lifetime, this is not a direct concern because it primarily runs inside this EDT, but bootstrapping is a special case and requires your intervention.</p>\n\n<pre><code>public static void main(String[] args)\n{\n SwingUtilities.invokeLater(\n new Runnable() {\n public void run() {\n Guess guess = new Guess();\n guess.start();\n }\n }\n };\n}\n</code></pre>\n\n<p>Or, since Java 8:</p>\n\n<pre><code>public static void main(String[] args)\n{\n SwingUtilities.invokeLater(\n () -> {\n Guess guess = new Guess();\n guess.start();\n }\n );\n}\n</code></pre>\n\n<p>Yes, even running a single method or constructor requires this, and you may get away with it most of the time but, as I learned to my shame, not all of the time. ;)</p>\n\n<hr>\n\n<h1>Layout and Resizing</h1>\n\n<p>Not having a layout manager makes it easier to have components right where you want them, but it makes your container ignore resizing. If you've already picked the (only) size you're going to support, you may want to constrain it:</p>\n\n<pre><code>setMinimumSize(getSize());\n</code></pre>\n\n<hr>\n\n<h1>Randoms in Java</h1>\n\n<p><code>Math.random()</code> returns a value \\$\\in [0,1[\\$, so if you want an integer between min and max, inclusive, you'll need to change a bit:</p>\n\n<pre><code>rand = (int) (Math.random() * (max - min + 1)) + min;\n</code></pre>\n\n<p>...which, for 1..100 would make:</p>\n\n<pre><code>rand = (int) (Math.random() * 100) + 1;\n</code></pre>\n\n<p>Because I got 0 on my first run of your game. :p</p>\n\n<hr>\n\n<h1>Seperation of Concerns</h1>\n\n<p>Your GUI and your game are intimately connected. Separation could help you maintain your code and make it more robust to changes.</p>\n\n<p>The guessing part can be extracted into a class of its own, which will also take care of your magic numbers:</p>\n\n<pre><code>class GuessingGame {\n int value;\n int tries;\n int topScore = Integer.MAX_VALUE;\n\n Random random = new Random();\n\n public void reset() {\n tries = 0;\n value = random.nextInt(getMaximum() - getMinimum() + 1) + getMinimum();\n }\n\n public Result guess(int guess) {\n tries++;\n\n if ( guess == value ) {\n if ( topScore > tries ) {\n topScore = tries;\n }\n return Result.EXACT;\n }\n\n return guess < value ? Result.TOO_HIGH : Result.TOO_LOW;\n }\n\n public int getNumberOfTries() {\n return tries;\n }\n\n public int getTopScore() {\n return topScore;\n }\n\n public int getMinimum() { return 1; }\n public int getMaximum() { return 100; }\n}\n\nenum Result {\n TOO_HIGH, TOO_LOW, EXACT;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:16:54.307",
"Id": "48863",
"ParentId": "48856",
"Score": "11"
}
},
{
"body": "<p><code>\"Give up!\"</code> and <code>\"Play again!\"</code> should be the same button. If you've just won the game, it should be <code>\"Play again!\"</code>, and if you tried and failed and want to reset the game, it should be <code>\"Give Up!\"</code>. If you don't want to change the label every time, <code>\"Reset\"</code> will work for both scenarios.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T11:54:14.130",
"Id": "48922",
"ParentId": "48856",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48862",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T11:02:48.720",
"Id": "48856",
"Score": "6",
"Tags": [
"java",
"game",
"swing",
"number-guessing-game"
],
"Title": "\"Guess my number\" game in Java Swing"
} | 48856 |
<p>I have the following method for multiplying two polynomials in GF(2<sup>32</sup>):</p>
<pre><code>#include <iostream>
#include <cassert>
#include <ctime>
#include <random>
#include <wmmintrin.h>
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
unsigned get_high16(unsigned x)
{
return (x >> 16) & 0xffff;
}
unsigned get_low16(unsigned x)
{
return x & 0xffff;
}
uint32_t mul_reduce_32(uint32_t x, uint32_t y)
{
const __m128i a = _mm_set_epi32(0, 0, 0, x);
const __m128i b = _mm_set_epi32(0, 0, 0, y);
const __m128i c =_mm_clmulepi64_si128(a, b, 0);
uint16_t D = _mm_extract_epi16(c, 2);
D ^= _mm_extract_epi32(c, 1) >> 31;
D ^= _mm_extract_epi32(c, 1) >> 30;
D ^= _mm_extract_epi32(c, 1) >> 29;
D ^= _mm_extract_epi32(c, 1) >> 27;
D ^= _mm_extract_epi32(c, 1) >> 25;
const uint16_t X3 = _mm_extract_epi16(c, 3);
const __m128i X3D = _mm_set_epi16(0, 0, 0, 0, 0, 0, X3, D);
const uint32_t E = _mm_extract_epi32(X3D, 0) << 7;
const uint32_t F = _mm_extract_epi32(X3D, 0) << 5;
const uint32_t G = _mm_extract_epi32(X3D, 0) << 3;
const uint32_t I = _mm_extract_epi32(X3D, 0) << 2;
const uint32_t J = _mm_extract_epi32(X3D, 0) << 1;
const uint16_t H1 = X3 ^ get_high16(E) ^ get_high16(F) ^ get_high16(G) ^ get_high16(I) ^ get_high16(J);
const uint16_t H0 = D ^ get_low16(E) ^ get_low16(F) ^ get_low16(G) ^ get_low16(I) ^ get_low16(J);
const uint16_t R1 = _mm_extract_epi16(c, 1) ^ H1;
const uint16_t R0 = _mm_extract_epi16(c, 0) ^ H0;
return _mm_extract_epi32(_mm_set_epi16(0, 0, 0, 0, 0, 0, R1, R0), 0);
}
</code></pre>
<p>The following is a small test program and benchmark for the function.</p>
<pre><code>int main()
{
assert(mul_reduce_32(1, 1) == 1);
assert(mul_reduce_32(23523, 34651) == 744709325);
assert(mul_reduce_32(34652346, 5534651) == 1329462203);
// A little benchmark
std::mt19937 rng(std::time(0));
std::uniform_int_distribution<uint32_t> uint_dist10(0, std::numeric_limits<uint32_t>::max());
const int N = 100000000;
std::vector<uint32_t> vec1(N, 0);
std::cout << "mul_reduce_32\n";
clock_t startTime = clock();
for(int i = 0; i < N; ++i)
{
vec1[i] = mul_reduce_32(rng(), rng());
}
std::cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC << " seconds.\n";
}
</code></pre>
<p>I'm interested in getting more out of <code>mul_reduce_32</code> in terms of performance. Here are my main concerns:</p>
<ol>
<li><p>I'm setting <code>a</code> and <code>b</code> using <code>_mm_set_epi32</code>. Is this even a good idea? I suppose I could have used <code>_mm_load_si128</code> or <code>_mm_loadu_si128</code>, but the problem seems to be that it doesn't touch the 98 higher bits, and makes those high bits garbage.</p></li>
<li><p>Currently, I am using many temporary variables. I could try to help the compiler by removing many of them, but this way the code should be more readable and easier for someone to modify.</p></li>
<li><p>I'm using variables of different size -- is this a good idea? I might remember some old wisdom that says I should always just stick to the "most native" unsigned type. Concretely, should I replace say each <code>uint16_t</code> with <code>uint32_t</code> (or even a 64-bit type)?</p></li>
<li><p>Should I be mixing <code>__m128i</code> types with unsigned types to begin with? As I understand it, the <code>__m128i</code> types are guaranteed to be mapped to a dedicated register, whereas this is not the case for a <code>uint32_t</code>.</p></li>
</ol>
<p>Can you suggest additional optimizations? I'm knowledgeable in C++, but a total newbie with SSE intrinsics.</p>
| [] | [
{
"body": "<p>For the time output in <code>main()</code>:</p>\n\n<ul>\n<li>Use <code>std::clock_t</code> as opposed to <code>clock_t</code> in C++.</li>\n<li>You could have another variable, <code>endTime</code>, for the ending time.</li>\n<li>The computed time could also have its own variable, <code>elapsedTime</code>, to be printed.</li>\n<li>Only the clock time needs to be cast to a <code>double</code>, not the macro as well. You should also use <code>static_cast<>()</code> as this is C++.</li>\n</ul>\n\n<p>Example with changes:</p>\n\n<pre><code>std::clock_t startTime = std::clock();\n\n// ...\n\nstd::clock_t endTime = std::clock();\n\ndouble elapsedTime = static_cast<double>(endTime - startTime) / CLOCKS_PER_SEC;\n\nstd::cout << elapsedTime;\n</code></pre>\n\n<p>But, since you're using C++11, consider utilizing the <a href=\"http://en.cppreference.com/w/cpp/chrono\" rel=\"nofollow noreferrer\"><code><chrono></code></a> library instead. Unlike <code><ctime></code>, it is more C++-oriented but still contains some <code><ctime></code> aspects.</p>\n\n<p><strong>Side-notes:</strong></p>\n\n<ul>\n<li>For <code>std::time</code>, <code>0</code> can be replaced with <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a> in C++11.</li>\n<li>Consider renaming <code>N</code> to something more descriptive. Using a constant in place of a magic number is nice, but you can increase readability by using a better name.</li>\n<li>Since only your test program uses those first four libraries, they should just be in that file.</li>\n<li>You don't need those <code>typedef</code>s in your first file; they are already defined in <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\"><code><cstdint></code></a>.</li>\n</ul>\n\n<p><strong>Specific questions:</strong></p>\n\n<blockquote>\n <p>Currently, I am using many temporary variables. I could try to help the compiler by removing many of them, but this way the code should be more readable and easier for someone to modify.</p>\n</blockquote>\n\n<p>I would rely on the compiler to handle this, as it should be able to optimize them out. But you're right; readability and maintainability are also important. They can always be adjusted accordingly.</p>\n\n<p>You can also maintain these two things by:</p>\n\n<ol>\n<li>avoiding single-character variable names</li>\n<li>keeping variables as close in scope as possible</li>\n</ol>\n\n<p>You seem to do well with the second point, but not so much the first. I've already addressed this in the side-notes, but this is a problem throughout the first file. By using more descriptive names, it'll be much easier for others to understand your code and make any needed modifications.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T10:31:48.657",
"Id": "85882",
"Score": "0",
"body": "Thanks! This is useful, but doesn't really address my main issue of performance with respect to the SSE intrinsics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T18:05:29.093",
"Id": "85909",
"Score": "0",
"body": "@Gideon: I know. On Code Review, users are allowed to review any aspect of the code, even if it's not requested by the OP. Others can still come along and review other aspects, including performance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T21:42:09.203",
"Id": "48888",
"ParentId": "48857",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T11:52:26.893",
"Id": "48857",
"Score": "8",
"Tags": [
"c++",
"performance",
"c++11",
"bitwise",
"sse"
],
"Title": "Optimizing multiplication of two polynomials in GF(2^32)"
} | 48857 |
<p>I am currently developing a game for Android. One of the things I am working on is moving the map by touch.</p>
<p>This is the code that handles getting speed, which is then added to the screens position and the next update draws the corresponding portion of the map.</p>
<pre><code>@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (released) {
touchX = event.getX();
touchY = event.getY();
released = false;
}
else {
float newX = event.getX();
float newY = event.getY();
speedX = (int) (newX - touchX);
speedY = (int) (newY - touchY);
touchX = newX;
touchY = newY;
}
return true;
case MotionEvent.ACTION_UP:
released = true;
return true;
}
return false;
}
</code></pre>
<p>It works fine, it does. But it seems like it is not enough of a fluid movement.</p>
<p>Does anyone have any idea of how I can make it more like a seamless motion?</p>
<p>EDIT:</p>
<p>And just for info, my fps is currently 80. So I do not believe it is caused by the bitmap drawing itself.</p>
| [] | [
{
"body": "<p>My experience with Android and handling touch events is that it's very hard to look at the code and understand how it will work when you're running the application. It can even be a difference with different Android devices, so make sure that you test your app on an Android 2.3.5 device as well as an Android 4+ device (assuming you're targeting Android 2.3.5 as well).</p>\n\n<p>From what I understand, \"moving the map by touch\" you mean that you are scrolling through the map, like a <code>HorizontalScrollView</code> combined with an ordinary (vertical) <code>ScrollView</code>. It is said to be possible to combine these two together to create a \"two dimensional scroll view\", I myself have not been able to accomplish that in a way that creates a smooth user experience (I actually think this is a bad way of doing it). I have however, managed to find a quite easy-to-use Android view class that takes care of all this scrolling. It seems however like the link has disappeared but you could try <a href=\"https://github.com/ened/Android-Tiling-ScrollView\" rel=\"nofollow\">this GitHub project</a>, if that doesn't work for you then let me know either by a comment or find me in <a href=\"http://chat.stackexchange.com/rooms/8595/the-2nd-monitor\">The 2nd Monitor</a> chatroom and I can provide the implementation I'm using.</p>\n\n<p>As for your existing code, it's clean, it's straight-forward. But where/how is <code>speedX</code>/<code>speedY</code> and <code>touchX</code>/<code>touchY</code> used? Could the problem be there?</p>\n\n<p>I only have one suggestion for improvement of your code:</p>\n\n<pre><code>switch(event.getAction()) {\n</code></pre>\n\n<p>Should be (<a href=\"http://developer.android.com/reference/android/view/MotionEvent.html#getAction%28%29\" rel=\"nofollow\">see here</a>)</p>\n\n<pre><code>switch(event.getActionMasked()) {\n</code></pre>\n\n<p>A general suggestion when working with touch events:</p>\n\n<p><strong>Log, Log, and Log</strong> Use <code>Log.d(\"YOUR_TAG\", \"A whole bunch of information\")</code> like a maniac! The more you log, the more you will hopefully be able to understand about MotionEvents, and the better code you will be able to write.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T14:56:48.377",
"Id": "85900",
"Score": "0",
"body": "I forgot to mention that I am using a SurfaceView.\nThank you.\nAnd I removed the Log lines from the code to make it more clear and a shorter read.\ntouchX/Y and newX/Y are used only for speedX/Y calculation. The speed is then added to the screenX/Y at the next update() call (update is called by a thread). screenX/Y gives information about which part of the map is to be drawn to the bitmap."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T15:07:33.057",
"Id": "85901",
"Score": "0",
"body": "@Simon I did the best I could with what you provided. The code you posted didn't include any scrolling so it's hard to tell what's causing the lack of fluid movement for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:45:38.273",
"Id": "48877",
"ParentId": "48860",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T13:17:49.183",
"Id": "48860",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Tile map movement by touch"
} | 48860 |
<p>I have to say without sounding arrogant, because I am only a novice coder, yet after looking at other's solutions, my solution is definitely not the shortest and most lightweight one and probably not even close to one of the most optimized ones. But! I think I have made a very readable solution and I think that it is true to the OOP paradigm.</p>
<p>Anyhow with that in mind everything can always be improved, I look forward to your feedback.</p>
<blockquote>
<p>Problem 11</p>
<p>Largest product in a grid</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><strong>Program</strong></p>
<pre><code>static void Main(string[] args)
{
var grid = new Grid (20, 20, // This is the size of the grid <-
08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08,
49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00,
81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65,
52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91,
22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80,
24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50,
32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70,
67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21,
24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72,
21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95,
78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92,
16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57,
86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58,
19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40,
04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66,
88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69,
04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36,
20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16,
20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54,
01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48);
var greatestProducts = new HashSet<int>();
// Okay let's loop through all numbers in the grid and find the one with the greatest product
foreach (Cell<int> cell in grid)
{
int[] sums = new int[8];
for (int i = 0; i < 8; i++)
{
var neighbours = grid.GetNeighbours(cell, (Direction)i, 4);
if(neighbours.Count > 0 )
{
sums[i] = neighbours.Aggregate((a, b) => a * b);
}
}
greatestProducts.Add(sums.Max());
}
Console.WriteLine(greatestProducts.Max());
Console.ReadKey();
}
</code></pre>
<p><strong>Position</strong></p>
<pre><code>struct Position
{
public readonly int Row;
public readonly int Column;
public Position(int row, int column)
{
Row = row;
Column = column;
}
}
</code></pre>
<p><strong>Cell</strong></p>
<pre><code>class Cell<T>
{
public readonly T Value;
public readonly Position Position;
public Cell(Position position, T value)
{
Value = value;
Position = position;
}
}
</code></pre>
<p><strong>Grid</strong></p>
<pre><code>enum Direction
{
Left, Right, Up, Down,
DiagonalUpperLeft, DiagonalLowerLeft,
DiagonalUpperRight, DiagonalLowerRight
}
class Grid
{
private Cell<int>[,] cells;
public Cell<int> this[int row, int column]
{
get { return cells[row, column]; }
}
public Grid(int sizeY, int sizeX, params int[] numbers)
{
cells = new Cell<int>[sizeY, sizeX];
int m = 0;
for (int i = 0; i < cells.GetLength(0); i++)
{
for (int j = 0; j < cells.GetLength(1); j++)
{
cells[i, j] = new Cell<int>(new Position(i, j), numbers[m++]);
}
}
}
public System.Collections.IEnumerator GetEnumerator()
{
return cells.GetEnumerator();
}
public List<int> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
return GetNeighbours(cell, direction, neighboursToGet, new List<int>());
}
public List<int> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet, List<int> neighbours)
{
if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell<int> neighbour;
switch (direction)
{
case Direction.Left:
x = cell.Position.Column - 1;
break;
case Direction.Right:
x = cell.Position.Column + 1;
break;
case Direction.Up:
y = cell.Position.Row - 1;
break;
case Direction.Down:
y = cell.Position.Row + 1;
break;
case Direction.DiagonalLowerLeft:
y = cell.Position.Row + 1;
x = cell.Position.Column - 1;
break;
case Direction.DiagonalUpperLeft:
y = cell.Position.Row - 1;
x = cell.Position.Column - 1;
break;
case Direction.DiagonalLowerRight:
y = cell.Position.Row + 1;
x = cell.Position.Column + 1;
break;
case Direction.DiagonalUpperRight:
y = cell.Position.Row - 1;
x = cell.Position.Column + 1;
break;
}
//Check so there are more cells to get
if (x < cells.GetLowerBound(0) || x > cells.GetUpperBound(0) || y < cells.GetLowerBound(0) || y > cells.GetUpperBound(0))
{
return neighbours;
}
neighbour = cells[y, x];
neighbours.Add(neighbour.Value);
GetNeighbours(neighbour, direction, neighboursToGet - 1, neighbours);
}
return neighbours;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cells.GetLength(0); i++)
{
for (int j = 0; j < cells.GetLength(1); j++)
{
if (cells[j, i].Value < 10)
{
sb.Append("0" + cells[j, i].Value + " ");
}
else
{
sb.Append(cells[j, i].Value + " ");
}
}
sb.AppendLine(); // Line break here
}
return sb.ToString();
}
}
}
</code></pre>
<p>Some final remarks,</p>
<ol>
<li>In the <code>Grid</code> constructor I know that I should've opted for accepting a int array instead of params int[] by the time I realized that it would have been smarter it was too late however, and changing it would've meant that I would've had to re-format the whole constructor call (indentations, line breaks and such).</li>
<li>There is no need for the <code>Cell</code> class to be generic in this application, but my rationale behind it was, I re-use code like many others do, I might need to use a <code>Grid</code> class in another application and in that case it's better to have <code>Cell</code> as a generic class since I can't know what I will store in the cells.</li>
</ol>
| [] | [
{
"body": "<p>You've built quite the object-oriented structure for this quite procedural assignment. Two of your classes are simple structures, which, I argue, are not even needed:</p>\n\n<p><code>Cell</code> contains a <code>Value</code> and a <code>Position</code>, but nowhere are both needed - all the outer loop cares about is the position, which it can simply iterate over (from <code>[0,0]</code> to <code>[sizeY, sizeX]</code>) without caring about <code>Cell</code> at all. Given position (<code>x</code> and <code>y</code>), the <code>Grid</code> class doesn't need the <code>Cell</code> object, since it knows where it is, and can simply get the value, so you might as well hold within your grid a two-dimensional array of <em>values</em> rather than <em>cells</em>.</p>\n\n<p>You chose to implement <code>GetNeighbours</code> as a recursion, which is a curious choice. Why not simply iterate 4 steps in the required direction?</p>\n\n<p>Some other minor ticks: </p>\n\n<ol>\n<li>If you do decide to make it a recursion, the overload of the <code>GetNeighbours</code> method with the internal <code>List<int></code> should be <code>private</code>.</li>\n<li><code>GetNeighbours</code> does not actually get neighbours, it gets neighbours' <em>values</em>, and should be named <code>GetNeighbourValues</code>.</li>\n<li><p>Don't iterate over <code>Direction</code> values using <code>int</code> - iterate over the values:</p>\n\n<pre><code>var directions = Enum.GetValues(typeof(Direction));\n\nforeach (Direction direction in directions)\n{\n // ...\n</code></pre></li>\n<li>You need only half the directions - since you'll get the same results for <code>Left</code> and <code>Right</code>, <code>Up</code> and <code>Down</code>, etc.</li>\n</ol>\n\n<p>I would suggest a simple, procedural solution:</p>\n\n<pre><code>public static void Main(string[] args) {\n var grid = new int[20,20] { ... };\n Console.WriteLine(MaxProduct(grid));\n}\n\npublic int MaxProduct(int[,] grid) {\n var products = new HashSet<int>();\n var directions = Enum.GetValues(typeof(Direction));\n\n for (int y = 0; y < grid.getLength(0); y++) {\n for (int x = 0; x < grid.getLength(1); x++) {\n foreach (Direction direction in directions) {\n products.Add(GetProductFor(grid, x, y, direction, 4))\n }\n }\n }\n return products.Max();\n}\n\nprivate directionMap = new Dictionary<Direction, int[]>()\n{\n {Right, {0, 1}},\n {Down, {1, 0}},\n {DiagonalUpperLeft, {-1, -1}},\n {DiagonalLowerLeft, {1, -1}}\n};\n\npublic int GetProductFor(int[,] grid, int x, int y, Direction direction, int length) {\n int result = 1;\n for (int i = 0; i < length; i++) {\n result *= grid[y + directionMap[direction][0]*length]\n [x + directionMap[direction][1]*length];\n }\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T16:17:01.970",
"Id": "48871",
"ParentId": "48861",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:01:31.037",
"Id": "48861",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"programming-challenge"
],
"Title": "Project Euler 11 - Largest Product in a grid"
} | 48861 |
<p>I'm making a script that generates imgur.com URLs which contain only <code>.png</code> images bigger than 256 bytes, but smaller than 1200 bytes.</p>
<p>Problem: the script is as slow as a snail, any more than one image and it takes more than ten seconds.</p>
<p>What can I do to improve it, like code-wise? I want to make it faster also.</p>
<pre><code>$GLOBALS[0] = array(); //store valid getimagesize ARRAY
$GLOBALS[1] = array(); //store invalid links ARRAY STRING
$GLOBALS[2] = 0; //store attempts INTEGER
function guess()
{
$possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$result = array();
for ($i=0; $i<=4; $i++)
{
$num = round(mt_rand(0,99999)%strlen($possible));
$word = $word . substr($possible,$num,1);
}
$url = "http://i.imgur.com/".$word.".png";
$result = getimagesize($url);
if($result['mime'] AND $result['mime'] == "image/png" AND $result[0]>256 AND $result[1]>256 AND $result[0]<1200 AND $result[1]<1200)
{
//echo($result['mime']. "<br>");
$result['url'] = $url;
array_push($GLOBALS[0],$result);
echo("Result " . count($GLOBALS[0]) . ": ".$GLOBALS[0][count($GLOBALS[0])-1]['url'] . "<br>");
}
else
{
array_push($GLOBALS[1],$url);
//echo("Invalid image, OR image is not png, OR image too small, OR image too large <br>");
}
return($result['mime']);
}
function attempt()
{
$GLOBALS[2]++;
$bord = guess();
if($bord!=='image/png')
{
attempt();
}
}
function getlinks($num)
{
echo("Fetching ".$num." images...<br>");
attempt();
if($num>($GLOBALS[2] - count($GLOBALS[1])))
{
echo("Attempt failed, trying again...<br>");
$amount = $num;
getlinks($amount);
}
else
{
echo("Done. ". $GLOBALS[2] . " attempts, of which ". count($GLOBALS[1]) . " are failures.<br>");
}
}
getlinks(1);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:12:14.683",
"Id": "85817",
"Score": "0",
"body": "Consider using their api http://api.imgur.com/endpoints/image"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T10:36:57.367",
"Id": "85883",
"Score": "0",
"body": "I still have to get the ID manually by guessing it, so I don't think that would improve performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T15:28:10.120",
"Id": "85902",
"Score": "0",
"body": "Alright, I figured cause you mentioned 1 picture/10 secs that you were getting rate-limited. You might want to profile your code and see where its slow. I don't know php so can't help ya there much"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-30T23:07:12.600",
"Id": "173936",
"Score": "0",
"body": "**WARNING**: Imgur hosts NSFW content, so keep that in mind when opening the results of this script."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:34:59.633",
"Id": "48864",
"Score": "1",
"Tags": [
"php",
"performance",
"image"
],
"Title": "Imgur .png image-fetcher"
} | 48864 |
<p>Usually when I make mock-up programs (like this one), I look for things I can improve on in case the situation happens again. </p>
<p>Today I thought I'd brush up on basic OOP (I understand the concept of OOP, just haven't messed around with it for a bit and wanted to freshen my memory). So I decided to make a little game that just creates 3 monsters on a 10x10 plane and 1 player (you), you are able to move your player in any x/y direction. My program works but I can't help but feel that I'm doing something incorrectly.</p>
<p>So the basic layout of my program was to have 5 classes. A GUI class that shows the game and gives you directional buttons for movement control, a class that creates the monsters, a class that creates the players, a class that creates the 10x10 board and keeps track of monster/player locations, and of course a main class that creates all the objects and has the main game loop and whatnot.</p>
<p>I was having a bit of a hard time interacting with my main class and my GUI class. What I ended up doing was doing a while loop in my main class and waiting until the player presses the start button, and once the player presses it (via action listener) the GUI class sets a public variable (running) from false to true, and I am able to act accordingly once the variable is changed. </p>
<p>HERE is where I feel like I am doing something wrong: At first my while loop would not terminate unless I printed out to the console. I Googled the issue and apparently people have said that it's some sort of issue with threading or "active polling", which I did not understand. I went to my program and added a small 10ms thread sleep in my while loops and everything started working great.</p>
<p><strong>My question to you guys is, why do my while loops only terminate when adding a thread sleep? And is there a better way of interacting with a GUI class and a main class?</strong></p>
<p>Sorry for the giant wall of text but I like to be thorough when explaining a situation!</p>
<p><strong>TL;DR: Am I interacting correctly with my GUI class and my main class? If not what is the proper way to do it?</strong></p>
<p><strong>My main class:</strong></p>
<pre><code>public class MainGame {
public static void main(String[] args) throws InterruptedException{
ShowGUI gui = new ShowGUI();
while(!gui.running){
Thread.sleep(10);
}
Board gameBoard = new Board();
gui.setLabelText(gameBoard.getBoard());
//Add Player
Player playerOne = new Player(1000, "Player 1");
//Add monsters
Monster monstMatt = new Monster(1000, "Matt");
Monster monstJon = new Monster(1000, "Jon");
Monster monstAbaad = new Monster(1000, "Abaad");
while(gui.running){
Thread.sleep(10);
int x, y;
x = playerOne.getX();
y = playerOne.getY();
if(gui.buttonPress != -1){
if(gui.buttonPress == 1){
playerOne.move(x, --y);
}else if(gui.buttonPress == 2){
playerOne.move(x, ++y);
}else if(gui.buttonPress == 3){
playerOne.move(--x, y);
}else if(gui.buttonPress == 4){
playerOne.move(++x, y);
}
gui.buttonPress = -1;
gui.setLabelText(gameBoard.getBoard());
}
}
}
}
</code></pre>
<p><strong>My GUI Class:</strong></p>
<pre><code>public class ShowGUI {
private JTextArea board;
private JButton moveUp;
private JButton moveDown;
private JButton moveLeft;
private JButton moveRight;
public boolean running = false;
public int buttonPress = -1;
public ShowGUI(){
System.out.println("GUI Successfully Loaded");
createAndShow();
}
private void createAndShow(){
JFrame mainFrame = new JFrame("Bad Game");
addComponents(mainFrame.getContentPane());
mainFrame.setSize(500, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
private void addComponents(Container pane){
pane.setLayout(null);
board = new JTextArea(1, JLabel.CENTER);
moveUp = new JButton("Up");
moveDown = new JButton("Down");
moveLeft = new JButton("Left");
moveRight = new JButton("Right");
moveUp.setBounds(185, 225, 130, 35);
moveLeft.setBounds(115, 280, 130, 35);
moveRight.setBounds(255, 280, 130, 35);
moveDown.setBounds(185, 335, 130, 35);
board.setEditable(false);
board.setBounds(115, 30, 270, 145);
board.setFont(new Font("Consolas", Font.BOLD, 12));
addActionListeners();
pane.add(board);
pane.add(moveUp);
pane.add(moveRight);
pane.add(moveLeft);
pane.add(moveDown);
}
private void addActionListeners(){
moveUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
running = true;
buttonPress = 1;
}
});
moveDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPress = 2;
}
});
moveLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPress = 3;
}
});
moveRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPress = 4;
}
});
}
public void setLabelText(char[][] boardToShow){
board.setText(" ");
for(int i = 0; i < boardToShow.length; i++){
for(int j = 0; j < boardToShow[i].length; j++){
board.append(boardToShow[i][j] + " ");
}
board.append("\n ");
}
}
}
</code></pre>
<p>If you require my Board/Monster/Player classes I can post them, but I don't think the problem is with those classes.</p>
| [] | [
{
"body": "<p>I have very little experience with Swing, so forgive me if I cannot answer your specific question (though Stack Overflow might be a better place for that). Still, one thing I always see with Swing programs is the use of <code>SwingUtilities.invokeLater</code>, so maybe that's why you're having troubles. <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java\" rel=\"nofollow\">Take a look at how this example starts a Swing project</a>.</p>\n\n<p>I'm sure more experienced people can comment on your overall design and the MVC pattern than I could, so I'll limit myself to a line-by-line review here.</p>\n\n<p><strong>The <code>main</code> method</strong></p>\n\n<p>You are doing far too much here. With a few exceptions, the <code>main</code> method should just get your class up and going. I would like to see something like a <code>Game</code> class which takes the board, players (as a list), and monsters (as a list) in its constructor. Maybe the GUI too, I'm not sure. Like I said, I'm terrible at MVC practices.</p>\n\n<p>The <code>while</code> loop in the <code>main</code> method should also be moved into this Game glass, which controls the main game loop. There's a lot of things you can find on Google about main game loops that are worth reading.</p>\n\n<pre><code> int x, y;\n x = playerOne.getX();\n y = playerOne.getY();\n</code></pre>\n\n<p>can be simplified to </p>\n\n<pre><code> int x = playerOne.getX();\n int y = playerOne.getY();\n</code></pre>\n\n<p>Alternatively, the whole input section could be simplified to</p>\n\n<pre><code>while(gui.running){\n if (gui.buttonPress == -1)\n continue;\n }\n\n if (gui.buttonPress == 1) {\n playerOne.move(playerOne.getX(), playerOne.getY() - 1);\n } else if (gui.buttonPress == 2) {\n playerOne.move(playerOne.getX(), playerOne.getY() + 1);\n } else if (gui.buttonPress == 3) {\n playerOne.move(playerOne.getX() - 1, playerOne.getY());\n } else if (gui.buttonPress == 4) {\n playerOne.move(playerOne.getX() + 1, playerOne.getY());\n }\n\n ...\n</code></pre>\n\n<p>(Actually, not really, because you have some additional lines after all this input stuff, but why are you mixing the input logic with anything else? Put it in its own method.)</p>\n\n<p>There's a lot that can be said about this, so I'll just list them in no particular order:</p>\n\n<ul>\n<li><p>Add spaces in your control statements! Everyone's eyes will thank you! Compare</p>\n\n<pre><code>if(gui.buttonPress == 1){\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (gui.buttonPress == 1) {\n</code></pre></li>\n<li><p>There's no point in storing the player's coordinates in these less descriptive variables. They're only going to be accessed once because of the <code>if</code> statement structure.</p></li>\n<li><p>As a tip, this is my enum that I use for handling direction in my programs:</p>\n\n<pre><code>public enum Direction {\n LEFT(-1, 0), RIGHT(1, 0), UP(0, 1), DOWN(0, -1);\n\n private final int x;\n\n private final int y;\n\n Direction(final int x, final int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n}\n</code></pre>\n\n<p>With this, you could create a map of your button input values to directions, and simply do the following:</p>\n\n<pre><code>Direction direction = DIRECTION_MAP.get(gui.buttonPress); // your new direction map\nif (direction != null) {\n playerOne.move(playerOne.getX() + direction.getX(), playerOne.getY() + direction.getY();\n}\n</code></pre></li>\n</ul>\n\n<p>The most egregious part so far, though, is your abuse of magic numbers. What does it mean when <code>buttonPress</code> = 1? Also, why can I even access that variable in the first place?! For more on that, we go to</p>\n\n<p><strong>The <code>ShowGUI</code> class</strong></p>\n\n<p>Purely a stylistic criticism, but I think it <code>ShowGui</code> would be more conventional, even though that that's still a bad class names. This class is named like a method (with a leading verb) which is odd. Why not just <code>Gui</code> or something? Make the class name sound like a noun, not a verb.</p>\n\n<p>Some other comments:</p>\n\n<ul>\n<li><p><code>running</code> and <code>buttonPress</code> variables should be private with public <code>get</code> methods. In fact, <code>buttonPress</code> shouldn't have one at all. Rather, some controller class should be invoked when this changes (or not, like I said, terrible with MVC). The point is, your game logic shouldn't be asking the view about things; rather, the view should be telling your game logic what happened.</p></li>\n<li><p>There's magic numbers everywhere, which can understand when making a Swing app, though you could look into frame layouts (or whatever they're called) to do positioning for you. As it is, you just have</p>\n\n<pre><code>pane.setLayout(null);\n</code></pre>\n\n<p>which is a useless call and which I assume was added by a Swing builder.</p></li>\n<li><p>Constants are your friend.</p>\n\n<pre><code>moveUp.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n running = true;\n buttonPress = 1;\n }\n});\n</code></pre>\n\n<p>Why are you modifying <code>running</code> here? And more importantly, why are you setting <code>buttonPress</code> to an integer? Two Alternatives:</p>\n\n<pre><code>private static final int MOVE_UP = 1;\n// later...\nbuttonPress = MOVE_UP;\n</code></pre>\n\n<p>or, using the <code>Direction</code> enum above,</p>\n\n<pre><code>buttonPress = Direction.UP;\n</code></pre>\n\n<p>though that only would work if <code>buttonPress</code> only stored directions.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T16:03:16.747",
"Id": "86021",
"Score": "0",
"body": "Thank you for the answer. While I was waiting I rewrote my program with an actual MVC layout. I've also implemented the enum you suggested. I don't know why I didn't think of that earlier. This has explained some things I was confused about however I realize now I should have organized my code a bit better before posting it. It just got all really hectic because I was trying to make it work before making it look pretty. Guess I need to work on doing both at the same time! Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T01:33:34.363",
"Id": "48949",
"ParentId": "48868",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48949",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T15:11:23.153",
"Id": "48868",
"Score": "7",
"Tags": [
"java",
"object-oriented",
"game",
"swing"
],
"Title": "Interacting with GUI class and Main class"
} | 48868 |
<p>I decided to roll out my own EventBus system which is intended to be thread-safe.</p>
<p>Hence a review should focus extra on thread safety apart from all regular concerns.</p>
<p>The <code>EventBus</code> can work in two ways:</p>
<ul>
<li>You can register events and listeners directly on the <code>EventBus</code>.</li>
<li>You can the methods, of a specific object, that are single argument void-methods annotated with <code>@Event</code>.</li>
</ul>
<p>First the code, then the unit tests below:</p>
<pre><code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Event { }
</code></pre>
<hr>
<pre><code>public interface EventBus {
void registerListenersOfObject(final Object callbackObject);
<T> void registerListener(final Class<T> eventClass, final Consumer<? extends T> eventListener);
void executeEvent(final Object event);
void removeListenersOfObject(final Object callbackObject);
<T> void removeListener(final Class<T> eventClass, final Consumer<? extends T> eventListener);
void removeAllListenersOfEvent(final Class<?> eventClass);
void removeAllListeners();
}
</code></pre>
<hr>
<pre><code>public class SimpleEventBus implements EventBus {
private final static Set<EventHandler> EMPTY_SET = new HashSet<>();
private final ConcurrentMap<Class<?>, Set<EventHandler>> eventMapping = new ConcurrentHashMap<>();
private final Class<?> classConstraint;
public SimpleEventBus() {
this(Object.class);
}
public SimpleEventBus(final Class<?> eventClassConstraint) {
this.classConstraint = Objects.requireNonNull(eventClassConstraint);
}
@Override
public void registerListenersOfObject(final Object callbackObject) {
Arrays.stream(callbackObject.getClass().getMethods())
.filter(method -> (method.getAnnotation(Event.class) != null))
.filter(method -> method.getReturnType().equals(void.class))
.filter(method -> method.getParameterCount() == 1)
.forEach(method -> {
Class<?> clazz = method.getParameterTypes()[0];
if (!classConstraint.isAssignableFrom(clazz)) {
return;
}
synchronized (eventMapping) {
eventMapping.putIfAbsent(clazz, new HashSet<>());
eventMapping.get(clazz).add(new MethodEventHandler(method, callbackObject, clazz));
}
});
}
@Override
@SuppressWarnings("unchecked")
public <T> void registerListener(final Class<T> eventClass, final Consumer<? extends T> eventListener) {
Objects.requireNonNull(eventClass);
Objects.requireNonNull(eventListener);
if (!classConstraint.isAssignableFrom(eventClass)) {
return;
}
synchronized(eventMapping) {
eventMapping.putIfAbsent(eventClass, new HashSet<>());
eventMapping.get(eventClass).add(new ConsumerEventHandler((Consumer<Object>)eventListener));
}
}
@Override
public void executeEvent(final Object event) {
if (classConstraint.isAssignableFrom(event.getClass())) {
eventMapping.getOrDefault(event.getClass(), EMPTY_SET).forEach(eventHandler -> eventHandler.invoke(event));
}
}
@Override
public void removeListenersOfObject(final Object callbackObject) {
Arrays.stream(callbackObject.getClass().getMethods())
.filter(method -> (method.getAnnotation(Event.class) != null))
.filter(method -> method.getReturnType().equals(void.class))
.filter(method -> method.getParameterCount() == 1)
.forEach(method -> {
Class<?> clazz = method.getParameterTypes()[0];
if (classConstraint.isAssignableFrom(clazz)) {
eventMapping.getOrDefault(clazz, EMPTY_SET).remove(new MethodEventHandler(method, callbackObject, clazz));
}
});
}
@Override
@SuppressWarnings("unchecked")
public <T> void removeListener(final Class<T> eventClass, final Consumer<? extends T> eventListener) {
Objects.requireNonNull(eventClass);
Objects.requireNonNull(eventListener);
if (classConstraint.isAssignableFrom(eventClass)) {
eventMapping.getOrDefault(eventClass, EMPTY_SET).remove(new ConsumerEventHandler((Consumer<Object>)eventListener));
}
}
@Override
public void removeAllListenersOfEvent(final Class<?> eventClass) {
Objects.requireNonNull(eventClass);
eventMapping.remove(eventClass);
}
@Override
public void removeAllListeners() {
eventMapping.clear();
}
private static interface EventHandler {
void invoke(final Object event);
}
private static class MethodEventHandler implements EventHandler {
private final Method method;
private final Object callbackObject;
private final Class<?> eventClass;
public MethodEventHandler(final Method method, final Object object, final Class<?> eventClass) {
this.method = Objects.requireNonNull(method);
this.callbackObject = Objects.requireNonNull(object);
this.eventClass = Objects.requireNonNull(eventClass);
}
@Override
public void invoke(final Object event) {
try {
method.setAccessible(true);
method.invoke(callbackObject, Objects.requireNonNull(event));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.method);
hash = 71 * hash + Objects.hashCode(this.callbackObject);
hash = 71 * hash + Objects.hashCode(this.eventClass);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MethodEventHandler other = (MethodEventHandler)obj;
if (!Objects.equals(this.method, other.method)) {
return false;
}
if (!Objects.equals(this.callbackObject, other.callbackObject)) {
return false;
}
if (!Objects.equals(this.eventClass, other.eventClass)) {
return false;
}
return true;
}
}
private static class ConsumerEventHandler implements EventHandler {
private final Consumer<Object> eventListener;
public ConsumerEventHandler(final Consumer<Object> consumer) {
this.eventListener = Objects.requireNonNull(consumer);
}
@Override
public void invoke(final Object event) {
eventListener.accept(Objects.requireNonNull(event));
}
@Override
public int hashCode() {
int hash = 5;
hash = 19 * hash + Objects.hashCode(this.eventListener);
return hash;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ConsumerEventHandler other = (ConsumerEventHandler)obj;
if (!Objects.equals(this.eventListener, other.eventListener)) {
return false;
}
return true;
}
}
}
</code></pre>
<hr>
<pre><code>public class SimpleEventBusTest {
static {
assertTrue(true);
}
private AtomicInteger alphaCounter;
private AtomicInteger betaCounter;
private AtomicInteger gammaCounter;
@Before
public void before() {
alphaCounter = new AtomicInteger(0);
betaCounter = new AtomicInteger(0);
gammaCounter = new AtomicInteger(0);
}
private Stream<AtomicInteger> counters() {
return Stream.of(alphaCounter, betaCounter, gammaCounter);
}
@Test
public void testConstructor() {
EventBus eventBus = new SimpleEventBus();
eventBus.registerListenersOfObject(new Object() {
@Event
public void onAlphaEvent(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
});
eventBus.executeEvent(new AlphaEvent());
assertEquals(1, alphaCounter.get());
}
@Test
public void testConstructorWithEventClassConstraint() {
EventBus eventBus = new SimpleEventBus(BetaEvent.class);
eventBus.registerListenersOfObject(new Object() {
@Event
public void onAlphaEvent(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
});
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.executeEvent(new AlphaEvent());
assertEquals(0, alphaCounter.get());
}
@Test
public void testRegisterListenersOfObject() {
EventBus eventBus = new SimpleEventBus();
eventBus.registerListenersOfObject(new Object() {
@Event
public void onAlphaEvent1(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
@Event
public void onAlphaEvent2(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
@Event
public void onAlphaEvent3(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
@Event
public void onBetaEvent1(final BetaEvent betaEvent) {
betaCounter.incrementAndGet();
}
@Event
public void onBetaEvent2(final BetaEvent betaEvent) {
betaCounter.incrementAndGet();
}
@Event
public void onGammaEvent(final GammaEvent gammaEvent) {
gammaCounter.incrementAndGet();
}
});
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(6, alphaCounter.get());
assertEquals(4, betaCounter.get());
assertEquals(2, gammaCounter.get());
}
@Test
public void testRegisterListener() {
EventBus eventBus = new SimpleEventBus();
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(BetaEvent.class, betaEvent -> betaCounter.incrementAndGet());
eventBus.registerListener(BetaEvent.class, betaEvent -> betaCounter.incrementAndGet());
eventBus.registerListener(GammaEvent.class, gammaEvent -> gammaCounter.incrementAndGet());
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(6, alphaCounter.get());
assertEquals(4, betaCounter.get());
assertEquals(2, gammaCounter.get());
}
@Test
public void testExecuteEvent() {
EventBus eventBus = new SimpleEventBus();
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.executeEvent(new AlphaEvent());
assertEquals(1, alphaCounter.get());
}
@Test
public void testExecuteEventSameInstance() {
AlphaEvent specificAlphaEvent = new AlphaEvent();
EventBus eventBus = new SimpleEventBus();
eventBus.registerListener(AlphaEvent.class, alphaEvent -> assertTrue(alphaEvent == specificAlphaEvent));
}
@Test
public void testRemoveListenersOfObject() {
EventBus eventBus = new SimpleEventBus();
Object object1 = new Object() {
@Event
public void onAlphaEvent(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
@Event
public void onBetaEvent(final BetaEvent betaEvent) {
betaCounter.incrementAndGet();
}
@Event
public void onGammaEvent(final GammaEvent gammaEvent) {
gammaCounter.incrementAndGet();
}
};
Object object2 = new Object() {
@Event
public void onAlphaEvent(final AlphaEvent alphaEvent) {
alphaCounter.incrementAndGet();
}
@Event
public void onBetaEvent(final BetaEvent betaEvent) {
betaCounter.incrementAndGet();
}
@Event
public void onGammaEvent(final GammaEvent gammaEvent) {
gammaCounter.incrementAndGet();
}
};
eventBus.registerListenersOfObject(object1);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
counters().allMatch(counter -> counter.get() == 1);
eventBus.registerListenersOfObject(object2);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
counters().allMatch(counter -> counter.get() == 3);
eventBus.removeListenersOfObject(object2);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
counters().allMatch(counter -> counter.get() == 4);
eventBus.removeListenersOfObject(object1);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
counters().allMatch(counter -> counter.get() == 4);
}
@Test
public void testRemoveListener() {
EventBus eventBus = new SimpleEventBus();
Consumer<AlphaEvent> alphaEventListener = alphaEvent -> alphaCounter.incrementAndGet();
Consumer<BetaEvent> betaEventListener = betaEvent -> betaCounter.incrementAndGet();
Consumer<GammaEvent> gammaEventListener = gammaEvent -> gammaCounter.incrementAndGet();
eventBus.registerListener(AlphaEvent.class, alphaEventListener);
eventBus.registerListener(BetaEvent.class, betaEventListener);
eventBus.registerListener(GammaEvent.class, gammaEventListener);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(1, alphaCounter.get());
assertEquals(1, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.removeListener(GammaEvent.class, gammaEventListener);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(2, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.removeListener(BetaEvent.class, betaEventListener);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.removeListener(AlphaEvent.class, alphaEventListener);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
}
@Test
public void testRemoveAllListenersOfEvent() {
EventBus eventBus = new SimpleEventBus();
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(BetaEvent.class, betaEvent -> betaCounter.incrementAndGet());
eventBus.registerListener(BetaEvent.class, betaEvent -> betaCounter.incrementAndGet());
eventBus.registerListener(GammaEvent.class, gammaEvent -> gammaCounter.incrementAndGet());
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.removeAllListenersOfEvent(AlphaEvent.class);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(4, betaCounter.get());
assertEquals(2, gammaCounter.get());
eventBus.removeAllListenersOfEvent(BetaEvent.class);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(4, betaCounter.get());
assertEquals(3, gammaCounter.get());
eventBus.removeAllListenersOfEvent(GammaEvent.class);
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(4, betaCounter.get());
assertEquals(3, gammaCounter.get());
}
@Test
public void testRemoveAllListeners() {
EventBus eventBus = new SimpleEventBus();
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(AlphaEvent.class, alphaEvent -> alphaCounter.incrementAndGet());
eventBus.registerListener(BetaEvent.class, betaEvent -> betaCounter.incrementAndGet());
eventBus.registerListener(BetaEvent.class, betaEvent -> betaCounter.incrementAndGet());
eventBus.registerListener(GammaEvent.class, gammaEvent -> gammaCounter.incrementAndGet());
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
eventBus.removeAllListeners();
eventBus.executeEvent(new AlphaEvent());
eventBus.executeEvent(new BetaEvent());
eventBus.executeEvent(new GammaEvent());
assertEquals(3, alphaCounter.get());
assertEquals(2, betaCounter.get());
assertEquals(1, gammaCounter.get());
}
private static class AlphaEvent { }
private static class BetaEvent { }
private static class GammaEvent { }
}
</code></pre>
| [] | [
{
"body": "<p>The synchronization in the code is in some places overly broad, and in others, it is absent where it is needed.</p>\n\n<p>synchronizing on <code>eventMapping</code> in your <code>registerListenersOfObject</code> method means that only one thread can be accessing the <code>eventMapping</code> instance at any one time. This defeats using the <code>ConcurrentHashMap</code> concept entirely (where only a small portion of the map is locked and other portions are available for other threads). The granularity of this lock is overly broad.</p>\n\n<p>Inside that lock, you add data to (and potentially create) a <code>HashSet<EventHandler></code> instance. This HashSet is then used in other methods, but without any synchronization. Those other methods may have issues with concurrency because they are not included in any synchronization at all.</p>\n\n<blockquote>\n<pre><code>@Override\npublic void executeEvent(final Object event) {\n if (classConstraint.isAssignableFrom(event.getClass())) {\n eventMapping.getOrDefault(event.getClass(), EMPTY_SET).forEach(eventHandler -> eventHandler.invoke(event));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>in the above code, while performing the forEach, any of the following things are possible (and other things as well, I am sure):</p>\n\n<ul>\n<li>data could be added to the Set you are streaming, and that data may, or may not be included in the stream.</li>\n<li>the stream could throw a ConcurrentModificationException</li>\n<li>the steam could end early (and some data may not be processed at all.</li>\n<li>......</li>\n</ul>\n\n<p>Consider the following code in the <code>SimpleEventBus</code>. This code handles adding and using event handlers (though removing handlers needs to be fixed as well)....</p>\n\n<pre><code>private final void includeEventHandler(final Class<?> clazz, final EventHandler handler) {\n Set<EventHandler> existing = eventMapping.get(clazz);\n if (existing == null) {\n final Set<EventHandler> created = new HashSet<>();\n // optimistically assume that we are the first thread for this particular class.\n existing = eventMapping.putIfAbsent(clazz, created);\n if (existing == null) {\n // we are the first thread to add one for this clazz\n existing = created;\n }\n }\n synchronized (existing) {\n existing.add(handler);\n }\n}\n\nprivate final EventHandler[] getEventHandlers(final Class<?> clazz) {\n Set<EventHandler> handlers = eventMapping.get(clazz);\n if (handlers == null) {\n return new EventHandler[0];\n }\n synchronized(handlers) {\n return handlers.toArray(new EventHandler[handlers.size()]);\n }\n}\n\n\n\n@Override\npublic void registerListenersOfObject(final Object callbackObject) {\n Arrays.stream(callbackObject.getClass().getMethods())\n .filter(method -> (method.getAnnotation(Event.class) != null))\n .filter(method -> method.getReturnType().equals(void.class))\n .filter(method -> method.getParameterCount() == 1)\n .forEach(method -> {\n Class<?> clazz = method.getParameterTypes()[0];\n if (!classConstraint.isAssignableFrom(clazz)) {\n return;\n }\n includeEventHandler(clazz, new MethodEventHandler(method, callbackObject, clazz));\n });\n}\n\n@Override\n@SuppressWarnings(\"unchecked\")\npublic <T> void registerListener(final Class<T> eventClass, final Consumer<? extends T> eventListener) {\n Objects.requireNonNull(eventClass);\n Objects.requireNonNull(eventListener);\n if (!classConstraint.isAssignableFrom(eventClass)) {\n return;\n }\n includeEventHandler(eventClass, new ConsumerEventHandler((Consumer<Object>)eventListener));\n}\n\n@Override\npublic void executeEvent(final Object event) {\n if (classConstraint.isAssignableFrom(event.getClass())) {\n Arrays.stream(getEventHandlers(event.getClass())).forEach(eventHandler -> eventHandler.invoke(event));\n }\n}\n</code></pre>\n\n<p>The above code uses the ConcurrentHashMap in a way that is minimally locked. It uses an optimistic process for creating a new HashSet only when it is likely going to be used (instead of creating, and throwing it away almost all the time). It also makes sure that, if one is created in a different thread, and our optimism was proven wrong, that we use the one that other threads are using.</p>\n\n<p>Then, for the actual HashSet, it synchronizes on the whole set, and all operations are completely isolated from other threads.</p>\n\n<p>This is OK, because, the only time there will be thread blocking, is when two threads are accessing the event handlers for a single Class.... which is likely to be uncommon.</p>\n\n<p>Note, that the getHandlers creates a defensive copy of the Set, so that iteration has a consistent copy of the data, and that there does not need to be any locking during the iteration.</p>\n\n<p><strong>Edit:</strong> To remove unnecessary work in the code, I would actually recommend the following:</p>\n\n<pre><code>private final EventHandler[] getEventHandlers(final Class<?> clazz) {\n Set<EventHandler> handlers = eventMapping.get(clazz);\n if (handlers == null) {\n return null;\n }\n synchronized(handlers) {\n return handlers.toArray(new EventHandler[handlers.size()]);\n }\n}\n\n@Override\npublic void executeEvent(final Object event) {\n if (classConstraint.isAssignableFrom(event.getClass())) {\n EventHandler[] handlers = getEventHandlers(event.getClass());\n if (handlers != null) {\n Arrays.stream(handlers).forEach(eventHandler -> eventHandler.invoke(event));\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T22:07:39.430",
"Id": "48889",
"ParentId": "48869",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48889",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T15:15:00.053",
"Id": "48869",
"Score": "7",
"Tags": [
"java",
"thread-safety",
"reflection",
"event-handling"
],
"Title": "My EventBus system"
} | 48869 |
<p>I am writing a Python script that scrapes data from Google search results and stores it in a database. I couldn't find any Google API for this, so I am just sending a HTTP GET request on Google's main site (and also Google News site). Then, using Beautiful Soup, I extract the number of search results found. I store this number in a mongo database using pymongo.</p>
<p>I want to collect the number of search results for specific keywords for next few months and then visualize the data. I would want something like this in the end:</p>
<p><img src="https://i.stack.imgur.com/dBfj5.jpg" alt="enter image description here"></p>
<p>Here is my code and I will run this following script four times a day using cron:</p>
<pre><code>#! /bin/python
import re
import datetime
import pymongo
from pymongo import MongoClient
import requests
from bs4 import BeautifulSoup
REGEX = r'About (.*) results'
keywords = ['Barack Obama', 'Gandhi', 'Putin']
def number_of_search_results(key):
def extract_results_stat(url):
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0'
}
search_results = requests.get(url, headers=headers, allow_redirects=True)
soup = BeautifulSoup(search_results.text)
result_stats = soup.find(id='resultStats')
m = re.match(REGEX, result_stats.text)
# print m.group(1)
return int(m.group(1).replace(',',''))
google_main_url = 'https://www.google.co.in/search?q=' + key
google_news_url = 'https://www.google.co.in/search?hl=en&gl=in&tbm=nws&authuser=0&q=' + key
return (extract_results_stat(google_main_url), extract_results_stat(google_news_url))
if __name__ == '__main__':
conn = MongoClient()
db = conn['search_results']
current_time = datetime.datetime.utcnow()
for key in keywords:
google_main, google_news = number_of_search_results(key)
# print key, google_main, google_news
db.search_results.insert({'time': current_time, 'name': key, 'google_main': google_main, 'google_news': google_news})
</code></pre>
<ol>
<li>I am new to databases, so is my mongo schema good for my project?</li>
<li>Any general improvements?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T12:59:55.193",
"Id": "86327",
"Score": "0",
"body": "I would suggest passing the keywords as command-line arguments."
}
] | [
{
"body": "<ol>\n<li><p>As MongoDB doesn't enforce schema, and you are storing rows in schema, there shouldn't be any issue.</p>\n<p>But there are follow up questions (It seems I don't have enough points to comment). Is there any particular reason why you selected MongoClient? You would be performing suits better for relational DB or key value stores.</p>\n</li>\n<li><p>If it saves time and helps, check <a href=\"https://www.google.com/trends/explore#q=barack%20obama%2C%20gandhi%2C%20putin&date=today%203-m&cmpt=q\" rel=\"nofollow noreferrer\">Google Trends</a>.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T14:48:46.400",
"Id": "49153",
"ParentId": "48870",
"Score": "0"
}
},
{
"body": "<p>If you just need the number of search results, you can surely use what you're using now and grep the total result number, otherwise you may use <a href=\"https://developers.google.com/custom-search/docs/tutorial/creatingcse\" rel=\"nofollow\">Google Search API</a>, or find an open source scrawling tool like <a href=\"http://scrapy.org/\" rel=\"nofollow\">Scrappy</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T15:40:16.733",
"Id": "49160",
"ParentId": "48870",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T15:47:55.017",
"Id": "48870",
"Score": "3",
"Tags": [
"python",
"mongodb",
"web-scraping",
"beautifulsoup",
"pymongo"
],
"Title": "Number of Google search results over a period of time, saved to database"
} | 48870 |
<p>I had time measuring pretty much <a href="https://stackoverflow.com/a/21995693/2567683">figured out</a> when I ended up using this structure.</p>
<pre><code>#include <iostream>
#include <chrono>
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
template<typename F>
static typename TimeT::rep execution(F const &func)
{
auto start = std::chrono::system_clock::now();
func();
auto duration = std::chrono::duration_cast< TimeT>(
std::chrono::system_clock::now() - start);
return duration.count();
}
};
</code></pre>
<p>a use case would be</p>
<pre><code>struct functor
{
int state;
functor(int state) : state(state) {}
void operator()() const
{
std::cout << "In functor run for ";
}
};
void func()
{
std::cout << "In function, run for " << std::endl;
}
void func(int arg) {}
int main()
{
int dummy(1);
std::cout << measure<>::execution( [&]() {
func(dummy);
}) << std::endl;
std::cout << measure<>::execution(functor(dummy)) << std::endl;
std::cout << measure<>::execution(func);
return 0;
}
</code></pre>
<p>But since I started using my struct in various posts on Stack Exchange sites, I've had remarks and comments about the code (like on <code>func</code> being a const ref or not etc). </p>
<p>I'd like a review on the above and your suggestions on how I can approve this code (or leave it alone <a href="https://github.com/picanumber/bureaucrat/blob/master/time_lapse.h" rel="noreferrer">at last</a>).</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:42:59.773",
"Id": "85809",
"Score": "2",
"body": "Your class won't work with functions which need paramaters. Is it supposed to be so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:45:12.130",
"Id": "85810",
"Score": "0",
"body": "It'll work, just call the function throught a lambda"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:50:57.820",
"Id": "85813",
"Score": "0",
"body": "@ NikosAthanasiou Yes, that's possible. But measurements will be out of phase, since you are measuring the other function's execution time too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:53:47.307",
"Id": "85814",
"Score": "0",
"body": "@black Lambda functions are always inlined, so the code is called in place. Besides, for any measurement to take place, a single function call (which as stated before will be inlined) is not a factor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:07:22.827",
"Id": "85815",
"Score": "0",
"body": "@NikosAthanasiou As you prefer. But consider that it is neither logical nor expected to work that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:28:31.000",
"Id": "85822",
"Score": "0",
"body": "@black OK I'll have to give you credit after all. I wouldn't consider it a problem, but after seeing Loki's answer, I have to admit it has a more natural feel. So +1 to your initial comment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T22:34:16.387",
"Id": "85838",
"Score": "0",
"body": "@NikosAthanasiou: One thing to keep in mind is that for each function you measure it this way, you'll get a separate chunk of code instantiated, so using it many places in the same program could lead to some degree of code bloat which may also somewhat interfere with the timing."
}
] | [
{
"body": "<ol>\n<li>Extend your timer function so it can take all the parameters needed by <code>func()</code></li>\n<li>Don bother to pass <code>func</code> by const reference.</li>\n</ol>\n<h3>What I would have done</h3>\n<pre><code>template<typename TimeT = std::chrono::milliseconds>\nstruct measure\n{\n template<typename F, typename ...Args>\n static typename TimeT::rep execution(F func, Args&&... args)\n {\n auto start = std::chrono::system_clock::now();\n\n // Now call the function with all the parameters you need.\n func(std::forward<Args>(args)...);\n\n auto duration = std::chrono::duration_cast< TimeT>(std::chrono::system_clock::now() - start);\n\n return duration.count();\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:34:48.000",
"Id": "85823",
"Score": "1",
"body": "+1 . Those variadic templates solve so many problems! Would you recommend a source where I can learn more ? (please don't say the Standard)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:36:30.253",
"Id": "85824",
"Score": "2",
"body": "@NikosAthanasiou: This person seems to know what he is talking about. http://codereview.stackexchange.com/users/39083/iavr read some of his answers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:52:50.063",
"Id": "85826",
"Score": "0",
"body": "Quick question. Why can't it [compile](http://ideone.com/OeERav) the original example ? I'm supposing due to the overloads func, but can I have any thoughts on that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T23:20:55.213",
"Id": "85840",
"Score": "1",
"body": "@NikosAthanasiou: Its because you have two functions named `func()`. It does not know which one you mean when you go `measure<>::execution(func);` (it could be either). You can either name the functions differently or you can be specific when specifying them by providing the functions type `measure<>::execution<void()>(func);`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-28T12:00:08.100",
"Id": "187049",
"Score": "0",
"body": "I updated the [SO post](http://stackoverflow.com/a/21995693/2567683) with an improvement : We can use a universal reference for the `func` provided that we [forward the function call](http://stackoverflow.com/q/31253334/2567683)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-29T18:05:02.873",
"Id": "371252",
"Score": "0",
"body": "Isn't this kind of overkill, seeing how we could just wrap the function call in a lambda and time that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-30T02:01:41.227",
"Id": "371300",
"Score": "0",
"body": "@einpoklum I have no idea what you are talking about. Write an answer and get votes on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-11T23:41:54.273",
"Id": "378135",
"Score": "0",
"body": "Sorry for the late question, but - why return the count rather than the duration? I know OP did that but is that really a good idea?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:24:10.060",
"Id": "48880",
"ParentId": "48872",
"Score": "21"
}
},
{
"body": "<p>There isn't much more to improve after the code has begun to accept function parameters.</p>\n\n<p>These are some details, you could freely ignore them:</p>\n\n<ul>\n<li><p>Class names should begin with an uppercase letter </p>\n\n<pre><code>struct Measure\n</code></pre></li>\n<li><p>You don't need the <code>duration</code> variable; just do:</p>\n\n<pre><code>return std::chrono::duration_cast< TimeT>(std::chrono::system_clock::now() - start).count();\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T23:25:02.870",
"Id": "85841",
"Score": "2",
"body": "I agree that it is a good idea to have type names begin with Upper case letters (seems to be a common practice). But `should` is a bit strong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T23:27:07.080",
"Id": "85842",
"Score": "2",
"body": "Disagree on removing the variable `duration`. The compiler will remove all wasted space so the code will still be optimal (ie no different than your version) with the variable. But it helps in reading the code (and code is for the human to read so make it easy on us humans and leave the variables in to make it easier to read). Also when debugging it makes it easier to check the result when you have it stored in a variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T04:58:26.077",
"Id": "106590",
"Score": "0",
"body": "I kind of disagree on both: `duration` removal for the same reason as Loki, class name capitalization because you are free to choose your own code style (actually standard library classes are not capitalized, aren't they?)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:43:49.277",
"Id": "48883",
"ParentId": "48872",
"Score": "2"
}
},
{
"body": "<p>It seems a bit of a bother to approach it as a function template when it seems to me that it's more like an object. For that reason, here's an alternative that might be a little more natural to use:</p>\n\n<pre><code>template<typename TimeT = std::chrono::microseconds, \n typename ClockT=std::chrono::high_resolution_clock,\n typename DurationT=double>\nclass Stopwatch\n{\nprivate:\n std::chrono::time_point<ClockT> _start, _end;\npublic:\n Stopwatch() { start(); }\n void start() { _start = _end = ClockT::now(); }\n DurationT stop() { _end = ClockT::now(); return elapsed();}\n DurationT elapsed() { \n auto delta = std::chrono::duration_cast<TimeT>(_end-_start);\n return delta.count(); \n }\n};\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>Stopwatch<> sw;\nfunctionToBeTimed(arg1, arg2);\nsw.stop();\nstd::cout << \"functionToBeTimed took \" << sw.elapsed() << \" microseconds\\n\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T23:29:56.007",
"Id": "85843",
"Score": "0",
"body": "Disagree with `more natural`. But this has the advantage you can time multiple function calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T00:38:30.123",
"Id": "85845",
"Score": "1",
"body": "You can also time things that are not functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T15:52:15.557",
"Id": "86202",
"Score": "2",
"body": "I would be careful about timing things that are not functions because of optimizations that the compiler is allowed to do. I am not sure about the sequencing requirements and the observable behavior understanding of such a program. With a function call the compiler is not allowed to move statements across the call point (they are sequenced before or after the call)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T00:53:06.400",
"Id": "86263",
"Score": "0",
"body": "+1. I find this quite natural. I usually write my own timer object like that, with members called `tic()`, `toc()` (instead of `start()`, `stop()`), following the [matlab style](http://www.mathworks.com/help/matlab/ref/tic.html). Plus `tac()`, which measures elapsed time without stopping the timer. But all this is complementary rather than competitive to the proposed `measure()` function template (including parameters). Why not have all in a timer object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T01:51:06.037",
"Id": "86271",
"Score": "0",
"body": "@iavr: good point about them being complementary mechanisms. Also, while I never liked the overly cute matlab names, I'll point out that `stop()` isn't an entirely accurate name and actually functions more like `toc()` in that neither `stop()` nor `toc()` actually stop the timer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T04:54:29.327",
"Id": "106589",
"Score": "0",
"body": "@LokiAstari i would guess that if compiler would not reorder instructions around calls to `ClockT:now()`. It would make sense for that function's implementation to have some kind of memory barrier or similar primitive to avoid reordering"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:47:18.880",
"Id": "48884",
"ParentId": "48872",
"Score": "10"
}
},
{
"body": "<p>You should use <code>std::chrono::steady_clock</code> instead of <code>std::chrono::system_clock</code>. This is because <code>system_clock</code> may get adjusted every now and then (e.g. it may rewind back a bit, or jump forward more than the actual elapsed time in order to keep in sync with the wall/world clock), whereas steady_clock is a monotonic clock that is never adjusted. Therefore, <code>steady_clock</code> is better suited for what you're doing.</p>\n\n<p>P.S. If you need to know how much CPU-time your function is actually taking, even <code>steady_clock</code> may not be ideal, as it will only measure the duration from the time your function is called, to the time it returns. This may not necessarily be equal to the amount of CPU-time the function took, as other processes and threads can interrupt your function and result in significantly longer execution times. If you want to isolate the effects of other system activities, you should google OS/platform-specific alternatives for getting the thread execution time or look up the <a href=\"http://www.boost.org/doc/libs/1_56_0/doc/html/chrono.html\" rel=\"nofollow\">chrono functions in Boost</a> (look for the <code>process_...cpu_clock</code> and <code>thread_clock</code> classes).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-30T07:37:03.063",
"Id": "64227",
"ParentId": "48872",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48880",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T16:50:45.037",
"Id": "48872",
"Score": "27",
"Tags": [
"c++",
"c++11"
],
"Title": "Measuring execution time in C++"
} | 48872 |
<p>I wrote my first simple image upload script that allows users to add items to a database along with pictures of said item. My script takes the images uploaded via a form, processes and resizes them and finally saves them to a hard disk, with their file paths added to a database.</p>
<p>While my code is currently working, I have the following questions:</p>
<ol>
<li>Should I be processing the images after the items have been successfully inserted into the database?</li>
<li>Should I be hard-coding/ specifying the image width and height explicitly or is there a better/ more efficient way of going about it.</li>
<li>Is my code an acceptable way of handling uploaded images?</li>
<li>Are there any better/ more efficient/ neater methods of refactoring my code?</li>
</ol>
<p></p>
<pre><code>//Code to add the item to database.....
//If the insertion is successful
if($insertdata)
{
$upload=$_FILES['ImageUpload']['tmp_name'];
$uploadnum=count($upload);
for($i=0;$i<$uploadnum;$i++)
{
/*--------------------------------------------------------------------
| Image upload Conditions |
--------------------------------------------------------------------*/
//Valid image extensions
$validext=array('.jpg','.png','.gif');
// Maximum filesize in BYTES (currently 2.0MB).
$maxsize = 2097152;
if(isset($upload[$i]) && !empty($upload[$i]) && is_uploaded_file($upload[$i]))
{
if($_FILES['ImageUpload']['size'][$i] < $maxsize)
{
/*------------------------------------------------------------------------------
| Prepares Image for uploading |
------------------------------------------------------------------------------*/
//Replaces spaces in the item name with underscores
$itemname=str_replace(' ', '_', $itemname);
//Sets the upload path for the images to be uploaded
$displayuploadpath='..\\..\\images\\'.$shopid."\\item\\".$itemname."\\display\\";
$thumbuploadpath='..\\..\\images\\'.$shopid."\\item\\".$itemname."\\thumb\\";
//Checks if the upload path directory exists and creates it if it's not
if(!is_dir($thumbuploadpath))
{
mkdir($thumbuploadpath,0644,true);
}
if(!is_dir($displayuploadpath))
{
mkdir($displayuploadpath,0644,true);
}
//New random filename
$renamedfile=uniqid("",true);
//Gets the image's width,height and filetype
list($width,$height,$type)=getimagesize($upload[$i]);
//checks the mime type, gets the extension and creates an image identifier
switch($type)
{
case 1://GIF
$uploadedfile=$_FILES["ImageUpload"]["tmp_name"][$i];
$src=imagecreatefromgif($uploadedfile);
$ext=".gif";
break;
case 2://JPEG
$uploadedfile=$_FILES["ImageUpload"]["tmp_name"][$i];
$src=imagecreatefromjpeg($uploadedfile);
$ext=".jpg";
break;
case 3://PNG
$uploadedfile=$_FILES["ImageUpload"]["tmp_name"][$i];
$src=imagecreatefrompng($uploadedfile);
$ext=".png";
break;
default:
die("An error has occurred.Please follow the <a href='#'>link to try again</a>");
}
//Creates thumbnail
$thumbnewwidth=100;
$thumbnewheight=100;
$thumbimg=imagecreatetruecolor($thumbnewwidth, $thumbnewheight);
imagecopyresampled($thumbimg,$src,0,0,0,0,$thumbnewwidth,$thumbnewheight,$width,$height);
//Creates displayimage
$displaynewwidth=250;
$displaynewheight=250;
$displayimg=imagecreatetruecolor($displaynewwidth, $displaynewheight);
imagecopyresampled($displayimg,$src,0,0,0,0,$displaynewwidth,$displaynewheight,$width,$height);
//If the image currently being processed is the display pic, add "DP" to the fileuploadname
if($i==0)
{
//Sets thumbnail filepaths to the pictures and saves it
$thumbfilename=$thumbuploadpath.$renamedfile."DP";
$thumbfilepath=$thumbuploadpath.$renamedfile."DP".$ext;
//Sets displaypic filepaths to the pictures and saves it
$displayfilename=$displayuploadpath.$renamedfile."DP";
$displayfilepath=$displayuploadpath.$renamedfile."DP".$ext;
}
else
{
//Sets thumbnail filepaths to the pictures and saves it
$thumbfilename=$thumbuploadpath.$renamedfile;
$thumbfilepath=$thumbuploadpath.$renamedfile.$ext;
//Sets displaypic filepaths to the pictures and saves it
$displayfilename=$displayuploadpath.$renamedfile;
$displayfilepath=$displayuploadpath.$renamedfile.$ext;
}
/*-------------------------------------------------------------------------------
| Starts uploading image |
-------------------------------------------------------------------------------*/
if(in_array($ext,$validext))
{
if(is_writable($thumbuploadpath) && is_writable($displayuploadpath))
{
if($ext==".gif")
{
imagegif($thumbimg,$thumbfilepath);
imagegif($displayimg,$displayfilepath);
}
elseif($ext==".jpg")
{
imagejpeg($thumbimg,$thumbfilepath);
imagejpeg($displayimg,$displayfilepath);
}
elseif($ext==".png")
{
imagepng($thumbimg,$thumbfilepath);
imagepng($displayimg,$displayfilepath);
}
else
{
die("There was an error in saving the images.Please follow the <a href='#'>link to try again</a>");
}
//End of image saving
if($i==0)//This is the display pic
{
$insertDP=$cxn->prepare("UPDATE `Items` SET `ItemDP`=:dp WHERE `ItemID`=:itemid");
$insertDP->bindValue(":dp",$displayfilepath);
$insertDP->bindValue(":itemid",$iteminsertid);
$insertDP->execute();
//Inserts the displaypic info into database
$insertimage=$cxn->prepare("INSERT INTO `ItemPics` (`ShopID`,`ItemID`,`FileName`,`Extension`) VALUES (:shopid,:itemid,:filename,:ext)");
$insertimage->bindValue(":shopid",$shopid);
$insertimage->bindValue(":itemid",$iteminsertid);
$insertimage->bindValue(":filename",$displayfilename);
$insertimage->bindValue(":ext",$ext);
$insertimage->execute();
//Inserts the thumbnail's info into database
$insertthumb=$cxn->prepare("INSERT INTO `ItemThumbs` (`ShopID`,`ItemID`,`FileName`,`Extension`) VALUES (:shopid,:itemid,:filename,:ext)");
$insertthumb->bindValue(":shopid",$shopid);
$insertthumb->bindValue(":itemid",$iteminsertid);
$insertthumb->bindValue(":filename",$thumbfilename);
$insertthumb->bindValue(":ext",$ext);
$insertthumb->execute();
}
else//Image currently being processed is not the display pic
{
//Inserts the displaypic info into database
$insertimage=$cxn->prepare("INSERT INTO `ItemPics` (`ShopID`,`ItemID`,`FileName`,`Extension`) VALUES (:shopid,:itemid,:filename,:ext)");
$insertimage->bindValue(":shopid",$shopid);
$insertimage->bindValue(":itemid",$iteminsertid);
$insertimage->bindValue(":filename",$displayfilename);
$insertimage->bindValue(":ext",$ext);
$insertimage->execute();
//Inserts the thumbnail's info into database
$insertthumb=$cxn->prepare("INSERT INTO `ItemThumbs` (`ShopID`,`ItemID`,`FileName`,`Extension`) VALUES (:shopid,:itemid,:filename,:ext)");
$insertthumb->bindValue(":shopid",$shopid);
$insertthumb->bindValue(":itemid",$iteminsertid);
$insertthumb->bindValue(":filename",$thumbfilename);
$insertthumb->bindValue(":ext",$ext);
$insertthumb->execute();
}
//End of data insertion into ItemPics and ItemThumbs tables
//Grabs the ShopName, to use in updates, if any.
$getshopname=$cxn->prepare("SELECT `ShopName` FROM `Shops` WHERE `ShopID`=:shopid");
$getshopname->bindValue(":shopid",$shopid);
$getshopname->execute();
while($fetchshopname=$getshopname->fetch(PDO::FETCH_ASSOC))
{
$shopname=$fetchshopname['ShopName'];
}
//Add item to the updates table
$additemupdate=$cxn->prepare("INSERT INTO `Updates` (`ShopID`,`UpdateMsg`) VALUES (:shopid,:updatemsg)");
$additemupdate->bindValue(":shopid",$shopid);
$additemupdate->bindValue(":updatemsg",$shopname." has added ".$itemname." to their inventory");
$additemupdate->execute();
//Redirect to success page
$cxn->commit();
header("Location:success.php");
}
else
{
die("Invalid file path specified".$displayfilepath."Please try again <a href='#'>here</a> ");
}
//End of filepath validity check
}
else
{
die("Invalid file extension.Please try again <a href='#'>here</a> ");
}
//End of extension check
}
//Image exceeds maximum file limit
else
{
die("Your image exceeded the maximum size of 2MB.Please reduce the size and try again <a href='#'>here</a>.");
}
//End of Image size check
}
//If image being uploaded fails the upload checks
else
{
die("An error has occurred.Please follow the <a href='#'>link to try again</a>");
}
//End of image upload checks
}
//End of image uploading
}
//If insertion is not successful
else
{
die("An error has occurred.Please follow the <a href='#'>link to try again</a>");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T11:03:28.130",
"Id": "85884",
"Score": "0",
"body": "In relation to 2. I tend to keep the original image, then resize it as necessary from the page that requests it (and keep that cached copy). See this SO topic for a bit of an idea of how it works, http://stackoverflow.com/questions/10515985/php-dynamic-images/10516231#10516231"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T11:05:40.827",
"Id": "85885",
"Score": "0",
"body": "In relation to 4. You can easily split some of that code into functions, and have a much smaller (easily readable/maintainable) main for loop."
}
] | [
{
"body": "<h2>Let's start with a review:</h2>\n\n<ul>\n<li><p>Use <a href=\"http://il1.php.net/manual/en/control-structures.foreach.php\" rel=\"nofollow\"><code>foreach</code></a>: When iterating an array (or an Iterator), PHP provides you with the <code>foreach</code> loop, which allows you to easily iterate over the array.</p>\n\n<pre><code>foreach ($_FILES as $file) { //$file now holds the current item, i.e. $_FILES[$i];\n</code></pre></li>\n<li><p>Use absolute paths. Relative paths are brittle, and bound to cause hard-to-track errors when changing the directory structures. Absolute paths will allow you to very quickly know that you need to change something in case of structure shift.</p></li>\n<li><p>Better filename handling: I usually save the file as a hash of the contents of the image (<code>sha1($image_file_contents) . \".$ext\"</code>), this has the nice added property of not allowing duplicate images (It won't catch all cases, but it works nicely). Also, dividing the images into subdirectories (by the first letter or two of the filename) will help you out tremendously when you start getting thousands of images.</p></li>\n<li><p>Don't <code>die()</code>: Calling <code>die()</code> in your code will cause the script to terminate instantly. If you were in an included file or something else still needs to run, it won't. Store the error message, and output it at the end of the script.</p></li>\n</ul>\n\n<h2>Now, for your questions</h2>\n\n<ol>\n<li>Depends, are the pictures extremely heavy or otherwise take a burden on the server? If you're uploading 100 2MB pictures at a time, that may be the case. If you're only upload 2-3, it wouldn't.</li>\n<li>Don't generate the thumbnail in advance. Generate it on-demand and based on the requester's needs (i.e. an avatar in a forum is 64x64, but in the profile page it's 128x128). Save the results normally to a file and create a database entry for it, so that next time, you won't have to generate the thumbnail again.</li>\n<li>It is. It depends on the rest of the application. Personally, I'd go with a more OO solution, but that's because I understand how OO works and how to incorporate it into my needs.</li>\n<li>Split the code into smaller pieces of work. Either objects or functions, that do small tasks each (get input, do something, return output). This will help code readability tremendously. </li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-10T08:00:06.917",
"Id": "53863",
"ParentId": "48876",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "53863",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:38:40.823",
"Id": "48876",
"Score": "5",
"Tags": [
"php",
"beginner",
"pdo",
"image"
],
"Title": "Image upload script for adding items to a database"
} | 48876 |
<p>This is a class to hold an animation and be able to refer to different animations by titles, but it seems like calling <code>draw(Graphics2D g)</code> and <code>update</code> every frame, would, with this implementation, cause a big slowdown with all the <code>list.get(Object obj)</code> calls. Is this a big deal, and if so how should I change the implementation? Other comments on the code are very welcome.</p>
<pre><code>package core.graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AnimationSet {
private int currentAnimation;
private Map<String, Integer> namesToAnimation;
private List<Animation> animations;
public AnimationSet() {
currentAnimation = 0;
namesToAnimation = new HashMap<String, Integer>();
animations = new ArrayList<Animation>();
}
public void addAnimation(String title, Animation animation){
animations.add(animation);
namesToAnimation.put(title, animations.size()-1);
}
public void goToAnimation(String title){
currentAnimation = namesToAnimation.get(title);
}
public void removeAnimation(String title){
animations.remove(namesToAnimation.get(title));
namesToAnimation.remove(title);
}
public void draw(Graphics2D g, int x, int y){
g.drawImage(animations.get(currentAnimation).getImage(), x, y, null);
}
public void update(){
animations.get(currentAnimation).update();;
}
}
</code></pre>
| [] | [
{
"body": "<p>As your <code>List</code> is instantiated as an <code>ArrayList</code>, the lookup time for <code>get</code> is constant time, \\$O(1)\\$.</p>\n\n<p>There is however, somethings that I can point out.</p>\n\n<h1>Final</h1>\n\n<p>Whenever possible, add the keyword <code>final</code> to member fields of your class. This keyword should be used for values/references that never change. Your <code>namesToAnimation</code> and <code>animations</code> variables can be marked with <strong><code>final</code></strong>.</p>\n\n<h1>Why <code>Map<String, Integer></code>?</h1>\n\n<p>You seem to only use your <code>namesToAnimation</code> as a lookup for <code>String</code> to <code>index in the 'animations' list</code>. You never increase/decrease your <code>currentAnimation</code> value. Then why do you use <code>Map<String, Integer></code>? I think you can get rid of your list entirely and use <code>Map<String, Animation></code></p>\n\n<h3>Rewritten code according to what I have mentioned above:</h3>\n\n<pre><code>public class AnimationSet {\n\n private Animation currentAnimation;\n private final Map<String, Animation> animations;\n\n public AnimationSet() {\n animations = new HashMap<>();\n }\n public void addAnimation(String title, Animation animation){\n animations.put(title, animation);\n }\n public void goToAnimation(String title){\n currentAnimation = animations.get(title);\n }\n public void removeAnimation(String title){\n animations.remove(title);\n }\n public void draw(Graphics2D g, int x, int y){\n g.drawImage(currentAnimation.getImage(), x, y, null);\n }\n public void update(){\n currentAnimation.update();\n } \n}\n</code></pre>\n\n<h3>Usefulness</h3>\n\n<p>I'm sorry, but I can't really understand why you have this class? What functionality does it provide to you? Would it be easier to have the same functionality without this class?</p>\n\n<p>Hopefully you have a good use case for this class, in which case, great! I'm just not sure how I myself would use this class, which brings me to the next point:</p>\n\n<h3>Documentation</h3>\n\n<p>Although your naming is really good (you have no idea how happy I am to be able to say that!), your class could use some documentation in the form of <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\">JavaDoc</a>. Stating the purpose of the class and the usage of the class and it's methods in JavaDoc helps any potential users of your class, it can even help yourself several times.</p>\n\n<h3>Thread safety</h3>\n\n<p>Your code would likely cause problems if it would be used from multiple threads. To avoid those problems, learn about <a href=\"http://docs.oracle.com/javase/tutorial/essential/concurrency/\">Java Concurrency</a>. If you're not using multiple threads now, you might be later, that's why I'm mentioning this. It's something for you to learn in the future :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T21:01:25.433",
"Id": "85830",
"Score": "2",
"body": "Good answer, as an additional point: I'd initialize final members right where they are declared if they don't depend on constructor parameters."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T20:21:30.140",
"Id": "48886",
"ParentId": "48882",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:27:05.880",
"Id": "48882",
"Score": "5",
"Tags": [
"java",
"game",
"animation"
],
"Title": "Improving speed of Animation class"
} | 48882 |
<p>I am still learning the javascript language. </p>
<p>Recently I've written simple code for a task list. I am searching for improvements and advice from more experienced users. Are there any improvements, changes or specific patterns for this task?</p>
<p><strong>PS</strong>- I wanted to use pure JavaScript (e.g. no jQuery or AngularJS) as this is only for learning.</p>
<p>The complete source code can be found at <a href="http://jsfiddle.net/cachaito/c5M4B/4/">jsfiddle</a>.</p>
<p>JS code:</p>
<pre><code>var scheduleListApp = (function() {
'use strict';
var helpers = {},
listArr = ['My birthdays', 'Take a pill', 'Eat something'],
elems = {
arrayContainer : document.getElementsByClassName('container')[0],
inputTask : document.getElementsByClassName('task')[0],
inputAdd : document.getElementsByClassName('addTask')[0],
inputDelete : document.getElementsByClassName('deleteTask')[0],
submitForm : document.getElementsByTagName('form')[0],
listNumber : document.getElementsByClassName('number')[0].getElementsByTagName('span')[0]
},
inserted = false;
helpers = {
readFromArr : function() {
return listArr.length;
},
clearList : function() {
if(elems.arrayContainer.hasChildNodes()) {
console.log('ready for cleaning.');
elems.arrayContainer.removeChild(elems.arrayContainer.firstChild);
}
},
displayArr : function() {
var tempArr = document.createDocumentFragment().appendChild(document.createElement('ul')),
list = listArr.length,
i = 0,
number = this.readFromArr();
if(inserted === true) {
console.log('Array is loaded.');
return false;
}
this.clearList();
for(;i < list; i+=1) {
var elem = document.createElement('li');
elem.textContent = listArr[i];
elem.insertAdjacentHTML('afterBegin', '<input type="checkbox">');
tempArr.appendChild(elem);
}
elems.arrayContainer.appendChild(tempArr);
inserted = true;
this.updateNumber(number);
return elems.arrayContainer;
},
updateNumber : function(number) {
return elems.listNumber.textContent = number;
},
submitProxy : function(event) {
event.preventDefault();
if(document.activeElement === elems.inputAdd) {
return this.addTask(event);
}
return this.deleteTask(event);
},
addTask : function(e) {
var newValue = elems.inputTask.value,
oldValue = listArr[listArr.length-1];
console.log(e, oldValue);
if(newValue === oldValue || newValue === "") {
console.log('Please enter new value.');
return false;
}
this.displayNewTask(newValue);
},
emptyArr : function() {
var elem = elems.arrayContainer;
if(listArr.length === 0) {
elem.innerHTML = '<p>There is no tasks added</p>';
}
},
deleteTask : function(e) {
var elem = document.querySelectorAll('input[type="checkbox"]'),
i = 0,
j = 0,
list = elem.length,
toDelete = [];
for(; i < list; i+=1) {
if(elem[i].checked === true) {
toDelete.push(i);
//toDelete.push(elem[i].nextSibling.nodeValue);
}
}
for(; j < toDelete.length; j+=1) {
listArr.splice(toDelete[j] - j,1);
}
console.log('Array to delete: ', listArr);
if (toDelete.length === 0) {
console.log('Nothing to delete.');
return false;
}
inserted = false;
this.displayArr();
this.emptyArr();
},
displayNewTask : function(task) {
var number = this.readFromArr();
listArr.push(task);
inserted = false;
this.updateNumber(number);
this.displayArr();
}
}
elems.submitForm.addEventListener('submit', helpers.submitProxy.bind(helpers), true);
window.addEventListener('load', helpers.displayArr.bind(helpers), false);
return {
readFromArr : helpers.readFromArr,
displayArr : helpers.displayArr
}
})();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T04:25:52.200",
"Id": "85855",
"Score": "0",
"body": "I sometimes hear that using DOM elements inside a closure can lead to memory leaks and one much set them to null to have them garbage collected. I;m curious if this is true and if the above code has a potential for a memory leak. Could someone enlighten me?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T19:15:43.727",
"Id": "86060",
"Score": "0",
"body": "Please… https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label"
}
] | [
{
"body": "<p>First reading -- a couple of notes.</p>\n\n<h2>Using classnames as selectors</h2>\n\n<p>For a long time, using class-names as JavaScript selectors was the common and accepted practice. For a solo-developer, this often works well enough.</p>\n\n<p>However, when developing as a team when someone else is responsible for managing the CSS and layout, it is not uncommon to have CSS class names removed from the markup, thus breaking the site.</p>\n\n<p>There are some common approaches as below:</p>\n\n<ul>\n<li>Use a <code>js-</code> prefix on CSS class names as a warning to the designers that some class names are to be left alone.</li>\n<li>Use the new <code>data-*</code> attributes.</li>\n<li>Use the <code>form</code> element's <code>name</code> attribute</li>\n<li>Use IDs.</li>\n</ul>\n\n<p>All of these have pros and cons and without seeing your whole application, I couldn't steer you towards the best of these choices.</p>\n\n<h2>The use of the <code>Helpers</code> object</h2>\n\n<p>This is, of course, far more subjective.</p>\n\n<p>But, since you already have everything wrapped up in a module thanks to the <code>IIFE</code>, your use of the <code>helpers</code> object is just a bit of over-plumbing. No reason not to have those separate stand-alone functions, free of their own name space.</p>\n\n<p>When reading through, I was surprised to find the use of <code>this</code> that wasn't part of a typical constructor pattern and I had to scroll down to the invocation to find your <code>bind</code> statement.</p>\n\n<p>If you really wanted to keep it is own object, then I'd fall back to the standard prototypical pattern, including capitalizing the constructor name, to make a bit of mental burden off the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T18:31:10.010",
"Id": "85915",
"Score": "0",
"body": "resuming your comment:\n1) better class naming\n2) when using IIFE, use function statement instead methods\n3) unnecesary 'this' (I agree!)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T20:40:25.657",
"Id": "48887",
"ParentId": "48885",
"Score": "5"
}
},
{
"body": "<p>From a once over</p>\n\n<ul>\n<li><p>Do not select by class name ( as per Jeremy ), I would suggest to setting id's and select by <code>id</code></p>\n\n<p>HTML: <code><input type=\"text\" value=\"\" class=\"task\" id=\"taskInput\"/></code><br>\nJS: <code>inputTask : document.getElementsById('taskInput'),</code></p></li>\n<li><p><code>'use strict'</code> is good</p></li>\n<li>Your event handling is too cumbersome\n<ul>\n<li>I would get rid of of these : \n<ul>\n<li><code>submitForm : document.getElementsByTagName('form')[0],</code> </li>\n<li>The function <code>submitProxy</code></li>\n<li><code>elems.submitForm.addEventListener('submit'..</code></li>\n</ul></li>\n<li>I would then simply go for \n<ul>\n<li><code>elems.inputAdd.addEventListener('click',helpers.addTask, false);</code> and <br>\n<code>elems.inputDelete.addEventListener('click',helpers.deleteTask, false);</code></li>\n</ul></li>\n<li>Though really, I would probably not group elements under <code>elems</code> and prefix them with <code>$</code>, I would also not group the helpers under <code>helpers</code>:\n<ul>\n<li><code>$addButton.addEventListener('click',addTask, false);</code> and <br>\n<code>$deleteButton.addEventListener('click',deleteTask, false);</code></li>\n</ul></li>\n</ul></li>\n<li>Your naming is odd, sometimes too verbose, sometimes not verbose enough, these are my suggestion:\n<ul>\n<li><code>helpers</code> -> don't use that any more</li>\n<li><code>listArr</code> -> I would suggest <code>items</code> or <code>tasks</code></li>\n<li><code>elems</code> -> don't use that any more</li>\n<li><code>arrayContainer</code> -> <code>$items</code> ?</li>\n<li><code>inputTask</code> -> <code>$input</code> ?</li>\n<li><code>inputAdd</code> -> <code>addButton</code> ?</li>\n<li><code>inputDelete</code> -> <code>deleteButton</code></li>\n<li><code>submitForm</code> -> don't use that any more</li>\n<li><code>readFromArr</code> -> This gets the count of items, how about <code>itemsCount</code> or simply removing the whole function since it's a one liner that you are already not using for <code>emptyArr</code></li>\n<li><code>clearList</code> -> This, is where you could have create a todo-list model class. And have <code>clear</code> be a function of that class.</li>\n<li><code>displayArr</code> -> Your naming is not consistent, either <code>clearList</code> and <code>displayList</code> or <code>clearArr</code> and <code>displayArr</code>. I prefer <code>xList</code> by far, or you could have gone for <code>xTasks</code></li>\n<li><code>submitProxy</code> - don't use that any more</li>\n</ul></li>\n</ul>\n\n<p>Other than that, there are few small items:</p>\n\n<ul>\n<li>Run JsHint in JsFiddle, you have some missing semi colons</li>\n<li>Don't use <code>console.log</code> in your final code</li>\n<li>Don't keep commented out code</li>\n</ul>\n\n<p>I kind of rewrote the app : <a href=\"http://jsfiddle.net/konijn_gmail_com/L7emH/\" rel=\"nofollow\">http://jsfiddle.net/konijn_gmail_com/L7emH/</a></p>\n\n<p>The code employs a model/view/controller approach to keep things separated/cleaner.</p>\n\n<pre><code>var tasksApp = (function () {\n 'use strict';\n\n var tasks = ['My birthdays', 'Take a pill', 'Eat something'],\n $header = document.getElementById('header'),\n $tasks = document.getElementById('tasks'),\n $input = document.getElementById('input'),\n $addButton = document.getElementById('addButton'),\n $deleteButton = document.getElementById('deleteButton');\n\n function fillTemplate(s) {\n //Replace ~ with further provided arguments \n for (var i = 1, a = s.split('~'), s = ''; i < arguments.length; i++)\n s = s + a.shift() + arguments[i];\n return s + a.join(\"\");\n }\n\n var model = {\n add: function (task) {\n tasks.push(task);\n },\n delete: function (index) {\n if (index > -1) {\n tasks.splice(index, 1);\n }\n },\n getTasks: function () {\n return tasks || [];\n },\n taskPrefix: 'task_'\n };\n\n var ui = {\n update: function (model) {\n var tasks = model.getTasks(),\n title = 'Task list (' + tasks.length + ')',\n html = '';\n $header.innerText = title;\n for (var i = 0; i < tasks.length; i++) {\n html += fillTemplate('<li><input type=\"checkbox\" id=\"task_~\">~</li>', i, tasks[i]);\n }\n //Using innerHTML might be a bit controversial, but oh so convenient\n $tasks.innerHTML = '<ul>' + html + '</ul>'\n }\n };\n //The controller does the initialization, button event binding and handles events\n var controller = {\n initialize: function () {\n ui.update(model);\n $addButton.addEventListener('click', controller.add);\n $deleteButton.addEventListener('click', controller.delete);\n },\n add: function (e) {\n model.add($input.value);\n ui.update(model);\n },\n delete: function (e) {\n var checkboxes = document.getElementsByTagName('input'),\n checkbox, idParts;\n //We know it is a task checkbox if the id starts with task_\n //Not the perfect design decision but okay for this app\n for (var i = 0; i < checkboxes.length; i++) {\n checkbox = checkboxes[i];\n idParts = checkbox.id.split(model.taskPrefix);\n if ( idParts.length > 1 && checkbox.checked ) {\n model.delete(+idParts[1]);\n }\n }\n ui.update(model);\n }\n }\n //Bind all al controllers when the document is loaded\n window.addEventListener('load', controller.initialize, false);\n //For giggles, return model, ui and controller\n return {\n model: model,\n ui: ui,\n controller: controller\n }\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T22:55:17.430",
"Id": "86097",
"Score": "0",
"body": "konijn Your answer and refactoring my code is such a big thing that I must spend more time on it to analyse. Anyway that's impressive answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T13:18:11.133",
"Id": "48979",
"ParentId": "48885",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48979",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T20:16:27.463",
"Id": "48885",
"Score": "5",
"Tags": [
"javascript",
"array"
],
"Title": "Simple tasks list"
} | 48885 |
<p>Here's how I wrote the Haskell <code>splitAt</code> function:</p>
<pre><code>splitAt' :: Int -> [a] -> ([a], [a])
splitAt' n ys
| n < 0 = ([], ys)
| otherwise = splitAt'' n ys []
where splitAt'' a (x:xs) acc
| a == 0 = (acc, x:xs)
| null xs = (acc ++ [x], [])
| otherwise = splitAt'' (a-1) xs (acc ++ [x])
</code></pre>
<p>I don't like I'm using the append (<code>++</code>) function to add an element to the end of my <code>acc(umulator)</code>.</p>
<p>But, given the importance of ordering, I'm not sure how to avoid using it.</p>
<p>Please review this code as well.</p>
| [] | [
{
"body": "<p>You should be able to implement it without <code>++</code>.</p>\n\n<pre><code>splitAt' :: Int -> [a] -> ([a], [a])\nsplitAt' 0 ys = ([], ys)\nsplitAt' _ [] = ([], [])\nsplitAt' n (y:ys)\n | n < 0 = ([], (y:ys))\n | otherwise = ((y:a), b)\n where (a, b) = splitAt' (n - 1) ys\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T13:41:36.453",
"Id": "85895",
"Score": "0",
"body": "Hi @200_success. Re: negatives aren't allowed: `*Main> splitAt (-3) \"heyman\"` produces `(\"\",\"heyman\")` using GHCI 7.6.3. Also, with your above function, using a negative won't produce an error. It'll simply put the entire list in the first part of the tuple, leaving `[]` for the second part. Example: `*Main> splitAt' (-3) [1..100]` produces `([1,...,100],[])`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T10:14:53.513",
"Id": "85977",
"Score": "0",
"body": "You're right! I've added a case to handle negative `n`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T11:06:52.757",
"Id": "85983",
"Score": "0",
"body": "Thanks! Out of curiosity, when do you use the \"don't care\" (`_`) for arguments? Example: `splitAt' n []` but n isn't used so why not use don't care? Maybe there's a general style rule?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T14:34:44.607",
"Id": "86005",
"Score": "0",
"body": "Right again! The \"don't care\" placeholder should be used whenever possible. I've edited that in."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:26:57.517",
"Id": "48910",
"ParentId": "48895",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48910",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T01:22:30.537",
"Id": "48895",
"Score": "2",
"Tags": [
"haskell",
"reinventing-the-wheel"
],
"Title": "Haskell#splitAt"
} | 48895 |
<p>I am writing a fully functional single player Connect 4 game. I am working on the second player and the while loop that tells the player who won. </p>
<p>GUI</p>
<pre><code>package lab7;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUIClass implements Runnable {
@Override
public void run() {
JFrame f = new JFrame("CSE 115 Connect 4");
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout myGrid = new GridLayout(7, 6);
JPanel panel;
panel = new JPanel();
panel.setLayout(myGrid);
f.setLayout(myGrid);
f.pack();
ArrayList<JButton> col_button = new ArrayList<JButton>();
for (Integer i = 1; i <= 7; i++)
{
JButton b = new JButton("Col " + i.toString());
col_button.add(b);
f.add(b);
}
ArrayList<ArrayList<JLabel>> col_list = new ArrayList<ArrayList<JLabel>>();
for (int i = 0; i < 7; i++)
{
col_list.add(new ArrayList<JLabel>());
}
for (int i = 0; i < 42; i++)
{
JLabel label = new JLabel(new ImageIcon("images/blank.png"));
//System.out.println(label.getIcon().toString())
col_list.get(i % 7).add(label);
f.add(label);
}
GameClass gc = new GameClass(col_list);
for (int i = 0; i < 7; i++)
{
col_button.get(i).addActionListener(new ColButton(col_list.get(i)));
}
f.pack();
}
ImageIcon whiteCircle = new ImageIcon("blank.png");
}
</code></pre>
<p>that contains all of the graphical interface behind my code, as you might have guessed I used Java and Eclipse. </p>
<p>This is my game class where my second player is going to be, and I also assume my winning loop will be here. </p>
<pre><code>import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JLabel;
public class GameClass{
public GameClass(ArrayList<ArrayList<JLabel>> col_list)
{
}
}
</code></pre>
<p>finally this is my column class which contains the 1st player and all the buttons. </p>
<pre><code>package lab7;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class ColButton implements ActionListener {
private ArrayList<JLabel> _column;
private GameClass _game;
public ColButton(ArrayList<JLabel> c)
{
_column = c;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for (int i = _column.size() - 1; i >= 0; i--)
{
JLabel l = _column.get(i);
if(l.getIcon().toString().equals("images/blank.png"))
{
l.setIcon(new ImageIcon("images/red.png"));
break;
}
}
}
}
</code></pre>
<p>What do you think? Any suggestions on how to get get going for the second part? I am working on the 2<sup>nd</sup> player but I have run into some setbacks.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T21:40:01.170",
"Id": "85848",
"Score": "0",
"body": "Great article on game loop implementation here: http://gafferongames.com/game-physics/fix-your-timestep/ Also, your question is too generic. Try doing an actual game loop implementation, and then ask a more punctual question, if you have issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T22:03:08.983",
"Id": "85849",
"Score": "0",
"body": "thanks for the article shivan dragon, I will get with it then."
}
] | [
{
"body": "<p>Typically, a Swing application would be written using a Model-View-Controller pattern to split the responsibilities:</p>\n\n<ul>\n<li>The Model would be a data structure to represent the game state. It could, for example, consist of an <code>ConnectFourBoard</code> class that holds a two-dimensional array of chips in the board.</li>\n<li>The View would be the Swing UI code</li>\n<li>The Controller acts as the glue between the Model and View. It handles actions triggered by the View, and notifies the View when the Model has changed.</li>\n</ul>\n\n<p>Here, I see View and Controller code, commingled. However, I don't see any Model code. In fact, in <code>ColButton.actionPerformed()</code>, it appears that the lack of a Model is causing you some difficulty: you're resorting to determining the model state by parsing the icon name out of the view.</p>\n\n<p>Without a Model, you are no doubt going to have a difficult time examining the model state to determine the winner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:00:05.157",
"Id": "85922",
"Score": "0",
"body": "I thought of what you said, and I decided to create a Volatile Boolean Loop and so far so good, I have not run into any trouble for now, at least. I'll show you the final product."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T01:56:45.867",
"Id": "85934",
"Score": "0",
"body": "Feel free to [post a new question with the revised code](http://meta.codereview.stackexchange.com/q/1763/9357)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:32:33.877",
"Id": "48912",
"ParentId": "48896",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48912",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T19:55:22.167",
"Id": "48896",
"Score": "4",
"Tags": [
"java",
"homework",
"swing",
"connect-four"
],
"Title": "Winning Loop Connect 4"
} | 48896 |
<p>I am running my shell script on <code>machineA</code> which copies the files from <code>machineB</code> and <code>machineC</code> to <code>machineA</code>.</p>
<p>If the file is not there in <code>machineB</code>, then it should be there in <code>machineC</code> for sure. So I will try to copy from <code>machineB</code> first, if it is not there in <code>machineB</code> then I will go to <code>machineC</code> to copy the same files. </p>
<p>In <code>machineB</code> and <code>machineC</code> there will be a folder like this <code>YYYYMMDD</code> inside this folder:</p>
<pre><code>/data/pe_t1_snapshot
</code></pre>
<p>Whatever date is the latest date in this format <code>YYYYMMDD</code> inside the above folder - I will pick that folder as the full path from where I need to start copying the files.</p>
<p>Suppose, if this is the latest date folder <code>20140317</code> inside <code>/data/pe_t1_snapshot</code>, then this will be the full path for me:</p>
<pre><code>/data/pe_t1_snapshot/20140317
</code></pre>
<p>from where I need to start copying the files in <code>machineB</code> and <code>machineC</code>. I need to copy around <code>400</code> files in <code>machineA</code> from <code>machineB</code> and <code>machineC</code> and each file size is 3.5 GB.</p>
<p>I currently have my below shell script which works fine as I am using scp, but somehow it takes ~3 hours to copy the 400 files in <code>machineA</code>.</p>
<p>Below is my shell script:</p>
<pre><code>#!/bin/bash
readonly PRIMARY=/export/home/david/dist/primary
readonly SECONDARY=/export/home/david/dist/secondary
readonly FILERS_LOCATION=(machineB machineC)
readonly MEMORY_MAPPED_LOCATION=/data/pe_t1_snapshot
PRIMARY_PARTITION=(0 3 5 7 9) # this will have more file numbers around 200
SECONDARY_PARTITION=(1 2 4 6 8) # this will have more file numbers around 200
dir1=$(ssh -o "StrictHostKeyChecking no" david@${FILERS_LOCATION[0]} ls -dt1 "$MEMORY_MAPPED_LOCATION"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | head -n1)
dir2=$(ssh -o "StrictHostKeyChecking no" david@${FILERS_LOCATION[1]} ls -dt1 "$MEMORY_MAPPED_LOCATION"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | head -n1)
echo $dir1
echo $dir2
if [ "$dir1" = "$dir2" ]
then
# delete all the files first
find "$PRIMARY" -mindepth 1 -delete
for el in "${PRIMARY_PARTITION[@]}"
do
scp -o ControlMaster=auto -o 'ControlPath=~/.ssh/control-%r@%h:%p' -o ControlPersist=900 david@${FILERS_LOCATION[0]}:$dir1/t1_weekly_1680_"$el"_200003_5.data $PRIMARY/. || scp -o ControlMaster=auto -o 'ControlPath=~/.ssh/control-%r@%h:%p' -o ControlPersist=900 david@${FILERS_LOCATION[1]}:$dir2/t1_weekly_1680_"$el"_200003_5.data $PRIMARY/.
done
# delete all the files first
find "$SECONDARY" -mindepth 1 -delete
for sl in "${SECONDARY_PARTITION[@]}"
do
scp -o ControlMaster=auto -o 'ControlPath=~/.ssh/control-%r@%h:%p' -o ControlPersist=900 david@${FILERS_LOCATION[0]}:$dir1/t1_weekly_1680_"$sl"_200003_5.data $SECONDARY/. || scp -o ControlMaster=auto -o 'ControlPath=~/.ssh/control-%r@%h:%p' -o ControlPersist=900 david@${FILERS_LOCATION[1]}:$dir2/t1_weekly_1680_"$sl"_200003_5.data $SECONDARY/.
done
fi
</code></pre>
<p>I am copying <code>PRIMARY_PARTITION</code> files in <code>PRIMARY</code> folder and <code>SECONDARY_PARTITION</code> files in <code>SECONDARY</code> folder in <code>machineA</code>.</p>
<p>Is there any way to move the files faster in <code>machineA</code>? Can I copy 10 files at a time or 5 files at a time in parallel instead of <strong>downloading all the files in parallel</strong> to speed up this process or any other approach?</p>
<p><strong>I don't want to download all the files in parallel.</strong> <code>rsync</code> is not helping me as well, I tried copying with <code>rsync</code> as well. I guess, I need to go multithreaded way, meaning copy 3 files in parallel instead of one file at a time. If those three files are done, then only move to next three files to copy it.</p>
<p>Maybe I only need to run two parallel processes, one downloading from B and one from C. Each process removes a file name from the master list, puts that file name into its own list, and tries to download it. If downloading is unsuccessful, then it puts that file name back onto the master list. The loop then repeats itself again, making sure not to try to download any file if its name is already in its own list. I simply need to run two processes which do this in parallel, one each from machine B and C.</p>
<p>Is this possible to do? If yes, then can anyone provide an example on this? I am trying to limit the number of threads, not have 400 parallel processing.</p>
<p>NOTE: <code>machineA</code> is running on SSD and has 10 gig ethernet.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:25:39.167",
"Id": "85861",
"Score": "0",
"body": "I would expect network bandwidth to be the bottleneck here. If packets from both B and C travel through the same pipe, you're unlikely to gain anything by running in parallel. Can you describe the network topology a little?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:27:01.347",
"Id": "85862",
"Score": "0",
"body": "@DavidHarkness: As far as I know, we have 10 gig network. I am not a unix guy, so not sure what other information you might need? if you can ask me specifically, then I might be able to answer or I can check with our unix admin."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:27:54.783",
"Id": "85863",
"Score": "0",
"body": "Are these machines all on the same local network? Of course, compressing the files first may shave quite a bit of time if these are simple log files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:29:03.867",
"Id": "85864",
"Score": "0",
"body": "Yeah they are all on same local network but there might be some cross datacenter file transfer as well. The files which I am transferring are memory-mapped files generated by Java program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:29:46.947",
"Id": "85865",
"Score": "0",
"body": "But I guess, that same pipe can handle three file transfer at a time, instead of one file transfer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:31:31.763",
"Id": "85866",
"Score": "0",
"body": "That's the trick with bandwidth: if you're filling the pipe to capacity with one file, doing three in parallel will take the same time at best but more likely slow the process down as the packets will cause collisions. I'm not a network guy, and there are more factors involved. It really depends on whether or not you're saturating the link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:41:33.703",
"Id": "85867",
"Score": "0",
"body": "Ignoring overhead, the best case time to send 400 * 3.5GB over 10Gbps is 18m40s. Even with compression and packet headers, 3 hours seems quite long. My guess is that the transfers are being throttled or the network is very busy already. Try running a test with several in parallel to see if the throughput improves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T18:24:19.080",
"Id": "86050",
"Score": "0",
"body": "Would using rsync here not be a much simpler solution? It would likely just handle the up-to-date detection of already existing files (those found on `machineB`) during the run against `machineC` and would allow for two ssh connections/command runs instead of 400. Just saw rsync mentioned in the OP. Which means try the parallel test that @DavidHarkness suggests. Also time how long simply creating 400+ ssh connections in your script takes without transferring any data to see what sort of overhead that has."
}
] | [
{
"body": "<p>You have already posted <a href=\"https://codereview.stackexchange.com/q/51168/12390\">another question</a> on this same topic two weeks later, with a better solution using GNU parallel.\nI'll review this one too anyway on its own merit,\nthough it might be a bit of a moot point.</p>\n\n<hr>\n\n<p>It's not a good idea to set <code>StrictHostKeyChecking=no</code> when using <code>ssh</code>.\nThe host key of servers should normally not change.\nWhen they do, and you don't know why,\nit might be a man in the middle attack.\nIf it's part of a scheduled server update,\nyou can manually update the <code>~/.ssh/known_hosts</code> file accordingly.</p>\n\n<hr>\n\n<p>When filtering the output of <code>ls</code> like this:</p>\n\n<blockquote>\n<pre><code>ls -dt1 path | head -n1\n</code></pre>\n</blockquote>\n\n<p>you don't need the <code>-1</code> flag.\nThe purpose of that flag is to print the list of files in a single column.\nBut when you pipe the output to another command,\nthe output will be always a single column.</p>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>if [ \"$dir1\" = \"$dir2\" ]\n</code></pre>\n</blockquote>\n\n<p>This is easier (because you don't need to quote the variables) and more modern:</p>\n\n<pre><code>if [[ $dir1 = $dir2 ]]\n</code></pre>\n\n<hr>\n\n<p>Instead of cramming so many <code>ssh</code> options on the command line:</p>\n\n<pre><code>scp -o ControlMaster=auto -o 'ControlPath=~/.ssh/control-%r@%h:%p' -o ControlPersist=900 david@machineA:...\n</code></pre>\n\n<p>it's better to add these options in the <code>~/.ssh/config</code> file, like this:</p>\n\n<pre><code>Host machineA\nHostname machineA\nUser david\nControlMaster auto\nControlPath ~/.ssh/control-%r@%h:%p\nControlPersist 900\n</code></pre>\n\n<p>This way the <code>scp</code> command becomes simply:</p>\n\n<pre><code>scp machineA:...\n</code></pre>\n\n<hr>\n\n<p>I hope this (and even more, <a href=\"https://codereview.stackexchange.com/a/64448/12390\">my other answer</a>) helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-04T20:28:59.140",
"Id": "64745",
"ParentId": "48898",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "64745",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T02:47:10.980",
"Id": "48898",
"Score": "6",
"Tags": [
"optimization",
"bash",
"file-system",
"linux",
"network-file-transfer"
],
"Title": "Copying files as fast as possible"
} | 48898 |
<p>I wrote this code, but it feels like it could be a bit more elegant:</p>
<h2>Relevant code only:</h2>
<pre><code>GameObject newBall;
GameObject pathBall;
if (tag.Equals(pathBallTagName))
{
newBall = other.gameObject;
pathBall = gameObject;
}
else
{
newBall = gameObject;
pathBall = other.gameObject;
}
</code></pre>
<h2>Entire .cs file:</h2>
<pre><code>using UnityEngine;
using System.Collections;
using BallDelegate;
public class BallCollider : MonoBehaviour {
public Spline mySpline;
private SplineController mySplineController;
public AllBallManager abm;
public string pathBallTagName = "PathBalls";
public string ballTagEnd = "Balls";
public BoxCollider front;
public BoxCollider back;
public BoxCollider spawnArea;
public string frontName = "BallBox Front";
public string backName = "BallBox Back";
public bool isInSpawn = true;
void Start() {
mySplineController = GetComponent<SplineController> ();
BoxCollider[] frontBack = GetComponentsInChildren<BoxCollider> ();
foreach (BoxCollider bc in frontBack)
if (bc != null) {
if (bc.name.Equals (frontName))
front = bc;
else if (bc != null && bc.name.Equals (backName))
back = bc;
}
}
void OnTriggerEnter(Collider other) {
if (mySplineController)
{
mySplineController.go = true;
if (mySpline)
mySplineController.gravSpline = mySplineController.currentSpline = mySpline;
}
if (other == spawnArea) {
isInSpawn = true;
}
else if (!isInSpawn) {
BallDelegateCS bd = other.gameObject.GetComponent<BallDelegateCS>();
if (bd) // only balls, no other game objects
{
GameObject newBall;
GameObject pathBall;
if (tag.Equals(pathBallTagName))
{
newBall = other.gameObject;
pathBall = gameObject;
}
else
{
newBall = gameObject;
pathBall = other.gameObject;
}
while (newBall.transform.parent)
newBall = newBall.transform.parent.gameObject; // make sure we don't get BallBall
abm.MakeWayFor(newBall, pathBall);
}
}
}
void OnTriggerExit(Collider other) {
if (other == spawnArea) {
isInSpawn = false;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:04:31.070",
"Id": "85875",
"Score": "0",
"body": "The code is not complete and it misses some important elements. To me it looks clean. The only improvement that I can suggest is to use an enum instead of a magic string in if condition and if you are planning to use a string you can specify if this comparison is case insensitive."
}
] | [
{
"body": "<p>One alternative, note how we <em>must</em> store the bool result to ensure identical semantics (otherwise you risk calling tag.Equals twice... which in addition to performance considerations might change its result between calls or have side effects!)</p>\n\n<pre><code>bool swap = tag.Equals(pathBallTagName);\nGameObject newBall = swap ? other.gameObject : gameObject;\nGameObject pathBall = swap ? gameObject : other.gameObject;\n</code></pre>\n\n<p>Alternatively one could implement a Swap function elsewhere:</p>\n\n<pre><code>GameObject newBall = other.gameObject;\nGameObject pathBall = gameObject;\nif (tag.Equals(pathBallTagName)) Swap (ref newBall, ref pathBall);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T11:32:33.937",
"Id": "48920",
"ParentId": "48899",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T03:49:20.080",
"Id": "48899",
"Score": "4",
"Tags": [
"c#",
"optimization"
],
"Title": "Is there a better way to assign two variable to two others conditionally?"
} | 48899 |
<p>It looks like it should be shortened but I can't see how.</p>
<p>I have my methods <= 5 lines but that's as far as I got:</p>
<pre><code>def check_lines
if horizontal?(@player) || vertical?(@player) || diagonal?(@player)
@win=@player
end
end
def horizontal?(player)
((@squares[0] == player) && (@squares[1] == player) && (@squares[2] == player)) ||
((@squares[3] == player) && (@squares[4] == player) && (@squares[5] == player)) ||
((@squares[6] == player) && (@squares[7] == player) && (@squares[8] == player))
end
def vertical?(player)
((@squares[0] == player) && (@squares[3] == player) && (@squares[6] == player)) ||
((@squares[1] == player) && (@squares[4] == player) && (@squares[7] == player)) ||
((@squares[2] == player) && (@squares[5] == player) && (@squares[8] == player))
end
def diagonal?(player)
((@squares[0] == player) && (@squares[4] == player) && (@squares[8] == player)) ||
((@squares[2] == player) && (@squares[4] == player) && (@squares[6] == player))
end
</code></pre>
| [] | [
{
"body": "<p>When all of your code is the same, just with different numbers, you want to use data-directed programming.</p>\n\n<pre><code>WINS = [\n [0, 1, 2], [3, 4, 5], [6, 7, 8], # <-- Horizontal wins\n [0, 3, 6], [1, 4, 7], [2, 5, 8], # <-- Vertical wins\n [0, 4, 8], [2, 4, 6], # <-- Diagonal wins\n]\n\ndef check_lines\n if WINS.any? { |line| line.all? { |square| @squares[square] == @player } }\n @win = @player\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T05:31:14.927",
"Id": "48905",
"ParentId": "48902",
"Score": "12"
}
},
{
"body": "<p><strong>[Edit:</strong> a couple of days ago an anonymous user proposed an edit that was rejected by two members, both on the grounds that \"the edit deviates from the original intent of the post.\" While I'm sure those members had good intentions, neither appears to have experience with Ruby, so I don't understand how they were able to arrive at that conclusion.</p>\n\n<p>The anonymous user was not just improving my code, he or she was correcting an error I made. It was a good catch and a good fix. I've edited to incorporate the fix (and made a few other small changes).</p>\n\n<p>If you are that anonymous user, please accept my thanks. A small suggestion: it probably would have been better if you had just left a comment, but the main thing is that the code is now fixed. (I hope.)<strong>]</strong></p>\n\n<hr>\n\n<p>You can also use Ruby's <a href=\"http://www.ruby-doc.org/stdlib-2.1.1/libdoc/matrix/rdoc/Matrix.html\" rel=\"nofollow\">Matrix</a> and <a href=\"http://ruby-doc.org/stdlib-2.2.0/libdoc/matrix/rdoc/Vector.html\" rel=\"nofollow\">Vector</a> classes to see if player <code>p</code> wins. In the following, <code>square[i][j]</code> is the player in row <code>i</code>, column <code>j</code>. </p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>require 'matrix'\n\ndef win?(square,p)\n n = square.size\n m = Matrix[*square]\n pvec = Matrix.build(1,n){p}.row(0)\n m.row_vectors.any? { |r| r == pvec } ||\n m.column_vectors.any? { |c| c == pvec } ||\n Vector[*m.each(:diagonal).to_a] == pvec ||\n n.times.all? { |i| square[i][n-i-1] == p }\nend\n</code></pre>\n\n<p><strong>Example</strong></p>\n\n<pre><code>square = [[1,3,2],\n [4,2,6],\n [2,8,9]]\n\nwin?(square, 2) #=> true\nwin?([[1,3,2],[4,3,6],[2,3,9]], 3) #=> true\nwin?([[1,3,2],[3,3,3],[2,7,9]], 3) #=> true\nwin?([[1,3,2],[4,5,6],[7,8,9]], 1) #=> false\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<pre><code>pvec = Matrix.build(1,n){p}.row(0)\n</code></pre>\n\n<p>creates a vector for which every element is the value of the player argument <code>p</code> (e.g., <code>pvec # => Vector[2,2,2]</code>).</p>\n\n<pre><code>m.row_vectors.any? { |r| r == pvec }\n</code></pre>\n\n<p>determines if player <code>p</code> wins in any row,</p>\n\n<pre><code>m.column_vectors.any? { |c| c == pvec }\n</code></pre>\n\n<p>determines if player <code>p</code> wins in any column,</p>\n\n<pre><code>Vector[*m.each(:diagonal).to_a] == pvec\n</code></pre>\n\n<p>determines if player <code>p</code> wins on the main diagonal, and</p>\n\n<pre><code>(0...n).all? { |i| square[i][n-i-1] == p }\n</code></pre>\n\n<p>determines if player <code>p</code> wins on the minor diagonal (top right to bottom left).</p>\n\n<p>I was unable to find a way to check the minor diagonal using <code>Matrix</code> class methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T07:03:41.570",
"Id": "86126",
"Score": "0",
"body": "I wouldn't advise the OP to use this for a simple tic-tac-toe game, but it's interesting to show the capabilities of `Matrix` nonetheless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-08T04:21:46.793",
"Id": "168907",
"Score": "0",
"body": "@MannyMeng: a couple of days ago you rejected an edit proposed by \"an anonymous user\". If you have access to that user's SO name, please let me know, as I'd like to thank him or her."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T06:07:42.943",
"Id": "48960",
"ParentId": "48902",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T04:21:19.593",
"Id": "48902",
"Score": "7",
"Tags": [
"ruby",
"tic-tac-toe"
],
"Title": "Checking for a win in TicTacToe"
} | 48902 |
<p>I'm working through learning Go, so as an exercise, I'm writing a simple raytracer. I'd like general feedback on the code style & architecture. Specific areas of concern:</p>
<ul>
<li>Is the project layout reasonable?</li>
<li>Are my types and interfaces clear, and the right types/interfaces to be using? </li>
<li>should the receiver of a function typically be named something like this, self, or other? is it important to be consistent with this across different source files?</li>
<li>transformation.Inverse computes cofactors() twice, once through Det, and once for itself. avoiding this seems to come at the cost of duplicating Det's code inside Inverse. is there a clean way to avoid this?</li>
<li>with Sphere & Spatial Object, the idea was, I'm going to implement multiple geographic primitives, that just differ in how intersections are calculated. They all have the common data components of Transform. I want InverseTransform cached on them, since it's expensive to calculate, at least in theory.</li>
</ul>
<p>The project is currently about 500 lines of code, including tests, so I've abbreviated in places.</p>
<p>render_scene.go:</p>
<pre><code>package main
import (
"image"
"image/color"
"image/png"
"log"
"math"
"os"
"pathtrace/spatial_object"
"pathtrace/transformation"
"pathtrace/vector"
)
func find_first_hit(ray vector.Ray, scene []spatial_object.Hittable) (did_hit bool, intersection spatial_object.Intersection) {
did_hit = false
best_distance := math.Inf(1)
for _, obj := range scene {
this_hit, this_inter := obj.Hit(ray)
if this_hit && this_inter.T < best_distance {
best_distance = this_inter.T
intersection = this_inter
did_hit = true
}
}
return
}
func main() {
scene := []spatial_object.Hittable{
spatial_object.Sphere(spatial_object.New(transformation.Translation(vector.NewVector(0, 0, 0)))),
spatial_object.Sphere(spatial_object.New(transformation.Translation(vector.NewVector(2.5, 0, 0)))),
spatial_object.Sphere(spatial_object.New(transformation.Translation(vector.NewVector(-0.5, 0.5, 1)))),
}
//set up the view stuff
size := image.Rect(0, 0, 640, 480)
eye_pos := vector.NewPoint(0, 0, -4)
eye_up := vector.NewVector(0, 1, 0)
eye_right := vector.NewVector(1, 0, 0)
eye_forward := vector.NewVector(0, 0, 1)
view_angle := math.Pi / 2
dist := 0.5
h := dist * math.Tan(view_angle/2)
w := h * float64(size.Max.X) / float64(size.Max.Y)
img := image.NewNRGBA(size)
background_color := color.NRGBA{0, 0, 0xFF, 0xFF}
light_dir := vector.NewVector(0, 1, 0)
for y := size.Min.Y; y < size.Max.Y; y++ {
for x := size.Min.X; x < size.Max.X; x++ {
up_component := eye_up.Multiply(h * (1.0 - (2.0 * float64(y) / float64(size.Max.Y))))
right_component := eye_right.Multiply(w * ((2.0 * float64(x) / float64(size.Max.X)) - 1.0))
forward_component := eye_forward.Multiply(dist)
dir := forward_component.Add(up_component).Add(right_component)
ray := vector.Ray{eye_pos, dir}
did_hit, inter := find_first_hit(ray, scene)
if did_hit {
diffuse_intensity := light_dir.Dot(inter.Normal) / (light_dir.Magnitude() * inter.Normal.Magnitude())
diffuse_intensity = math.Max(0, diffuse_intensity)
shaded_green := color.NRGBA{0, uint8(255 * diffuse_intensity), 0, 0xFF}
img.Set(x, y, shaded_green)
} else {
img.Set(x, y, background_color)
}
}
}
outfile, err := os.Create("test.png")
if err != nil {
log.Fatal(err)
}
png.Encode(outfile, img)
}
</code></pre>
<p>transformation/transformation.go</p>
<pre><code>//a Transformation is a 4x4 matrix, which represents a linear transformation of a point
//in addition to some standard matrix operations, constructors from typical transformations such as Translation, Scale, Rotation, and Shear are provided.
package transformation
import "pathtrace/vector"
//hold the actual matrix in a 1-dimensional array, for efficiency.
type Transformation [4 * 4]float64
func Translation(t vector.Vector) Transformation {
return Transformation{
1, 0, 0, t[0],
0, 1, 0, t[1],
0, 0, 1, t[2],
0, 0, 0, 1}
}
...
var Identity = Transformation {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1}
//rotate by r[0] radians aronud x, then r[1] radians aronud y, then r[2] radians around z
//func Rotation (r vector.Vector) Transformation {
//todo
//}
func (self Transformation) Multiply(other Transformation) Transformation {
//just writing out the multiplication inline.
//this should whole thing really should be done in an existing library
...
}
func (self Transformation) MultiplyVec(vec vector.Vector) vector.Vector{
return vector.Vector{
self[ 0]*vec[0] + self[ 1]*vec[1] + self[ 2]*vec[2] + self[ 3]*vec[3],
self[ 4]*vec[0] + self[ 5]*vec[1] + self[ 6]*vec[2] + self[ 7]*vec[3],
self[ 8]*vec[0] + self[ 9]*vec[1] + self[10]*vec[2] + self[11]*vec[3],
self[12]*vec[0] + self[13]*vec[1] + self[14]*vec[2] + self[15]*vec[3]}
}
//internal use. compute the cofactors of the matrix
//we return a list of float64 instead of a transform, because it's not really a transform
func (t Transformation) cofactors() [16]float64 {
...
}
func (t Transformation) Det() float64 {
cf := t.cofactors()
return t[0]*cf[0] + t[1]*cf[1] + t[2]*cf[2] + t[3]*cf[3]
}
func (t Transformation) Inverse() (result Transformation) {
d := t.Det()
cf := t.cofactors()
for i, v := range cf {
//result, transposed, is cofactor / determinite
result[(i%4)*4+i/4] = v / d
}
return
}
</code></pre>
<p>transformation/transformation_test.go:</p>
<pre><code>package transformation
import (
"math"
"testing"
)
func TestMultiply(t *testing.T) {
a := Transformation{
8, 7, 2, 1,
9, 4, 33, 8,
1, 5, 0, -2,
7, 5, 4, 22}
b := Transformation{
18, 6, 66, 0,
-3, -7, 8, 89,
1, 2, 3, 4,
5, 6, 7, 8}
expected := Transformation{
130, 9, 597, 639,
223, 140, 781, 552,
-7, -41, 92, 429,
225, 147, 668, 637}
if a.Multiply(b) != expected {
t.Errorf("expected %v, but got %v\n", expected, a.Multiply(b))
}
}
....
</code></pre>
<p>vector/vector.go</p>
<pre><code>package vector
import "math"
//homogenous coordinates 4-tuple.
//a purely directional vector is {x,y,z,0}
//a point in space is {x,y,z,1}
//for now, we'll treat a Point exactly as if it's a vector
type Vector [4]float64
func NewVector(x, y, z float64) Vector {
return Vector{x, y, z, 0}
}
func NewPoint(x, y, z float64) Vector {
return Vector{x, y, z, 1}
}
type Ray struct {
Position, Direction Vector
}
func (v Vector) MagnitudeSquared() float64 {
return v.Dot(v)
}
...etc
func (r Ray) PositionAt(t float64) (position Vector) {
return r.Position.Add(r.Direction.Multiply(t))
}
</code></pre>
<p>spatial_object/spatial_object.go:</p>
<pre><code>package spatial_object
import (
"math"
"pathtrace/transformation"
"pathtrace/vector"
)
type Hittable interface {
Hit(vector.Ray) (did_hit bool, intersection Intersection)
}
type SpatialObject struct {
Transform, InverseTransform transformation.Transformation
}
func New(transform transformation.Transformation) SpatialObject {
inverse := transform.Inverse()
return SpatialObject{transform, inverse}
}
type Sphere SpatialObject
type Intersection struct {
T float64
Position vector.Vector
Normal vector.Vector
}
func (s Sphere) Hit(ray vector.Ray) (did_hit bool, intersection Intersection) {
pos := s.InverseTransform.MultiplyVec(ray.Position)
dir := s.InverseTransform.MultiplyVec(ray.Direction)
transformed_ray := vector.Ray{pos, dir}
//a transformed ray hits the generic sphere at time t if |position+dir*t|^2 = 1
//this expands to |dir|^2*t^2 + 2*(position dot dir)*t + (|position+^2) - 1 = 0
//which is a quadratic equation over t. we solve for f(t)=0.
a := dir.MagnitudeSquared()
b := pos.Dot(dir)
c := pos.MagnitudeSquared() - 1
discrim := math.Pow(b, 2) - a*c
if discrim < 0 {
return false, Intersection{}
}
//discrim / a must be positive, so t1 <= t2
t1 := -b/a - math.Sqrt(discrim)/a
t2 := -b/a + math.Sqrt(discrim)/a
var hit_t float64
if t1 >= 0 {
hit_t = t1
} else if t2 >= 0 {
hit_t = t2
} else {
return false, Intersection{}
}
hit_point := ray.PositionAt(hit_t)
hit_normal := transformed_ray.PositionAt(hit_t)
hit_normal[3] = 0 //make it a vector
return true, Intersection{hit_t, hit_point, hit_normal}
}
</code></pre>
<p>spatial_object/spatial_object_test.go not shown.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T04:55:44.113",
"Id": "48903",
"Score": "4",
"Tags": [
"beginner",
"image",
"go",
"graphics",
"raytracing"
],
"Title": "Does this go raytracing program follow best practices, and typical project layout?"
} | 48903 |
<p><a href="http://en.wikipedia.org/wiki/Ray_tracing_%28graphics%29" rel="nofollow">Ray tracing</a> is a physics-based method for simulating photorealistic 3D scenes. Light rays are drawn from the eye through each pixel of the desired image, and the rays' interactions with the scene determine the displayed pixel color.</p>
<p>It is capable, among other visual effects, to simulate light scattering, reflection, dispersion and refraction with more reaslistically than most of the other graphics rendering methods.</p>
<p>Related tags:</p>
<ul>
<li><a href="/questions/tagged/computational-geometry" class="post-tag" title="show questions tagged 'computational-geometry'" rel="tag">computational-geometry</a></li>
<li><a href="/questions/tagged/graphics" class="post-tag" title="show questions tagged 'graphics'" rel="tag">graphics</a></li>
<li><a href="/questions/tagged/image" class="post-tag" title="show questions tagged 'image'" rel="tag">image</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T05:42:11.140",
"Id": "48906",
"Score": "0",
"Tags": null,
"Title": null
} | 48906 |
Ray tracing is a physics-based method for simulating photorealistic 3D scenes. Light rays are drawn from the eye through each pixel of the desired image, and the rays' interactions with the scene determine the displayed pixel color. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T05:42:11.140",
"Id": "48907",
"Score": "0",
"Tags": null,
"Title": null
} | 48907 |
<p>This little program was written for an assignment in a data structures and algorithms class. I'll just note the basic requirements:</p>
<blockquote>
<p>Given an inputted string, the program should check to see if it exists
in a dictionary of correctly spelled words. If not, it should return a
list of words that are obtainable by:</p>
<ul>
<li>adding any character to the beginning or end of the inputted string</li>
<li>removing any single character from the inputted string</li>
<li>swapping any two adjacent characters in the string</li>
</ul>
</blockquote>
<p>The primary data structure is embodied in the <code>Dictionary</code> class, which is my implementation of a separately-chaining hash list, and the important algorithms are found in the <code>charAppended()</code>, <code>charMissing()</code> and <code>charsSwapped()</code> methods. </p>
<p>Everything works as expected - I'm just looking for tips about anything that can be done more cleanly, efficiently or better aligned with best practices.</p>
<p><strong>SpellCheck.java</strong></p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class SpellCheck {
private Dictionary dict;
final static String filePath = "d:/desktop/words.txt";
final static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
SpellCheck() {
dict = new Dictionary();
dict.build(filePath);
}
void run() {
Scanner scan = new Scanner(System.in);
boolean done = false;
String input;
while (true) {
System.out.print("\n-------Enter a word: ");
input = scan.nextLine();
if (input.equals("")) {
break;
}
if (dict.contains(input)) {
System.out.println("\n" + input + " is spelled correctly");
} else {
System.out.print("is not spelled correctly, ");
System.out.println(printSuggestions(input));
}
}
}
String printSuggestions(String input) {
StringBuilder sb = new StringBuilder();
ArrayList<String> print = makeSuggestions(input);
if (print.size() == 0) {
return "and I have no idea what word you could mean.\n";
}
sb.append("perhaps you meant:\n");
for (String s : print) {
sb.append("\n -" + s);
}
return sb.toString();
}
private ArrayList<String> makeSuggestions(String input) {
ArrayList<String> toReturn = new ArrayList<>();
toReturn.addAll(charAppended(input));
toReturn.addAll(charMissing(input));
toReturn.addAll(charsSwapped(input));
return toReturn;
}
private ArrayList<String> charAppended(String input) {
ArrayList<String> toReturn = new ArrayList<>();
for (char c : alphabet) {
String atFront = c + input;
String atBack = input + c;
if (dict.contains(atFront)) {
toReturn.add(atFront);
}
if (dict.contains(atBack)) {
toReturn.add(atBack);
}
}
return toReturn;
}
private ArrayList<String> charMissing(String input) {
ArrayList<String> toReturn = new ArrayList<>();
int len = input.length() - 1;
//try removing char from the front
if (dict.contains(input.substring(1))) {
toReturn.add(input.substring(1));
}
for (int i = 1; i < len; i++) {
//try removing each char between (not including) the first and last
String working = input.substring(0, i);
working = working.concat(input.substring((i + 1), input.length()));
if (dict.contains(working)) {
toReturn.add(working);
}
}
if (dict.contains(input.substring(0, len))) {
toReturn.add(input.substring(0, len));
}
return toReturn;
}
private ArrayList<String> charsSwapped(String input) {
ArrayList<String> toReturn = new ArrayList<>();
for (int i = 0; i < input.length() - 1; i++) {
String working = input.substring(0, i);// System.out.println(" 0:" + working);
working = working + input.charAt(i + 1); //System.out.println(" 1:" + working);
working = working + input.charAt(i); //System.out.println(" 2:" + working);
working = working.concat(input.substring((i + 2)));//System.out.println(" FIN:" + working);
if (dict.contains(working)) {
toReturn.add(working);
}
}
return toReturn;
}
public static void main(String[] args) {
SpellCheck sc = new SpellCheck();
sc.run();
}
}
</code></pre>
<p><strong>Dictionary.java</strong></p>
<pre><code>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Dictionary {
private int M = 1319; //prime number
final private Bucket[] array;
public Dictionary() {
this.M = M;
array = new Bucket[M];
for (int i = 0; i < M; i++) {
array[i] = new Bucket();
}
}
private int hash(String key) {
return (key.hashCode() & 0x7fffffff) % M;
}
//call hash() to decide which bucket to put it in, do it.
public void add(String key) {
array[hash(key)].put(key);
}
//call hash() to find what bucket it's in, get it from that bucket.
public boolean contains(String input) {
input = input.toLowerCase();
return array[hash(input)].get(input);
}
public void build(String filePath) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
add(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
//this method is used in my unit tests
public String[] getRandomEntries(int num){
String[] toRet = new String[num];
for (int i = 0; i < num; i++){
//pick a random bucket, go out a random number
Node n = array[(int)Math.random()*M].first;
int rand = (int)Math.random()*(int)Math.sqrt(num);
for(int j = 0; j<rand && n.next!= null; j++) n = n.next;
toRet[i]=n.word;
}
return toRet;
}
class Bucket {
private Node first;
public boolean get(String in) { //return key true if key exists
Node next = first;
while (next != null) {
if (next.word.equals(in)) {
return true;
}
next = next.next;
}
return false;
}
public void put(String key) {
for (Node curr = first; curr != null; curr = curr.next) {
if (key.equals(curr.word)) {
return; //search hit: return
}
}
first = new Node(key, first); //search miss: add new node
}
class Node {
String word;
Node next;
public Node(String key, Node next) {
this.word = key;
this.next = next;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-23T13:17:20.880",
"Id": "142047",
"Score": "0",
"body": "I suggest you to replace the LinkedList with TernarySearchTries for dictionary skeleton."
}
] | [
{
"body": "<p>Other than in the Bucket.get() method, you can replace the while loop with a for loop like in put(), it looks good! You might want to combine Dictionary.printSuggestions() and Dictionary.makeSuggestions() because that was a little weird. But if you want to be super OO, then good for you!</p>\n\n<p>If this is for a class, you can look like a pro by replacing:</p>\n\n<pre><code>System.out.println(\"\\n\" + input + \" is spelled correctly\");\n</code></pre>\n\n<p>with</p>\n\n<pre><code>System.out.println(new StringBuffer(1 + input.length() + \" is spelled correctly\".length).append(\"\\n\").append(input).append(\" is spelled correctly\").toString());\n</code></pre>\n\n<p>Also if you have an if statement or while or for or whatever, you can use no brackets if there is only one thing inside it. For example:</p>\n\n<pre><code>for (Node curr = first; curr != null; curr = curr.next) {\n if (key.equals(curr.word)) {\n return; //search hit: return\n }\n}\n</code></pre>\n\n<p>Can be replaced by:</p>\n\n<pre><code>for(Node curr = first; curr != null; curr = curr.next)\n if(key.equals(curr.word))\n return; //search hit: return\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:46:55.753",
"Id": "85870",
"Score": "3",
"body": "-1 Using braces consistently helps avoid errors when adding a line to a one-line block later, and replacing an implicit `StringBuilder` (fine for such a short message) with an explicit `StringBuffer` (why the thread-safe version?) is error-prone and completely overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:56:34.287",
"Id": "85871",
"Score": "0",
"body": "@DavidHarkness - I have the same opinion about using braces. Occasionally, in cases where it seems obvious that additional lines will never be added, I will go without braces. In those cases, I tend to place the line inline with the loop: `for (; ; ;) foo()`, to avoid the sort of bugs you mentioned (which can be doozies to catch). Would you caution me against this practice as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:05:51.920",
"Id": "85877",
"Score": "0",
"body": "@DavidHarkness Also, I generally have the same approach to braces around conditional blocks. I'm assuming whatever your answer is about this approach to braces with `for` loops would be the same with those, but I'm curious: Is there any reason it would be different?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:06:53.223",
"Id": "85878",
"Score": "2",
"body": "@Czipperz - down-votes aside, I appreciate your answer and the input it has generated here. Please leave it up!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:11:10.737",
"Id": "85879",
"Score": "2",
"body": "@drewmore I did that once in a Java project for throwing exceptions from guard clauses because the editor would keep these on a single line. However, that requires that everyone uses a tool to enforce this. If not, it's only a matter of time until someone breaks it. I've learned not to care about the wasted space over time and *always* use braces on *every* block: `for`, `while`, `if`, etc. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:32:38.207",
"Id": "48911",
"ParentId": "48908",
"Score": "-3"
}
},
{
"body": "<p><strong>General</strong></p>\n\n<p>Many of the variable names lack meaning and are inconsistent. I cover some of them specifically below, but for example <code>print</code> is not a good choice for a list of suggestions--even though you intend to print them. Instead, <code>suggestions</code> clearly identifies what the list holds.</p>\n\n<p>Learn to use JavaDoc for documenting public classes and methods. Not only is it nicer to read than one-liners, developing this habit early will demonstrate your goal to become a professional engineer (if that's the case).</p>\n\n<pre><code>/**\n * Adds the key to this dictionary if not already present.\n *\n * @param key hash determines the bucket to receive it\n */\npublic void add(String key) { ... }\n\n/**\n * Determines if the key is present in this dictionary.\n *\n * @param key hash determines the bucket to search\n * @return true if key is present\n */\npublic boolean contains(String input) { ... }\n</code></pre>\n\n<p><strong>SpellCheck</strong></p>\n\n<p>You make a good effort at breaking up the methods and separating concerns, but I would take it a step further. The methods that build alternate spellings should not be responsible for checking the dictionary. Instead, combine all misspellings into a single list and search the dictionary in one place. This also allows you to remove duplicates and avoid wasted lookups.</p>\n\n<p>I would also completely separate all output, possibly to a new UI class to allow reuse. You did pretty well here, but <code>printSuggestions</code> should receive the list of suggestions instead of calling <code>makeSuggestions</code> itself.</p>\n\n<pre><code> private void printStatusAndSuggestions(String input) {\n System.out.println();\n System.out.print(input);\n if (dict.contains(input) {\n System.out.println(\" is spelled correctly.\");\n } else {\n System.out.print(\" is not spelled correctly,\");\n printSuggestions(suggest(input));\n }\n }\n\n private void printSuggestions(Set<String> suggestions) {\n if (suggestions.isEmpty()) {\n System.out.println(\" and I have no idea what word you could mean.\"\n } else {\n ... print them ...\n }\n }\n\n private Set<String> suggest(String input) {\n Set<String> suggestions = new HashSet<>();\n Set<String> alternates = makeAlternates(input);\n for (String alternate : alternates) {\n if (dict.contains(alternate) {\n suggestions.add(alternate);\n }\n }\n return suggestions;\n }\n</code></pre>\n\n<p>If <code>Dictionary</code> implemented the <code>Set</code> interface, you could use the built-in intersection method to do the lookups for you.</p>\n\n<pre><code>private Set<String> suggest(String input) {\n return makeAlternates(input).retainAll(dict);\n}\n</code></pre>\n\n<ul>\n<li><p><code>input.equals(\"\")</code> is better expressed as <code>input.isEmpty()</code>. You may want to trim the input to remove leading/trailing spaces: <code>input = scan.nextLine().trim();</code></p></li>\n<li><p>This applies similarly to <code>ArrayList</code>: <code>print.isEmpty()</code> instead of <code>print.size() == 0</code>.</p></li>\n<li><p><code>pringSuggestions</code> creates a <code>StringBuilder</code> needlessly when there are no suggestions.</p></li>\n<li><p>You use two different methods of concatenating strings when building suggestions: an implicit <code>StringBuilder</code> and <code>String.concat</code>. Both are fine in different circumstances (though I confess that I've never used the latter), but make sure you combine all the concatenations in one statement. Breaking them across statements uses a new builder for each statement. <code>charsSwapped</code> is especially egregious requiring three for each suggestion instead of one.</p>\n\n<pre><code>String working = input.substring(0, i)\n + input.charAt(i + 1);\n + input.charAt(i);\n + input.substring(i + 2);\n</code></pre></li>\n</ul>\n\n<p><strong>Dictionary</strong></p>\n\n<ul>\n<li><p>Turn <code>M</code> into a constant. As it stands, you're initializing the field to <code>1319</code> and then reassigning it to itself in the constructor. Perhaps <code>BUCKET_COUNT</code> is a better name.</p>\n\n<p>Alternatively, add a constructor that takes the value as a parameter. While we're at it, how about <code>buckets</code> in place of the very generic name <code>array</code>? It's rarely a good idea to name a primitive variable based solely on its type.</p>\n\n<pre><code>public static final int DEFAULT_BUCKET_COUNT = 1319;\n\nprivate final bucketCount;\nprivate final Bucket[] buckets;\n\npublic Dictionary() {\n this(DEFAULT_BUCKET_COUNT);\n}\n\npublic Dictionary(int bucketCount) {\n this.bucketCount = bucketCount;\n ... create empty buckets ...\n}\n</code></pre></li>\n</ul>\n\n<p><strong>Bucket/Node</strong></p>\n\n<ul>\n<li><p>Both of these can be static since they don't access the outer classes' members.</p></li>\n<li><p>You don't really need <code>Bucket</code> and may consider rewriting the code to remove it to see the difference. It's not a huge improvement but may simplify the code.</p></li>\n<li><p>As with <code>Dictionary</code>, <code>add</code> and <code>contains</code> make more sense than <code>put</code> and <code>get</code>.</p></li>\n<li><p>Be consistent with naming across methods. In <code>Bucket</code>, <code>get</code> takes <code>in</code> while <code>put</code> takes <code>key</code>, but <code>in</code> and <code>key</code> represent the same things and as such should use the same name: <code>key</code>. Also, stick with <code>curr</code> to avoid confusion with <code>Node.next</code>.</p></li>\n<li><p>@Czippers nailed this one: <code>get</code> and <code>put</code> should use the same looping construct since they're both walking the list in order and possibly stopping at some point.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T08:40:54.793",
"Id": "48914",
"ParentId": "48908",
"Score": "13"
}
},
{
"body": "<ol>\n<li>Take a wrongly spelled word as input.</li>\n<li>Store the list of English words along with their frequencies in a text file. I have used <a href=\"http://norvig.com/google-books-common-words.txt\" rel=\"nofollow noreferrer\">this</a> text file from Norvig’s post.</li>\n<li>Insert all the available English words(stored in the text file) along with their frequencies (<em>measure of how frequently a word is used in English language</em>) in a Ternary Search Tree.</li>\n<li>Now traverse along the Ternary Search Tree\n\n<ul>\n<li>For each word encountered in the Ternary Search Tree, calculate its Levenshtein Distance from the wrongly spelled word.</li>\n<li>if Levenshtein Distance <= 3, store the word in a Priority Queue.</li>\n<li>If two words have same edit distance, the one with higher frequency is grater.\n\n<ol start=\"5\">\n<li>Print the top 10 items from Priority Queue.</li>\n</ol></li>\n</ul></li>\n</ol>\n\n<p>You can see the whole code on <a href=\"http://github.com/amarjeetanandsingh/spell_correct\" rel=\"nofollow noreferrer\">github</a>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-10T16:43:46.007",
"Id": "293314",
"Score": "0",
"body": "I really want to thank you, this answer is way better than the previous one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-26T04:04:05.183",
"Id": "365373",
"Score": "0",
"body": "I don't think this solution answers the question at all. This is arguably a better spell check method, but not the one that the problem was trying to solve."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-10T16:41:29.747",
"Id": "155032",
"ParentId": "48908",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48914",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T05:46:21.663",
"Id": "48908",
"Score": "19",
"Tags": [
"java",
"algorithm",
"homework",
"hash-map"
],
"Title": "Java implementation of spell-checking algorithm"
} | 48908 |
<p>Up for review today is some C++11 code to recursively search a maze for a path to a specified goal. This one shows dead-ends it explored on the way to finding the solution.</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
enum { GOAL = '*', SPACE = ' ', WALL = '#', TRIED = '!', USED = '+' };
class maze {
std::vector<std::string> data;
public:
char &operator()(size_t x, size_t y) {
return data[y][x];
}
friend std::istream &operator>>(std::istream &is, maze &m) {
std::string temp;
while (std::getline(is, temp))
m.data.push_back(temp);
return is;
}
friend std::ostream &operator<<(std::ostream &os, maze const &m) {
for (auto const &s : m.data)
os << s << '\n';
return os;
}
size_t y_dim() { return data.size(); }
size_t x_dim() { return data[0].size(); }
};
bool solve(maze &m, size_t x = 0, size_t y=0) {
if (x < 0 || y < 0 || x >= m.x_dim() || y >= m.y_dim())
return false;
if (m(x, y) == GOAL)
return true;
if (m(x, y) != SPACE)
return false;
m(x, y) = USED;
bool solved
= solve(m, x - 1, y)
|| solve(m, x + 1, y)
|| solve(m, x, y - 1)
|| solve(m, x, y + 1);
if (!solved)
m(x, y) = TRIED;
return solved;
}
int main(){
maze m;
std::cin >> m;
solve(m);
std::cout << m;
}
</code></pre>
<p>Input is a simple text file of walls, spaces, and a goal, such as:</p>
<pre><code> #######
# # ##
# #### #
# ##
# ### ###
##### *#
</code></pre>
<p>Searching always commences from position 0, 0 (i.e., the top, left corner).</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T07:05:39.883",
"Id": "85876",
"Score": "1",
"body": "I don't have too much to say here. One obvious thing is that `y_dim()` and `x_dim()` should be `const`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T11:12:01.960",
"Id": "85984",
"Score": "0",
"body": "I'm not sure about it, but wouldn't it be a good idea to manually control the type of the enum with `enum: char { ... }`? Since you use `std::string`, I don't think that there is any advantage with letting it be implementation defined."
}
] | [
{
"body": "<p>Try and engage the move constructor:</p>\n\n<pre><code>m.data.push_back(temp);\n</code></pre>\n\n<p>Because <code>temp</code> is a named variable it will hit the version that uses <code>const& T</code>. To try and get the alternative version that engages the move constructor add <code>std::move</code></p>\n\n<pre><code>m.data.push_back(std::move(temp));\n</code></pre>\n\n<p>The input operator does not make any attempt to make sure each line is the same size.</p>\n\n<pre><code>size_t x_dim() { return data[0].size(); }\n</code></pre>\n\n<p>So the above may not be accurate.<br>\nYou can add a fake set of cells at the top/bottom/left/right of type 'WALL' then you don't need the test <code>if (x < 0 || y < 0 || x >= m.x_dim() || y >= m.y_dim())</code> as it can never reach outside the bounds of the maze (this can be forced to be true because it is part of the code and not part of the user input). This means you don't need <code>y_dim()</code> as that is the only use case.</p>\n\n<p>My main issue is that <code>solve()</code> actually mutates the <code>maze</code> object. Some form of visitor pattern may be a more re-usable technique, or <code>solve()</code> would be better as a member of <code>maze()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T14:51:46.043",
"Id": "85899",
"Score": "0",
"body": "Good catch on the use of `std::move`. I missed that one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T10:58:01.600",
"Id": "48918",
"ParentId": "48909",
"Score": "11"
}
},
{
"body": "<p>A few items:</p>\n\n<h2><code>solve</code> should be a member function</h2>\n\n<p>Since <code>solve</code> actively manipulates the maze and makes no sense outside the context of a <code>maze</code>, it really ought to be a member function.</p>\n\n<h2><code>size_t</code> is unsigned</h2>\n\n<p>Since <code>size_t</code> is an unsigned type it will never be less than zero and so checks for <code>x < 0 || y < 0</code> within <code>solve</code> should be removed.</p>\n\n<h2>Several methods should be <code>const</code></h2>\n\n<p>The <code>y_dim()</code> and <code>x_dim()</code> methods should be declared <code>const</code>.</p>\n\n<h2>The <code>enum</code> should be inside <code>maze</code></h2>\n\n<p>If <code>solve</code> becomes a member, then the <code>enum</code> should be made a private member of <code>maze</code>.</p>\n\n<h2>Add user validation to <code>operator>></code></h2>\n\n<p>The code seems to assume that each line is the same length and that it consists solely of valid characters. Interestingly, it accepts (but cannot solve) its own source code as though it were a maze. Perhaps it is! :)</p>\n\n<h2>Replace <code>y_dim()</code> and <code>x_dim()</code></h2>\n\n<p>The only reason to have the <code>x_dim</code> and <code>y_dim</code> functions is to check to make sure that the passed coordinates are within bounds. For that reason, what would make more sense, I think, is to have a <code>bool maze::in_bounds(size_t x, size_t y) const</code> function instead.</p>\n\n<h2>Make <code>operator()</code> private</h2>\n\n<p>Because the <code>operator()</code> returns a reference to internal data, it should be made private. Since the only user of the function is <code>solve</code> this works if <code>solve</code> is also made a member function. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T13:34:14.520",
"Id": "48929",
"ParentId": "48909",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "48929",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T06:25:56.357",
"Id": "48909",
"Score": "11",
"Tags": [
"c++",
"c++11",
"recursion",
"pathfinding"
],
"Title": "Recursive maze solver"
} | 48909 |
<p>So I'm doing a basic MVC layout for a pretty basic game that I am making. The game requires the user to move up/down/left/right via buttons on the GUI. Since I'm using an MVC layout and my buttons are in a different class than the ActionListeners, I was wondering what the best way to add the action listeners are?</p>
<h2>Method 1:</h2>
<p><strong>View Class ActionListener method:</strong></p>
<pre><code>public void addMovementListeners(ActionListener u, ActionListener d, ActionListener l, ActionListener r){
moveUp.addActionListener(u);
moveDown.addActionListener(d);
moveLeft.addActionListener(l);
moveRight.addActionListener(r);
}
</code></pre>
<p><strong>Control Class add ActionListener method:</strong></p>
<pre><code>private void addListeners(){
viewGUI.addMovementListeners(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 1;
}
},
new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 2;
}
},
new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 3;
}
},
new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 4;
}
});
}
</code></pre>
<hr>
<h2>Method 2:</h2>
<p><strong>View Class ActionListener method:</strong></p>
<pre><code>public void addMovementListeners(ActionListener a){
moveUp.addActionListener(a);
moveDown.addActionListener(a);
moveLeft.addActionListener(a);
moveRight.addActionListener(a);
}
public JButton[] getButtons(){
JButton[] temp = new JButton[4];
temp[0] = moveUp;
temp[1] = moveDown;
temp[2] = moveLeft;
temp[3] = moveRight;
return temp;
}
</code></pre>
<p><strong>Control Class add ActionListener method:</strong></p>
<pre><code>JButton[] movementButtons;
private void addListeners(){
movementButtons = viewGUI.getButtons();
viewGUI.addMovementListeners(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == movementButtons[0]){
buttonPressed = 1;
}else if(e.getSource() == movementButtons[1]){
buttonPressed = 2;
}else if(e.getSource() == movementButtons[2]){
buttonPressed = 3;
}else if(e.getSource() == movementButtons[3]){
buttonPressed = 4;
}
}
});
}
</code></pre>
<hr>
<p>Which method is better? Is there another method that is even better than these two? Let me know! Trying to get this MVC thing down :). (Any other suggestions welcome as well)!</p>
| [] | [
{
"body": "<p>Method #1 feels like the better approach, because it doesn't require your view to expose its buttons, but the four-times ActionListener method seems odd. Both methods have some trouble with magic numbers.</p>\n\n<p>Introduce an enum for directions. It may feel like overkill at the moment, but it'll take care of your direction-to-action mapping. It will also help shape some of your options.</p>\n\n<p>Then consider supplying <code>Action</code> instead of <code>ActionListener</code>. This will also make it easier to enable/disable the movement buttons in case something blocks your way (like going off-field), without your view having to expose its buttons.</p>\n\n<p>When you combine these two, you get something like the following:</p>\n\n<pre><code>View:\n void setAction(Direction dir, Action action);\n\nModel:\n void move(Direction dir);\n /** Returns directions possible to move to at this moment. */\n Set<Direction> getPossibleDirections();\n\nenum Direction { UP, RIGHT, DOWN, LEFT; }\n\nclass Controller {\n Map<Direction, MoveAction> actions;\n\n public void setView(View view) {\n actions = new EnumMap<>(Direction.class);\n for ( final Direction direction : Direction.values() ) {\n final MoveAction action = new MoveAction(direction, direction.toString());\n actions.put(direction, action);\n view.setAction(direction, action);\n }\n }\n\n void refreshState() {\n final Set<Direction> dirs = model.getPossibleDirections();\n for ( final MoveAction action : actions.values() ) {\n action.setEnabled(dirs.contains(action.direction));\n }\n }\n\n class MoveAction extends AbstractAction {\n final Direction direction;\n\n MoveAction(Direction direction, String name) {\n super(name);\n this.direction = direction;\n }\n\n public void actionPerformed(ActionEvent evt) {\n model.move(direction);\n refreshState(); // or have model firePropertyChange\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:15:55.790",
"Id": "85923",
"Score": "0",
"body": "So I understand where you're going with the enums and the whole setActions and setView thing, but after that you kind of lost me. It seems like you are doing the calculation for if whether the player can move or not inside the controller class. Shouldn't this be handled inside of the model?\n\nIn my current model class I have a movePlayer() method that checks to see if the desired location (based off of direction) is a) a free space and b) inside the bounds. If it is, it moves the player, if not, it executes nothing else. Is this incorrect thinking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T00:17:39.097",
"Id": "85930",
"Score": "0",
"body": "The controller doesn't calculate what directions to go: it asks the model through `getPossibleDirections()`, and then enables/disables actions according to that. `getPossibleDirections()` figures out what's legal to do. Is that clearer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T00:22:10.717",
"Id": "85931",
"Score": "0",
"body": "Yep, that makes sense! Thank you for the help!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T22:11:48.340",
"Id": "48941",
"ParentId": "48915",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T09:26:52.193",
"Id": "48915",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"game",
"mvc",
"swing"
],
"Title": "MVC Layout - Which way to add listeners is better?"
} | 48915 |
<p>I've borrowed the idea from the internet and I would like to know if my implementation is all right and what could be improved.</p>
<p>It uses the free memory to store links to each node, so there's no extra memory being used.</p>
<p><code>memory_pool.h</code></p>
<pre><code>#ifndef MEMORY_POOL_H
#define MEMORY_POOL_H
#include <stdlib.h>
#define MEMORY_POOL_SUCCESS 1
#define MEMORY_POOL_ERROR 0
#define MEMORY_POOL_MINIMUM_SIZE sizeof(void *)
typedef struct {
void **head;
void *memory;
} Memory_Pool;
//size must be greater than or equal to MEMORY_POOL_MINIMUM_SIZE
int mp_init(Memory_Pool *mp, size_t size, size_t slots);
void mp_destroy(Memory_Pool *mp);
void *mp_get(Memory_Pool *mp);
void mp_release(Memory_Pool *mp, void *mem);
#endif
</code></pre>
<p><code>memory_pool.c</code></p>
<pre><code>#include "memory_pool.h"
int mp_init(Memory_Pool *mp, size_t size, size_t slots)
{
//allocate memory
if((mp->memory = malloc(size * slots)) == NULL)
return MEMORY_POOL_ERROR;
//initialize
mp->head = NULL;
//add every slot to the list
char *end = (char *)mp->memory + size * slots;
for(char *ite = mp->memory; ite < end; ite += size)
mp_release(mp, ite);
return MEMORY_POOL_SUCCESS;
}
void mp_destroy(Memory_Pool *mp)
{
free(mp->memory);
}
void *mp_get(Memory_Pool *mp)
{
if(mp->head == NULL)
return NULL;
//store first address
void *temp = mp->head;
//link one past it
mp->head = *mp->head;
//return the first address
return temp;
}
void mp_release(Memory_Pool *mp, void *mem)
{
//store first address
void *temp = mp->head;
//link new node
mp->head = mem;
//link to the list from new node
*mp->head = temp;
}
</code></pre>
| [] | [
{
"body": "<p>The only addition I would make is:</p>\n\n<pre><code>int mp_init(Memory_Pool *mp, size_t size, size_t slots)\n{\n if (size < MEMORY_POOL_MINIMUM_SIZE)\n { return MEMORY_POOL_ERROR;\n }\n</code></pre>\n\n<p>But note: There is extra memory being used.</p>\n\n<pre><code>typedef struct {\n void **head;\n void *memory;\n} Memory_Pool;\n</code></pre>\n\n<p>You need space to store the above structure.</p>\n\n<p>How it is implemented:</p>\n\n<p>A call to <code>mp_init()</code> allocated a chunk of memory. This chunk of memory is <code>slots</code> count number of items each of size <code>size</code>.</p>\n\n<pre><code> // Let's examine this specific call:\n Memory_Pool memory;\n if (mp_init(&memory, sizeof(void*) * 4, 5) != MEMORY_POOL_SUCCESS)\n {\n exit(1);\n }\n\n\n if((mp->memory = malloc(size * slots)) == NULL)\n return MEMORY_POOL_ERROR;\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> mp->head----->Random\n mp->memory---> ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n</code></pre>\n\n\n\n<pre><code> mp->head = NULL;\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> mp->head-----|\n mp->memory---> ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n</code></pre>\n\n\n\n<pre><code> char *end = (char *)mp->memory + size * slots;\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> mp->head-----|\n mp->memory----------->***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n char *end----------------->\n</code></pre>\n\n\n\n<pre><code> for(char *ite = mp->memory; ite < end; ite += size)\n mp_release(mp, ite);\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> // Iteration 1:\n mp->head----------------|\n \\/\n mp->memory----------->**( null )*\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n char *end----------------->\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> // Iteration 2:\n mp->memory----------->**( null )*\n * /\\ *\n * | *\n mp->head--------------*-| | *\n * \\/ | *\n **( * )*\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n char *end----------------->\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> // Iteration 3:\n mp->memory----------->**( null )*\n * /\\ *\n * | *\n * *\n * | *\n **( * )*\n * /\\ *\n * | *\n mp->head--------------*-| | *\n * \\/ | *\n **( * )*\n * *\n * *\n * *\n * *\n ***********\n * *\n * *\n * *\n * *\n ***********\n char *end----------------->\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> // Iteration 4:\n mp->memory----------->**( null )*\n * /\\ *\n * | *\n * | *\n * | *\n **( * )*\n * /\\ *\n * | *\n * | *\n * | *\n **( * )*\n * /\\ *\n * | *\n mp->head--------------*-| | *\n * \\/ | *\n **( * )*\n * *\n * *\n * *\n * *\n ***********\n char *end----------------->\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code> // Iteration 5:\n mp->memory----------->**( null )*\n * /\\ *\n * | *\n * | *\n * | *\n **( * )*\n * /\\ *\n * | *\n * | *\n * | *\n **( * )*\n * /\\ *\n * | *\n * | *\n * | *\n **( * )*\n * /\\ *\n * | *\n mp->head--------------*-| | *\n * \\/ | *\n **( * )*\n char *end----------------->\n</code></pre>\n\n\n\n<pre><code> return MEMORY_POOL_SUCCESS;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:20:01.213",
"Id": "418498",
"Score": "0",
"body": "can you explain how the node linking works? The OP was last seen 4 years ago. Why is the head \\*\\*void and not just \\*void? Why in the release function, void\\* mem is being assigned to void\\*\\* head. I can't seem to understand the underlying logic, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T04:33:34.100",
"Id": "418519",
"Score": "0",
"body": "@susdu Hope the diagram helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T06:56:57.933",
"Id": "418528",
"Score": "0",
"body": "Thanks a lot, it definitely helped. So each cell basically functions both as a free block and holds a pointer to the previous block. Any reason why the last node is at the start of the block and not vice versa?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:50:15.363",
"Id": "418545",
"Score": "0",
"body": "it looks like the get/release operations could all this be done with void \\*head? I still don't understand the necessity of using a double head pointer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:52:32.040",
"Id": "418574",
"Score": "0",
"body": "@susdu `Any reason why the last node is at the start` Just the way it was implemented. There is no significance to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T14:54:00.790",
"Id": "418575",
"Score": "0",
"body": "@susdu ` I still don't understand the necessity of using a double head pointer` The head points at the location where there is a pointer to the next block. So it is definitely a `void**`. Could it have been implemented with `void*`? Sure. But why loose that extra information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T15:16:30.417",
"Id": "418581",
"Score": "0",
"body": "Thanks a lot Martin for all the detailed explanations after 5 years :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-05-04T11:38:15.467",
"Id": "48921",
"ParentId": "48919",
"Score": "4"
}
},
{
"body": "<p>I see a few things that might be changed. </p>\n\n<h2><code>mp_init</code></h2>\n\n<p>First, consider checking the passed <code>*mp</code> variable to see if it's <code>NULL</code> at least within the <code>mp_init</code> call. Alternatively, you could also allocate that structure within the <code>mp_init</code> routine and return a pointer to it or <code>NULL</code> on error.</p>\n\n<p>The initialization is more complex than it needs to be. Rather than make repeated calls to <code>mp_release</code> and do all of that pointer manipulation, you could use this:</p>\n\n<pre><code>char *ptr;\nfor (ptr = mp->memory; --slots; ptr+=size) \n *(void **)ptr = ptr+size;\n*(void **)ptr = NULL;\nmp->head = mp->memory;\n</code></pre>\n\n<h2><code>mp_release</code></h2>\n\n<p>Within <code>mp_release</code>, there is no error checking. This might be OK if we're looking for extreme performance, but it might be nice to have at least a debug version that checks that <code>mem</code> actually points to a slot. For that to work, of course, you'll have to add at least one more variable to the structure to contain the <code>size</code> parameter.</p>\n\n<h2><code>mp_destroy</code></h2>\n\n<p>In <code>mp_destroy</code> it might be prudent to set <code>mp->head = NULL</code> so that any subsequent <code>mp_get</code> attempts will fail.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T13:28:34.870",
"Id": "85890",
"Score": "0",
"body": "Wouldn't setting `mp->head = NULL` potentially hide a programmer's error?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T13:40:39.177",
"Id": "85894",
"Score": "2",
"body": "@2013Asker: Rather than hiding the error, it seems to me that the proposed change would make such an error easier to find and it costs nearly nothing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T12:38:33.690",
"Id": "48925",
"ParentId": "48919",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48925",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T11:06:18.320",
"Id": "48919",
"Score": "5",
"Tags": [
"c",
"memory-management"
],
"Title": "Simple memory pool using no extra memory"
} | 48919 |
<p>I am trying to make a basic auth password protected folder for Joomla. This script will simply ask for username and password to secure administrator folder in Joomla and creates .htaccess and .pass_file.</p>
<p>I want you to review it and offer suggestions so that I can do it more efficiently and learn to manage code.</p>
<pre><code>#!/usr/bin/env python
import os
import pwd
import sys
def ok():
os.chdir("/home/" + username);
os.system('htpasswd -c .pass_file '+ user);
os.chdir("/home/" + username + "/public_html/administrator/");
os.system('echo AuthUserFile /home/' + username + '/.pass_file > .htaccess');
os.system('echo AuthName Restricted >> .htaccess');
os.system('echo AuthType Basic >> .htaccess');
os.system('echo require valid-user >> .htaccess');
print "=" *40;
quit();
username = raw_input("Enter your cpanel username: ");
try:
pwd.getpwnam(username);
except KeyError:
print "User not found.";
quit();
print "=" * 40;
user = raw_input("Enter the username you want to create for authentication: ");
print "=" * 40;
print "Your username will be "+ user +" for authentication";
print "=" * 40;
filename="/home/"+username+"/public_html/administrator/.htaccess";
if os.path.isfile(filename):
yes = set(['yes','y', 'ye', ''])
no = set(['no','n'])
response = raw_input("Filename exists. Overwrite??");
ans = response.lower();
if ans in no:
print "Sorry we didn't secure the administrator folder. :(";
quit();
elif ans in yes:
ok();
else:
sys.stdout.write("Please respond with 'yes' or 'no'. Quiting...");
quit();
</code></pre>
| [] | [
{
"body": "<p>My suggestions would be:</p>\n\n<ul>\n<li><p>Rewrite ok() using python I/O rather than running echo in a subprocess. We're passing in arguments because they are no longer going to be global variables after some of the edits below.</p>\n\n<pre><code>def ok(passfile, htaccess, user):\n os.system(\"htpasswd -c %s %s\" % (passfile, user))\n with open(htaccess, 'w') as f:\n f.write('AuthUserFile %s\\n' % (passfile))\n f.write('AuthName Restricted\\n')\n f.write('AuthType Basic\\n')\n f.write('require valid-user\\n')\n print \"=\" *40\n quit()\n</code></pre></li>\n<li><p>Consider using the python module <a href=\"https://pypi.python.org/pypi/htpasswd\" rel=\"nofollow\">https://pypi.python.org/pypi/htpasswd</a> instead of calling htpasswd in a subprocess. For example:</p>\n\n<pre><code>import htpasswd\n\nwith htpasswd.Basic(\"/path/to/user.db\") as userdb:\ntry:\n userdb.add(\"bob\", \"password\")\nexcept htpasswd.basic.UserExists, e:\n print e\n</code></pre></li>\n<li><p>Take all the top level lines outside any function and put them in a main() routine at the top of the file (after the imports). Like so (I'm also doing some tweaks here to make things more portable and pythonic):</p>\n\n<pre><code>#!/usr/bin/env python\nimport os\nimport pwd\nimport sys\n\ndef main(args):\n username = raw_input(\"Enter your cpanel username: \");\n try:\n pwd.getpwnam(username);\n except KeyError:\n print \"User not found.\";\n quit();\n print \"=\" * 40;\n user = raw_input(\"Enter the username you want to create for authentication: \");\n print \"=\" * 40;\n print \"Your username will be \"+ user +\" for authentication\";\n print \"=\" * 40;\n\n # Note we're building up our file paths without ever using '/' or \n # '\\'. By letting python build our paths for us, they'll be portable\n homedir = os.getenv(\"HOME\")\n passfile = os.path.join(homedir, \".pass_file\")\n htaccess = os.path.join(homedir, \"public_html\", \"administrator\", \".htaccess\")\n\n # If htaccess already exists, we ask user whether to overwrite. \n # If the user says \"no\", we say sorry and call quit().\n # If the user says \"yes\", we break out of the loop and call ok().\n # Otherwise, we keep telling the user to answer 'yes' or 'no' \n # until they do.\n #\n # If htaccess does not exist, I think we want to create it. The \n # original code did not address this case.\n if os.path.isfile(htaccess):\n while True\n ans = raw_input(\"File %s exists. Overwrite??\" % htaccess);\n # re.findall() will return a list of regexp matches. If there\n # are no matches, the list is empty and the if evaluates to \n # False. Note the regexp handles mixed case and abbreviations.\n if re.findall('[Nn][Oo]?', ans):\n print \"Sorry we didn't secure the administrator folder. :(\";\n quit();\n elif re.findall('[Yy]?[Ee]?[Ss]?', ans):\n break\n else:\n sys.stdout.write(\"Please respond with 'yes' or 'no'.\"); \n ok(passfile, htaccess, user) \n quit();\n</code></pre>\n\n<p>Then at the bottom of the file, </p>\n\n<pre><code>if __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n\n<p>By using a main() routine and calling it from the bottom of the file if <code>__name__</code> contains the string '<code>__main__</code>', you can import this file into other files and reuse the code by calling the functions. With lines at the top level of the file, outside functions, those lines would get run if you ever imported the file. Following this convention consistently makes debugging and code reuse much easier.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:05:40.610",
"Id": "48942",
"ParentId": "48923",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T12:14:09.023",
"Id": "48923",
"Score": "2",
"Tags": [
"python",
"beginner",
"authentication"
],
"Title": "Password protected Joomla administrator folder with Python"
} | 48923 |
<p>Use this tag for code that is to be compiled as <a href="https://en.wikipedia.org/wiki/C%2B%2B14" rel="nofollow noreferrer">C++14</a>, published as ISO/IEC 14882:2011 in December 2014.</p>
<ul>
<li>Predecessor: C++11</li>
<li>Successor: C++17</li>
</ul>
<p>Some of the main improvements of C++14, compared to C++11, include:</p>
<ul>
<li>Generic Lambdas</li>
<li>Improved template and type deduction support</li>
<li>Read-Write Mutex (shared mutex)</li>
<li>Binary Literals</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-05-04T12:43:59.630",
"Id": "48926",
"Score": "0",
"Tags": null,
"Title": null
} | 48926 |
Code that is written to the 2014 version of the C++ standard. Use in conjunction with the 'c++' tag. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-05-04T12:43:59.630",
"Id": "48927",
"Score": "0",
"Tags": null,
"Title": null
} | 48927 |
<p>Like others (<code>FileSystemWatcher</code> Changed event is raised twice) I am facing the problem that events of <code>filesystemwatcher</code> are raised twice. I require to catch all non-duplicate events of watcher in real time. I came up with this. So, I want to know if it will be efficient/over-kill/buggy to use this class.</p>
<pre><code>class ModifiedFileSystemWatcher:FileSystemWatcher
{
public new event RenamedEventHandler Renamed;
public new event FileSystemEventHandler Deleted;
public new event FileSystemEventHandler Created;
public new event FileSystemEventHandler Changed;
class BooleanWrapper{
public bool value { get; set; }
}
//stores refrences of previously fired events with same file source
Dictionary<string, BooleanWrapper> raiseEvent = new Dictionary<string, BooleanWrapper>();
public int WaitingTime { get; set; } //waiting time, any new event raised with same file source will discard previous one
public ModifiedFileSystemWatcher(string filename="", string filter="*.*"):base(filename,filter)
{
base.Changed += ModifiedFileSystemWatcher_Changed;
base.Created += ModifiedFileSystemWatcher_Created;
base.Deleted += ModifiedFileSystemWatcher_Deleted;
base.Renamed += ModifiedFileSystemWatcher_Renamed;
WaitingTime = 100;
}
void PreventDuplicate(FileSystemEventHandler _event, FileSystemEventArgs e)
{
if (_event != null)
{
//create a reference
BooleanWrapper w = new BooleanWrapper() { value = true }; //this event will be fired
BooleanWrapper t; //tmp
if (raiseEvent.TryGetValue(e.FullPath, out t))
{
//a previous event occurred which is waiting [delayed by WaitingTime]
t.value = false; //set its reference to false; that event will be skipped
t = w;//store current reference in dictionary
}
else raiseEvent[e.FullPath] = w; //no previous event, store our reference
//Wait on a separate thread...
System.Threading.ThreadPool.QueueUserWorkItem(delegate
{
System.Threading.Thread.Sleep(WaitingTime);
if (w.value) //if we are still allowed to raise event
{
_event(this, e);
raiseEvent.Remove(e.FullPath);//remove instance from dictionary
}
}, null);
}
}
//Same as above with different event
void ModifiedFileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
if (Renamed != null)
{
BooleanWrapper w = new BooleanWrapper() { value = true };
BooleanWrapper t;
if (raiseEvent.TryGetValue(e.FullPath, out t))
{
t.value = false;
t = w;
}
else raiseEvent[e.FullPath] = w;
System.Threading.Thread.Sleep(WaitingTime);
if (w.value)
{
Renamed(this, e);
raiseEvent.Remove(e.FullPath);
}
}
}
void ModifiedFileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
PreventDuplicate(Deleted, e);
}
void ModifiedFileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
PreventDuplicate(Created, e);
}
void ModifiedFileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
PreventDuplicate(Changed, e);
}
}
</code></pre>
| [] | [
{
"body": "<p>I copied your code into a new console application. Your constructor is \"eating\" the base default constructor, and now I can't pass a <code>path</code> parameter, I have to trust that <code>filename</code> will work if I give it a folder path. Let's see..</p>\n\n<blockquote>\n<pre><code>public ModifiedFileSystemWatcher(string filename=\"\", string filter=\"*.*\"):base(filename,filter)\n{\n /* constructor */\n}\n</code></pre>\n</blockquote>\n\n<p>This would be easier to read on two lines:</p>\n\n<pre><code>public ModifiedFileSystemWatcher(string filename=\"\", string filter=\"*.*\")\n : base(filename,filter)\n{\n /* constructor */\n}\n</code></pre>\n\n<p>Changing the names of constructor arguments is confusing. In this case you're passing <code>filename</code> as the base constructor's <code>path</code> parameter, but <code>filter</code> is passed as <code>filter</code>. I would rename <code>filename</code> to <code>path</code> to avoid confusion.</p>\n\n<p>The optional parameters are surprising, too - a <code>FileSystemWatcher</code> exposes a parameterless constructor, one with only a <code>path</code>, and one with both a <code>path</code> and a <code>filter</code>. Your optional parameters add a constructor for a <code>filter</code> without a <code>path</code>.</p>\n\n<hr>\n\n<p>This is a rather unusual way of assigning a value in a dictionary:</p>\n\n<blockquote>\n<pre><code>BooleanWrapper w = new BooleanWrapper() { value = true };\nBooleanWrapper t;\nif (raiseEvent.TryGetValue(e.FullPath, out t))\n{\n t.value = false;\n t = w; //store current reference in dictionary\n}\n</code></pre>\n</blockquote>\n\n<p>This <em>might</em> work, but I find <code>raiseEvent[e.FullPath] = w;</code> makes the intent much more explicit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T09:32:09.697",
"Id": "85974",
"Score": "0",
"body": "Hi, Thanks for your review. I will change the constructor parameter names to make sense.\nFor the second part, t=w\ninstead of raiseEvent[e.FullPath] = w;. Yes that will increase readability. But my method skips searching dictionary again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T11:33:38.887",
"Id": "85986",
"Score": "0",
"body": "@AkshayVats the \"search\" is O(n), which will be instant in most cases since you keep the dictionary clean. My rule of thumb is to favor readability over performance, unless there's an actual performance issue, in which case a profiler will identify where the bottleneck is. If you refactored `BooleanWrapper` usages to work with a `Nullable<bool>` instead, the immutability of the type would blow it up. What else do you need `BooleanWrapper` for (that a `Nullable<bool>` can't do)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T12:06:57.580",
"Id": "85988",
"Score": "0",
"body": "I wasn't aware of Nullable<T>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T14:49:07.233",
"Id": "86353",
"Score": "0",
"body": "Hi, today I thought of removing BooleanWrapper. I learned about Nullable types, but they are struct. My point of creating wrapper was to have a reference. Give me some ideas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T14:54:05.867",
"Id": "86354",
"Score": "0",
"body": "@AkshayVats I don't think it's efficient to have a reference in this case - if all you need is a flag that tells you whether or not you can/should raise the event, then I think the most readable and efficient way of doing it is to have `raiseEvent` be a `Dictionary<string, bool>`. Keep it simple!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T00:14:59.870",
"Id": "48945",
"ParentId": "48930",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48945",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T15:55:12.383",
"Id": "48930",
"Score": "4",
"Tags": [
"c#",
"file-system",
"event-handling"
],
"Title": "FileSystemWatcher firing multiple events"
} | 48930 |
<p>I'm working on a library which will provide easier writing and calculations in Java using a fluent API. This is the library I have implemented with basic functionalities and am now working to improve the API.</p>
<p>I followed instructions given by <a href="http://theamiableapi.com/2012/01/16/java-api-design-checklist/" rel="nofollow">this</a> but I still have some doubts in naming some classes and methods.</p>
<p>I have several questions oriented on naming those:</p>
<ol>
<li><p>For calculations, there is the basic class <code>Calculator</code>. For executing calculations, there is the method <code>calculate()</code>. Which is more preferable name: <code>calculate()</code> or simplified <code>calc()</code>?</p></li>
<li><p>The <code>Calculator</code> class has the ability to track each step of a calculation.</p>
<p>For now I have these methods:</p>
<ul>
<li><code>setTrackSteps(boolean)</code>, which enable tracking each step of calculation.</li>
<li><code>getTrackedSteps()</code> - return list of each step in TrackedStep object.</li>
<li><code>hasTrackedStep</code> - check is tracking calculation steps is enabled/disabled.</li>
</ul>
<p>Does somebody have some better suggestions for those names?</p></li>
<li><p><code>Calculator.getTrackedSteps()</code> return list of object <code>TrackedStep</code>. <code>TrackedSteps</code> is little harsh name. Is there a better name for this?</p></li>
<li><p>I have separated public API with internal implementations into an internal package. In this package, I have a 'Utils' class with static methods and I'm trying to avoid this generic name. Would <code>HelperUtils</code> be a good name?</p>
<p>I'm trying to avoid prefixes with <code>Calc()</code> or <code>Calculator()</code>, because when the end user uses some IDE and when it start writing Cal, the IDE will provide several classes which start with Cal, including 'Calc..Utils'</p></li>
</ol>
<p>If somebody has some other suggestions, the API is available on <a href="https://github.com/d-sauer/JCalcAPI" rel="nofollow">GitHub</a>.</p>
<p>The class which is related to question 1, 2 and 3:</p>
<pre><code>package org.jdice.calc;
import java.text.ParseException;
import java.util.Iterator;
import java.util.LinkedList;
import org.jdice.calc.internal.BindExtensionProvider;
import org.jdice.calc.internal.Bracket;
import org.jdice.calc.internal.CList;
import org.jdice.calc.internal.CListListener;
import org.jdice.calc.internal.CacheExtension;
import org.jdice.calc.internal.FunctionData;
import org.jdice.calc.internal.InfixParser;
import org.jdice.calc.internal.PostfixCalculator;
import org.jdice.calc.internal.UseExtension;
/**
* Abstract class that concrete calculator extends
*
* @author Davor Sauer <davor.sauer@gmail.com>
*
* @param <CALC>
*/
public abstract class AbstractCalculator<CALC> {
/**
* Detect changes in infix expression
*/
private CList infix = new CList(new CListListener() {
@Override
public void change() {
isInfixChanged = true;
}
});
private boolean isInfixChanged = true;
private InfixParser infixParser;
private final PostfixCalculator postfixCalculator = new PostfixCalculator();
private CList postfix = new CList();
private Num lastCalculatedValue;
private LinkedList<TrackedStep> calculatingSteps;
private Properties properties;
private UseExtension localUseExtensions;
private static boolean isImplExtRegistered = false;
private AbstractCalculator<CALC> parentCalculator;
private AbstractCalculator<CALC> childCalculator;
private boolean isBind = false;
private boolean isUnbind = false;
private boolean trackSteps = false;
/**
* Register implemented operation and functions by subclass
*
*/
private void useImplmentedExtension() {
if (isImplExtRegistered == false) {
Object o = getThis();
Class thisClass = o.getClass();
// superclass interfaces
Class[] declared = thisClass.getSuperclass().getInterfaces();
for (Class declare : declared) {
useImplmentedExtension(declare);
}
// subclass interfaces
declared = thisClass.getInterfaces();
for (Class declare : declared) {
useImplmentedExtension(declare);
}
isImplExtRegistered = true;
}
}
/**
* Register defined operation or function class to global cache
*
* @param declare
*/
private void useImplmentedExtension(Class declare) {
Class c = BindExtensionProvider.getExtension(declare);
if (c == null && declare.isAnnotationPresent(BindExtension.class)) {
BindExtension impl = (BindExtension) declare.getAnnotation(BindExtension.class);
if (impl != null)
c = impl.implementation();
BindExtensionProvider.bind(declare, c);
}
if (c != null) {
if (Operator.class.isAssignableFrom(c))
CacheExtension.registerOperator(c);
if (Function.class.isAssignableFrom(c))
CacheExtension.registerFunction(c);
}
}
/**
* Return reference of subclass
* @return
*/
protected abstract CALC getThis();
/**
* Provide custom {@link Operator} or {@link Function} inside scope of this instance, that can be used during expression parsing.
* With registration of custom operation it's possible to override existing default operation implementation.
* Because during calculation API first scan scoped (registered) operation and after that default operation implementation inside {@link CacheExtension}
*
* @param operationClass
* @return
*/
public CALC use(Class<? extends Extension> operationClass) {
if (localUseExtensions == null)
localUseExtensions = new UseExtension();
if (Operator.class.isAssignableFrom(operationClass))
localUseExtensions.registerOperator(operationClass.asSubclass(Operator.class));
if (Function.class.isAssignableFrom(operationClass))
localUseExtensions.registerFunction(operationClass.asSubclass(Function.class));
return getThis();
}
/**
* List registered local scoped operations.
*
* @return
*/
public UseExtension getUsedExtensions() {
return this.localUseExtensions;
}
/**
* Append value to expression
*
* @param value
* @return
*/
public CALC val(Object value) {
Num val = null;
if (value instanceof Num)
val = (Num)value;
else
val = new Num(value);
infix.add(val);
return getThis();
}
/**
* Append value to expression
*
* @param value custom type value
* @param converter class for convert custom type to {@link Num}
* @return
*/
public CALC val(Object value, Class<? extends NumConverter> converter) {
infix.add(new Num(value, converter));
return getThis();
}
/**
* Append String value to expression that will be parsed to {@link Num} with defined decimal separator
*
*
* @param value String representation of number
* @param decimalSeparator used in string representation of number
* @return
*/
public CALC val(String value, char decimalSeparator) {
infix.add(new Num(value, decimalSeparator));
return getThis();
}
/**
* Copy calculator expression into this expression within brackets
*
* @param expression
* @return
*/
public CALC append(AbstractCalculator expression) {
return append(expression, true);
}
/**
*
* Copy expression from given calculator into this expression within or without brackets
*
* @param expression
* @param withinBrackets
* @return
*/
public CALC append(AbstractCalculator expression, boolean withinBrackets) {
append(expression.infix, withinBrackets);
return getThis();
}
/**
*
* Append copy of given infix expression into this expression within or without brackets
*
* @param infix
* @param withinBrackets
* @return
*/
public CALC append(CList infix, boolean withinBrackets) {
if (withinBrackets)
this.infix.add(Bracket.OPEN);
Iterator<Object> it = infix.iterator();
while (it.hasNext()) {
Object o = it.next();
if (o instanceof Num) {
this.infix.add((Num) o);
}
else if (o instanceof Operator) {
this.infix.add((Operator) o);
}
else if (o instanceof FunctionData) {
this.infix.add((FunctionData) o);
}
else if (o instanceof Function) {
this.infix.add((Function) o);
}
else if (o instanceof Bracket) {
this.infix.add((Bracket) o);
}
}
if (withinBrackets)
this.infix.add(Bracket.CLOSE);
return getThis();
}
/**
* Append operator to expression
* @param operator
* @return
*/
public final CALC append(Class<? extends Operator> operator) {
infix.add(operator);
return getThis();
}
/**
* Append operator and number to expression
* @param operator
* @param value
* @return
*/
protected final CALC append(Class<? extends Operator> operator, Object value) {
Num tmp = null;
if (value instanceof Num)
tmp = (Num)value;
else
tmp = new Num(value);
infix.add(CacheExtension.getOperator(operator));
infix.add(tmp);
return getThis();
}
/**
* Append operator and parsed String value with custom decimal separator used in String representation of value
* @param operator
* @param value
* @param decimalSeparator
* @return
*/
protected final CALC append(Class<? extends Operator> operator, String value, char decimalSeparator) {
return append(operator, new Num(value, decimalSeparator));
}
/**
* Append function with value to expression.
*
* <br/>
* e.g. Abs.class, -5 => abs(-5)
*
* @param function
* @param values can accept any object that {@link Num} can work with
* @return
* @see {@link Function}
*/
public final CALC append(Class<? extends Function> function, Object... values) {
Function fn = CacheExtension.getFunction(function);
FunctionData fd = new FunctionData(fn, values);
this.infix.addFunction(fd);
return getThis();
}
/**
* Parse and append given expression to existing expression
*
* @param expression
* @return
* @throws ParseException
*/
public CALC expression(String expression) throws ParseException {
useImplmentedExtension();
if (infixParser == null)
infixParser = new InfixParser();
CList infix = infixParser.parse(localUseExtensions, getProperties(), expression);
append(infix, false);
return getThis();
}
/**
* Parse and append given expression to existing expression
* String representation of expression that will be parsed with unknown variables.
* It is possible to define name of <tt>Num</tt> with {@link Num#setName(String)} then name will be matched with name of unknown variable.
* Otherwise unknown variable will be matched by declared order.
*
* <br/>
* e.g. X + 5 - (2 * X - Y)
*
* @param expression
* @param values that match unknown variable by name or by order
* @return {@link AbstractCalculator}
* @throws ParseException
*/
public CALC expression(String expression, Object... values) throws ParseException {
useImplmentedExtension();
if (infixParser == null)
infixParser = new InfixParser();
CList infix = infixParser.parse(localUseExtensions, getProperties(), expression, values);
append(infix, false);
return getThis();
}
/**
* Open bracket
* @return
*/
public CALC openBracket() {
infix.add(Bracket.OPEN);
return getThis();
}
/**
* Close bracket
*
* @return
*/
public CALC closeBracket() {
infix.add(Bracket.CLOSE);
return getThis();
}
/**
* Get defined properties
* @return
*/
public Properties getProperties() {
if (properties == null)
properties = new Properties();
return properties;
}
/**
* Set proeprties
* @param properties
* @return
*/
public CALC setProperties(Properties properties) {
this.properties = properties;
return getThis();
}
/**
* Set scale for entire expression
* @param scale
* @return
*/
public CALC setScale(Integer scale) {
getProperties().setScale(scale);
return getThis();
}
/**
* Get scale mode used throughout expression
* @return
*/
public Integer getScale() {
return getProperties().getScale();
}
/**
* Set rounding mode for entire expression
* @param roundingMode
* @return
*/
public CALC setRoundingMode(Rounding roundingMode) {
getProperties().setRoundingMode(roundingMode);
return getThis();
}
/**
* Get rounding mode used throughout expression
* @return
*/
public Rounding getRoundingMode() {
return getProperties().getRoundingMode();
}
/**
* Set decimal separator for entire expression
* @param decimalSeparator
* @return
*/
public CALC setDecimalSeparator(char decimalSeparator) {
getProperties().setInputDecimalSeparator(decimalSeparator);
getProperties().setOutputDecimalSeparator(decimalSeparator);
return getThis();
}
/**
* Get decimal separator used throughout expression
* @return
*/
public char getDecimalSeparator() {
return getProperties().getInputDecimalSeparator();
}
/**
* Set number grouping separator for entire expression
* @param decimalSeparator
* @return
*/
public CALC setGroupingSeparator(char decimalSeparator) {
getProperties().setGroupingSeparator(decimalSeparator);
return getThis();
}
/**
* Get grouping separator used throughout expression
* @return
*/
public char getGroupingSeparator() {
return getProperties().getGroupingSeparator();
}
public boolean hasStripTrailingZeros() {
return getProperties().hasStripTrailingZeros();
}
public CALC setStripTrailingZeros(boolean stripTrailingZeros) {
getProperties().setStripTrailingZeros(stripTrailingZeros);
return getThis();
}
public CALC setTrackSteps(boolean trackSteps) {
this.trackSteps = trackSteps;
return getThis();
}
public boolean hasTrackSteps() {
return trackSteps;
}
/**
* Get calculation steps if {@link #hasTrackSteps()} is TRUE
*
* @return
* @see {@link}
*/
public LinkedList<TrackedStep> getTrackedSteps() {
return calculatingSteps;
}
/**
* Calculate prepared expression.
*
* For tracking calculation
*
* @return
* @see {@link #calculate()}
* @see {@link #getCalculatedValue()}
*/
public Num calculate() {
unbind();
prepareForNewCalculation();
PostfixCalculator pc = convertToPostfix();
Num cv = pc.calculate(this, postfix, trackSteps);
lastCalculatedValue = cv.clone();
return cv;
}
/**
* Bind another Calculator class functionalities to expression.
*
* Way to combine two different implementation of calculators
*
* @param clazz
* @return
*/
public <T extends AbstractCalculator> T bind(Class<T> clazz) {
T childCalc = null;
try {
childCalc = clazz.newInstance();
}
catch (Exception e) {
throw new CalculatorException(e);
}
if (childCalc instanceof AbstractCalculator) {
// find last child from root
AbstractCalculator<CALC> bParent = this;
while (bParent != null) {
if (bParent.childCalculator != null)
bParent = bParent.childCalculator;
else
break;
}
((AbstractCalculator) childCalc).parentCalculator = bParent;
((AbstractCalculator) childCalc).isBind = true;
bParent.childCalculator = childCalc;
}
else {
throw new CalculatorException("Use calculator which is type of AbstractCalculator", new IllegalArgumentException());
}
return childCalc;
}
/**
* Unbind binded calculator
* @return
*/
private CALC unbind() {
if (childCalculator != null)
unbindAll(this);
return (CALC) this;
}
/**
* Unbind all binded calculators
* @param undbindFrom
* @return
*/
private CALC unbindAll(AbstractCalculator<CALC> undbindFrom) {
// find root and first child
AbstractCalculator root = undbindFrom.parentCalculator != null ? undbindFrom.parentCalculator : undbindFrom;
AbstractCalculator child = root.childCalculator;
while (root != null) {
AbstractCalculator tmpParent = root.parentCalculator;
if (tmpParent == null)
break;
else
root = tmpParent;
child = root.childCalculator;
}
// undbind all from root to last child
while (child != null) {
if (child.isUnbind == false)
root.append(child, false);
child.isUnbind = true;
child = child.childCalculator; // new unbind child
}
return (CALC) undbindFrom;
}
/**
* Convert defined expression to postfix <tt>String</tt>
*
* @return
*/
public String getPostfix() {
unbind();
convertToPostfix();
return InfixParser.toString(this.postfix);
}
/**
* Convert infix to postfix
* Conversion is made only first time or after any change in structure of infix expression
* @return
*/
private PostfixCalculator convertToPostfix() {
if (postfix == null || postfix.size() == 0 || isInfixChanged) {
postfixCalculator.toPostfix(infix);
postfix = postfixCalculator.getPostfix();
isInfixChanged = false;
}
return postfixCalculator;
}
/**
* Get infix (common arithmetic and logical expression notation) representation of given expression
*
* @return
* @see {@link getPostfix()}
*/
public String getInfix() {
unbind();
return toString();
}
/**
* Provide infix list for this calculator.
*
* @param infix
* @return
*/
public final CALC setInfix(CList infix) {
this.infix = infix;
return getThis();
}
/**
* Check whether the calculation is made according to a expression
*
* @return
* @see {@link getResult()}
*/
public boolean isCalculated() {
if (lastCalculatedValue != null)
return true;
else
return false;
}
/**
* Return calculated value
*
* @return
* @see {@link hasResult()}
*/
public Num getCalculatedValue() {
if (lastCalculatedValue != null)
return lastCalculatedValue.clone();
else
return null;
}
/**
* Reset result and calculation steps of previous calculation
*/
private void prepareForNewCalculation() {
lastCalculatedValue = null;
this.calculatingSteps = null;
}
public final void setSteps(LinkedList<TrackedStep> calculationSteps) {
this.calculatingSteps = calculationSteps;
}
@Override
public String toString() {
return InfixParser.toString(this.infix);
}
}
</code></pre>
<p>Code related to question 4:</p>
<pre><code>package org.jdice.calc.internal;
import org.jdice.calc.Num;
import org.jdice.calc.Properties;
public class Utils {
public static boolean equals(Object objA, Object objB) {
if (objA == objB)
return true;
else if (objA == null && objB == null)
return true;
else if (objA != null && objB == null)
return false;
else if (objA == null && objB != null)
return false;
else if (objA != null && objB != null && objA.getClass().isAssignableFrom(objB.getClass()))
return objA.equals(objB);
return false;
}
public static Num[] toNums(Object... object) {
Num[] values = new Num[object.length];
for (int i = 0; i < object.length; i++) {
values[i] = Num.toNum(object[i]);
}
return values;
}
/**
* Remove from string number representation all character except numbers and
* decimal point. <br>
* And replace given decimalSeparator with '.'
*
* <pre>
* ("44,551.06", '.') => 44551.06
* ("1 255 844,551.06", '.') => 1255844551.06
* ("44,551..06", '.') => 44551.06
* </pre>
*
* @param decimalSeparator
* @param value
*/
public static String extractNumber(String value, char decimalSeparator) {
String regex = "[^0-9-" + decimalSeparator + "]";
if (decimalSeparator == '.')
regex = regex.replace(".", "\\.");
String strip = value.replaceAll(regex, "");
strip = strip.replace(decimalSeparator + "", Properties.DEFAULT_DECIMAL_SEPARATOR + "");
return strip;
}
}
</code></pre>
| [] | [
{
"body": "<h1>For your specific questions:</h1>\n\n<blockquote>\n <p>For calculation there is basic class Calculator and for execute calculation, there is method calculate().</p>\n \n <p>Which is more preferable name calculate() or simplified calc() ?</p>\n</blockquote>\n\n<p>I'm cool with either, as long as it's applied somewhat consistently. If you don't use calculate and calc in different contexts and implying different meanings, either one's fine.</p>\n\n<blockquote>\n <p>For now I have those methods:</p>\n \n <ul>\n <li>setTrackSteps(boolean), which enable tracking each step of calculation.</li>\n <li>getTrackedSteps() - return list of each step in TrackedStep object.</li>\n <li>hasTrackedStep - check is tracking calculation steps is enabled/disabled.</li>\n </ul>\n</blockquote>\n\n<p>If you have <code>setTrackSteps</code>, consider mirroring with <code>isTrackSteps</code> or <code>getTrackSteps</code>, just to follow JavaBeans conventions.</p>\n\n<blockquote>\n <p>Calculator.getTrackedSteps() return list of object TrackedStep.\n TrackedSteps is little harsh name. Is there a better name for this?</p>\n</blockquote>\n\n<p>Maybe 'trace' is the word you're looking for?</p>\n\n<pre><code>boolean isTracingSteps()\nvoid setTracingSteps(boolean)\nList<CalcStep> getTracedSteps()\n</code></pre>\n\n<blockquote>\n <p>I have separated Public API with internal implementations into internal package. In this package, I have 'Utils' class with static methods and I'm trying to avoid this generic name.</p>\n</blockquote>\n\n<p>I don't really see an issue with having a generic name for a generic class. If your calculator class would've been called Utils, or your utility class Calculator, that would be an issue, but basically a namespace for utility methods? Utils is fine.</p>\n\n<p>That said, about that Utils:</p>\n\n<ul>\n<li><p><code>Utils.equals</code> could be left out and traded for <code>java.util.Objects.equals</code>, provided you can require Java 7 or up.</p></li>\n<li><p><code>Num[] toNums(Object[])</code> relies on <code>Num.toNum(Object)</code>; maybe put it with Num as well?</p></li>\n<li><p><code>extractNumber</code> -> divert this through NumberFormat? Perhaps a protected method in your Calculator class, if it's not used outside of it?</p></li>\n</ul>\n\n<hr>\n\n<h1>More general comments</h1>\n\n<p><strong>Self-typing through generics</strong> only works for subclasses one level in. I've tried serious wizardry with generics, and never found a good, reliable way to assure the <em>compiler</em> it would get an instance of the current type without having to override those methods manually.</p>\n\n<p><strong><code>val</code> instead of <code>append</code>?</strong> These methods have different names, but they appear to do the same thing: append something. Is there a reason you chose different names for them?</p>\n\n<p><strong><code>extractNumber</code> is too liberal in what it accepts.</strong> It feels a bit odd that I could write:</p>\n\n<blockquote>\n <p>\"Alfred, we're at 800mBar; add 25 cups of sugar and get me 2 cans of shark repellant.\"</p>\n</blockquote>\n\n<p>...and end up with <code>800252.</code> I'd expect the method to throw a NumberFormatException, and possibly shake its head at me for misquoting Batman.</p>\n\n<p><strong><code>Utils.equals</code> can be briefer.</strong> You're taking some responsibilities out of the hands of <code>Object.equals</code>, which is not necessarily a good thing. If you can't go to Java 7 or import the excellent Guava library, you can copy their implementation:</p>\n\n<pre><code>return (a == b) || (a != null && a.equals(b)); // JDK, Guava\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T20:51:39.267",
"Id": "86621",
"Score": "0",
"body": "Thanks for so detail clarification and suggestions.\n\nI already change Utils class to Objects class and use implementation Guava library. And remove toNums(..) because it's newer used.\n\nextractNumber, well I newer think of situation of giving this method entire sentence, but it's possible situation and thanks for pointing this out.\n\nSo I was thinking to rename append(..) to two separated methods, operator(Class<? extends Operator> operator) and function(Class<? extends Function> function, Object... values).\nSo it's will be more clear which one is for what purpose."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T13:28:18.293",
"Id": "49143",
"ParentId": "48931",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T16:38:27.050",
"Id": "48931",
"Score": "6",
"Tags": [
"java",
"api",
"library"
],
"Title": "Library for providing calculations in Java"
} | 48931 |
<p>I have never use css animations before, so I just want to know, is this the 'best' way to animate a Ticker? I 'best' in this case encompasses efficient and semantic use of html and css.</p>
<p>It's worth noting that I intend to add extra functionality to this, such as manual scrolling back and forth. Is this set up ok for extending with javascript or is something here too temperamental? </p>
<p>Basic functionality is, Tweets scroll from right to left. When you put your mouse on one the scrolling stops and the tweet expands, and the time posted appears.</p>
<p><a href="http://jsfiddle.net/easilyBaffled/dLe3p/5/" rel="nofollow">JSFiddle</a> to see it in action</p>
<p><strong>HTML:</strong></p>
<pre><code><span id="controller">
<span id="ticker">
<span id="tweet">test </span>
<span id="tweet">
<img src="http://goo.gl/NpDXFs"></img>
<div id="text">
<span id="username">@Something</span>
<span id="extra_info">3m</span>
<div id="content">content</div>
</div>
</span>
</span>
</span>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>#controller {
background-color: blue;
display: inline-block;
position: absolute;
width: 100%;
}
#controller:hover #ticker {
-webkit-animation-play-state: paused
}
#ticker {
-webkit-animation: move_eye 6s linear 0s infinite normal;
}
@-webkit-keyframes move_eye {
from {
margin-left:110%;
}
to {
margin-left:-50%;
}
90% {
}
}
#text{
display: inline-block;
}
#tweet {
box-sizing: border-box;
background-color: white;
display: inline-block;
position: relative;
border-radius:5px;
margin: 0px 1px;
padding: 0px 3px;
}
#tweet:hover {
font-size: 120%;
}
#tweet:hover #extra_info {
display: inline-block;
}
#tweet:hover img {
width: 40px;
height: 40px;
}
#extra_info {
display: none;
}
img{
width: 30px;
height: 30px;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T13:29:58.760",
"Id": "86514",
"Score": "0",
"body": "I'd do `overflow-x:hidden;` also on `body`."
}
] | [
{
"body": "<ul>\n<li><p>If you are targetting styles for more than one element, then consider using <code>class</code> instead of <code>id</code>.</p></li>\n<li><p>Block elements cannot be inside inline elements. <code><div></code> can't be inside <code><span></code></p></li>\n<li><p><code><img></code> is a self-closing tag. No need for a <code></img></code> though you need to end it with <code>/></code></p></li>\n<li><p>Put some padding on your containers. They look awful when they all stick to the edge.</p></li>\n<li><p>I have read somewhere that increasing the size on hover is awful CSS. Consider putting focus by changing the background color, or changing the font color or putting an outline in a subtle way.</p></li>\n<li><p>Constrain the slider by putting <code>overflow:hidden</code> on the container. That way you don't have that horrible scrollbar at the bottom.</p></li>\n<li><p>Use <code>transform</code> instead of <code>margin</code>. As far as I know, the new CSS3 properties are hardware accelerated (or were those just the 3D), so they're smoother.</p></li>\n<li><p>Also, <code>transform</code>'s values are relative to the element itself and not the parent. While 100% <code>margin</code> (top or bottom) is equal to the parent container, 100% <code>transform</code> is the height (for y) and width (for x) of the element. This is useful especially when the slider is longer than the container.</p></li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/dLe3p/7/\" rel=\"nofollow\">Too long to list down what I did so here's the code instead</a>:</p>\n\n<p>HTML:</p>\n\n<pre><code><div id=\"controller\">\n <div id=\"ticker\">\n <div class=\"tweet\">\n <img src=\"http://goo.gl/NpDXFs\" />\n <div class=\"text\">\n <span class=\"username\">@Something</span>\n <span class=\"extra_info\">3m</span>\n <div class=\"content\">content</div>\n </div>\n </div>\n </div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#controller {\n box-sizing: border-box;\n background-color: #06C;\n position: absolute;\n width: 100%;\n overflow:hidden;\n}\n#controller:hover #ticker {\n -webkit-animation-play-state: paused\n}\n#ticker {\n white-space: nowrap;\n -webkit-animation: move_eye 6s linear 0s infinite normal;\n}\n@-webkit-keyframes move_eye {\n from {\n -webkit-transform: translate(100%,0)\n }\n to {\n -webkit-transform: translate(-100%,0)\n }\n 90% {\n }\n}\n.text {\n display:inline-block;\n}\n.tweet {\n box-sizing: border-box;\n background-color: #EEE;\n display: inline-block;\n border-radius:5px;\n padding: 5px 10px;;\n vertical-align: top;\n margin: 5px 2px;\n height: 100%;\n}\n.tweet:hover .extra_info {\n display: inline;\n}\n.extra_info {\n display: none;\n}\nimg {\n display:inline-block;\n height: 30px;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T01:46:18.037",
"Id": "48950",
"ParentId": "48932",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48950",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T17:55:47.973",
"Id": "48932",
"Score": "1",
"Tags": [
"html",
"css",
"animation"
],
"Title": "CSS Ticker Animation"
} | 48932 |
<p>I have successfully coded a network request to fetch JSON data from our server. The remote function is written in ColdFusion. However, the code is quite lengthy and involved. I also noticed in the API there are other seemingly very similar ways one can go about making network requests, such as <code>NSURLSession</code>. (I know <code>NSURLConnection</code> will be deprecated in the future, replaced by <code>NSURLSession</code>.) I would like to know what is the best way to make a network request - using modern code that is not going to be deprecated in the near future. Is <code>NSURLSession</code> the best way to go? </p>
<p>Here are my requirements:</p>
<ul>
<li>Fetch JSON data from a function in a .cfc file on the server</li>
<li>Must be secure</li>
<li>Must be able to perform error checking</li>
<li>Only need to support iOS 7+</li>
<li>Preferably more concise code</li>
</ul>
<p>Here is my current and lengthy code, using several variables, <code>NSMutableURLRequest</code>, and <code>NSURLConnection</code>:</p>
<pre><code>dispatch_queue_t queue = dispatch_queue_create("Q", NULL);
dispatch_async(queue, ^{
NSInteger success = 1;
NSURL *url = [NSURL URLWithString:MYURL];
NSData *postData = [[[NSString alloc] initWithFormat:@"method=methodName&username=%@&password=%@", usernameVar, passwordVar] dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
//if communication was successful
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&serializeError];
success = [jsonData[@"ERROR"] integerValue];
if (success == 0) {
//success! do stuff with the jsonData dictionary here
}
else {
//handle ERROR from server
}
}
else {
//handle error for unsuccessful communication with server
}
});
</code></pre>
<p>Could you help me clean this up to be implemented the most preferred way for modern apps of today?</p>
| [] | [
{
"body": "<p><code>NSURLSession</code> was designed from the ground up to be as similar to <code>NSURLConnection</code> as possible, so that those accustomed to using the latter will have no problem transitioning to the former. Meanwhile, <code>NSURLSession</code> has a lot of major advantages over <code>NSURLConnection</code>. </p>\n\n<p>First of all, we can get rid of all the code for dispatching on a background thread. <code>NSURLSession</code> works on background threads automatically unless we specify otherwise.</p>\n\n<p>We still have to create our <code>NSURLRequest</code>. I don't know any way around this.</p>\n\n<p>But once we've got our request set up, and remember, all of this is outside the GCD block, we just do this:</p>\n\n<pre><code>NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];\n\n[[session dataTaskWithRequest:request \n completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {\n\n // do stuff\n\n}] resume];\n</code></pre>\n\n<p>As you can see, it's quite similar to <code>NSURLConnection</code>. We replace <code>// do stuff</code> with the stuff we want to do when the request is complete (completion handler). We have our data, our response, and our error all in this block.</p>\n\n<p>A lot of the new power from <code>NSURLSession</code> comes from the <code>NSURLSessionConfiguration</code> object. Using <code>NSURLSessionConfiguration</code>, we can easily set up downloads/uploads to happen in the background (when our app is not open). We can specify to only run on Wi-Fi and not use cellular data as setting a BOOL. We can set a BOOL to tell the OS to only try doing our background uploads/downloads when the device is on Wi-Fi and plugged into a power source. </p>\n\n<p><code>NSURLSessionConfiguration</code> also has an <code>HTTPAdditionalHeaders</code> property, which is an <code>NSDictionary</code> object containing additional headers that should be sent with requests using this configuration.</p>\n\n<p>There's a lot more information about <a href=\"https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/occ/clm/NSURLSessionConfiguration/ephemeralSessionConfiguration\"><code>NSURLSessionConfiguration</code> here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T00:08:09.053",
"Id": "49026",
"ParentId": "48934",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "49026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T18:08:13.947",
"Id": "48934",
"Score": "8",
"Tags": [
"objective-c",
"json",
"ios",
"coldfusion",
"server"
],
"Title": "Better way to fetch JSON data from a server from iOS app"
} | 48934 |
<p>I'm an experienced programmer that also has <em>a little</em> experience with functional programming, although mostly theoretical (as in hobby-level reading and very minor projects).</p>
<p>I recently decided to work through the new book "Beginning Haskell" to get up to speed with Haskell and try to crank out something worthy of a github repo. Early in the book you are asked to implement a <code>Client</code> ADT including some supportive data types for Person and Gender. I did it like this and I'm not liking it at all:</p>
<pre><code>data Gender = Male | Female | Unknown | None
deriving (Show, Eq)
data Person = Person { fName :: String, lName :: String, gender :: Gender }
deriving (Show, Eq)
data Client = GovOrg { code :: String, name :: String }
| Individual { code :: String, person :: Person }
| Company { code :: String, name :: String, contact :: Person }
deriving (Show, Eq)
</code></pre>
<p>After this you are asked to write a function that takes <code>[Client]</code> and returns the count for the different genders, e.g. "out of the 20 clients listed, we have 5 male, 5 female, 10 unknown". Let's call it <code>countGenders</code>. Below is the code I've ended up with, and I feel that it's a complete mess and lacks any feeling of clarity or elegance. I think my OOP-brain is forcing me into bad designs. I'll walk you through the lines below. Once again I am not at all happy with this.</p>
<p>First we have a result data type. Could be just an <code>(Int, Int, Int)</code>, but I feel like the location in the tuple isnt a natural fit with what the data should represent (as opposed to <code>Point Int Int</code>):</p>
<p><code>data GenderCount = GenderCount { male :: Int, female :: Int, unknown :: Int }</code></p>
<p>Then we have the top level function that is supposed to be invoked. Maps <code>genderCount</code> across a <code>[Client]</code>, which results in <code>[(Int, Int, Int)]</code>, then unzips those and sums each list.</p>
<pre><code>countGenders :: [Client] -> GenderCount
countGenders cs = GenderCount (sum m) (sum f) (sum u)
where (m, f, u) = unzip3 $ map genderCount cs
</code></pre>
<p>Then we have genderCount, which maps a Client to a result tuple (Male, Female, Unknown):</p>
<pre><code>genderCount :: Client -> (Int, Int, Int)
genderCount c = case cGender c of
Male -> (1, 0, 0)
Female -> (0, 1, 0)
Unknown -> (0, 0, 1)
None -> (0, 0, 0)
</code></pre>
<p>Last we have cGender, which gets the gender from a client (using <code>RecordWildCards</code> extension):</p>
<pre><code>cGender :: Client -> Gender
cGender GovOrg {} = None
cGender Individual { .. } = gender person
cGender Company { .. } = gender contact
</code></pre>
<p><strong>As you can see this is all a mess.</strong> But I'm having trouble thinking of how to refine it. I feel like my data model is bloated, which bleeds over into too many functions to do something that should be really simple. I would appreciate any feedback on the data model, the functions or anything else.</p>
<p>Here is the entire code if you want to look it over in full context: <a href="http://pastebin.com/Vymcd6Bj" rel="nofollow">http://pastebin.com/Vymcd6Bj</a></p>
| [] | [
{
"body": "<p>This isn't that much of a mess at all. Let's clean it up, then get a little fancy.</p>\n\n<p>Right off the bat it seems a little funky to have a <code>None</code> <code>Gender</code>, as it appears you're not actually trying to account for agender individuals but instead providing for the failure to produce a <code>Gender</code> for a particular <code>Client</code>. Operations that might fail in Haskell usually signal so by returning a <code>Maybe</code> value, so let's drop <code>None</code> from the definition and see what needs changing.</p>\n\n<pre><code>data Gender = Male | Female | Unknown\n deriving (Show, Eq)\n</code></pre>\n\n<p><code>genderCount</code> and <code>cGender</code> depend on <code>None</code>, let's start with the latter. <code>c</code> doesn't mean much as a prefix to me, so I'm going to call this function <code>clientGender</code>, but that's a stylistic preference. Changing this function to use <code>Maybe</code> is straightforward.</p>\n\n<pre><code>clientGender :: Client -> Maybe Gender\nclientGender GovOrg {} = Nothing\nclientGender Individual {..} = Just (gender person)\nclientGender Company {..} = Just (gender contact)\n</code></pre>\n\n<p>Now let's turn to <code>genderCount</code>. The first thing to notice is that the function is a tiny wrapped up <code>case</code> statement. This is usually a code smell to me that hints at a missed opportunity to break functions into smaller, more independent pieces. In this case <code>genderCount</code> has nothing to do with <code>Client</code>s, so let's rip that part out!</p>\n\n<pre><code>genderCount :: Gender -> (Int, Int, Int) -- Counting Genders, not Clients!\ngenderCount Male = (1, 0, 0)\ngenderCount Female = (0, 1, 0)\ngenderCount Unknown = (0, 0, 1)\n</code></pre>\n\n<p>This is still unsatisfactory, right? There's that convention-typed tuple, and we've got a perfectly good <code>GenderCount</code> datatype lying around, so let's use it.</p>\n\n<pre><code>genderCount :: Gender -> GenderCount\ngenderCount Male = GenderCount 1 0 0\ngenderCount Female = GenderCount 0 1 0\ngenderCount Unknown = GenderCount 0 0 1\n</code></pre>\n\n<p>It's a small change, but users of <code>GenderCount</code> can rely on the field names rather than a tuple ordering.</p>\n\n<p>And now <code>countGenders</code>, the piece that glues it all together. Our type is still correct, which is awesome! No changes there. The implementation though is doing a few different things we'll need to adjust. In an informational sense it's determining the genders of all of the clients, then accumulating a count of each <code>Gender</code>. What it looks like though is some weird tuple math to produce a <code>GenderCount</code> value from nowhere! We can rewrite it given our new implementations to be a little prettier, but first we're going to need a way to add two <code>GenderCount</code>s together.</p>\n\n<pre><code>addGenderCounts :: GenderCount -> GenderCount -> GenderCount\naddGenderCounts (GenderCount m f u) (GenderCount n g v) = GenderCount (m + n) (f + g) (u + v)\n</code></pre>\n\n<p>A lot of repeated instances of <code>GenderCount</code> in there, but that's not so bad given we can use this as a combinator. Now we can put our <code>countGenders</code> function together.</p>\n\n<pre><code>countGenders :: [Client] -> GenderCount\ncountGenders = foldr (addGenderCounts . genderCount) (GenderCount 0 0 0) . mapMaybe clientGender\n</code></pre>\n\n<p>This works! I've imported <code>mapMaybe</code> from <code>Data.Maybe</code> here to account for our <code>clientGender</code> function sometimes returning <code>Nothing</code> (<code>mapMaybe</code> drops all the <code>Nothing</code>s and returns a list of the <code>Just</code> values). We use a right fold to accumulate our <code>GenderCount</code> values, and a starting value of <code>GenderCount 0 0 0</code> for our accumulator.</p>\n\n<p>There are a few ways to go from here to clean things up further. You could get rid of the <code>GenderCount 0 0 0</code> value by using <code>foldr1</code>, at the cost of adding another composition with <code>map</code> into the mix. If you have sharp eyes and a working knowledge of the <a href=\"http://www.haskell.org/haskellwiki/Typeclassopedia\" rel=\"nofollow\">Typeclassopedia</a> you'll note a striking similarity between the way we use <code>GenderCount</code> with a right fold, and a <code>Monoid</code>. If you don't have a working knowledge of the Typeclassopedia, our motivation is that <code>Monoid</code>s allow us to specify an identity element and an associative reduction operation, revealing some higher level abstractions (and functions) we can use to wire our code together. Let's make a <code>Monoid</code>.</p>\n\n<pre><code>instance Monoid GenderCount where\n mempty = GenderCount 0 0 0\n mappend = addGenderCounts\n\n-- Laws:\n-- mempty <> x = x\n-- x <> mempty = x\n-- x <> (y <> z) = (x <> y) <> z\n</code></pre>\n\n<p>I won't prove the <code>Monoid</code> laws, but you should be able to see that they are trivial given the properties of addition and our definition of <code>GenderCount</code>.</p>\n\n<p>Let's try one more pass at <code>countGenders</code> now.</p>\n\n<pre><code>countGenders :: [Client] -> GenderCount\ncountGenders = foldMap genderCount . mapMaybe clientGender\n</code></pre>\n\n<p>Nice!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T14:52:13.320",
"Id": "86008",
"Score": "0",
"body": "Thanks a lot! You really got what I felt was at the heart of the issue for me - a misused data model. I had an inkling that `Maybe` would be better than a None gender, but it just bloated my code more. The `mapMaybe` function helps a bit with that and makes it a lot cleaner though.\n\nI'm aware of the Monoid type/laws and could see its applicability to the problem but wasn't sure how to proceed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T00:43:37.027",
"Id": "86105",
"Score": "0",
"body": "Glad to help! I find the best way to learn about nifty little functions like `mapMaybe` is to read through the [docs for `base`](http://hackage.haskell.org/package/base). Anywhere in the `Data` or `Control` namespaces is probably a good place to start."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T06:27:17.460",
"Id": "48961",
"ParentId": "48935",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48961",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T18:36:01.790",
"Id": "48935",
"Score": "4",
"Tags": [
"beginner",
"haskell",
"functional-programming"
],
"Title": "Counting items in categories"
} | 48935 |
<p>Note: This is the first time I've written anything whatsoever in straight C. In other words: <em>I have no idea what I'm doing.</em></p>
<p>I recently had a task that involved temporarily relaying responses from one server, through a web-facing server, and then on to the client. Along the way, the relay server had to dynamically add an HTTP header of its own to the relayed response. Came up with a quick and dirty scripted solution, but it worked for the duration it had to.</p>
<p>Still, I thought it might be a good exercise for getting to know a little C, just for fun, since something like this would benefit from being written closer to the metal.</p>
<p>So below is a program (I call it <code>headshape</code> for lack of a better name) where you pipe in (say, from a curl command) an HTTP response including headers, and the program will add/remove/modify one of those headers, and pass on the rest on as-is. Given no arguments, stdin will just pass to stdout.</p>
<p>E.g.</p>
<pre><code>$ curl -i example.com | headshape # pass through
$ curl -i example.com | headshape Server # remove the Server header
$ curl -i example.com | headshape Via 'foobar' # add/modify the Via header
</code></pre>
<p>So it does a bit of HTTP parsing to find the right header - or add it if it's not there - and to figure out what the response code is. Only responses with a 2xx status will be altered, 1xx responses will be ignored, and 3xx and above will cause it to just forward all remaining data unaltered (this partly an arbitrary choice; it's just a code exercise after all). It also defaults to forwarding everything as-is if it sees something it can't make sense of.</p>
<p>Below is the code. Much to my surprise it seems to work exactly as intended but, again, <em>I've never written C code</em>, so it's no doubt horrible. Any and all tips are welcome.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define CRLF "\r\n" // HTTP line ending
#define BLOCK_SIZE 1024 // Any reason to make this larger/smaller?
#define HEADER_DELIM ": " // Used to spot header lines
#define MAX_HEADER_LENGTH 100 // max length of a header *name*; not the whole header line
static int parseStatus(char* line);
static char* getHeaderName(char* line);
static int isDelimited(char* line, int continuation);
static int isBoundary(char* line);
void writeLine(char* line);
void passthru();
int main(int argc, char const *argv[]) {
// states
int should_parse = 0;
int effective_status = 0;
// options/
char* target_header = NULL;
char* payload_line = NULL;
// loop variables
int line_continued = 0;
int current_status = 0;
char* current_header = NULL;
char* line_out = NULL;
char line[BLOCK_SIZE];
// exit with >0 if nothing's being piped
if(isatty(fileno(stdin))) {
return 1; // TODO: is there a better code for this?
}
// Get the target header argument, if any
if(argc > 1) {
should_parse = 1; // could just check target_header, but this seems more descriptive
target_header = (char*) argv[1];
}
// Get the target value argument, if any
if(argc > 2) {
// build the payload header line (i.e. "Header: value")
size_t payload_length = 1;
payload_length += strlen(target_header);
payload_length += strlen(HEADER_DELIM);
payload_length += strlen(argv[2]);
payload_length += strlen(CRLF);
payload_line = (char *) malloc(payload_length);
strcpy(payload_line, target_header);
strcat(payload_line, HEADER_DELIM);
strcat(payload_line, argv[2]);
strcat(payload_line, CRLF);
}
// heading parsing loop
while(should_parse && fgets(line, BLOCK_SIZE, stdin)) {
// if previous fgets didn't get a complete, CRLF-delimited line
// (i.e. a line exceeded BLOCK_SIZE), assume the current chunk
// is the continuation, and output it without parsing
if(line_continued) {
writeLine(line_out);
line_continued = !isDelimited(line, line_continued);
continue;
}
// check if this is a "complete" CRLF-delimited line
line_continued = !isDelimited(line, line_continued);
// reference our input for later
line_out = line;
if((current_status = parseStatus(line))) {
// set the status code
effective_status = current_status;
// we're not interested in rewriting 3xx and higher responses
if(effective_status >= 300) {
// pass the remaining data directly to stdout
should_parse = 0;
}
} else if((current_header = getHeaderName(line))) {
// check if this is the header we're looking for
if(strcmp(current_header, target_header) == 0) {
// replace or remove the header
line_out = payload_line;
// pass the remaining data directly to stdout
should_parse = 0;
}
} else if(isBoundary(line)) {
// We've reached the end of the HTTP header section.
// If effective_status is 1xx, parsing continues but
// 2xx will stop the parsing and insert the header
// if need be
if(effective_status >= 200) {
// add the header, if this is a 2xx response
if(payload_line && effective_status < 300) {
writeLine(payload_line);
}
// pass the remaining data directly to stdout
should_parse = 0;
}
} else {
// stop parsing if the line isn't recognized and
// pass the remaining data directly to stdout
should_parse = 0;
}
// output the line (unless it's NULL)
if(line_out) writeLine(line_out);
}
// pass the remaining data directly to stdout
passthru();
// free the payload line, if necessary
if(payload_line) free(payload_line);
return 0;
}
// Gets the header name in the line, if any.
static char* getHeaderName(char* line) {
static char header[MAX_HEADER_LENGTH];
char* delim = strstr(line, HEADER_DELIM);
if(delim) {
size_t count = delim - line;
count = count >= MAX_HEADER_LENGTH ? MAX_HEADER_LENGTH - 1 : count;
strncpy(header, line, count);
header[count] = '\0';
return header;
}
return NULL;
}
// Match a line like "HTTP/1.x xxx..." and extract the status code
// Not exactly regex-like precision here, though. Maybe use strtok()?
static int parseStatus(char* line) {
size_t code_length = 4;
char* http = strstr(line, "HTTP/1.");
char* delim = strchr(line, ' ');
size_t remaining = strlen(line) - (delim - line) + 1;
if(http && delim && remaining > code_length) {
char code[remaining];
strncpy(code, delim, remaining);
return atoi(code);
}
return 0;
}
// Check whether a string ends with CRLF
// Note: This function keeps the last char of the line from its previous
// invocation in memory in order to spot the 2-character CRLF even if it's
// been split into separate fgets lines.
static int isDelimited(char* line, int continuation) {
static char prev = 0;
char tail[3] = {'\0', '\0', '\0'};
int offset = strlen(line) - 2;
if(offset >= 0) {
// grab last 2 chars
tail[0] = line[offset];
tail[1] = line[offset + 1];
} else if(continuation && offset == -1) {
// grab char carried over from earlier, and the line's single char
tail[0] = prev;
tail[1] = line[0];
}
prev = tail[1];
return !strcmp(tail, CRLF);
}
// is this line a "blank" CRLF line?
static int isBoundary(char* line) {
return strlen(line) == strlen(CRLF) && strcmp(line, CRLF) == 0;
}
// write to stdout & flush
void writeLine(char* line) {
fwrite(line, sizeof(char), strlen(line), stdout);
fflush(stdout);
}
// pass stdin through to stdout
void passthru() {
char buffer[BLOCK_SIZE];
while(1) {
size_t bytes = fread(buffer, sizeof(char), BLOCK_SIZE, stdin);
fwrite(buffer, sizeof(char), bytes, stdout);
fflush(stdout);
if(bytes < BLOCK_SIZE && feof(stdin)) break;
}
}
</code></pre>
| [] | [
{
"body": "<p>A few items:</p>\n<h2>Use <code>STDIN_FILENO</code></h2>\n<p>Instead of <code>fileno(stdin)</code> you can use the preprocessor symbol <code>STDIN_FILENO</code>, defined in <code><unistd.h></code> which you have already included.</p>\n<h2><code>should_parse</code> should be declared <code>bool</code></h2>\n<p>Assuming you're using a compiler that isn't decades old (<code>bool</code> was added in the c99 standard), you can include <code><stdbool.h></code> and use <code>bool</code> for the type of <code>should_parse</code>. It also allows you to use the values of <code>true</code> and <code>false</code> within the code to make the intention of that flag a little more explicit.</p>\n<p>The same is true for <code>line_continued</code>, the return value of <code>isBoundary</code>, and <code>isDelimited</code> and the second argument of <code>isDelimited</code>.</p>\n<h2><code>target_header</code> should be <code>const</code> and <code>argv</code> should not</h2>\n<p>Your <code>target_header</code> variable should be declared <code>const</code> because its contents are not altered by the program. If you make that change, you can also remove the cast from the line</p>\n<pre><code>target_header = (const char *)argv[1];\n</code></pre>\n<p>However, you wouldn't actually need that cast anyway if you had declared <code>main</code> as:</p>\n<pre><code>int main(int argc, char *argv[])\n</code></pre>\n<p>It does <em>seem</em> like that ought to be <code>const *argv</code> but that's counter to what the C standard says. In section 5.1.2.2.1, it says that:</p>\n<blockquote>\n<p>the strings pointed to by the <code>argv</code> array shall be modifiable by the program</p>\n</blockquote>\n<p>which implies that they're not <code>const</code>.</p>\n<h2>Don't abuse <code>fflush</code></h2>\n<p>You probably don't need to call <code>fflush</code> after every <code>fwrite</code>. The stream will automatically flush when the file is closed, which also happens automatically when <code>main</code> ends.</p>\n<h2>Make loop exits explicit</h2>\n<p>In <code>passthru()</code>, instead of using <code>while(1)</code> and then using a <code>break</code> it would be more clear to write it like this:</p>\n<pre><code>size_t bytes;\ndo {\n bytes = fread(buffer, sizeof(char), BLOCK_SIZE, stdin);\n fwrite(buffer, sizeof(char), bytes, stdout);\n} while (bytes == BLOCK_SIZE && !feof(stdin));\n</code></pre>\n<h2>Simplify <code>isBoundary</code></h2>\n<p>The <code>isBoundary</code> routine can be simplified as this:</p>\n<pre><code>// is this line a "blank" CRLF line?\nstatic bool isBoundary(char* line) {\n return strcmp(line, CRLF) == 0;\n}\n</code></pre>\n<p>There is no need to also compare their lengths, since that's already implicit in <code>strcmp</code>.</p>\n<h2>Calculation of <code>payload_line</code> is complex</h2>\n<p>The <code>payload_line</code> variable size is calculated, and then <code>malloc</code>'d and then copied, but it's only used a few other places. What you've got isn't wrong, but it might be worthwhile instead allocating a fixed size and then using <code>snprintf</code> to populate the string. That would collapse the dozen lines used for that calculation to the much simpler single line:</p>\n<pre><code>snprintf(payload_line, BLOCK_SIZE, "%s" HEADER_DELIM "%s" CRLF, target_header, argv[2]);\n</code></pre>\n<p>I'm sure there's more but I lack the time at the moment.</p>\n<h1>Update</h1>\n<p>I found some time and a few other things in the code.</p>\n<h2>Refactor <code>parseStatus</code></h2>\n<p>The current <code>parseStatus</code> routine does more work than needed to extract the status code. You don't need to copy the string to pass it to <code>atoi</code> so it can be greatly simplified like so:</p>\n<pre><code>static int parseStatus(char* line) {\n char* http = strstr(line, "HTTP/1.");\n if (http) {\n http = strchr(http, ' ');\n if (http) {\n return atoi(http);\n }\n }\n return 0;\n}\n</code></pre>\n<h2>Refactor <code>getHeaderName</code></h2>\n<p>Right now, the <code>getHeaderName</code> function is outlined something like this:</p>\n<pre><code>static char* getHeaderName(char* line) {\n static char header[MAX_HEADER_LENGTH];\n /* ... */\n return header;\n}\n</code></pre>\n<p>This works (and even some ancient library functions were done this way) but it's not thread-safe and the design can easily be improved. Instead, it's better to have the calling function allocate a buffer and pass it in, along with the length rather than pointing to an internal static buffer.</p>\n<h2>Refactor <code>isDelimited</code></h2>\n<p>In a similar vein, your <code>isDelimited</code> function is really only checking for two particular bytes, so it would be more clear and slightly faster to check for them directly instead of constructing a copy in memory and then using <code>strcmp</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:55:48.640",
"Id": "85925",
"Score": "0",
"body": "Great tips, thanks! Re `bool`: was trying some things out using ints, and it stuck; will definitely fix that. `argv`: I used my editor's C template and didn't ask questions. Good to know the `const` isn't required. `fflush`: I smelled that myself, but I also figured I'd have many Mbits/s streaming through, so maybe better to get stuff flushed asap? Loop exit: Guilty of googling and copy/pasting without thinking! `isBoundary`: Ah, of course! Should've seen that myself. `payload_line`: I could smell that code from a mile away, but I didn't know a better way to do it. Now I do - thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:58:06.637",
"Id": "85926",
"Score": "1",
"body": "It's a pretty good attempt for a first foray into C. You did well, despite all the nit picking!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:58:39.720",
"Id": "85927",
"Score": "1",
"body": "Oh, and in my defense, using `malloc` and `free` made me feel like I was _really_ writing C code after all these years of languages with GC ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T00:00:37.797",
"Id": "85928",
"Score": "0",
"body": "Thanks! And hey, nit-picking is what I want in a review! I mean, it'd be pretty cool if my very first stab at C was a gleaming example of perfection, but let's just say I didn't expect that to be the case :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T15:01:21.190",
"Id": "86012",
"Score": "0",
"body": "Just noticed your update - thanks again! Good point about the construction/signature of `getHeaderName` in particular. I definitely see your point (and I recognize the pass-in-a-buffer approach, now that you mention it). Great stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T17:08:09.943",
"Id": "86034",
"Score": "0",
"body": "Got to thinking: I assume stdin could contain a `NUL` char, which, as far as I can tell, wouldn't cause `fgets` to fail, but it would cause my `writeLine` function to mess up, since it uses `strlen`. Is there a good way to get around this, other than making my own (CRLF-based, while I'm at it) byte-for-byte `fgets` that also reports bytes-read? Obviously, valid HTTP headers shouldn't contain NULs, but I'd like the program to fail-safe and at minimum pass its input unaltered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T06:32:23.997",
"Id": "86121",
"Score": "0",
"body": "Under the heading:: \"Make loop exits explicit\"-> `fwrite(buffer, sizeof(char), bytes, stdout);1`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T07:19:23.537",
"Id": "86133",
"Score": "0",
"body": "Would you please correct that line? That is bothering me too much :-) \"There is a `1` at the end of line if you missed to spot it."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:32:24.387",
"Id": "48944",
"ParentId": "48937",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "48944",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T19:21:39.983",
"Id": "48937",
"Score": "11",
"Tags": [
"c",
"beginner",
"http"
],
"Title": "Modifying HTTP headers in a piped stream"
} | 48937 |
<p>I am posting this code up for review and debugging. This source code is for Java, and is meant to give you the exact day of the week from an entered date. </p>
<p><strong>Review</strong></p>
<ol>
<li>This program seems to have 2 case statements. Would it have made sense to use an enum variable to eliminate the second case statement?</li>
<li>How about restructuring my entire program to include one super class and a sub class?</li>
<li>Are these approach a good idea to shorten my code, or is my original code the best approach to my program's purpose?</li>
</ol>
<p><strong>Debugging</strong></p>
<p>Please feel free to test this program out, and reply with any incorrect output given from this code. I have tested this program with various dates and have gotten the correct output. However, it is always a good idea to have more eyes test this code out.</p>
<p><strong>Program Purpose:</strong></p>
<p>Enter any date from the 1800 to the present day, and this program will display the day of the week from the date entered.</p>
<p><strong>Example:</strong> </p>
<p>If a user entered "July 2 , 1985". This program will return "Tuesday", which was the day of the week that on "July 2, 1985".</p>
<pre><code>// Import Libraries
import javax.swing.*;
import java.util.*;
import java.io.*;
// This is my program.
public class DateCalc
{
public static void main (String[] args)
{
String month;
String day;
String inputYear;
Scanner keyboard = new Scanner(System.in);
// receiving input for my age variable
System.out.print( " \n \n Please Enter The Month Of The Date :");
month = keyboard.nextLine();
// receiving input for my weight variable
System.out.print( " \n Please Enter The Day Of The Date : ");
day = keyboard.nextLine();
// receiving input for my height variable
System.out.print( " \n Please Enter The Year OF The Date : ");
inputYear = keyboard.nextLine();
String stringYear = ""+ inputYear.charAt(inputYear.length()-2) + inputYear.charAt(inputYear.length()-1);
int year = Integer.parseInt(stringYear);
int intDay = Integer.parseInt(day);
switch(month.toLowerCase())
{
case "january" :
int janKey = 1;
results (day , inputYear, month, year, intDay, janKey);
break;
case "february":
int febKey = 4;
results (day , inputYear, month, year, intDay, febKey);
break;
case "march":
int marKey = 4;
results (day , inputYear, month, year, intDay, marKey);
break;
case "april":
int aprKey = 0;
results (day , inputYear, month, year, intDay, aprKey);
break;
case "may":
int maykey = 2;
results (day , inputYear, month, year, intDay, maykey);
break;
case "june":
int junKey = 5;
results (day , inputYear, month, year, intDay, junKey);
break;
case "july":
int julKey = 0;
results (day , inputYear, month, year, intDay, julKey);
break;
case "august":
int augKey = 3;
results (day , inputYear, month, year, intDay, augKey);
break;
case "september":
int septKey = 6;
results (day , inputYear, month, year, intDay, septKey);
break;
case "october":
int octKey = 1;
results (day , inputYear, month, year, intDay, octKey);
break;
case "november":
int novKey = 4;
results (day , inputYear, month, year, intDay, novKey);
break;
case "december":
int decKey = 4;
results (day , inputYear, month, year, intDay, decKey);
break;
// IN MY DEFUALT CASE " inputValidation " WILL BE EXECUTED
default:
JOptionPane.showMessageDialog(null," Invalid Entry Please Try Again " );
}
}
public static void results ( String day , String inputYear, String month, int year, int intDay, int key )
{
int quarter = year / 4;
int sum = year + quarter + intDay + key;
System.out.println(" \n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("*********************************************************************** ");
System.out.println("*********************** Result ********************************** ");
System.out.println("*********************************************************************** ");
System.out.println( " \n\n\t\t Date Entered Was : " );
System.out.println(" \n \t \t " + month + " "+ day + " , " + inputYear );
System.out.println( " \n\n Last Two Digits Of The Year Were : ........ " + year);
System.out.println( " \n One Quarter Of Last Two Digits : ........ " + quarter);
System.out.println( " \n The Given Day Of The Month Entered : ........ " + day);
System.out.println( " \n The Index Key Of This Month : ........ " + key);
System.out.println( " \n The Sum Of All The Numbers Above Is : ........ " + sum);
dayLookUp(sum);
String weekDay = dayLookUp(sum);
System.out.println( " \n \n \t The Day Of The Week Was : ........ " + weekDay);
}
public static String dayLookUp ( int sum )
{
String weekDay;
String error = " \n \n Please Check Your Dates And Try Again " ;
int day = sum % 7;
switch(day)
{
case 1 :
weekDay = " Sunday ";
return weekDay;
case 2:
weekDay = " Monday ";
return weekDay;
case 3:
weekDay = " Tuesday ";
return weekDay;
case 4:
weekDay = " Wednesday ";
return weekDay;
case 5:
weekDay = " Thursday ";
return weekDay;
case 6:
weekDay = " Friday ";
return weekDay;
case 7:
weekDay = " Saturday ";
return weekDay;
// IN MY DEFUALT CASE " inputValidation " WILL BE EXECUTED
default:
JOptionPane.showMessageDialog(null," Invalid Entry Please Try Again " );
return error;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T09:45:01.913",
"Id": "85975",
"Score": "2",
"body": "What good do you think it would do to introduce inheritance?"
}
] | [
{
"body": "<h1>Formatting</h1>\n\n<p>Your intentation is a bit off. Please improve that. Use your IDE's automatic indentation keyboard shortcut for an easy fix (Ctrl + I in Eclipse).</p>\n\n<p>In Java, braces go on the same line, for example</p>\n\n<pre><code>public class DateCalc\n\n{\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public class DateCalc {\n</code></pre>\n\n<h1>Your questions</h1>\n\n<blockquote>\n <p>This program seems to have two case statements. Would it have made sense to use an <code>enum</code> variable to eliminate the second case statement?</p>\n</blockquote>\n\n<p>Yes. And not only the second. The first as well.</p>\n\n<blockquote>\n <p>How about restructuring my entire program to include one super class and a sub class? </p>\n</blockquote>\n\n<p>I see absolutely no reason whatsoever why you'd want to include a superclass and a subclass in this program. The program is simple enough that there's no need to use polymorphism.</p>\n\n<blockquote>\n <p>Are these approach a good idea to shorten my code, or is my original code the best approach to my program's purpose?</p>\n</blockquote>\n\n<p>You need to learn how to use the data structures and types that Java provides.</p>\n\n<h1>Cleaning up</h1>\n\n<pre><code>results(day, inputYear, month, year, intDay, janKey);\n</code></pre>\n\n<p>You're calling one variant or another of <code>results</code> on all methods. The only variance is in the <code>janKey</code> variable and value that is used.</p>\n\n<h3>Months</h3>\n\n<p>Here's an example that is using <code>HashMap</code> for this lookup:</p>\n\n<pre><code>Map<String, Integer> monthMap = new HashMap<String, Integer>();\nmonthMap.put(\"january\" , 1);\nmonthMap.put(\"february\", 4);\nmonthMap.put(\"march\" , 4);\nint key = monthMap.get(month.toLowerCase());\nresults(day, inputYear, month, year, intDay, key);\n</code></pre>\n\n<p>Of course it'd be better to use an <code>enum</code>. </p>\n\n<pre><code>enum Month {\n JANUARY(1), FEBRUARY(4), MARCH(4);\n\n public final int key;\n\n private Month(int key) {\n this.key = key;\n }\n}\n\nint key = Month.valueOf(month.toUpperCase()).key;\n</code></pre>\n\n<h3>Weekdays</h3>\n\n<pre><code>weekDay = \" Wednesday \";\nreturn weekDay;\n</code></pre>\n\n<p><strong>Get rid of that temporary variable and return directly!</strong></p>\n\n<p>Or, again, even better: <strong>Use an enum!!</strong></p>\n\n<pre><code>enum Weekday {\n Sunday, Monday, Tuesday;\n}\n\nreturn Weekday.values()[day - 1];\n</code></pre>\n\n<h1>Input</h1>\n\n<p>You seem to only be accepting dates on the 1900's. This is bad. At least provide a decent error message for when a date is outside the range accepted by your program.</p>\n\n<p>I'd like to see more dates supported. At first I actually tried some other dates and discovered that it was incorrect result, then I found out why.</p>\n\n<pre><code>String stringYear = \"\"+ inputYear.charAt(inputYear.length()-2) + inputYear.charAt(inputYear.length()-1);\n</code></pre>\n\n<p>I don't like that line at all. First of all, it could be better expressed as</p>\n\n<pre><code>String stringYear = inputYear.substring(inputYear.length() - 2);\n</code></pre>\n\n<p>secondly, <em>you're asking the user to input more information than what you use</em>. Instead, ask for less input from the user.</p>\n\n<p>I would however, like to see that you instead <em>added support</em> for the following dates:</p>\n\n<ul>\n<li>April 22, 2000 was a saturday.</li>\n<li>September 4, 2012 was a tuesday.</li>\n<li>May 4, 2014 (today) is a sunday.</li>\n<li>March 22, year -5 was a friday. (If you extrapolate the Gregorian calendar that far)</li>\n</ul>\n\n<h1>Algorithm</h1>\n\n<p>Your algorithm seems to be based on a restricted variant of <a href=\"http://en.wikipedia.org/wiki/Doomsday_rule\" rel=\"nofollow\">The Doomsday Rule</a>. As is explained on Wikipedia, you could add support for any century. No need to be limited to the 1900's.</p>\n\n<h1>Java 8</h1>\n\n<p>If possible, <strong>use Java 8!</strong> Java 8 provides the <code>java.time</code> package which makes it very easy to look-up a day of week:</p>\n\n<pre><code>System.out.println(Year.of(1985).atMonth(Month.JULY).atDay(2).getDayOfWeek());\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>TUESDAY\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T02:09:34.567",
"Id": "85937",
"Score": "1",
"body": "If Java 8 is not an option, JodaTime is the precursor and provides a nice API."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T22:10:19.227",
"Id": "48940",
"ParentId": "48938",
"Score": "7"
}
},
{
"body": "<h2>User experience bugs</h2>\n\n<ul>\n<li><p>The UI is entirely console-based — except that errors are reported in a Swing message dialog. That's bizarre.</p></li>\n<li><p>The user has no way of knowing that the program only accepts fully spelled out month names, not numbers or abbreviations.</p></li>\n<li><p>The blank lines in the output result in excessive vertical spacing, in my opinion.</p></li>\n</ul>\n\n<h2>Algorithm bugs</h2>\n\n<ul>\n<li><p>Any Saturday will result in an error, since <code>int day = sum % 7</code> produces results in the range 0 to 6. Therefore, <code>case 7</code> will never match, and case 0 is never handled.</p>\n\n<pre><code>$ java DateCalc\n\n\n Please Enter The Month Of The Date :July\n\n Please Enter The Day Of The Date : 6\n\n Please Enter The Year OF The Date : 1985\n\n\n\n\n\n\n\n\n\n\n\n\n\n*********************************************************************** \n*********************** Result ********************************** \n*********************************************************************** \n\n\n Date Entered Was : \n\n July 6 , 1985\n\n\n Last Two Digits Of The Year Were : ........ 85\n\n One Quarter Of Last Two Digits : ........ 21\n\n The Given Day Of The Month Entered : ........ 6\n\n The Index Key Of This Month : ........ 0\n\n The Sum Of All The Numbers Above Is : ........ 112\n\n\n The Day Of The Week Was : ........ \n\n Please Check Your Dates And Try Again\n</code></pre></li>\n<li><p>You have a Y2K bug. Since you discard the first two digits of the year, calculations all seem to assume the 20th century.</p>\n\n<pre><code>$ java DateCalc\n\n\n Please Enter The Month Of The Date :May\n\n Please Enter The Day Of The Date : 5\n\n Please Enter The Year OF The Date : 2014\n\n\n\n\n\n\n\n\n\n\n\n\n\n***********************************************************************\n*********************** Result **********************************\n***********************************************************************\n\n\n Date Entered Was :\n\n May 5 , 2014\n\n\n Last Two Digits Of The Year Were : ........ 14\n\n One Quarter Of Last Two Digits : ........ 3\n\n The Given Day Of The Month Entered : ........ 5\n\n The Index Key Of This Month : ........ 2\n\n The Sum Of All The Numbers Above Is : ........ 24\n\n\n The Day Of The Week Was : ........ Tuesday\n</code></pre></li>\n</ul>\n\n<h2>Code structure issues</h2>\n\n<p>You have three functions: <code>main()</code>, <code>results()</code>, and <code>dayLookup()</code>.</p>\n\n<ul>\n<li><p><code>main()</code> is too long. You can't tell at a glance what the outline of the program is. Most of it has to do with prompting for a date, so that should be split into a separate function.</p></li>\n<li><p><code>dayLookup()</code>, being a lookup, should be replace by an array lookup.</p></li>\n<li><p>The method signature for <code>results()</code> is awkward.</p></li>\n</ul>\n\n<h2>Code hygiene issues</h2>\n\n<ul>\n<li><p><code>import java.io.*</code> is superfluous. The fact that it's a wildcard import makes it worse than an extra single-class import.</p></li>\n<li><p>You have some mismatched comments regarding the use of <code>Scanner</code>.</p></li>\n<li><p>You opened the <code>Scanner</code> without closing it after use.</p></li>\n<li><p>Your indentation is inconsistent.</p></li>\n</ul>\n\n<h2>Proposed implementation</h2>\n\n<p>Without changing the core of the algorithm, this is how I would reorganize the code.</p>\n\n<pre><code>import java.text.ParseException;\nimport java.util.*;\n\npublic class DateCalc\n{\n private static String[] MONTH_NAMES = new String[] {\n \"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\",\n \"September\", \"October\", \"November\", \"December\"\n };\n private static int[] MONTH_KEYS = new int[] {\n 1, 4, 4, 0,\n 2, 5, 0, 3,\n 6, 1, 4, 4\n };\n private static String[] DAYS_OF_WEEK = new String[] {\n \"Saturday\",\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\"\n };\n\n /**\n * Prompts for a date.\n *\n * @return A three-element array, consisting of the year, month, and day of\n * month. The month is 0-based, i.e. 0 represents January.\n */\n public static int[] promptDate(Scanner in) throws ParseException {\n System.out.print( \" Please Enter The Month (e.g. \\\"January\\\") : \");\n String month = in.nextLine();\n System.out.print( \" Please Enter The Day Of The Date : \");\n String day = in.nextLine();\n System.out.print( \" Please Enter The Year Of The Date : \");\n String year = in.nextLine();\n\n int[] result = new int[3];\n try {\n int yyyy = result[0] = Integer.parseInt(year);\n int dd = result[2] = Integer.parseInt(day);\n for (int i = 0; i < MONTH_NAMES.length; i++) {\n if (MONTH_NAMES[i].equalsIgnoreCase(month)) {\n int mm = result[1] = i;\n return result;\n }\n }\n throw new ParseException(\"Invalid month \" + month, 0);\n } catch (NumberFormatException e) {\n throw new ParseException(e.getMessage(), 0);\n }\n }\n\n public static String results(int[] ymd) {\n int yyyy = ymd[0];\n int mm = ymd[1];\n int dd = ymd[2];\n\n int yy = ymd[0] % 100;\n int quarter = yy / 4;\n int monthKey = MONTH_KEYS[mm];\n int sum = yy + quarter + dd + monthKey;\n\n return String.format(\n \"***********************************************************************\\n\" +\n \"*********************** Result **********************************\\n\" +\n \"***********************************************************************\\n\" +\n \"\\n\" +\n \"\\t\\t Date Entered Was :\\n\" +\n \"\\t \\t %s %s, %s\\n\" +\n \"\\n\" +\n \" Last Two Digits Of The Year Were : ........ %s\\n\" +\n \" One Quarter Of Last Two Digits : ........ %s\\n\" +\n \" The Given Day Of The Month Entered : ........ %s\\n\" +\n \" The Index Key Of This Month : ........ %s\\n\" +\n \" The Sum Of All The Numbers Above Is : ........ %s\\n\" +\n \"\\n\" +\n \" The Day Of The Week Was : ........ %s\",\n MONTH_NAMES[mm], dd, yyyy,\n yy, quarter, dd, monthKey, sum,\n DAYS_OF_WEEK[sum % 7]\n );\n }\n\n public static void main(String[] args) {\n int[] ymd = null;\n try (Scanner in = new Scanner(System.in)) {\n do {\n try {\n ymd = promptDate(in);\n } catch (ParseException badDate) {\n System.err.println(\" Invalid Entry Please Try Again \" );\n }\n } while (ymd == null);\n }\n\n System.out.println(\"\\n\");\n System.out.println(results(ymd));\n }\n\n}\n</code></pre>\n\n<h2>Using Java 7 libraries</h2>\n\n<p><a href=\"/questions/tagged/datetime\" class=\"post-tag\" title=\"show questions tagged 'datetime'\" rel=\"tag\">datetime</a>-handling code is always complicated. Unless you are deliberately <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a>, you should use existing libraries.</p>\n\n<p>@Simon has given a solution using Java 8. If you are not ready to use Java 8, then the following function would work.</p>\n\n<pre><code>import java.text.*;\nimport java.util.Date;\nimport java.util.Locale;\n\n/**\n * Computes the day of the week for a given date.\n *\n * @param ymd A date of the form \"January 1, 2014\"\n * @return The day of week, e.g. \"Saturday\"\n */\npublic static String dayOfWeek(String mmmmdyyyy) throws ParseException {\n DateFormat inFmt = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);\n Date d = inFmt.parse(mmmmdyyyy);\n\n StringBuffer sb = new StringBuffer();\n DateFormat outFmt = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);\n FieldPosition dowField = new FieldPosition(DateFormat.DAY_OF_WEEK_FIELD);\n outFmt.format(d, sb, dowField);\n return sb.substring(dowField.getBeginIndex(), dowField.getEndIndex());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T11:24:20.993",
"Id": "85985",
"Score": "0",
"body": "Closing the scanner closes `System.in` which means that the second time `promptDate` is called you get a `NoSuchElementException`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T17:13:22.053",
"Id": "86037",
"Score": "0",
"body": "@fgb You're right: closing the scanner also closes `System.in`. Rev 2 should address that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T23:33:55.213",
"Id": "86102",
"Score": "0",
"body": "100% behind use of static arrays over case statements -- just all positive -- easier to read -- easier to maintain -- and faster."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T09:25:20.780",
"Id": "48966",
"ParentId": "48938",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T21:12:27.243",
"Id": "48938",
"Score": "6",
"Tags": [
"java",
"datetime"
],
"Title": "Output day of the week from given date"
} | 48938 |
<p>Can someone review this code for me? I'm not completely sure I did this correctly. I also would like help creating the code for the "walk" "don't walk" lights.</p>
<p>I needed to create a traffic intersection. Each traffic light has a cycle of 31 seconds red, followed by 26 seconds green, followed by 3 seconds yellow. The red in the north-south direction starts at the same time as the green in the east-west direction. There will be a 60 second light cycle, and a 2 second overlap where the lights are red in all directions. The walk-don't walk signal reads walk for the 26 second green light, and don't walk for all other times.</p>
<pre><code>Public Class _12
Private Sub N_S_G_Lights()
pb_N.BackColor = Color.Green
lbl_N.BackColor = Color.Green
pb_S.BackColor = Color.Green
lbl_S.BackColor = Color.Green
End Sub
Private Sub N_S_Y_Lights()
pb_N.BackColor = Color.Yellow
lbl_N.BackColor = Color.Yellow
pb_S.BackColor = Color.Yellow
lbl_S.BackColor = Color.Yellow
End Sub
Private Sub N_S_R_Lights()
pb_N.BackColor = Color.Red
lbl_N.BackColor = Color.Red
pb_S.BackColor = Color.Red
lbl_S.BackColor = Color.Red
End Sub
Private Sub W_E_G_Lights()
pb_W.BackColor = Color.Green
lbl_W.BackColor = Color.Green
pb_E.BackColor = Color.Green
lbl_E.BackColor = Color.Green
End Sub
Private Sub W_E_Y_Lights()
pb_W.BackColor = Color.Yellow
lbl_W.BackColor = Color.Yellow
pb_E.BackColor = Color.Yellow
lbl_E.BackColor = Color.Yellow
End Sub
Private Sub W_E_R_Lights()
pb_W.BackColor = Color.Red
lbl_W.BackColor = Color.Red
pb_E.BackColor = Color.Red
lbl_E.BackColor = Color.Red
End Sub
Private Sub _12_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
pb_N.BackColor = Color.Red
pb_E.BackColor = Color.Red
pb_S.BackColor = Color.Red
pb_W.BackColor = Color.Red
lbl_N.BackColor = Color.Red
lbl_E.BackColor = Color.Red
lbl_S.BackColor = Color.Red
lbl_W.BackColor = Color.Red
End Sub
Private Sub Lights()
If lbl_time.Text <= 33 Then
W_E_R_Lights()
ElseIf lbl_time.Text >= 34 And lbl_time.Text <= 58 Then
W_E_G_Lights()
ElseIf lbl_time.Text >= 59 Then
W_E_Y_Lights()
ElseIf lbl_time.Text >= 60 Then
W_E_R_Lights()
End If
If lbl_time.Text <= 26 Then
N_S_G_Lights()
ElseIf lbl_time.Text >= 27 And lbl_time.Text <= 29 Then
N_S_Y_Lights()
ElseIf lbl_time.Text >= 30 Then
N_S_R_Lights()
End If
End Sub
Private Sub Timer_N_Tick(sender As System.Object, e As System.EventArgs) Handles Timer_N.Tick
lbl_time.Text = Val(lbl_time.Text) + 1
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
lbl_time.Text = "55"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
lbl_time.Text = "25"
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
If lbl_time.Text <= 60 Then
Lights()
Else
lbl_time.Text = "0"
End If
End Sub
End Class
</code></pre>
| [] | [
{
"body": "<h3>Naming.</h3>\n<p><code>N_S_G_Lights</code> could be called <code>NorthSouthGreenLights</code>, but that wouldn't make it a much better name. Method names should start with a verb, they <em>do something</em>.</p>\n<p>However, the pattern is consistent, which is a good thing. It's <em>redundant</em> though.</p>\n<h3>Structure.</h3>\n<p>The things you need to <em>do</em> depend on the <em>vocabulary</em> you're writing your code with - <em>methods</em> are <em>verbs</em>, <em>classes</em> are <em>subjects</em>. Classes are definitions for <em>objects</em>, which <em>encapsulate</em> a piece of functionality and <em>abstract</em> away the implementation details.</p>\n<p>The first <em>object</em> I'd think of a design for, would be some <code>TrafficLight</code> class. I'd want the UI code to only have to be told <em>what color that traffic light is</em>, and draw the appropriate background color in that <code>PictureBox</code>.</p>\n<p>The form code doesn't need to know about a <code>Timer</code> - it needs to know about a <code>TrafficLight</code>, and from that object it needs to know the <code>LightColor</code>, and it needs <em>to be notified</em> whenever the color changes.</p>\n<p>I'd be expecting something like this in a class called <code>TrafficLight</code>:</p>\n<pre><code>Private Const RedSeconds As Integer = 31\nPrivate Const GreenSeconds As Integer = 26\nPrivate Const YellowSeconds As Integer = 3\n\nPrivate LightTimer As Timer 'ticks every second\n\nPrivate CurrentColor As Color\n\nPublic Event Changed(ByVal NewColor As Color)\n</code></pre>\n<p>I like that you have a single timer for the whole 60-second cycle, but the magic numbers in <code>Lights()</code> make it hard to correlate what you've done with what the requirements are. Using constants as above, helps making the code more readable. The fact that your logic relies on UI values isn't very nice, too.</p>\n<p>When you have a <code>TrafficLight</code> that raises an event that says <em>"Hey there, if it's of any interest to you, I'm changing my current color right now"</em> to your form, the form itself doesn't know how the <code>TrafficLight</code> operates, but it knows that when color changes, it needs to change the background color of some <code>PictureBox</code>:</p>\n<pre><code>Private Sub NorthSouthLight_Changed(ByVal NewColor As Color)\n\n NorthTrafficLightPicture.BackColor = NewColor\n NorthLabel.BackColor = NewColor\n\n SouthTrafficLightPicture.BackColor = NewColor\n SouthLabel.BackColor = NewColor\n\nEnd Sub\n\nPrivate Sub EastWestLight_Changed(ByVal NewColor As Color)\n\n EastTrafficLightPicture.BackColor = NewColor\n EastLabel.BackColor = NewColor\n\n WestTrafficLightPicture.BackColor = NewColor\n WestLabel.BackColor = NewColor\n\nEnd Sub\n</code></pre>\n<p>What color that is, isn't important - it's conveyed by the <code>Changed</code> event, if a <code>TrafficLigth</code> wanted to be <code>Blue</code>, the form would happily comply.</p>\n<hr />\n<p><strong>TL;DR</strong>: In other words, I think your code could greatly benefit from a little bit more of an <em>Object-Oriented</em> approach, especially if this code is <a href=\"/questions/tagged/vb.net\" class=\"post-tag\" title=\"show questions tagged 'vb.net'\" rel=\"tag\">vb.net</a> (I was assuming <a href=\"/questions/tagged/vba\" class=\"post-tag\" title=\"show questions tagged 'vba'\" rel=\"tag\">vba</a> all along, when I came across a <code>Handles</code> keyword, which I haven't seen used in VBA).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T03:43:08.753",
"Id": "48955",
"ParentId": "48943",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T23:23:06.917",
"Id": "48943",
"Score": "7",
"Tags": [
"vb.net"
],
"Title": "Traffic light implementation"
} | 48943 |
<p>Please review my implementation of <code>mergesort</code>:</p>
<pre><code>mergesort' :: (Ord a) => [a] -> [a]
mergesort' [] = []
mergesort' xs = merge' (sort' fst', sort' snd')
where fst' = take half xs
snd' = drop half xs
half = len `div` 2
len = length xs
merge' :: (Ord a) => ([a], [a]) -> [a]
merge' ([], []) = []
merge' ([], ys) = ys
merge' (xs, []) = xs
merge' (x:xs, y:ys) = if x < y then x : merge' (xs, y:ys) else y : merge'(x:xs, ys)
sort' :: (Ord a) => [a] -> [a]
sort' [] = []
sort' (x:xs) = m : sort' rest
where m = foldl (\acc x -> if x < acc then x else acc) x xs
rest = filterOne' (/= m) (x:xs)
filterOne' :: (a -> Bool) -> [a] -> [a]
filterOne' _ [] = []
filterOne' f (x:xs) = if not $ f x then xs else x : filterOne' f xs
</code></pre>
<p>If it doesn't adhere to the <code>mergesort</code> algorithm, please let me know.</p>
<p>Also, is there a Haskell library function for my <code>filterOne'</code>?</p>
| [] | [
{
"body": "<p>For your <code>merge</code> function, you can simplify it a bit using <a href=\"http://www.haskell.org/haskellwiki/Keywords#.40\" rel=\"nofollow\">as-patterns</a>. This allows you to bind both <code>x</code>, <code>xs</code>, and the full list to a name:</p>\n\n<pre><code>merge' (xs'@(x:xs), ys'@(y:ys)) = if x < y then x : merge' (xs, ys') else y : merge (xs', ys)\n</code></pre>\n\n<p>This basically says \"Use the name <code>xs'</code> to refer to <code>(x:xs)</code>\".</p>\n\n<p>The closest thing in <code>Data.List</code> to your <code>filterOne'</code> function is probably <a href=\"http://hackage.haskell.org/package/base-4.7.0.0/docs/Prelude.html#v%3aspan\" rel=\"nofollow\">span</a>. This can be used as follows:</p>\n\n<pre><code>filterOne' :: (a -> Bool) -> [a] -> [a]\nfilterOne' f xs = fst z ++ (tail $ snd z)\n where z = span f xs\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T01:57:33.313",
"Id": "48952",
"ParentId": "48948",
"Score": "1"
}
},
{
"body": "<p>This isn't mergesort! <code>sort'</code> is a different sorting algorithm entirely, so you end up only performing one merge step before kicking it over to (I believe) selection sort.</p>\n\n<p>First let's address the easy stylistic issues so we have a good base to work from. The primary issue is that the argument passed to <code>merge'</code> is a tuple, which is unnecessary, uncurried, and not very Haskell-y. I'll also drop the extra apostrophes where there isn't an actual naming conflict with the Prelude. We use as-patterns to avoid reconstructing patterns we just deconstructed. And let's just toss <code>sort'</code> and <code>filterOne'</code>, they're not part of the solution!</p>\n\n<pre><code>mergesort :: (Ord a) => [a] -> [a]\nmergesort [] = []\nmergesort xs = merge (??? left) (??? right)\n where half = (length xs) `div` 2\n left = take half xs\n right = drop half xs\n\nmerge :: (Ord a) => [a] -> [a] -> [a]\nmerge [] [] = []\nmerge xs [] = xs\nmerge [] ys = ys\nmerge xss@(x:xs) yss@(y:ys) = if x <= y then x : merge xs yss else y : merge xss ys\n -- ^ Less than *or equal* so our sort is stable\n</code></pre>\n\n<p>One question is what goes in for the <code>???</code> where we used to call <code>sort'</code>? Well, <code>mergesort</code>!</p>\n\n<p>One more complex issue of style is the usage of <code>if</code> in <code>merge</code>. Top-level <code>if</code>s are better represented as guards in Haskell, it's easier to extend guards and their usage is more idiomatic.</p>\n\n<pre><code>merge xss@(x:xs) yss@(y:ys) | x <= y = x : merge xs yss\n | otherwise = y : merge xss ys\n</code></pre>\n\n<p>One small change we can make is adding another base case to <code>mergesort</code> to account for lists of length 1, which are by definition sorted.</p>\n\n<pre><code>mergesort xs@[x] = xs\n</code></pre>\n\n<p>There's only one more improvement I'd make to this, and that's to call <code>splitAt</code> rather than <code>take</code> and <code>drop</code> in <code>mergesort</code>. Using both <code>take</code> and <code>drop</code> leads to walking half the list twice in each recursive step where we can walk it only once by doing some more bookkeeping. <code>splitAt</code> takes an index to split a list at, and returns the prefix and remainder just like using <code>take</code> and <code>drop</code> separately would.</p>\n\n<p>So putting all of that together, here's the final version.</p>\n\n<pre><code>mergesort :: (Ord a) => [a] -> [a]\nmergesort [] = []\nmergesort xs@[x] = xs\nmergesort xs = merge (mergesort left) (mergesort right)\n where half = (length xs) `div` 2\n (left, right) = splitAt half xs\n\nmerge :: (Ord a) => [a] -> [a] -> [a]\nmerge [] [] = []\nmerge xs [] = xs\nmerge [] ys = ys\nmerge xss@(x:xs) yss@(y:ys) | x <= y = x : merge xs yss\n | otherwise = y : merge xss ys\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T02:45:26.647",
"Id": "86669",
"Score": "0",
"body": "when I re-implemented after peeking at your answer, I first ran into a non-convergent (never completed) result since I hadn't properly handled the `mergesort [x]` case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T08:22:16.533",
"Id": "49047",
"ParentId": "48948",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "49047",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T01:25:53.230",
"Id": "48948",
"Score": "2",
"Tags": [
"haskell",
"reinventing-the-wheel",
"mergesort"
],
"Title": "MergeSort w/ Custom Functions"
} | 48948 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.