body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I wrote a little C++ program for playing Chess:</p>
<p>Now I check the valid moves by filling an 8x8 board with different flags called <code>cBoard</code>.</p>
<ul>
<li><code>fNONE</code> = none type </li>
<li><code>canPASS</code> = the piece can go there</li>
<li><code>cannotPASS</code> = the piece is blocked </li>
<li><code>canEAT</code> = the piece can go there and will eat a piece</li>
</ul>
<p>The Piece has 2 properties:</p>
<ul>
<li><code>id</code> = ROOK,PAWN,...,NONE</li>
<li><code>color</code> = BLACK or WHITE </li>
</ul>
<p></p>
<pre><code>void ChessMoves::fillcBoardPawn(int row, int col){
//reset cBoard
resetcBoard();
//WHITE PAWN
//get pieceMaster
Piece const& pieceMaster = refBoard.getPieceAt(row,col);
if(pieceMaster.getColor() == WHITE){
//check if it can go fw
// |r-1c-1|r-1|r-1c+1|
Piece actualPiece = refBoard.getPieceAt(row-1,col);
if(actualPiece.getId() != NONE){
cBoard[row-1][col] = cannotPASS;
}
else{
cBoard[row-1][col] = canPASS;
}
//check if can eat
actualPiece = refBoard.getPieceAt(row-1,col-1);
if(actualPiece.getId() != NONE){
if(actualPiece.getColor() != pieceMaster.getColor()){
//different color can eat
cBoard[row-1][col-1] = canEAT;
}
}
actualPiece = refBoard.getPieceAt(row-1,col+1);
if(actualPiece.getId() != NONE){
if(actualPiece.getColor() != pieceMaster.getColor()){
//different color can eat
cBoard[row-1][col+1] = canEAT;
}
}
if(row == 2){
//check if in initial position, then can make two jump
actualPiece = refBoard.getPieceAt(row-2, col);
if (actualPiece.getId() != NONE){
cBoard[row-2][col] = cannotPASS;
}
else{
cBoard[row-2][col] = canPASS;
}
}
}
//BLACK PAWN
//the black pawn has everything the same but is going down instead of up
}
</code></pre>
<p>This is the function that checks the moves of the pawn. As you can see, this is a really big function and I wrote only half of it. How could I write this function in a more concise way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:28:25.553",
"Id": "12344",
"Score": "0",
"body": "oh thx for the edit @Loki Astari, why there was that error? I had it formatted correctly..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:29:36.837",
"Id": "12345",
"Score": "0",
"body": "Include your code block indented by 4 (more) spaces to get correct formatting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:37:32.740",
"Id": "12346",
"Score": "0",
"body": "I did but the first and last line were not parsed correctly and I don't know why..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:58:42.420",
"Id": "12347",
"Score": "0",
"body": "Assuming they are at top level (with no indentation in your original source code), leaving a blank line before the first line and having exactly 4 spaces before the opening declaration and the closing brace SHOULD trigger the code block formatter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T21:04:08.060",
"Id": "12348",
"Score": "0",
"body": "fyi, if you want to figure out formatting issues, you can experiment in the [formatting sandbox](http://meta.stackexchange.com/questions/3122/formatting-sandbox)."
}
] |
[
{
"body": "<h3>Main Comments:</h3>\n\n<ul>\n<li><p>I think (by the name of your function) you are missing out on polymorphism (see at bottom)</p></li>\n<li><p>Make sure your code is correctly indented.<br>\nI think you had tabs mixed in with your spaces and the last half was uneven<br>\n(I fixed it so I could read it).</p></li>\n<li><p>Personally I like the { and } to line up (but it is personal taste)<br>\nBut in this case it would have made it easier to see why the code was not lining up correctly.</p></li>\n<li><p>Don't write comments that mimic the code. Comments are supposed to explain stuff in the code that is not obvious and documents the code. The worst thing that can happen is that the code and comments will get out of sync over time. By explaining <strong>what</strong> is supposed to happen rather than how it whould happen your comments are more likely to stay good.</p></li>\n</ul>\n\n<p>This comment is completely useless.</p>\n\n<pre><code> //reset cBoard\n resetcBoard();\n</code></pre>\n\n<ul>\n<li>Unless you really want to copy the piece always get a reference to them:</li>\n</ul>\n\n<p>Here</p>\n\n<pre><code>// This is making a copy of a piece\nPiece actualPiece = refBoard.getPieceAt(row + direction, col);\n\n// You probably ment:\nPiece const& actualPiece = refBoard.getPieceAt(row + direction, col);\n\n// Note you can't change a reference once seated so for other squares you\n// need other variables. Don't worry about this it will not cost extra space\n// in the executable.\n</code></pre>\n\n<h3>Stuff to make it more concise:</h3>\n\n<p>The same code can be used for both black and white.<br>\nYou just need to set a direction variable:</p>\n\n<pre><code>int direction = pieceMaster.getColor() == WHITE ? -1 : +1;\n</code></pre>\n\n<p>Then wherever you use:</p>\n\n<pre><code>cBoard[row-1][col]\n\n// instead use:\n\ncBoard[row + direction][col]\n</code></pre>\n\n<p>Rather then write if test that assign the same variable in both branches use a ternary expression:</p>\n\n<pre><code>if (test)\n{\n state = result1;\n}\nelse\n{\n state = result2;\n}\n\n// Instead you can use:\n\nstate = test ? result1 : result2;\n</code></pre>\n\n<p>Rather than doing 2 consecutive tests with no other options bring them into a single test:</p>\n\n<pre><code>if (test1)\n{\n if (test2)\n {\n action;\n }\n}\n\n// can be simplified too:\n\nif (test1 && test2)\n{\n action;\n}\n</code></pre>\n\n<p>Simplified too:</p>\n\n<pre><code>void ChessMoves::fillcBoardPawn(int row, int col)\n{\n resetcBoard();\n\n Piece const& pieceMaster = refBoard.getPieceAt(row,col);\n int const direction = (pieceMaster.getColor() == WHITE) ? -1 : +1;\n\n //check if it can go forward\n Piece const& actualPieceAhead = refBoard.getPieceAt(row + direction, col);\n\n cBoard[row + direction ][col] = actualPieceAhead.getId() == NONE ? canPASS :cannotPASS;\n\n //check if can eat (take a piece)\n for(int side = -1; side <= 1; side += 2)\n {\n Piece const& actualPieceTake = refBoard.getPieceAt(row + direction, col + side);\n if ((actualPieceTake.getId() != NONE) && (actualPieceTake.getColor() != pieceMaster.getColor()))\n {\n cBoard[row + direction][col + side] = canEAT;\n }\n }\n\n //check if in initial position, then can make two jump\n if(row == 2)\n {\n Piece const& actualPiece2Ahead = refBoard.getPieceAt(row + 2*direction, col);\n cBoard[row+ 2*direction][col] = actualPiece2Ahead.getId() == NONE ? canPASS : cannotPASS;\n }\n}\n</code></pre>\n\n<h3>Polymorphism:</h3>\n\n<p>It looks like all this work is done on the board. But really you should be using polymorphism to mark the board. ie the piece knows its own type and can mark the board appropriately.</p>\n\n<pre><code>class ChessPiece\n{\n public:\n virtual ~ChessPiece() {}\n virtual void fillcBoard(ChessMoves& board) = 0;\n}\n\nclass ChessPiecePawn: public ChessPiece\n{\n public:\n virtual void fillcBoard(ChessMoves& board)\n {\n // Code As above\n }\n};\n</code></pre>\n\n<p>Now a piece on a board can fill in the cBoard without the user of the piece actually knowing what the piece is:</p>\n\n<pre><code>board[1][1].fillcBoard(board);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T22:28:34.250",
"Id": "12354",
"Score": "0",
"body": "about the polymorfism, is a design choice (maybe a bad one), I check the board, if it contains a piece or not, and the class piece just store 2 things, id and color (in my logic the piece doesn't know about the board). \n So I actually stored the refBoard as an array of pieces. After this, in the program I have a function that fill the board automatically, like the last one line you wrote. \nAn other question, do you know in vim if there is a function to change the tab to 4 spaces?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T23:02:07.507",
"Id": "12355",
"Score": "0",
"body": "(on four lines of your ~/.vimrc file) add: `set tabstop =4\nset softtabstop =4\nset shiftwidth =4\nset expandtab` See http://thorsanvil.com/vimrc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T23:10:51.160",
"Id": "12356",
"Score": "0",
"body": "Yes polymorhism is a design choice. But it what makes C++ different to C. Without it you are not writing OO but procedural code and thus not really using C++ (We call what you are doing `C with classes`). In my opinion your code will be much simpler using polymorhism because you will not need to check the type of a piece (each piece knows its type (and thus is known and checked by the compiler) and can then be asked the action it needs to perform)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T11:41:48.640",
"Id": "12552",
"Score": "0",
"body": "I agree in general that each piece should derive from a ChessPiece class or similar to check for its own legal moves. It will need to see the whole board to determine if a move is legal: for example in the case of a pawn, if it is moving diagonally it needs to know it is capturing, and moving ahead the square must be unoccupied even by enemy pieces. With the bishop we need to know we are not jumping over anything so b2 to d4 may be legal but won't be if there is a piece on c3. \n\nOther things that make moves illegal, e.g. leaving yourself in check, could be for a more \"master\" class to check."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:55:11.427",
"Id": "7814",
"ParentId": "7811",
"Score": "4"
}
},
{
"body": "<p>Each piece id (PAWN, etc.) should have its own class with a method that calculates its legal moves. The \"constants\" that take on different values for different colors (direction of pawn movement (+1 or -1), location of starting rows (1 or 8) should be variables that are set by either indexing a static const vector by a color enum or by referencing properties of a piece's associated Color object.</p>\n\n<p>The detailed behavior for each piece id should be encoded into a few virtual functions originally defined on an abstract \"PieceId\" class (PieceId as opposed to Piece which is something that has a Color, PieceId, position, and isAlive flag) and overridden in a class for each specific piece id (PAWN, ROOK, etc).</p>\n\n<p>If you are going to use row and col as vector indexes, you should follow the 0-based indexing idiom, using values 0 through 7 in 8-element vectors rather than using values 1 through 8 requiring 9-element vectors with unused [0] slots.</p>\n\n<p>It's not really clear how you are using this fillcBoard -- I imagine that you are using it when a piece is selected to identify legal moves (whether internally or as a visual hint for learners). Depending on usage, it might be simpler NOT to distinguish canPass and canEat in this function. Since canEat really means the same as \"canPass && the refBoard position is not empty\", which might be simpler to test later as you need to.</p>\n\n<p>You might want to make your actualPiece local variable a const Piece* so you don't have to keep copying an object. An alternative would be to use a simpler function than getPieceAt like getColorAt that returned a pointer to the occupying piece's color or null for an empty space -- or just return a Color but add a NO_COLOR enum value that can apply only to board locations but not to pieces.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T15:52:12.003",
"Id": "12409",
"Score": "0",
"body": "thank you for he feedback, but as I said to Loki, I think is a matter of taste if I want to use inheritance or not on a piece. I encoded the piece behaviour in a ChessMoves class ( a class that manage the board and the piece and then passed to the game engine or the AI). I'm using the 0 based indexing idiom. Finally fillcBoard will be used by the GE to look for valid moves, and for the AI to look for the best moves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T19:04:06.763",
"Id": "12412",
"Score": "0",
"body": "With 0-based indexing, `if (row == 2)` tests for pawns on the third row."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T19:40:51.977",
"Id": "12416",
"Score": "0",
"body": "\"Best practices\" are not simply \"matters of taste\". You have to decide whether you want better code or just code that you like better. I'm not sure how much this site can help you with the latter, as that's a much more specialized field."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T21:42:37.310",
"Id": "7816",
"ParentId": "7811",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7814",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:09:04.077",
"Id": "7811",
"Score": "3",
"Tags": [
"c++",
"game"
],
"Title": "Chess game function"
}
|
7811
|
<pre><code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
/**
* Solution for Quora Classifier question from CodeSprint 2012 This class
* implements a logistic regression classifier trained with Stochastic Gradient
* Descent. No regularization is used as it wasn't necessary for this problem
*/
public class QuoraClassifier {
static boolean debug;
double[] theta; // regression coefficients
double[] yTraining; // training targets
double[][] xTraining; // training predictors
double[] xMean; // mean of each training predictor
double[] xVarSqrt; // variance of each training predictor
double alpha = 5; // training rate
int numTrainingExamples; // number of training examples
int numFeatures; // number of features in predictor
/**
* Load training data
*
* @param sc
*/
private void loadTrainingData(Scanner sc) {
String[] trainingDimString = sc.nextLine().split("\\s");
numTrainingExamples = Integer.parseInt(trainingDimString[0]);
numFeatures = Integer.parseInt(trainingDimString[1]);
yTraining = new double[numTrainingExamples];
xTraining = new double[numTrainingExamples][numFeatures];
for (int i = 0; i < numTrainingExamples; i++) {
String[] trainingPoint = sc.nextLine().split("\\s");
// read training targets and convert from -1/+1 to 0/1
yTraining[i] = (Double.parseDouble(trainingPoint[1]) + 1) / 2;
// read training predictors
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
String featureString = trainingPoint[2 + fIndex];
xTraining[i][fIndex] = Double.parseDouble(featureString
.substring(featureString.indexOf(":") + 1));
}
}
}
/**
* Normalize training data by mean and variance
*/
private void normalizeTrainingData() {
// calculate mean of each feature
xMean = new double[numFeatures];
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
double runningSum = 0.0;
for (int i = 0; i < numTrainingExamples; i++) {
runningSum += xTraining[i][fIndex];
}
xMean[fIndex] = runningSum / numTrainingExamples;
}
// normalize by feature means
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
for (int i = 0; i < numTrainingExamples; i++) {
xTraining[i][fIndex] -= xMean[fIndex];
}
}
// calculate variance of each feature
xVarSqrt = new double[numFeatures];
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
double runningSum = 0.0;
for (int i = 0; i < numTrainingExamples; i++) {
runningSum += xTraining[i][fIndex] * xTraining[i][fIndex];
}
if (runningSum > 0.0) {
xVarSqrt[fIndex] = Math.sqrt(runningSum / numTrainingExamples);
} else {
xVarSqrt[fIndex] = 1.0;
}
}
// normalize by feature variances
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
for (int i = 0; i < numTrainingExamples; i++) {
xTraining[i][fIndex] /= xVarSqrt[fIndex];
}
}
}
/**
* Train logistic regression coefficients
*/
private void trainLogistic() {
theta = new double[numFeatures];
for (int i = 0; i < numTrainingExamples; i++) {
double yEstimate = classify(xTraining[i]);
// calculate error in prediction
double e = yEstimate - yTraining[i];
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
// update regression coefficient
theta[fIndex] -= alpha / numTrainingExamples * e * xTraining[i][fIndex];
}
}
}
/**
* Classify feature vector x
*
* @param x
* array of doubles containing the features
* @return double containing the soft classification
*/
private double classify(double[] x) {
double z = 0;
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
double xNormalized = (x[fIndex] - xMean[fIndex]) / xVarSqrt[fIndex];
z += theta[fIndex] * xNormalized;
}
return sigmoid(z);
}
/**
* Run classification for a set of queries and output the result to System.out
*
* @param scIn
* input data (contains test and training sets)
* @param scOut
* training targets for validation
*/
private void classifyQueries(Scanner scIn, Scanner scOut) {
int numQueries = Integer.parseInt(scIn.nextLine());
double[] xQuery = new double[numFeatures];
double numMisclassifications = 0;
for (int i = 0; i < numQueries; i++) {
// load query
String[] queryString = scIn.nextLine().split("\\s");
String label = queryString[0];
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
String featureString = queryString[1 + fIndex];
xQuery[fIndex] = Double.parseDouble(featureString
.substring(featureString.indexOf(":") + 1));
}
// classify
double classification = classify(xQuery);
// output result to System.out
if (classification > 0.5) {
System.out.printf("%s +1\n", label);
} else {
System.out.printf("%s -1\n", label);
}
if (debug) {
// read training targets
String[] outString = scOut.nextLine().split("\\s");
String correctClassification = outString[1];
// display misclassifications
if (classification > 0.5) {
if (correctClassification.equals("-1")) {
numMisclassifications++;
System.out.printf("%s +1 %s\n", label, correctClassification);
}
} else {
if (correctClassification.equals("+1")) {
numMisclassifications++;
System.out.printf("%s -1 %s\n", label, correctClassification);
}
}
}
}
if (debug) {
System.out.printf("Misclassification rate: %.1f%%\n",
(100.0 * numMisclassifications) / numQueries);
}
}
/**
* Sigmoid function
*
* @param z
* a double
* @return double containing 1/(1 + exp(-z))
*/
private double sigmoid(double z) {
return 1.0 / (1.0 + Math.exp(-z));
}
/**
* Run classification using input data from scanner scIn and validate against
* training targets in scanner scOut
*
* @param scIn
* input data (contains test and training sets)
* @param scOut
* training targets for validation
*/
public void run(Scanner scIn, Scanner scOut) {
loadTrainingData(scIn);
normalizeTrainingData();
trainLogistic();
classifyQueries(scIn, scOut);
}
/**
* Run classification and profile execution time. If no arguments are supplied
* input is read from standard input and output is written to standard output
* If two arguments are supplied then input is read from the file specified by
* the first argument and output is written to the file specified by the
* second argument
*
*/
public static void main(String[] args) throws FileNotFoundException {
Scanner scIn; // input file
Scanner scOut; // output file
if (args.length > 0) { // input stream from file (for testing)
BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
scIn = new Scanner(in);
BufferedReader out = new BufferedReader(new FileReader(new File(args[1])));
scOut = new Scanner(out);
debug = true;
} else { // input streamed from System.in (used in competition)
scIn = new Scanner(System.in);
scOut = null;
debug = false;
}
long startTime = 0;
if (debug) {
startTime = System.nanoTime();
}
// run classification
QuoraClassifier classifier = new QuoraClassifier();
classifier.run(scIn, scOut);
if (debug) {
long endTime = System.nanoTime();
System.out.printf("Execution time: %f\n",
((double) endTime - (double) startTime) / 1e9);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Same answer as your other <a href=\"https://codereview.stackexchange.com/questions/7813/general-java-style-suggestions-clustering-question-from-codesprint-2012/7841#7841\">question</a>.</p>\n\n<p>You should have some class to load (and contain) the original data; some Normalizer interface (you might have many different classes that implement different normalizations); some Classifier interface; you are training something, so that something should be a class with a train(?,...) method. And then again, there are probably many ways to train it, so there should be some interface for that too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T15:59:14.007",
"Id": "7842",
"ParentId": "7812",
"Score": "2"
}
},
{
"body": "<p>Just off the top of my head:</p>\n\n<ul>\n<li>In main - what should happen if <code>args.length == 1</code> ? Currently, you'll get an exception. </li>\n<li>Your field names are a bit odd - <code>xTraining</code> and <code>yTraining</code> in particular. Instead of having these names, and comments about what the variables actually mean, why not just call your variables <code>regressionCoefficients</code>, <code>trainingTargets</code>, <code>trainingPredictors</code> and so on?</li>\n<li>Some of the methods are a bit long. The fact that your methods mostly have internal comments kind of indicates this. In my opinion, each method should do just one thing; and that one thing should be explained in a javadoc comment at the top of the method. No comments at all inside methods.</li>\n<li>Comments should be used to explain things, not just to repeat what's in the code. For example, your \"return\" comment at the top of <code>sigmoid</code> is pointless. I suggest removing it.</li>\n<li>Do you really want to use <code>System.out.printf</code> for logging? There are more versatile ways of logging (which you could google), and more readable means of formatting.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T04:16:36.133",
"Id": "7856",
"ParentId": "7812",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7856",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:35:39.077",
"Id": "7812",
"Score": "4",
"Tags": [
"java"
],
"Title": "General Java Style Suggestions - Classification Problem from CodeSprint 2012"
}
|
7812
|
<pre><code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Solution for Newsle Clustering question from CodeSprint 2012. This class
* implements clustering of text documents using Cosine or Jaccard distance
* between the feature vectors of the documents together with k means
* clustering. The number of clusters is adapted so that the ratio of the
* intracluster to intercluster distance is below a specified threshold.
*/
public class NewsleClusterer {
private static boolean debug;
// number of iterations to use in k means clustering
private final int kMeansIter;
// size of document feature vector
private final int numFeatures;
// set true to use cosine distance, otherwise Jaccard distance is used
private final boolean useCosineDistance;
// threshold used to determine number of clusters k
private final double clustThreshold;
// contents of documents (document ID, document title and document contents)
private String[][] documents;
// number of documents
private int numDocuments;
// encoded document vectors
private double[][] documentVectors;
// precalculated document vector norms
private double[] vectorNorms;
// clusters specified as document IDs
private ArrayList<ComparableArrayList> clusters;
// cluster centroids
private double[][] centroids;
// cluster centroid norms
private double[] centroidNorms;
/**
* Instantiate clusterer
*
* @param numFeatures
* number of features to use in document feature vectors
* @param kMeansIter
* number of iterations to use in k means clustering
* @param useCosineDistance
* set true to use cosine distance, otherwise Jaccard distance will
* be used
* @param clustThreshold
* threshold for intracluster to intercluster distance. Used to
* determine number of clusters k
*/
public NewsleClusterer(int numFeatures, int kMeansIter,
boolean useCosineDistance, double clustThreshold) {
this.numFeatures = numFeatures;
this.kMeansIter = kMeansIter;
this.useCosineDistance = useCosineDistance;
this.clustThreshold = clustThreshold;
}
/**
* Parse input into document ID, document title and contents
*
* @param input
*/
private void parseInput(String input) {
StringTokenizer st = new StringTokenizer(input, "{");
numDocuments = st.countTokens() - 1;
String record = st.nextToken(); // empty split to left of {
documents = new String[numDocuments][3];
Pattern pattern = Pattern
.compile("\"content\": \"(.*)\", \"id\": (.*), \"title\": \"(.*)\"");
for (int i = 0; i < numDocuments; i++) {
record = st.nextToken();
Matcher matcher = pattern.matcher(record);
if (matcher.find()) {
documents[i][0] = matcher.group(2); // document ID
documents[i][1] = matcher.group(3); // document title
documents[i][2] = matcher.group(1); // document contents
}
}
}
/**
* Hash word into integer between 0 and numFeatures-1. Used to form document
* feature vector
*
* @param word
* String to be hashed
* @return hashed integer
*/
private int hashWord(String word) {
return Math.abs(word.hashCode()) % numFeatures;
}
/**
* Class which extends ArrayList to allow for easy sorting of clusters
*/
private class ComparableArrayList extends ArrayList<Integer> implements
Comparable<ComparableArrayList> {
private static final long serialVersionUID = 1L;
/**
* Allows sorting of ArrayList of ArrayList<Integer> by comparing first
* entry of constituent ArrayList<Integer>
*/
public int compareTo(ComparableArrayList x) {
if (this.get(0) > x.get(0)) {
return 1;
} else if (this.get(0) < x.get(0)) {
return -1;
} else {
return 0;
}
}
}
/**
* Vectorize documents using Term Frequency - Inverse Document Frequency
*/
private void vectorizeDocuments() {
long[] docFreq = new long[numFeatures];
double[][] termFreq = new double[numDocuments][numFeatures];
documentVectors = new double[numDocuments][numFeatures];
for (int docIndex = 0; docIndex < numDocuments; docIndex++) {
String[] words = documents[docIndex][2].split("[^\\w]+");
// Calculate word histogram for document
long[] freq = new long[numFeatures];
for (int i = 0; i < words.length; i++) {
int hashCode = hashWord(words[i]);
freq[hashCode]++;
}
// Calculate maximum word frequency in document
long maxFreq = 0;
for (int i = 0; i < numFeatures; i++) {
if (freq[i] > maxFreq) {
maxFreq = freq[i];
}
}
// Normalize word histogram by maximum word frequency
for (int i = 0; i < numFeatures; i++) {
if (freq[i] > 0) {
docFreq[i]++;
}
if (maxFreq > 0) {
termFreq[docIndex][i] = (double) freq[i] / maxFreq;
}
}
}
// Form document vector using TF-IDF
for (int i = 0; i < numFeatures; i++) {
if (docFreq[i] > 0) {
// Calculate inverse document frequency
double inverseDocFreq = Math.log((double) numDocuments
/ (double) docFreq[i]);
// Calculate term frequency inverse document frequency
for (int docIndex = 0; docIndex < numDocuments; docIndex++) {
documentVectors[docIndex][i] = termFreq[docIndex][i] * inverseDocFreq;
}
}
}
// Precalculate norms of document vectors
vectorNorms = new double[numDocuments];
for (int docIndex = 0; docIndex < numDocuments; docIndex++) {
vectorNorms[docIndex] = calcNorm(documentVectors[docIndex]);
if (useCosineDistance) {
for (int i = 0; i < numFeatures; i++) {
documentVectors[docIndex][i] /= vectorNorms[docIndex];
}
}
}
}
/**
* Calculate distance between a document and a cluster's centroid
*
* @param docIndex
* document index
* @param clusterIndex
* cluster index
* @return distance between document docIndex and cluster clusterIndex
*/
private double calcDocClustDistance(int docIndex, int clusterIndex) {
double[] vector1 = documentVectors[docIndex];
double[] vector2 = centroids[clusterIndex];
return calcDistance(vector1, vector2, vectorNorms[docIndex],
vectorNorms[clusterIndex]);
}
/**
* Calculate distance between two documents
*
* @param docIndex1
* index of first document
* @param docIndex2
* index of second document
* @return distance between document docIndex1 and document docIndex2
*/
private double calcDocDocDistance(int docIndex1, int docIndex2) {
double[] vector1 = documentVectors[docIndex1];
double[] vector2 = documentVectors[docIndex2];
return calcDistance(vector1, vector2, vectorNorms[docIndex1],
vectorNorms[docIndex2]);
}
/**
* Calculate distance between two vectors
*
* @param vector1
* first vector
* @param vector2
* second vector
* @param norm1
* precalculated norm of first vector
* @param norm2
* precalculated norm of second vector
* @return distance between vector1 and vector2
*/
private double calcDistance(double[] vector1, double[] vector2, double norm1,
double norm2) {
if (useCosineDistance) {
return calcCosineDistance(vector1, vector2, 1.0, 1.0);
} else {
return calcJaccardDistance(vector1, vector2, norm1, norm2);
}
}
/**
* Calculate cosine distance between two vectors
*
* @param vector1
* first vector
* @param vector2
* second vector
* @param norm1
* precalculated norm of first vector
* @param norm2
* precalculated norm of second vector
* @return cosine distance between vector1 and vector2
*/
private double calcCosineDistance(double[] vector1, double[] vector2,
double norm1, double norm2) {
double innerProd = 0.0;
for (int i = 0; i < numFeatures; i++) {
innerProd += vector1[i] * vector2[i];
}
// normalization by norms may be necessary if comparison is done between
// document and cluster
return 1.0 - innerProd / norm1 / norm2;
}
/**
* Calculate Jaccard distance between two vectors
*
* @param vector1
* first vector
* @param vector2
* second vector
* @param norm1
* precalculated norm of first vector
* @param norm2
* precalculated norm of second vector
* @return Jaccard distance between vector1 and vector2
*/
private double calcJaccardDistance(double[] vector1, double[] vector2,
double norm1, double norm2) {
double innerProd = 0.0;
for (int i = 0; i < numFeatures; i++) {
innerProd += vector1[i] * vector2[i];
}
return Math.abs(1.0 - innerProd / (norm1 + norm2 - innerProd));
}
/**
* Calculate minimum distance between a document and the existing documents in
* clusters. Assumes that each cluster has only one document. Used during
* initialization of k means
*
* @param documentIndex
* @return minimum distance between document documentIndex and documents in
* clusters
*/
private double calcDistanceToExistingClusters(int documentIndex) {
double distance = Double.MAX_VALUE;
for (int existingPoint = 0; existingPoint < clusters.size(); existingPoint++) {
int existingPointIndex = clusters.get(existingPoint).get(0);
distance = Math.min(distance,
calcDocDocDistance(documentIndex, existingPointIndex));
}
return distance;
}
/**
* Returns norm of a vector
*
* @param x
* vector
* @return norm of x
*/
private double calcNorm(double[] x) {
double normSquared = 0.0;
for (int i = 0; i < x.length; i++) {
normSquared += x[i] * x[i];
}
return Math.sqrt(normSquared);
}
/**
* Update centroids and centroidNorms for a specific cluster
*
* @param clusterIndex
* cluster to update
*/
private void updateCentroid(int clusterIndex) {
ComparableArrayList cluster = clusters.get(clusterIndex);
for (int i = 0; i < numFeatures; i++) {
centroids[clusterIndex][i] = 0;
for (int docIndex : cluster) {
centroids[clusterIndex][i] += documentVectors[docIndex][i];
}
centroids[clusterIndex][i] /= cluster.size();
}
centroidNorms[clusterIndex] = calcNorm(centroids[clusterIndex]);
}
/**
* Run k mean clustering on document vectors
*
* @param k
* target number of clusters
*/
private void runKMeansClustering(int k) {
clusters = new ArrayList<ComparableArrayList>(k);
centroids = new double[k][numFeatures];
centroidNorms = new double[k];
// marks if a document has already been allocated to a cluster
boolean[] isAllocated = new boolean[numDocuments];
// pick initial document for clustering
Random rnd = new Random(2);
ComparableArrayList c0 = new ComparableArrayList();
int rndDocIndex = rnd.nextInt(k);
// add random document to first cluster
c0.add(rndDocIndex);
isAllocated[rndDocIndex] = true;
clusters.add(c0);
updateCentroid(0);
// create new cluster containing furthest document from existing clusters
for (int clusterIndex = 1; clusterIndex < k; clusterIndex++) {
// find furthest document
double furthestDistance = -1;
int furthestDocIndex = -1;
for (int candidatePoint = 0; candidatePoint < numDocuments; candidatePoint++) {
if (!isAllocated[candidatePoint]) {
double distance = calcDistanceToExistingClusters(candidatePoint);
if (distance > furthestDistance) {
furthestDistance = distance;
furthestDocIndex = candidatePoint;
}
}
}
ComparableArrayList c = new ComparableArrayList();
c.add(furthestDocIndex);
isAllocated[furthestDocIndex] = true;
clusters.add(c);
updateCentroid(clusterIndex);
}
// process remaining documents
for (int iter = 0; iter < kMeansIter; iter++) {
// allocate documents to clusters
for (int i = 0; i < numDocuments; i++) {
if (!isAllocated[i]) {
int nearestCluster = findNearestCluster(i);
clusters.get(nearestCluster).add(i);
}
}
// update centroids and centroidNorms
for (int i = 0; i < k; i++) {
updateCentroid(i);
}
// prepare for reallocation in next iteration
if (iter < kMeansIter - 1) {
for (int i = 0; i < numDocuments; i++) {
isAllocated[i] = false;
}
emptyClusters();
}
}
}
/**
* Clear out documents from within each cluster. Used to cleanup at the end of
* each iteration of k means
*/
private void emptyClusters() {
for (int clusterIndex = 0; clusterIndex < clusters.size(); clusterIndex++) {
clusters.set(clusterIndex, new ComparableArrayList());
}
}
/**
* Find cluster whose centroid is closest to a document
*
* @param docIndex
* @return cluster closest to docIndex
*/
private int findNearestCluster(int docIndex) {
int nearestCluster = -1;
double nearestDistance = Double.MAX_VALUE;
for (int clusterIndex = 0; clusterIndex < clusters.size(); clusterIndex++) {
double docClustDistance = calcDocClustDistance(docIndex, clusterIndex);
if (docClustDistance < nearestDistance) {
nearestDistance = docClustDistance;
nearestCluster = clusterIndex;
}
}
return nearestCluster;
}
/**
* Calculate ratio of average intracluster distance to average intercluster
* distance. Used to optimize number of clusters k
*
* @return ratio of average intracluster distance to average intercluster
* distance
*/
private double calcAvgIntraInterClusterDistance() {
// calculate average intracluster distance
double intraDist = 0.0;
for (int clusterIndex = 0; clusterIndex < clusters.size(); clusterIndex++) {
ComparableArrayList cluster = clusters.get(clusterIndex);
for (int docIndex : cluster) {
intraDist += calcDocClustDistance(docIndex, clusterIndex);
}
}
intraDist /= numDocuments;
// calculate average intercluster distance
if (clusters.size() > 1) {
double interDist = 0.0;
for (int cluster1Index = 0; cluster1Index < clusters.size(); cluster1Index++) {
for (int cluster2Index = 0; cluster2Index < clusters.size(); cluster2Index++) {
if (cluster1Index != cluster2Index) {
interDist += calcDocClustDistance(cluster1Index, cluster2Index);
}
}
}
// there are N*N-1 unique pairs of clusters
interDist /= (clusters.size() * (clusters.size() - 1));
if (interDist > 0) {
return intraDist / interDist;
} else {
return Double.MAX_VALUE;
}
} else {
return Double.MAX_VALUE;
}
}
/**
* Run k means clustering on documents in input and evaluate results with
* expected clustering in expectedOutput
*
* @param input
* documents to be clustered
* @param expectedOutput
* expected clustering
*/
public void run(String input, String expectedOutput) {
parseInput(input);
vectorizeDocuments();
/*
* increase number of clusters k until ratio of average intracluster
* distance to intercluster distance is greater than clustThreshold
*/
for (int k = 1; k <= numDocuments; k++) {
runKMeansClustering(k);
double intraInterDistRatio = calcAvgIntraInterClusterDistance();
if (intraInterDistRatio < clustThreshold) {
break;
}
}
sortAndDisplayClusters();
}
/**
* Display clusters in sorted order
*/
public void sortAndDisplayClusters() {
System.out.print("[");
for (int i = 0; i < clusters.size(); i++) {
Collections.sort(clusters.get(i)); // sort within cluster
}
Collections.sort(clusters); // sort clusters
for (int i = 0; i < clusters.size(); i++) {
System.out.print(clusters.get(i));
if (i < clusters.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
/**
* Run clustering and profile execution time. If no arguments are supplied
* input is read from standard input and output is written to standard output
* If two arguments are supplied then input is read from the file specified by
* the first argument and output is validated against the file specified by
* the second input
*
*/
public static void main(String[] args) throws IOException {
String expectedOutput;
String input;
if (args.length > 0) {
BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
BufferedReader out = new BufferedReader(new FileReader(new File(args[1])));
expectedOutput = out.readLine();
input = in.readLine();
debug = true;
} else {
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
expectedOutput = null;
debug = false;
}
long startTime = 0;
if (debug) {
startTime = System.nanoTime();
}
NewsleClusterer clusterer = new NewsleClusterer(10000, 3, true, 0.6);
clusterer.run(input, expectedOutput);
if (debug) {
long endTime = System.nanoTime();
System.out.println("Expected output: " + expectedOutput);
System.out.printf("Execution time: %f\n",
(endTime - (double) startTime) / 1e9);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A \"General Java Style Suggestion\" is to use class definitions to promote type safety within your system and promote semantically descriptive names. </p>\n\n<p>For example, the statement <code>documents[0][1]</code> means what? The title of the first document in documents. That's not very Java-like. Such a refactoring would also likely have the documentVector belong to the Document, not just live as an array with data at the same index as the document it is calculated from.</p>\n\n<p>You could get as picky as you want. There are a few <code>double[][]</code> variables in the system. But it doesn't really make sense to have a statement like <code>documentVectors[4] = centroids[3]</code>. You could make types DocumentVector and Centroid. Note: I wouldn't. The variable names are reasonable guides, and the refactoring away from one single class would make such a mistake extremely unlikely.</p>\n\n<p>Many of your int index parameters could probably be refactored to use the objects they index instead of the position of the underlying entity. The utility of this is questionable, though. Most, if not all such methods are likely to stay private during a refactoring. Still, it's not very OO in general to refer to an object by its position in a collection when the actual object could be used. It makes it less likely that an error could occur like the following:</p>\n\n<p><code>calcDocClustDistance(clusterIndex, docIndex)</code></p>\n\n<p>Again, the naming makes this error a little easier to catch (Doc comes before Clust in the function name). However, this function could be <code>distance(doc, cluster)</code> just as easy with a refactor, and swapping arguments would result in a compilation error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T02:44:14.373",
"Id": "7825",
"ParentId": "7813",
"Score": "4"
}
},
{
"body": "<p>I just glanced over for 30 seconds, and that is C code.</p>\n\n<p>You should think harder about OO-design. For example, you compute all sorts of distances, so you should have a Distance class with subclasses. You should probably have some Cluster class too. And the initial reading in and parsing of the documents should be in some separate class(es), some kind of DocumentSet, which you would also use to access the documents instead of the arrays.</p>\n\n<p>Some say that a class should be no more than 1 page long. I don't agree, but you should try it for fun on your code. You might be surprised how things will group themselves logically and make your code much easier to read.</p>\n\n<p>Another advantage of good OO design is than when you deal with some other somewhat similar problem, you might be able to reuse the \"library\" you have created. By the way, always design thinking that you are developing a general library that might be used for other purposes: not only might it be used elsewhere, but it helps in deciding how to split cleanly the project in classes.</p>\n\n<p>A small detail: you use the old for-loop with indices everywhere. You might want to consider making your new classes implement <code>Iterable</code> such that you can use the for-each-loop instead. It makes code more compact and more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T15:34:57.790",
"Id": "7841",
"ParentId": "7813",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7841",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:42:36.323",
"Id": "7813",
"Score": "5",
"Tags": [
"java"
],
"Title": "General Java Style Suggestions - Clustering Question from CodeSprint 2012"
}
|
7813
|
<p>My task was to write a function in C where a string such as <code>{2210090,34566,87234,564676}</code> would be given as input and the function had to find out the count of numbers separated by comma whose average of single digits is greater than or equal to 5.</p>
<p>In the below example, the average of 2210090 is 2, the average of 34566 is 4.8, the average of 87234 is 4.8 and the average of 564676 is 5.6, hence the count is 1. </p>
<pre><code>void GetCount(int n,char* input2)
{
int sum=0;
n=0;
h:
*input2++;
if((*input2) && !isdigit(*input2))
{
if(sum>n<<2)
output1++;
sum=0;
n=0;
goto h;
}
else if(*input2!='\0')
{
sum+=*input2-'0';
n++;
goto h;
}
}
</code></pre>
<p>The first parameter <code>n</code> is the total count of number. The program is working fine and I just wanted to know if anyone could give input on improving the time complexity of the program. I would also appreciate a better way of solving this problem, reducing the number of <code>if</code>s and <code>goto</code>s or completely eliminating the need of <code>if</code> or <code>goto</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:04:45.397",
"Id": "12358",
"Score": "4",
"body": "Why is `n` passed into the function if the first thing you do is set it to zero?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:05:09.580",
"Id": "12359",
"Score": "5",
"body": "Goto here will probably get you a failing grade. Did you come from a BASIC or assembler background? ALso, I don't think the above is working as well as you believe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:06:36.523",
"Id": "12360",
"Score": "0",
"body": "@JonathanLeffler well actually that part was written by some one else....i just had to write that particular function.If needed i could use the n or just let it be"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:08:21.217",
"Id": "12361",
"Score": "0",
"body": "What part was written by someone else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:11:58.500",
"Id": "12362",
"Score": "2",
"body": "Does the string include the braces you showed? Can spaces appear? What should happen if a non-digit, non-comma (non-space) appears?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T01:08:12.597",
"Id": "12366",
"Score": "2",
"body": "Regarding `goto`: You are going to hear, again and again, that you should never use `goto`. Like any best practice, try to adhere to it, but take it with a grain of salt. Since C lacks exceptions and closures, and does not guarantee optimized tail recursion, there *are* legitimate uses for `goto` (e.g. jumping to cleanup code at the end of your function). However, it takes a *lot* of maturity to know when `goto` is a good idea. Take a look at [this parser I wrote in C a couple years ago](http://tinyurl.com/7b8awbl), and decide for yourself if it abuses `goto`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T07:29:16.780",
"Id": "12547",
"Score": "0",
"body": "@JoeyAdams I'm not sure whether you were ironic or not, but I would definitely say that the linked code abuses goto. That code is spaghetti - it looks like assembler not C. A far more elegant solution would have been to implement the parser as a state machine, with one function for each state."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T10:06:27.880",
"Id": "82725",
"Score": "0",
"body": "`goto`?? Seriously?? After the infamous `goto fail;`, I'd sort of hoped that finally we'd all agree on the evil that is `goto`. Oh, the humanity..."
}
] |
[
{
"body": "<p>First, what is the n parameter for, and do you need it?\nSecond, try structuring your code basically like:</p>\n\n<pre><code>function definition\n int n = 0;\n int val = 0;\n int count = 0;\n iterate over the string\n if the character is a numeral\n val += character value\n n++;\n if the character is a ,\n if the avg (which is val / n) is greater than 5\n count++\n reset n and val to zero\n if the character is a }\n return count\n else\n reset n and val to zero\n return count\n</code></pre>\n\n<p>Or something to that effect</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:14:31.730",
"Id": "12363",
"Score": "2",
"body": "Don't take it further than this - it is homework..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T10:26:56.263",
"Id": "12403",
"Score": "1",
"body": "Note: If the character is a }, you still have to post-process the number (calculate the average and update count if appropriate) before returning."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:09:36.140",
"Id": "7819",
"ParentId": "7818",
"Score": "1"
}
},
{
"body": "<p>Your function should return the number of numbers that meet your criterion, and you only need the input string, so the interface should be:</p>\n\n<pre><code>int GetCount(const char *str)\n</code></pre>\n\n<p>You really don't need the <code>goto</code> statements; you need a <code>while</code> loop. I would probably have a loop like:</p>\n\n<pre><code>while ((c = *str++) != '\\0')\n{\n ...\n}\n</code></pre>\n\n<p>You haven't shown where <code>output1</code> is defined or initialized. It should probably be a local variable initialized to 0 and should be the value returned.</p>\n\n<p>Your calculation is dubious. For a number of <code>m</code> digits, the sum of its digits should be greater than or equal to <code>5 * m</code>.</p>\n\n<p>Also, note that:</p>\n\n<pre><code>*input2++; \n</code></pre>\n\n<p>does exactly the same as:</p>\n\n<pre><code>input2++; \n</code></pre>\n\n<p>While the compiler will eliminate the dereference (since it doesn't use it), so there won't be a runtime performance, there is no point in fetching a value which you never use. <code>*input++</code> has its uses, but as the sole expression in a statement, it is not needed. GCC set fussy will warn you about it:</p>\n\n<pre><code>error: value computed is not used [-Werror=unused-value]\n</code></pre>\n\n<p>(compiled with <code>-Werror</code> to convert all warnings into errors).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:16:11.487",
"Id": "12364",
"Score": "0",
"body": "well actually output1 was globally declared hence was skipped from the code..apology for dat....."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:22:55.600",
"Id": "12365",
"Score": "0",
"body": "Don't use global variables - especially not for a neat, self-contained function like this. They make it harder to use the code; they make it *much* harder to reuse the code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:10:49.483",
"Id": "7820",
"ParentId": "7818",
"Score": "7"
}
},
{
"body": "<p>Before addressing efficiency, some improvements I would recommend:</p>\n\n<ul>\n<li><p>No need for a <code>goto</code> here. This is easy to turn into a <code>for</code> loop.</p></li>\n<li><p>Say <code>const char *input2</code>, to avoid accidentally modifying your input string.</p></li>\n<li><p>Use whitespace to clarify order of operations:</p>\n\n<ul>\n<li><p><code>if(sum > n<<2)</code> Relational operators and shifts are right next to each other on the <a href=\"https://en.wikipedia.org/wiki/Operators_in_C_and_C++#Operator_precedence\">operator precedence table</a>.</p></li>\n<li><p><code>sum += *input2 - '0';</code></p></li>\n</ul></li>\n<li><p>Take out the asterisk in <code>*input2++;</code> You aren't using the character.</p></li>\n</ul>\n\n<p>And a more subtle issue:</p>\n\n<ul>\n<li><p><code>isdigit</code> expects an <code>unsigned char</code> casted to an <code>int</code>. <code>char</code> is usually signed (but on some platforms, it's unsigned). Thus, if one of your input bytes is not ASCII, it may lead to undefined behavior.</p>\n\n<pre><code>isdigit((unsigned char) *input2)\n</code></pre></li>\n</ul>\n\n<p>Here is an editorialized version of your code:</p>\n\n<pre><code>void GetCount(const char* input2)\n{\n int sum = 0; /* Sum of digits in current number */\n int n = 0; /* Number of digits in current number */\n\n for (;;)\n {\n input2++;\n if (*input2 == '\\0')\n break;\n\n /*\n * If we have a digit, increment sum and n appropriately.\n *\n * Otherwise (we ran into a brace or comma), tally the current number,\n * and clear the stats for the next number.\n */\n if(isdigit((unsigned char) *input2))\n {\n sum += *input2 - '0';\n n++;\n }\n else\n {\n if(sum > n<<2)\n output1++;\n sum = 0;\n n = 0;\n }\n }\n}\n</code></pre>\n\n<p>Let's look at the <code>sum > n<<2</code> line, which looks wrong to me. Here's the condition we want to test (simple, but inefficient):</p>\n\n<pre><code>1. (double)sum / n >= 5.0\n</code></pre>\n\n<p>We can express it in integer arithmetic as:</p>\n\n<pre><code>2. sum >= n * 5\n</code></pre>\n\n<p>Now I get what you were trying to do. Your next steps converted the multiplication to a less expensive shift:</p>\n\n<pre><code>3. sum > n * 4\n4. sum > n<<2\n</code></pre>\n\n<p>Step 3 is wrong. <code>sum</code> can be greater than <code>n * 4</code> but less than <code>n * 5</code>. Example:</p>\n\n<pre><code>34566: sum = 24, n = 5\n\nn * 4 = 20 sum > n * 4 holds\nn * 5 = 25 sum >= n * 5 does not hold\n</code></pre>\n\n<p>The good news is, we can get rid of the multiply and even the shift! Just increment <code>n</code> by 5 each iteration:</p>\n\n<pre><code> if(isdigit((unsigned char) *input2))\n {\n sum += *input2 - '0';\n n += 5;\n }\n else\n {\n if(sum >= n)\n output1++;\n sum = 0;\n n = 0;\n }\n</code></pre>\n\n<p>Finally, let's get rid of that <code>isdigit</code>. It's probably pretty fast, but it has to guard against <code>EOF</code> and do a table lookup. Assuming your input is guaranteed to be in the syntax you describe (non-negative integers delimited by commas and wrapped in braces), you can test for two specific characters instead of having to do a character class lookup.</p>\n\n<p>Here is a final version, with more cleanups:</p>\n\n<pre><code>/*\n * Given a list of numbers in the following syntax:\n *\n * list ::= '{' '}'\n | '{' number (',' number)* '}'\n *\n * number ::= [0-9]+\n *\n * Count how many numbers have digits that average to 5 or more.\n */\nint GetCount(const char* input)\n{\n int sum = 0; /* Sum of digits in current number */\n int length_times_five = 0; /* Number of digits in current number, times 5 */\n int ret = 0;\n\n /*\n * Handle empty list. Otherwise, the following code\n * would return 1 because 0 >= 0.\n */\n if (input[0] == '{' && input[1] == '}')\n return 0;\n\n while (*++input != '\\0')\n {\n if (*input == ',' || *input == '}')\n {\n if(sum >= length_times_five)\n ret++;\n sum = 0;\n length_times_five = 0;\n }\n else\n {\n sum += *input - '0';\n length_times_five += 5;\n }\n }\n\n return ret;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T00:18:27.403",
"Id": "7821",
"ParentId": "7818",
"Score": "11"
}
},
{
"body": "<p>It's an annotated revision. It's still O(n) -- don't see how it could NOT be.\nIt's more idiomatic and less redundant. It's not compiled or tested.</p>\n\n<p>It doesn't raise the question \"What does <code>(sum>n<<2)</code> have to do with anything?\"</p>\n\n<p>It's a non-void return type. It describes the type of the result. It doesn't mess with some global like output1 that you would have to remember to define somewhere.</p>\n\n<pre><code>unsigned int GetCount(char* input2)\n{\n unsigned count = 0;\n int sum = 0;\n</code></pre>\n\n<p>It's a comment. It explains things that aren't at all apparent like, just for example, what <code>(sum>n<<2)</code> might have to do with anything.</p>\n\n<pre><code> int saw_a_digit = 0; /* only consider counting (again) after seeing a digit */\n</code></pre>\n\n<p>It's a loop. It's better than a goto. It's a for loop. It works well when incrementing a pointer once after each time through the loop.</p>\n\n<p>It's got a test for null that only needs to be in this one place.</p>\n\n<p>It's got an increment that doesn't need to dereference the pointer with '*'. </p>\n\n<pre><code> for(; *input2; input2++)\n {\n if(isdigit(*input2))\n {\n</code></pre>\n\n<p>It's a minor optimization over summing digits. It doesn't require counting digits or calculating an average or calculating anything even remotely like <code>(sum>n<<2)</code>. Why would it? It's a little tricky, so there's another comment.</p>\n\n<pre><code> /* We don't need the digit, just how it relates to 5.\n * Amounts > 5 gets canceled out by amounts < 5,\n * 0s and 9s have more influence than 4s and 6s.\n * '5' has no effect at all.\n * This would take a very long string of digits mostly \n * on on the same side of 5 to overflow sum. */\n</code></pre>\n\n<p>It's white space in a non-trivial statement.\nIt's readable.</p>\n\n<pre><code> sum += *input2-'5';\n saw_a_digit = 1;\n }\n else if (saw_a_digit) // found end of digit string\n {\n if (sum >= 0) // low influence did not dominate\n {\n ++count;\n }\n sum = 0;\n saw_a_digit = 0;\n }\n }\n}\n</code></pre>\n\n<p>It's an alternative that uses two smaller loops.\nIt avoids mode variables like <code>saw_a_digit</code>.\nIt MAY be a little faster.</p>\n\n<pre><code>unsigned int GetCount(char* input2)\n{\n unsigned count=0;\n int sum;\n while (*input2)\n {\n for (;!isdigit(*input2);input2++) /* skip non-digits */\n if (!*input2)\n return count;\n sum=0;\n do {\n /* We don't need the digit, just how it relates to 5.\n * Amounts > 5 get canceled out by amounts < 5,\n * 0s and 9s have more influence than 4s and 6s.\n * '5' has no effect at all.\n * This would take a very long string of digits mostly \n * on on the same side of 5 to overflow sum. */\n sum += *input2-'5';\n } while (isdigit(*++input2));\n if (sum>=0) // low influence did not dominate\n {\n ++count;\n }\n }\n return count;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T00:32:35.783",
"Id": "7822",
"ParentId": "7818",
"Score": "5"
}
},
{
"body": "<p>I'm going to focus not on speed, but on clarity with regard to the original specification:</p>\n\n<pre><code>int GetCount(const char *str)\n{\n int count = 0;\n int sum_digits = 0;\n int num_digits = 0;\n\n for (int i = 0; str[i]; i++)\n {\n switch (str[i])\n {\n case '{':\n {\n break;\n }\n\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n {\n int digit = str[i] - '0';\n sum_digits += digit;\n num_digits++;\n break;\n }\n\n case ',':\n case '}':\n {\n if (num_digits > 0) // Could be 0 if input was \"{}\",\n if (sum_digits >= num_digits * 5) // e.g., sum_digits/num_digits > 5\n count++;\n sum_digits = num_digits = 0; // Reset accumulators for next input number.\n break;\n }\n\n default:\n {\n return -1; // Invalid input character encountered\n }\n }\n }\n\n return count;\n}\n</code></pre>\n\n<p>That actually turns out to be extremely fast. With a good compiler, the <code>str[i]</code> should be just as fast as incrementing a pointer. There is still a table lookup here, by the way. It's hidden in the <code>switch</code> statement. But such things are extremely fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T18:40:08.920",
"Id": "12456",
"Score": "1",
"body": "This doesn't compile (at least not with GCC). It is a syntax error to declare a variable after a label: `int digit = str[i] - '0';`. You'll need to wrap that part in braces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T20:01:10.170",
"Id": "12459",
"Score": "0",
"body": "@JoeyAdams — ah yes, thank you. Fixed in the above."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T10:25:19.353",
"Id": "7837",
"ParentId": "7818",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T18:02:49.693",
"Id": "7818",
"Score": "5",
"Tags": [
"optimization",
"c",
"strings",
"homework"
],
"Title": "String traversal program in C"
}
|
7818
|
<p>I'm using django and I wrote this decorator to take away some of the repetitive code I found for ajax views and I want to know your opinion (too basic, bad design, try this instead, etc).</p>
<pre><code>def ajax_only(func):
def _ajax_only(request,*args,**kwargs):
if not request.is_ajax():
return HttpResponse('<p>Ajax not supported.</p>')
else:
return func(request,*args,**kwargs)
return _ajax_only
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>You should use the functools.wraps function, it makes sure the docstring/name/etc gets passed through</li>\n<li>Instead of \"ajax not supported\" shouldn't it be: \"only ajax supported\"?</li>\n<li>Shouldn't you respond with a Status Code 400 or something if not using ajax when you should be</li>\n<li>Why do you want to check this? What's the point of enforcing ajax calls, won't that just make testing harder?</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T19:29:30.900",
"Id": "12415",
"Score": "0",
"body": "thanks for the comment. For 2, i meant \"ajax not supported by the browser\", for 3 i've got just one handler function that receive's the response for the server, with a 400 code i would need to create a separate function to handle that type of response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T01:33:22.463",
"Id": "12425",
"Score": "0",
"body": "@user1108631, your test only checks whether the current request is AJAX, it tells you nothing about whether the browser supports it. You don't need to handle the 400 response, it means the request was incorrectly made to the server."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T05:12:17.270",
"Id": "7835",
"ParentId": "7826",
"Score": "6"
}
},
{
"body": "<p>It might be not exactly what you need, but have a look at <a href=\"https://bitbucket.org/offline/django-annoying/src/a0de8b294db3/annoying/decorators.py#cl-150\" rel=\"nofollow\">annoying \"ajax_request\" decorator</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T12:34:46.703",
"Id": "7838",
"ParentId": "7826",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7835",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T03:58:49.123",
"Id": "7826",
"Score": "4",
"Tags": [
"python",
"django"
],
"Title": "Decorator to take away repetitive code"
}
|
7826
|
<p><code>HtmlAgilityPack</code> is being really slow pulling back results. I have seen similar tools that get results a lot faster, but it's taking over a minute just to get the viewcounts on YouTube, and that's just with the first page of results.</p>
<p>Ideally I want to loop through multiple elements, but a nested loop wouldn't work for this code.</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
//webBrowser1.Navigate("www.youtube.com/results?search_query=grindtime");
StringBuilder output = new StringBuilder();
string raw = "http://www.youtube.com/results?search_query=grindtime";
HtmlWeb webGet = new HtmlWeb();
webGet.UserAgent = "Mozilla/5.0 (Macintosh; I; Intel Mac OS X 11_7_9; de-LI; rv:1.9b4) Gecko/2012010317 Firefox/10.0a4";
var document = webGet.Load(raw);
var viewcount = document.DocumentNode.SelectNodes("//*[@class='viewcount']");
//var videotitle = document.DocumentNode.SelectNodes("//a[@class='yt-uix-tile-link']");
//var browser = document.DocumentNode.SelectNodes("//*[@class='viewcount']");
if (viewcount != null)
{
foreach (var v in viewcount)
{
output.AppendLine(v.InnerHtml);
ListViewItem lvi = new ListViewItem("#1");
lvi.SubItems.Add("video title here");
lvi.SubItems.Add(b.InnerHtml);
//views
//desc..
//lid = link in desc yes/no
listView1.Items.Add(lvi);
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/weM3V.png" alt="enter image description here"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:11:58.833",
"Id": "12370",
"Score": "0",
"body": "How long does the `webGet.Load(raw);` take? IO (be it disk, network, etc) will always be the slowest part of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:15:53.467",
"Id": "12371",
"Score": "0",
"body": "Seems that the URL he is using is responding well. I cant imagine what 'b' from \"b.InnerHtml\" is. Maybe it is a huge HTML :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:16:40.983",
"Id": "12372",
"Score": "0",
"body": "about over a minute, I don't know if its a youtube thing or not but google and other places are just as slow. (I also tried my own page)@programad ignore the comments b used to be browser :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:17:11.000",
"Id": "12373",
"Score": "2",
"body": "@programad - The URL may be responding well for you but I'd imagine user1148562 is not sitting next to you at the moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:17:51.673",
"Id": "12374",
"Score": "1",
"body": "@user1148562 - That seems ridiculously slow to me. Looks like you found your bottleneck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:18:48.710",
"Id": "12375",
"Score": "0",
"body": "If other sites are slow too, maybe there is no problem in your code, just your internet connection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:26:57.323",
"Id": "12376",
"Score": "0",
"body": "no the site works just fine, it just parses the html slow in the program, I have very fast internet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:35:52.123",
"Id": "12377",
"Score": "0",
"body": "@user1148562 - Now that you've identified that HTMLAgilityPack's attempt to load your page is the slowest part of your program, what is the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:39:59.683",
"Id": "12378",
"Score": "0",
"body": "@M.Babcock basically I wanted to know how to make it go faster, I'm sure it will be even slower when I append all the pages."
}
] |
[
{
"body": "<p>Doing a simple regex on the page result would be most certainly more efficient, though several people will tell you that using an <em>HTML parser</em> to parse <em>HTML</em> is always the best practice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T07:32:49.490",
"Id": "12398",
"Score": "0",
"body": "Although regex may seem fit for this kind of tasks, in the end it may lead to vary complex implementations that still don't cover all possible cases. I've seen such a case once and I can say that while the regex was so complicated it was hard to maintain, the AgilityPack implementation was trivial and 100% accurate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T07:38:59.970",
"Id": "12399",
"Score": "0",
"body": "Agreed but if performance is the OP primary (or possibly *only*) focus then a proper RegEx would be more appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T01:46:23.287",
"Id": "12535",
"Score": "0",
"body": "I noticed that the first search is extremely slow, but the second search is pretty rapid, maybe if I load the search results page before the actual searches are done, this way when people get to the search page, the results page has already been loaded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T03:06:36.927",
"Id": "12539",
"Score": "0",
"body": "@chuckakers Are you still encountering performance problems despite the answer provided?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T03:16:37.430",
"Id": "12540",
"Score": "0",
"body": "yes im going to try preloading the page before parsing the html, I notice it is really fast on any second or future searches, its just the first search that is slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T03:30:10.773",
"Id": "12541",
"Score": "0",
"body": "@chuckakers - You'll need to either mark this question as unanswered (uncheck the checkbox on the answer you've selected) and update your question with *relevant* facts based on your findings (including updated source code); *or* ask another question (probably here on CR). Either way be sure to post your most recent source code exemplifying the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T04:50:11.363",
"Id": "12544",
"Score": "0",
"body": "ill mark it as answered and try the suggestions out before posting a follow up question.. thanks."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T02:13:11.917",
"Id": "7829",
"ParentId": "7827",
"Score": "0"
}
},
{
"body": "<p>First, the web request itself will take some time.</p>\n\n<p>To be able to profile it, maybe do some test with opening saved HTML file instead, to make sure that the parsing is your actual bottleneck, maybe even commenting the lines that create the result UI as well.</p>\n\n<p>I haven't used HTML Agility Pack much, but I see you are using an XPATH selector there, and it only uses a CSS Class. I'd assume the path will scan the entire document to check eevery element in it if it has the desired class or not.</p>\n\n<p>So, it may be a good idea to try to add some parents to the selector, so that it only looks for elements inside a given parent, best selected by ID or a tag. Those are general rules for browsers, I don't expect them to work the same with HTML Agility Pack, but they may provide some gain still.<br>\nAlso, check if there are any options in the library to match a single element, and if so, find that element and go through its children till you find your desired elements. This may improve things. Also, if there are any strict mode or less tolerant parsing options, try turning those on if they don't break the parsing.</p>\n\n<p>If you expect the page to be well structured and HTML valid, and parsing speed isn't getting any better however you enhance the selector, you may consider reverting to classic old Regex matching.</p>\n\n<p>Also, I recommend separating the Windows Forms rendering from the loop. Maybe the bottleneck is the drawing (unlikely, but maybe), try to add all your elements to a list, and then outside the loop, add the list to the windows forms control.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T03:03:11.110",
"Id": "12388",
"Score": "0",
"body": "yes! i think this is the problem, but I thought the xpath I had was selecting every span tag with the class of viewcount. I used the same thing with haptestbed and it wasn't slow at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T03:09:55.433",
"Id": "12389",
"Score": "0",
"body": "Cool. I hope this has solved the problem you were looking to solve them :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T03:02:16.917",
"Id": "12390",
"Score": "0",
"body": "yes, you was right, the xpath was causing it to be slow so i changed it to //body//span[@class='viewcount'] now it only takes about 5 seconds to parse those elements :) Im going to work on that path and make it faster though. I assume it was loading the scripts with the path I had."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T02:28:09.633",
"Id": "7830",
"ParentId": "7827",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "7830",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:05:47.513",
"Id": "7827",
"Score": "5",
"Tags": [
"c#"
],
"Title": "HtmlAgilityPack is being slow"
}
|
7827
|
Intel Thread Building Blocks
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T04:43:56.843",
"Id": "7833",
"Score": "0",
"Tags": null,
"Title": null
}
|
7833
|
<p>I'm interested in the idea of not having my BLL dependent on ASP.NET MVC. This means that I would like to have model binding occur within my service layer. But I want to take advantage of ASP.MVC's model validation as well. So I'm considering returning a custom validation dictionary from my BLL service methods like so</p>
<pre><code> [Authorize(Roles = "ADMIN")]
[HttpPost]
public ActionResult Create(PostEditViewModel postEditViewModel)
{
BlogPost post = new BlogPost();
postEditViewModel.MapTo(post);
//returns custom validation dictionary
var dic = _postService.CreatePost(post);
//extension method that allows Controller ModelState to merge with customer error dictionary (returns ModelState)
if (!ModelState.Merge(dic).IsValid)
return View();
return RedirectToAction("Index", "Home");
}
</code></pre>
<p>and merge the returned validation errors with my Controller's <code>ModelState</code> using an extension method on <code>ModelStateDictionary</code> (the extension method will be part of the MVC application and not the BLL). Can anyone foresee any problems going down the road? Is there a more elegant or intelligent way to accomplish what I'm trying to do here? I've also considered <a href="http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validating-with-a-service-layer-cs" rel="noreferrer">this</a> approach.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-02T15:49:39.297",
"Id": "256205",
"Score": "0",
"body": "Regarding your link, this seems to boil down to: work through a custom validation interface, wrap the ModelStateDictionary, pass it and update in the service; or (your option) return custom validation class, convert and merge to ModelStateDictionary? The steps involving the abstraction seem (to me) to be more-or-less equivalent, the real difference seems to be in the \"pass-update\" or \"return-merge\". Would you agree?"
}
] |
[
{
"body": "<p>It feels somewhat awkward to answer a question this old, but there are some things that can be done.</p>\n\n<hr>\n\n<p>First, I want to comment on the naming, simply from the fact that I'm currently building an ASP.NET app which is <em>very</em> large, and I've learned through the process that the <code>ViewModel</code> name becomes cumbersome, and is partially a lie. I've begun to name my 'View Models' as 'DTOs' instead, that is: Data-Transfer Object.</p>\n\n<p>This has begun to make my code <em>much</em> more clear, as it's now obvious that the DTO can be a two-way object: data can be fed to it from the back-end or from the UI.</p>\n\n<hr>\n\n<p>Regarding the service-layer handling database access: this is a good approach, I'll tell you that a lot of my code in this project I've mentioned previously is in the controller, and it's cumbersome. What I <em>would</em> change is reject the idea of needing to create a <code>dict</code> (or pass it to the <code>.Merge</code> method) controller-side, and do one of two things:</p>\n\n<ul>\n<li>Create a <code>BaseController</code> that will handle adding the validation errors to the <code>ModelState</code> itself, though this can become complicated.</li>\n<li>Pass the <code>Controller</code> to the method doing the validation, and allow it to add the errors to the <code>ModelState</code>.</li>\n</ul>\n\n<p>It's been a while since I've touched ASP.NET MVC 3, but in 4 and 5 you can directly manipulate the <code>ModelStateDictionary</code>, and use <code>.Add</code> or <code>.AddModelError</code>. I do this on various validation methods to remove that responsibility from the controller, and reduce the call to:</p>\n\n<pre><code>[Authorize(Roles = \"ADMIN\")]\n[HttpPost]\npublic ActionResult Create(PostEditViewModel postEditViewModel)\n{\n BlogPost post = new BlogPost();\n\n postEditViewModel.MapTo(post);\n _postService.CreatePost(post, this);\n\n if (!ModelState.IsValid)\n return View();\n\n return RedirectToAction(\"Index\", \"Home\");\n}\n</code></pre>\n\n<hr>\n\n<p>Another pointer: I would recommend converting your <code>Roles</code> attribute parameters to constants, I've found that it becomes unpleasant to change the name of a <code>Role</code> later, if you need to. I actually have a <code>Constants.Roles</code> class that has each role string associated to a type, so that if I have to change the name from <code>Controllers</code> to <code>Inventory</code>, it's <em>right there</em>, and my code can still reference the <code>InventoryControllers</code> constant. (You can also use the constants with XML-docs to make things more descriptive in the future.)</p>\n\n<hr>\n\n<p>You have:</p>\n\n<blockquote>\n<pre><code>BlogPost post = new BlogPost();\n</code></pre>\n</blockquote>\n\n<p>But then:</p>\n\n<blockquote>\n<pre><code>var dic = _postService.CreatePost(post);\n</code></pre>\n</blockquote>\n\n<p>Be consistent. If you're using <code>var</code> in one location, use it in the others. I used to be anti-<code>var</code> period because I felt it made my code look less organized, but to be honest, it helps align all the variable names to the fifth textual column (counting the space), so it's easy to identify where something is declared. (Of course, with the highlighting Visual Studio does it's not necessary, and F12 is a wonderful tool, but it's still helpful at times.)</p>\n\n<p>It also allows you to <em>ignore</em> what type it is when declaring. I'd have to type <code>BlogPost</code> out in one of those two places on that line (though one can argue that with intellisense when you type <code>BlogPost thing = new</code> it automatically suggests <code>BlogPost()</code> to finish it) so I don't mind changing the manual typing from <code>BlogPost post =</code> to <code>var post = new BlogPost();</code>, personally I type faster that way anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-13T18:11:53.920",
"Id": "169177",
"ParentId": "7845",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:00:28.303",
"Id": "7845",
"Score": "7",
"Tags": [
"c#",
"asp.net-mvc-3"
],
"Title": "Model validation from within the Service Layer"
}
|
7845
|
<p>Reading <a href="http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare" rel="nofollow">the article</a> in Wikipedia about cycle detection I came across a relatively small code snipped of Floyd's cycle-finding algorithm. I'll put it here to keep everything in one place:</p>
<pre><code>def floyd(f, x0):
# The main phase of the algorithm, finding a repetition x_mu = x_2mu
# The hare moves twice as quickly as the tortoise
tortoise = f(x0) # f(x0) is the element/node next to x0.
hare = f(f(x0))
while tortoise != hare:
tortoise = f(tortoise)
hare = f(f(hare))
# at this point the start of the loop is equi-distant from current tortoise
# position and x0, so hare moving in circle and tortoise (set to x0 )
# moving towards circle, will intersect at the beginning of the circle.
# Find the position of the first repetition of length mu
# The hare and tortoise move at the same speeds
mu = 0
tortoise = x0
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare)
mu += 1
# Find the length of the shortest cycle starting from x_mu
# The hare moves while the tortoise stays still
lam = 1
hare = f(tortoise)
while tortoise != hare:
hare = f(hare)
lam += 1
return lam, mu
</code></pre>
<p>But then I decided, why not rewrite this algorithm using iterators.</p>
<p>The result wasn't as good as I had hoped it to be.</p>
<p>In some parts of the code I needed the values that the iterators have already returned. So I had keep the values apart from iterators themselves. And I introduced the class <code>animal</code> to keep them in one place.</p>
<p>To my mind, the code got very hefty and ugly. Here it is:</p>
<pre><code># -*- coding: utf-8 -*-
from __future__ import print_function
from itertools import islice,cycle,chain
def detect_cycle(iterable):
class animal(object):
'''Holds the iterator and keeps the last value returned by the iterator'''
def __init__(self,iterable):
self.it = iter(iterable)
self.value = next(self.it) #get the first value
def next(self):
self.value = next(self.it)
return self.value
def __iter__(self):
return self
tortoise = animal(iterable)
hare = animal(islice(iter(iterable),None,None,2)) #two steps at a time
while True:
if next(tortoise) == next(hare):
break
hare = tortoise #put hare in the place of tortoise
tortoise = animal(iterable) #start tortoise from the very beginning
mu = 0
while True:
if hare.value == tortoise.value:
break
next(hare)
next(tortoise)
mu += 1
lamb = 0
tortoise_val = tortoise.value #save the value of tortoise as the object is reassigned to hare
hare = tortoise
while True:
next(hare)
lamb += 1
if hare.value == tortoise_val: #check AFTER the first step by hare
break
print('mu: {}'.format(mu))
print('lamb: {}'.format(lamb))
if __name__ == '__main__':
class iterable(object):
'''Emulate the object returning iterators having cycles'''
def __init__(self,beginning,cycling):
'''
beginning: the beginning part with no cycles (its length corresponds to mu)
cycling: the part which will be cycling (its length corresponds to lamb)
'''
self.beginning = beginning
self.cycling = cycling
def __iter__(self):
return chain(iter(self.beginning),cycle(iter(self.cycling)))
detect_cycle(iterable('1234','678'))
</code></pre>
<p>Is there anything that can be done to improve the code?
Is it the best that can be done using iterators?</p>
|
[] |
[
{
"body": "<pre><code># -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom itertools import islice,cycle,chain\n\n\ndef detect_cycle(iterable):\n\n class animal(object):\n</code></pre>\n\n<p>Putting classes inside function is usually not all that helpful. Also, the name doesn't really suggest what this class does. </p>\n\n<pre><code> '''Holds the iterator and keeps the last value returned by the iterator'''\n def __init__(self,iterable): \n self.it = iter(iterable)\n</code></pre>\n\n<p>I'd do something like iter, just because it isn't a really obvious abbreviation</p>\n\n<pre><code> self.value = next(self.it) #get the first value\n\n def next(self):\n self.value = next(self.it)\n return self.value\n\n def __iter__(self):\n return self\n\n\n tortoise = animal(iterable)\n hare = animal(islice(iter(iterable),None,None,2)) #two steps at a time\n</code></pre>\n\n<p>You end up create two iterators from the same iterable. That might be problematic as you can't be sure those two iterators are independent.</p>\n\n<pre><code> while True:\n if next(tortoise) == next(hare):\n break\n</code></pre>\n\n<p>You get most of the benefit of iterators when you can use for loops. In this case, I might use a for loop with itertools.izip.</p>\n\n<pre><code> hare = tortoise #put hare in the place of tortoise\n tortoise = animal(iterable) #start tortoise from the very beginning\n mu = 0\n while True:\n if hare.value == tortoise.value:\n break\n next(hare)\n next(tortoise)\n mu += 1\n</code></pre>\n\n<p>You do this basic thing three times. You loop through both iterators, until they match. Write a function that takes the two iterators, does that and then returns the count of them.</p>\n\n<pre><code> lamb = 0\n tortoise_val = tortoise.value #save the value of tortoise as the object is reassigned to hare\n hare = tortoise\n while True:\n next(hare)\n lamb += 1\n if hare.value == tortoise_val: #check AFTER the first step by hare\n break\n\n print('mu: {}'.format(mu))\n print('lamb: {}'.format(lamb))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T13:22:22.257",
"Id": "12449",
"Score": "0",
"body": "Thank you for suggestions. I have updated the code. Here it is: http://ideone.com/fYZ35. About the independence of iterators. I think it's very important. But I only came up with adding a warning in the description. Because I can't use `itertools.tee` since it'll defeat all the benefits of using this algorithm (since it'll be storing all the intermediary values). Also the usage of `chain(repeat((tortoise.val, hare.val),1)...` looks particularly ugly for me. But I haven't found any other way to add a single value to the chain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T13:31:50.253",
"Id": "12450",
"Score": "0",
"body": "I've made another version of the code which uses no class: http://ideone.com/fAlML All the logic which used to be covered in the code is no scattered around the code (the calculation of the first value follows a new iterator initialization always). Still, I don't like the code. The only conclusion I can draw from the experiment is that the original version of the code operating with indexes is more clear, short and straightforward."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T13:40:43.773",
"Id": "12451",
"Score": "0",
"body": "Update 1: http://ideone.com/vJKiv Still curious, if it's the best way to add a single value before the main iterator: `chain(repeat(hare_val,1),hare)` (here `hare_val` is added befor all the other values returned by `hare` iterator)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T14:15:27.897",
"Id": "12453",
"Score": "0",
"body": "Update 2: http://ideone.com/fgrwM Put all `while True:` code fragments into the function. Had to bring back the holding iterator class since otherwise I would have to return the current values of the iterator from that function somehow which will make the code completely cumbersome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:51:17.130",
"Id": "12472",
"Score": "0",
"body": "@ovgolovin, instead of `repeat(hare_val, 1)` just use `[hare_val]`. What if `consume_iterator...` returned the matching value as well as the count? I think then you can get rid of keeping iterator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T18:11:51.670",
"Id": "12509",
"Score": "0",
"body": "Thank you! My initial idea to use itertools wasn't that good definitely."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T20:37:27.997",
"Id": "7851",
"ParentId": "7847",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7851",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T18:03:03.690",
"Id": "7847",
"Score": "1",
"Tags": [
"python",
"iterator"
],
"Title": "Tortoise and hare cycle detection algorithm using iterators in Python"
}
|
7847
|
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace ReactiveExtensions
{
class Program
{
static void Main(string[] args)
{
var start = Observable.Start(() =>
{
Console.WriteLine("Getting some work done");
for (var i = 0; i < 10; i++)
{
Thread.Sleep(10000);
//go call stackoverflow
var d = CallStackOverFlow();
//send the result for checking to a delegate
foreach (var q in d.questions)
{
var list = (q.tags as JArray).Values().Select(v => v.ToString()).ToList();
var result = FindByTag(list);
if(result)
Console.WriteLine("Quesion title :{0}",q.title);
}
}
return "I am done observing";
});
Console.WriteLine("Subscribing"); // Make visible when we subscribe
start.Subscribe(Console.WriteLine);
Console.ReadKey();
}
private static readonly Func<List<String>,bool> FindByTag =(x => x.Contains("c#"));
private static dynamic CallStackOverFlow()
{
var client = new RestClient("http://api.stackoverflow.com/1.1");
var request = new RestRequest("/questions/no-answers", Method.POST);
var response = client.Execute(request);
var content = response.Content; // raw content as string
dynamic deserialised = JsonConvert.DeserializeObject(content);
return deserialised;
}
}
}
</code></pre>
<p>Please add the tag for ReactiveExtensions , my reputation does not allow me to do that.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T23:34:14.827",
"Id": "12422",
"Score": "5",
"body": "Please describe what it does, what is it's purpose, and what features of Rx does it demonstrate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T04:50:19.860",
"Id": "12429",
"Score": "0",
"body": "i am not sure exactly what features of Rx it demonstrates. I think i have created a pseudo stream , although i am not doing much work in an async manner . I think i should make the code do the checking while it waits for the next round of results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T10:35:41.967",
"Id": "12929",
"Score": "0",
"body": "At least start by removing nesting levels. Extract the parts of each for loop to a method. Consider whether parameters should be fields. It will make each part of your logic easier to maintain and read."
}
] |
[
{
"body": "<p>possible improvements :</p>\n\n<ol>\n<li>make CallStackOverflow asynchronous</li>\n<li>use Observavle.Timer instead of thread.sleep</li>\n</ol>\n\n<p>Here is what it would look like</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n\n Observable\n .Timer(TimeSpan.Zero,TimeSpan.FromSeconds(10))\n .Take(10)\n .Select(() => CallStackOverFlow().ToObservable())\n .Select(d => {\n //send the result for checking to a delegate\n foreach (var q in d.questions)\n {\n var list = (q.tags as JArray).Values().Select(v => v.ToString()).ToList();\n var result = FindByTag(list);\n if(result)\n Console.WriteLine(\"Quesion title :{0}\",q.title);\n }\n })\n .Wait();\n\n Console.WriteLine(\"Subscribing\"); // Make visible when we subscribe\n start.Subscribe(Console.WriteLine);\n Console.ReadKey();\n }\n\n private static readonly Func<List<String>,bool> FindByTag =(x => x.Contains(\"c#\"));\n\n private static async Task<dynamic> CallStackOverFlow()\n {\n var client = new RestClient(\"http://api.stackoverflow.com/1.1\");\n var request = new RestRequest(\"/questions/no-answers\", Method.POST);\n // -- async invocation\n var response = await client.ExecuteAsync(request); \n // or var response = await Task.Factory.FromAsync<TResponse>(client.BeginExecute, client.EndExecute, null);\n var content = response.Content; // raw content as string\n dynamic deserialised = JsonConvert.DeserializeObject(content);\n return deserialised;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-14T19:17:16.620",
"Id": "19623",
"ParentId": "7849",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T18:25:54.797",
"Id": "7849",
"Score": "2",
"Tags": [
"c#",
".net",
"system.reactive"
],
"Title": "Is this a good example of Reactive Extensions? How can I make this better?"
}
|
7849
|
<p>I am endeavoring to build my first non-trivial web application and so I'd like to confirm a couple of design decisions.</p>
<p>I have three tiers as follows:</p>
<ol>
<li>UI (my MVC project)</li>
<li>Business Logic (separate project)</li>
<li>Data Access Logic (a simple .dbml that is part of project #2)</li>
</ol>
<p>Is this a reasonable approach to separating concerns? Should my DAL consist of more than just my Linq .dbml file?</p>
<p>To play this out, lets say I have an Orders table and a Shipments table in my database. Furthermore lets say that I want to pass a list of orders and shipments through to a page in the UI. Here's how I'm envisioning that would work.</p>
<pre><code>OrdersBLL.cs
Public IEneumerable<Order> GetAllOrders()
{
DataContext db = new DataContext();
return db.Orders;
}
</code></pre>
<p>ShipmentsBLL.cs</p>
<pre><code>Public IEneumerable<Shipment> GetAllShipments()
{
DataContext db = new DataContext();
return db.Shipments;
}
</code></pre>
<p>ViewModels.cs</p>
<pre><code>public class ShowAll
{
public IQueryable<Order> order { get; set; }
public IQueryable<Shipment> shipment { get; set; }
}
</code></pre>
<p>Then when I create the view in the MVC app to display all orders and shipments I would simply pass in a ShowAll object from the ViewModel.</p>
<p>Over all I think this approach separates concerns reasonably well. However, I'd be interested in learning if others have a better approach. One concern I have is that my approach requires instantiating Order and Shipment objects in the View Model. However, these come from classes that are defined in my data layer. This strikes me as a bad idea given that I read somewhere that only the BLL should talk to the DAL. Is this correct? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T14:42:11.697",
"Id": "71205",
"Score": "0",
"body": "Have you tried Neos-SDI MVC4 Template? It's a good start for creating a MVC n-tiers web site.\nOnce this template is installed, it will create for you all your layers, use injection between layers."
}
] |
[
{
"body": "<p>An accepted design pattern for separation of concerns is the Repository design pattern. There is a pretty good description of using this design pattern in MVC <a href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application\" rel=\"nofollow\">here</a>. Your example is close to this pattern in your BLL layer, although your simple example does not have any business logic and just encapsulates the DAL. If you need to access multiple Repositories for your view it is recommended to use a Service Layer that coordinates transactions between multiple Repositories. There is a good description of this pattern <a href=\"http://www.asp.net/mvc/tutorials/contact-manager/iteration-4-make-the-application-loosely-coupled-cs\" rel=\"nofollow\">here</a>.</p>\n\n<p>Your View Model should be totally separated from the BLL and not query it directly. I assume you are querying the results in the View since you are returning an IQueryable object. The controller for the MVC should take any query parameters from the View, pass them to the Model (Repository or Service Layer) and get back an object graph that represents the View Model, which in turn is passed to the View. The View Model usually does not clone the objects that are manipulated in the Repository. For example you would not need to pass things like foreign keys used for navigation in the DAL to the View Model. Only pass to the View Model what it needs to get its job done, which is to allow the View to render a user interface. This usually requires a lot of data mapping from one object to another. Although it is a hassle upfront you will appreciate it going forward because you will have a code base that is not fragile to changes in either your model or view. A good tool to help with the data mapping is <a href=\"http://automapper.org/\" rel=\"nofollow\">AutoMapper</a>.\nFor a great example on how to create a robust modern website using MVC take a look at Microsoft's <a href=\"http://silk.codeplex.com/\" rel=\"nofollow\">Silk Project</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T19:46:34.677",
"Id": "7872",
"ParentId": "7855",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7872",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T03:48:18.573",
"Id": "7855",
"Score": "3",
"Tags": [
"c#",
"asp.net-mvc-3"
],
"Title": "nTier architecture for an MVC application"
}
|
7855
|
<p>I am doing my homework and i have done this? Is there any other better way to do this?
<br>
<br></p>
<pre><code>def write_log(name, total):
# change user input with shape names
name = name.replace('1', 'triangle')
name = name.replace('2', 'square')
name = name.replace('3', 'rectangle')
name = name.replace('4', 'pentagon')
name = name.replace('5', 'hexagon')
name = name.replace('6', 'octagon')
name = name.replace('7', 'circle')
total = int(total)
logfile = open("text.txt", "a")
if (total == 1):
towrite = ('%i %s \n'
% (total, name))
elif (total >= 2 and total <= 5):
name += 's' # add s to name to make it plural
towrite = ('%i %s \n'
% (total, name))
else:
towrite = ''
try:
logfile.write(towrite)
finally:
logfile.close()
return
</code></pre>
|
[] |
[
{
"body": "<p><strong>-- One --</strong></p>\n\n<p>You can use a dictionary to hold your translation data:</p>\n\n<pre><code>mydict = {'1':'triangle', '2':'square', '3':'rectangle',\n '4':'pentagon','5':'hexagon', '6':'octagon','7':'circle'}\n</code></pre>\n\n<p>Now your list of replacement lines becomes simply:</p>\n\n<pre><code>for key, value in mydict.iteritems():\n name = name.replace(key, value)\n</code></pre>\n\n<p>another option would be:</p>\n\n<pre><code>for key in mydict:\n name = name.replace(key, mydict[key])\n</code></pre>\n\n<p>To make this part complete, consider also a tuple for holding your data as indicated in @larmans answer. See also comments in the answers. I think there are interesting hints about which could be the best alternative for different cases.</p>\n\n<p><strong>-- Two --</strong></p>\n\n<p>also remember you can do</p>\n\n<pre><code>2 <= total <= 5\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>total >= 2 and total <= 5\n</code></pre>\n\n<p><strong>-- Three --</strong></p>\n\n<p>Note you dont need parenthesis in the <code>if</code> expressions. Just do this:</p>\n\n<pre><code>if total == 1:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:32:24.537",
"Id": "12431",
"Score": "2",
"body": "No need for a `dict`, since there's no lookup going on. A list of tuples would suffice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:32:40.563",
"Id": "12432",
"Score": "0",
"body": "But better create the dict like this: `mydict = {'1':'triangle', '2':square ... }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:36:45.670",
"Id": "12433",
"Score": "0",
"body": "And who said a \"list of tuples\" is better than a dict for anything? A dict is simpler to input and lighter on the system. No need for a listof tuples in there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:42:33.010",
"Id": "12434",
"Score": "0",
"body": "This doesn't work as written. The `mydict=` line is a syntax error, and iterating over mydict (if it were a dict) gives the keys, not (key, value) pairs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:43:24.753",
"Id": "12435",
"Score": "0",
"body": "@larsman, use of a dict for lookup is a very common strategy. I'm not sure if a tuple is a bit more light or a bit more faster, but I think a dict is a good thing to show for a homework. He want to translate numbers into figures, so lets provide him with a dictionary !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:45:05.003",
"Id": "12436",
"Score": "0",
"body": "@DSM already seen, corrected"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:46:14.783",
"Id": "12437",
"Score": "0",
"body": "@leo thanks, some link about why this is better ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:50:44.243",
"Id": "12438",
"Score": "0",
"body": "@joaquin I don't have a link, but I find it better more because it's just shorter. :) (but of course you can also use your method instead)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:53:54.683",
"Id": "12439",
"Score": "0",
"body": "@joaquin: my point is that the `dict` is *not* used for lookup, just iteration. There's a syntax error in your example, btw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T18:06:06.880",
"Id": "12440",
"Score": "0",
"body": "@leo, No, you were right, it was an error I always, **always** fall in. You can not do `dict('1'='b')` It produces `SyntaxError: keyword can't be an expression` (you can do `dict(b='1')` though)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T18:07:35.830",
"Id": "12441",
"Score": "0",
"body": "@jsbueno: `dict` is not \"lighter on the system\". Iterating over a list is faster than iterating over a `dict`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T21:47:17.433",
"Id": "12464",
"Score": "0",
"body": "Use [enumerate](http://docs.python.org/library/functions.html#enumerate) to build the dictionary as I show in [my answer](http://codereview.stackexchange.com/a/7873/9370).There is no need to iterate over the dictionary; once you have the dictionary you can just access the dictionary using the number as the key."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:30:17.820",
"Id": "7858",
"ParentId": "7857",
"Score": "7"
}
},
{
"body": "<p>I'd find it a bit more elegant to use a list of tuples:</p>\n\n<pre><code>replacements = [('1', 'triangle'),\n ('2', 'square'),\n # etc.\n ]\n\nfor old, new in replacements:\n name = name.replace(old, new)\n</code></pre>\n\n<p>This way, you can more easily change the code later on; e.g., when you decide you want to use <code>re.sub</code> instead of <code>.replace</code>.</p>\n\n<p>Also, I'd use the <a href=\"http://effbot.org/zone/python-with-statement.htm\"><code>with</code> statement</a> for the logfile:</p>\n\n<pre><code>with open(\"text.txt\", \"a\") as logfile:\n # write stuff\n</code></pre>\n\n<p>This saves you the trouble of closing the file explicitly, so you can remove the exception-handling logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T21:45:51.617",
"Id": "12463",
"Score": "0",
"body": "Use [enumerate](http://docs.python.org/library/functions.html#enumerate) to build the dictionary as I show in [my answer](http://codereview.stackexchange.com/a/7873/9370). Then just access the dictionary using the number as the key. +1 for using `with`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:33:29.327",
"Id": "7859",
"ParentId": "7857",
"Score": "7"
}
},
{
"body": "<p>If you want something a bit fancy you can use <code>re.sub</code>:</p>\n\n<pre><code>import re\nSHAPES = {\n '1': 'triangle',\n '2': 'square',\n '3': 'rectangle',\n '4': 'pentagon',\n '5': 'hexagon',\n '6': 'octagon',\n '7': 'circle',\n}\n\nname = re.sub('[1-7]', lambda m: SHAPES[m.group(0)], name)\n</code></pre>\n\n<p>Also for the output probably use a single test and format:</p>\n\n<pre><code>if 1 <= total <= 5:\n towrite = ('%i %s%s \\n' % (total, name, \"s\" if name > 1 else \"\"))\n</code></pre>\n\n<p>Note that Python lets you run similar conditions together so you don't need to use <code>and</code> for this sort of condition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T21:44:06.207",
"Id": "12462",
"Score": "0",
"body": "@Duncan Use [enumerate](http://docs.python.org/library/functions.html#enumerate) to build the dictionary as I show in [my answer](http://codereview.stackexchange.com/a/7873/9370). Also, once you have the dictionary, there is no need to use `re` when you can just access the dictionary using the number as the key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T22:02:57.350",
"Id": "12465",
"Score": "0",
"body": "@aculich, using `re.sub` means a single pass through the string so it scales much better than lots of repeated `replace` calls. That isn't important here, but it can be significant in other similar situations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T23:11:38.217",
"Id": "12468",
"Score": "0",
"body": "@Duncan I would consider that to be premature optimization and harder to maintain in a way that will lead to bugs. For example, if they added three more shapes, so the total was 10, then your code would produce the incorrect result: `triangle0`. And even if you correct the regular expression in `re.sub()`, it is still worth using `dict(enumerate())` on the list to make the code easier to maintain, for example if they wanted to start the numbering from 0 or to re-order items in the list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T08:43:17.880",
"Id": "12474",
"Score": "0",
"body": "@aculich hence the 'If you want something a bit fancy'. I wasn't proposing it as better than the accepted solution for this case but as an alternative technique that is worth knowing. I'm agnostic about `enumerate` here: you have to either convert the matching groups to `int` or `str` the keys so it adds complexity. Also say it was mapping error numbers to messages then quite likely the numbers would soon cease being consecutive and you *have* to go back to the literal dictionary. As for the regex going wrong: `\\d+` and using `SHAPES.get(m.group(0), m.group(0))` sorts that one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T21:50:00.800",
"Id": "12522",
"Score": "0",
"body": "@Duncan I don't understand what \"fancy\" means. I take it to mean \"over-complicated\". `int()` will do a better job of parsing the value into a list index than `re.sub()` which will raise `TypeError: expected string or buffer` if the argument passed in is already an `int`, whereas `int()` will do the correct thing whether the value is an `int` or a `string`. Since the numbering starts at 1, pad the array like this: `SHAPES = ['not a shape', 'triangle', ... ]` and then the code simplifies to `name = SHAPES[int(name)]`. Padding is not ideal, but it is a more readable declarative approach."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:39:36.443",
"Id": "7861",
"ParentId": "7857",
"Score": "2"
}
},
{
"body": "<p>Below I've answered the question about a better way to write the replacement, but I've also re-written your code in some other ways that I will explain below how and why I changed it the way I did.</p>\n\n<p>Starting with <code>def write_log(name, total):</code> it would be better to use a more meaningful variable name, <code>num</code>, since you expect a number which you'll later be converting into a <code>name</code>.</p>\n\n<p>It is good that you used <code>total = int(total)</code> to make sure that the input is, indeed, a number. We'll do that with the new variable <code>num</code>, as well. Note, that if this fails it will throw a <code>ValueError</code> exception.</p>\n\n<p>Next, since you have a list of names, make them explicitly a list with <code>['triangle','square'...]</code>. Here I also give it a meaningful variable name, <code>shapes</code>.</p>\n\n<p>For the replacements, this is a good candidate for using a <a href=\"http://docs.python.org/tutorial/datastructures.html#dictionaries\" rel=\"nofollow\"><code>dict</code>ionary data structure</a>. And since you want to number each of these names in order you can use the <a href=\"http://docs.python.org/library/functions.html#enumerate\" rel=\"nofollow\"><code>enumerate</code></a> function; note that by default it will start the numbering from 0, but since you want to start from 1 in your example, I added the starting number as the second argument to <a href=\"http://docs.python.org/library/functions.html#enumerate\" rel=\"nofollow\"><code>enumerate</code></a>.</p>\n\n<p>Once you have enumerated your shapes list into a dictionary you can now use <code>num</code> as a key to get the value (the shape name). I wrapped it in a <code>try ... except</code> block in case someone called <code>write_log</code> with an invalid value. If an exception happens, then we print an error to <code>stderr</code> and then <code>return</code> from the function. I used this exception handling as an example to show when you would want to use <code>return</code>; in this case we are returning from the middle of the function. Note that I removed the return at the <em>end</em> of your program because you don't have to explicitly write <code>return</code> at the end unless you are actually returning some value, but in your example your function returns nothing at the end, so there is no need to write it out explicitly there at the end.</p>\n\n<p>For pluralization we can simplify further by separating out the pluralization from the log message itself. We only append an <code>'s'</code> if <code>total</code> is greater than 1; I'm not sure when you had <code>total <= 5</code>, but if you really only wanted pluralization for <code>>=2 and <=5</code>, then you could write it that way, but <code>>1</code> seems to make more sense here. Then building the string for the log message is the same whether or not name is plural.</p>\n\n<p>To open the log file it is better to use the <a href=\"http://docs.python.org/reference/compound_stmts.html#the-with-statement\" rel=\"nofollow\"><code>with</code></a> statement. That will put a <code>try ... finally</code> block around the code so that the file is automatically closed once the logfile variable is no longer in scope (including if an exception is thrown). What you wrote here is definitely correct (and good practice), but since it is such a common pattern the <code>with</code> statement was created for exactly this purpose (see <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow\">PEP 343</a>).</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport sys\n\ndef write_log(num, total):\n # ensure that inputs are numbers\n num = int(num)\n total = int(total)\n\n shapes = ['triangle', 'square', 'rectangle', 'pentagon', 'hexagon', 'octagon', 'circle']\n replacements = dict(enumerate(shapes, 1))\n try:\n name = replacements[num]\n except KeyError:\n sys.stderr.write('Error: %i is not a valid input.\\n' % (num))\n return\n\n if total > 1:\n name += 's' # add s to name to make it plural\n\n with open('text.txt', 'a') as logfile:\n msg = '%i %s \\n' % (total, name)\n logfile.write(msg)\n\ndef main():\n write_log(1, 2)\n write_log(23, 5) # this will generate an error\n write_log(3, 4)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T21:04:33.760",
"Id": "7873",
"ParentId": "7857",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7859",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T17:26:21.557",
"Id": "7857",
"Score": "4",
"Tags": [
"python",
"homework"
],
"Title": "is there a better way than replace to write this function?"
}
|
7857
|
<p>I tried to implement the dispose-finalize pattern on this WCF wrapper.</p>
<p>Do you have any comments about this? Something I missed?</p>
<pre><code>namespace System.ServiceModel
{
public class WCFClientWrapper<TProxy> : IDisposable where TProxy : class
{
private string _endpointAddress;
public TProxy Service { get; private set; }
public WCFClientWrapper(string endpointAddress)
{
_endpointAddress = endpointAddress;
var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(endpointAddress));
Service = factory.CreateChannel();
(Service as IClientChannel).Faulted += WCFClientWrapper_Faulted;
}
private TProxy CreateChannel(string endpointAddress)
{
var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(endpointAddress));
return factory.CreateChannel();
}
void WCFClientWrapper_Faulted(object sender, EventArgs e)
{
DisposeService();
Service = CreateChannel(_endpointAddress);
}
public void Dispose(bool disposing)
{
if (disposing)
{
// get rid of managed resources
}
DisposeService();
GC.SuppressFinalize(this);
}
private void DisposeService()
{
IClientChannel serviceChannel = Service as IClientChannel;
if (serviceChannel == null)
return;
bool success = false;
try
{
(Service as IClientChannel).Faulted -= WCFClientWrapper_Faulted;
if (serviceChannel.State != CommunicationState.Faulted)
{
serviceChannel.Close();
success = true;
}
}
finally
{
if (!success)
{
serviceChannel.Abort();
}
}
}
public void Dispose()
{
Dispose(true);
}
~WCFClientWrapper()
{
Dispose(false);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T08:26:13.887",
"Id": "116691",
"Score": "0",
"body": "Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real \n\napplications with full source code and good patterns_"
}
] |
[
{
"body": "<p>Given that much of the code seems to rely on Service being an IClientChannel, and the name of the class implies as such, it may be worth simply adding IClientChannel to your type constraints and remove all the type conversion code.</p>\n\n<p>Building upon that thought, I notice that IClientChannel extends IChannel, and everything you use seems to be present on IChannel. You may consider using that interface instead, and renaming your class to reflect that it is not limited to IClientChannel.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T07:55:17.267",
"Id": "12783",
"Score": "0",
"body": "Thank you but there is no constraint that defines an inheritance from an interface."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T18:17:50.563",
"Id": "7871",
"ParentId": "7862",
"Score": "2"
}
},
{
"body": "<p>I saw some duplication of code, which could easily be centralized and eliminated. I also <a href=\"http://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow noreferrer\">renamed a few pieces as per Microsoft Framework Design Guidelines</a>. Finally, you may also want to look at <a href=\"https://stackoverflow.com/a/7248638/3312\">this bit of code</a> which seems somewhat similar and caches the service proxy rather than recreating it for each call.</p>\n\n<pre><code>namespace System.ServiceModel\n{\n public class WcfClientWrapper<TProxy> : IDisposable where TProxy : class\n {\n private string endpointAddress;\n\n private TProxy service;\n\n public WcfClientWrapper(string endpointAddress)\n {\n this.service = this.CreateChannel(endpointAddress);\n\n var serviceChannel = this.service as IClientChannel;\n\n if (serviceChannel == null)\n {\n return;\n }\n\n serviceChannel.Faulted += this.ClientChannelFaulted;\n }\n\n ~WcfClientWrapper()\n {\n this.Dispose(false);\n }\n\n public TProxy Service\n {\n get\n {\n return this.service;\n }\n }\n\n public void Dispose()\n {\n this.Dispose(true);\n }\n\n public void Dispose(bool disposing)\n {\n if (disposing)\n {\n // get rid of managed resources\n }\n\n this.DisposeService();\n GC.SuppressFinalize(this);\n }\n\n private TProxy CreateChannel(string newEndpointAddress)\n {\n this.endpointAddress = newEndpointAddress;\n\n var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(newEndpointAddress));\n\n return factory.CreateChannel();\n }\n\n private void ClientChannelFaulted(object sender, EventArgs e)\n {\n this.DisposeService();\n this.service = this.CreateChannel(this.endpointAddress);\n }\n\n private void DisposeService()\n {\n var serviceChannel = this.service as IClientChannel;\n\n if (serviceChannel == null)\n {\n return;\n }\n\n var success = false;\n\n try\n {\n serviceChannel.Faulted -= this.ClientChannelFaulted;\n if (serviceChannel.State != CommunicationState.Faulted)\n {\n serviceChannel.Close();\n success = true;\n }\n }\n finally\n {\n if (!success)\n {\n serviceChannel.Abort();\n }\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-16T23:06:02.263",
"Id": "23997",
"Score": "0",
"body": "The `DisposeService()` method will get called for both an explicit `Dispose()` and during finalization. Is this safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-17T00:49:41.227",
"Id": "24000",
"Score": "0",
"body": "You might want to set `serviceChannel` to `null` at the end of the `DisposeService()` method to be sure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T03:12:20.743",
"Id": "7878",
"ParentId": "7862",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T06:55:59.577",
"Id": "7862",
"Score": "3",
"Tags": [
"c#",
"wcf"
],
"Title": "WCF wrapper implementing dispose-finalize pattern"
}
|
7862
|
<p>I'm a beginner, currently taking the <a href="http://see.stanford.edu/see/courseinfo.aspx?coll=824a47e1-135f-4508-a5aa-866adcae1111" rel="nofollow">Stanford's free CS106A cours</a>e which teaches Java. The <a href="http://see.stanford.edu/materials/icspmcs106a/19-assignment-3-breakout.pdf" rel="nofollow">second assignment</a> has you build Breakout from scratch using the ACM programs and graphics packages. </p>
<p>Since it's an online course and I don't have anyone who can review my code, I thought I might ask you what newbie mistakes I'm making. I'm sure there are a lot.</p>
<p>I had some trouble figuring out where to stick some of the behavior. I have a <code>Ball</code> class within which I wanted to put the collision detection and reaction, but ended up having to put it in the main program, because ACM wouldn't let me check the canvas around the ball from within the ball. </p>
<p>I also could manage to get the main program's instance from anywhere, only its class, which wasn't what I needed. Any ideas on how to do this? Other instances were problems, too. For instance, is there any way for me to get the <code>Paddle</code>'s instance within the <code>Ball</code> without passing the paddle into the constructor? Is there any way to call it?</p>
<p>I wasn't sure about where to use private/public and static. I feel as though a lot of my uses were workarounds.</p>
<p>How would you have built this differently? What huge mistakes should I stop making? Is it organized awfully?</p>
<p><strong>Main program:</strong></p>
<pre><code>import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Breakout extends GraphicsProgram {
public void init() {
setBricks();
add(paddle);
add(ball,WIDTH/2,500);
lifeBar.setColor(Color.WHITE);
add(lifeBar,20,60);
addMouseListeners();
setBackground(Color.BLACK);
}
public void run() {
while(gameOver != true) {
pause(20);
checkCollision(ball);
ball.move();
if (prize != null) {
prize.drop();
if (prize.leftScreen()) remove(prize);
}
}
addMouseListeners();
}
private void setBricks() {
for (int row = 0; row < NBRICK_ROWS; row++) {
Color rowColor = checkColor(row);
for (int col = 0; col < NBRICKS_PER_ROW; col++) {
add(new Brick(col,row,rowColor));
}
}
}
public void mouseClicked(MouseEvent e) {
removeBrick(getElementAt(e.getX(),e.getY()));
}
public void mouseMoved(MouseEvent e) {
paddle.followMouse(e.getX());
}
private Color checkColor(int row) {
switch (row) {
case 0:
case 1: return Color.RED;
case 2:
case 3: return Color.ORANGE;
case 4:
case 5: return Color.YELLOW;
case 6:
case 7: return Color.GREEN;
case 8:
case 9: return Color.CYAN;
}
return Color.CYAN;
}
private void removeBrick(GObject brick) {
/* add test to see if removing brick is possible */
if (brick != null && brick instanceof Brick) {
remove(brick);
if (((Brick) brick).isSpecial()) callPrize(brick.getX(),brick.getY());
if (Brick.decreaseBricks()) callGameOver(true);
}
}
private void removeLife() {
lives--;
lifeBar.setLabel("Lives: " + lives);
if (lives <= 0) callGameOver(false);
}
public void callPrize(double x, double y) {
prize = new Prize(x,y,Color.MAGENTA, paddle);
add(prize);
}
public void callGameOver(boolean won) {
GRect gameOverScreen = new GRect(0,0,WIDTH,HEIGHT);
gameOverScreen.setFilled(true);
gameOverScreen.sendToFront();
GLabel gameOverLabel = new GLabel("");
if (won == true) {
gameOverScreen.setColor(Color.WHITE);
gameOverLabel.setColor(Color.BLUE);
gameOverLabel.setLabel("WOO YOU WON!!!");
if (lives == 3) gameOverLabel.setLabel("HOLY SHIT PERFECT SCORE!!!");
} else {
gameOverScreen.setColor(Color.RED);
gameOverLabel.setColor(Color.WHITE);
gameOverLabel.setLabel("HAH WHAT A LOSER");
}
add(gameOverScreen);
add(gameOverLabel,WIDTH/2-gameOverLabel.getWidth()/2,HEIGHT/2+gameOverLabel.getAscent()/2);
gameOver = true;
}
private void checkCollision(Ball ball) {
double r = ball.getRadius();
ball.move();
double x = ball.getX();
double y = ball.getY();
ball.moveBack();
GObject collider = null;
int dir = 0;
// Check walls + keep within bounds (keep from getting stuck)
if (x-r <= 0) {
ball.setLocation(r,y);
ball.changeDirection(1);
} else if (x+r >= WIDTH) {
ball.setLocation(WIDTH-r,y);
ball.changeDirection(1);
}
if (y-r <= 0) {
ball.setLocation(x,r);
ball.changeDirection(2);
// less life
} else if (y+r >= HEIGHT) {
removeLife();
ball.restart();
}
//Check elements
//Check right
if (getElementAt(x+r,y) != null && getElementAt(x+r,y) != ball && !(getElementAt(x+r,y) instanceof GLabel) && !(getElementAt(x+r,y) instanceof Prize)) {
ball.changeDirection(1);
collider = getElementAt(x+r,y);
}
//Check left
if (getElementAt(x-r,y) != null && getElementAt(x-r,y) != ball && !(getElementAt(x-r,y) instanceof GLabel) && !(getElementAt(x-r,y) instanceof Prize)) {
ball.changeDirection(1);
collider = getElementAt(x-r,y);
}
//Check bottom
if (getElementAt(x,y+r) != null && getElementAt(x,y+r) != ball && !(getElementAt(x,y+r) instanceof GLabel) && !(getElementAt(x,y+r) instanceof Prize)) {
ball.changeDirection(2);
collider = getElementAt(x,y+r);
}
//Check top
if (getElementAt(x,y-r) != null && getElementAt(x,y-r) != ball && !(getElementAt(x,y-r) instanceof GLabel) && !(getElementAt(x,y-r) instanceof Prize)) {
ball.changeDirection(2);
collider = getElementAt(x,y-r);
}
ball.changeDirection(dir);
if (collider instanceof Brick) removeBrick(collider);
if (collider == paddle) {
ball.setDirection(paddle.collide(x,r));
}
}
/* Init things */
private Paddle paddle = new Paddle();
private Ball ball = new Ball(BALL_RADIUS);
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
public static final int WIDTH = APPLICATION_WIDTH;
public static final int HEIGHT = APPLICATION_HEIGHT;
/** Offset of the paddle up from the bottom */
public static final int PADDLE_Y_OFFSET = 30;
/** Number of bricks per row */
public static final int NBRICKS_PER_ROW = 10;
/** Number of rows of bricks */
private static final int NBRICK_ROWS = 10;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
public static final int BRICK_Y_OFFSET = 70;
/** Number of turns */
private static final int NTURNS = 3;
/** Points */
private int lives = NTURNS;
/** Game is Over */
private boolean gameOver = false;
/* Prize on Board */
Prize prize = null;
private GLabel lifeBar = new GLabel("Lives: " + lives);
}
</code></pre>
<p><strong><code>Ball</code> Class</strong></p>
<pre><code>import acm.graphics.*;
import acm.util.*;
import java.awt.*;
public class Ball extends GCompound {
public Ball(double radius) {
r = radius;
GOval ball = new GOval(-r,-r,r*2,r*2);
ball.setFilled(true);
ball.setColor(new Color(200,200,200));
GOval light = new GOval(-r+3,-r+3,r*2-6,r-2);
light.setFilled(true);
light.setColor(new Color(255,255,255,150));
add(ball);
add(light);
direction = rgen.nextDouble(220,320);
direction = 290;
}
public void move() {
this.movePolar(velocity,direction);
}
public void moveBack() {
this.movePolar(velocity, (direction+180)%360);
}
public void restart() {
this.setVisible(false);
pause(100);
this.setVisible(true);
pause(100);
this.setVisible(false);
pause(100);
this.setLocation(Breakout.WIDTH/2,Breakout.HEIGHT/2);
this.setVisible(true);
direction = rgen.nextDouble(220,320);
}
public double getRadius() {
return r;
}
public void changeDirection(int xory) {
if (xory == 1) direction -= (direction-270)*2;
if (xory == 2) direction -= (direction-180)*2;
}
public double getDirection() {
return direction;
}
public static void setVelocity(double v) {
velocity = v;
}
public void setDirection(double d) {
direction = d;
}
private double r;
private double direction;
private static final double STARTING_VELOCITY = 5.0;
private static double velocity = STARTING_VELOCITY;
private RandomGenerator rgen = RandomGenerator.getInstance();
}
</code></pre>
<p><strong><code>Brick</code> Class</strong></p>
<pre><code>import acm.graphics.*;
import acm.util.*;
import java.awt.*;
public class Brick extends GCompound {
public Brick(int colNum, int rowNum, Color color) {
if (rgen.nextBoolean(0.01)) {
color = Color.MAGENTA;
special = true;
}
GRect fill = new GRect(0,0,BRICK_WIDTH, BRICK_HEIGHT);
fill.setFilled(true);
fill.setColor(color);
GRect light = new GRect(0,0,BRICK_WIDTH,BRICK_HEIGHT/2);
light.setFilled(true);
light.setColor(new Color(255,255,255,120+10*rowNum));
if (special == true) light.setColor(new Color(255,255,255,120));
add(fill);
add(light);
// Find and set location
double x = START_X + colNum * (BRICK_WIDTH + BRICK_SEP);
double y = START_Y + rowNum * (BRICK_HEIGHT + BRICK_SEP);
setLocation(x,y);
// Add to bricks remaining;
bricksRemaining++;
}
public static int getBricksRemaining() {
return bricksRemaining;
}
/* decreases bricks remaining and checks for end */
public static boolean decreaseBricks() {
bricksRemaining--;
if (bricksRemaining < 75) Ball.setVelocity(7); //Set the velocity higher if
if (bricksRemaining < 50) Ball.setVelocity(9);
if (bricksRemaining < 25) Ball.setVelocity(11);
return (bricksRemaining > 0) ? false : true;
}
public boolean isSpecial() {
return special;
}
/** Separation between bricks */
public static final int BRICK_SEP = 4;
/** Width of a brick */
public static final int BRICK_WIDTH =
(Breakout.WIDTH - (Breakout.NBRICKS_PER_ROW - 1) * BRICK_SEP) / Breakout.NBRICKS_PER_ROW;
/** Height of a brick */
public static final int BRICK_HEIGHT = 12;
/** Starting point X and Y values for first brick */
private static final double START_X = (Breakout.WIDTH - ((Breakout.NBRICKS_PER_ROW * BRICK_WIDTH) + (Breakout.NBRICKS_PER_ROW - 1) * BRICK_SEP)) / 2 ;
private static final int START_Y = Breakout.BRICK_Y_OFFSET;
private boolean special = false;
private static int bricksRemaining = 0;
private RandomGenerator rgen = RandomGenerator.getInstance();
}
</code></pre>
<p><strong><code>Paddle</code> Class</strong></p>
<pre><code>import acm.graphics.*;
import java.awt.*;
public class Paddle extends GCompound {
public Paddle() {
fill = new GRect(0,0, PADDLE_STARTING_WIDTH, PADDLE_HEIGHT);
fill.setFilled(true);
fill.setColor(Color.GRAY);
light = new GRect(0,PADDLE_HEIGHT/2, PADDLE_STARTING_WIDTH, PADDLE_HEIGHT/2);
light.setFilled(true);
light.setColor(new Color(0,0,0,50));
add(fill);
add(light);
this.setLocation((Breakout.WIDTH - PADDLE_STARTING_WIDTH) / 2, PADDLE_Y);
}
public void followMouse(double mouseX) {
if (mouseX < paddleWidth/2) {
this.setLocation(0, PADDLE_Y);
} else if (mouseX > Breakout.WIDTH - paddleWidth/2) {
this.setLocation(Breakout.WIDTH - paddleWidth,PADDLE_Y);
} else {
this.move(mouseX-paddleWidth/2 - this.getX(), 0);
}
}
public double collide(double ballX, double r) {
double paddleX = this.getX();
setColor(Color.RED);
double hitSpot = ballX - paddleX;
double maxPaddle = paddleWidth + r;
double minPaddle = -r;
double paddleRange = maxPaddle - minPaddle;
double minAngle = 160;
double maxAngle = 20;
double angleRange = maxAngle - minAngle;
double newDirection = ((hitSpot * angleRange) / paddleRange) + minAngle;
return newDirection;
}
private void widen() {
paddleWidth += 30;
this.move(-15, 0);
fill.setSize(paddleWidth, PADDLE_HEIGHT);
light.setSize(paddleWidth, PADDLE_HEIGHT / 2);
}
public void checkForPrize(Prize prize, double x, double y) {
if ((y >= PADDLE_Y) && (y <= PADDLE_Y + PADDLE_HEIGHT) && x > this.getX() && x < this.getX() + paddleWidth) {
prize.pickUp();
this.widen();
}
}
/** Dimensions of the paddle */
private static final int PADDLE_STARTING_WIDTH = 60;
private static final int PADDLE_HEIGHT = 15;
private GRect fill;
private GRect light;
private int paddleWidth = PADDLE_STARTING_WIDTH;
/** Dimensions of the paddle */
public static final int PADDLE_Y = Breakout.HEIGHT - Breakout.PADDLE_Y_OFFSET;
}
</code></pre>
<p><strong><code>Prize</code> Class</strong></p>
<pre><code>import acm.graphics.*;
import java.awt.*;
public class Prize extends GOval {
public Prize(double x, double y, Color color, Paddle pad) {
super(x + Brick.BRICK_HEIGHT/2, y + Brick.BRICK_WIDTH/2, PRIZE_RADIUS * 2, PRIZE_RADIUS * 2);
setFilled(true);
setColor(color);
paddle = pad;
}
public void drop() {
this.move(0, PRIZE_SPEED);
paddle.checkForPrize(this,this.getX()+PRIZE_RADIUS,this.getY()+PRIZE_RADIUS*2);
}
public boolean leftScreen() {
if (this.getY() - PRIZE_RADIUS > Breakout.HEIGHT || pickedUp == true) {
return true;
} else {
return false;
}
}
public void pickUp() {
pickedUp = true;
}
private boolean pickedUp = false;
private Paddle paddle;
public static final int PRIZE_RADIUS = 5;
public static final int PRIZE_SPEED = 10;
}
</code></pre>
|
[] |
[
{
"body": "<p>I haven't tried to get into the high level design of your game but here are a few details you might want to fix.</p>\n\n<ul>\n<li><p><code>if (won == true)</code> can be written <code>if (won)</code></p></li>\n<li><p>You can use the ternary operator to use setLabel only once : <code>gameOverLabel.setLabel((lives == 3)?\"HOLY SHIT PERFECT SCORE!!!\":\"WOO YOU WON!!!\");</code></p></li>\n<li><p>I guess the code to check elements can be factorised.</p></li>\n<li><p>Using <code>instanceof</code> is usually a bad thing.</p></li>\n<li><p>You probably want to store your magic numbers in constant variables to make things easier to understand.</p></li>\n<li><p>The way you initialise direction in the Ball constructor is weird (and the way you change direction is pretty awkward as well)</p></li>\n<li><p>There's probably a problem in the <code>decreaseBricks()</code> method : you might want to do the test in the other order and separated by else and you can simply <code>return (bricksRemaining > 0)</code> (maybe returning bricksRemaining would work but I just can't remember how it works in Java)</p></li>\n<li><p>The <code>leftScreen()</code> method could be a <code>return <your big expression>;</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T17:58:20.430",
"Id": "12572",
"Score": "0",
"body": "Hey, thanks so much for the tips. Just one question, I've read in several other places that instanceof is a bad thing, but couldn't find another way to check for the type of object I'm hitting. How else would I go about this?\n\nAlso: magic numbers?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T16:19:15.420",
"Id": "7868",
"ParentId": "7865",
"Score": "4"
}
},
{
"body": "<h2>General</h2>\n\n<p>Your code would be more readable without the redundant \"<code>this.</code>\"s.</p>\n\n<h2>Main program</h2>\n\n<pre><code>private void checkCollision(Ball ball) {\n double r = ball.getRadius();\n//// If you moved the ball BEFORE checkCollision, you wouldn't need\n//// to move it here, and move it back only to move it again, AFTER.\n ball.move();\n double x = ball.getX();\n double y = ball.getY(); \n\n//// There's no point in finishing this function after removeLife,\n//// so test for it up-front and get it out of the way.\n\n // less life\n if (y+r >= HEIGHT) {\n removeLife();\n ball.restart();\n return;\n }\n\n ball.moveBack();\n GObject collider = null;\n int dir = 0;\n\n // Check walls + keep within bounds (keep from getting stuck)\n if (x-r <= 0) {\n ball.setLocation(r,y);\n ball.changeDirection(1);\n } else if (x+r >= WIDTH) {\n ball.setLocation(WIDTH-r,y);\n ball.changeDirection(1);\n }\n\n if (y-r <= 0) {\n ball.setLocation(x,r);\n ball.changeDirection(2);\n }\n\n //Check elements\n</code></pre>\n\n<p>This \"Check elements\" part could be much faster if you established \"zones\" (y value ranges) where you would expect to collide with a brick or a paddle and only test for collisions with these things when the ball is in their zones.</p>\n\n<p>Calling getElementAt ONCE for each given argument pair and reusing the result\nis faster to execute and easier to read.</p>\n\n<p>You are not handling the case of hitting two bricks at once that \nare side-by-side, top-to-bottom, or touching corners. \nYou only process the second collision detected.\nBut if you fix this, don't forget that the SAME brick might also match\nin multiple directions.</p>\n\n<p>You only have to test for bricks in the 1 or 2 direction(s) that the ball \nis currently heading one each of +/-x (unless direction is 90) and +/-y. </p>\n\n<p>Since the bricks aren't moving, it might be easier to code your own function that tests which bricks you are colliding with, based on where you originally placed them.\nIt would help, then, to have your bricks in a 2D array.\nThen you could deal with the paddle separately and forget about the GLabels.</p>\n\n<p>Either zoning or special casing the brick collisions relieves you of\nthe need to check for (collider instanceof Brick) which is good to avoid.</p>\n\n<p>You don't need to check for the paddle when moving upward.</p>\n\n<h2>Ball class</h2>\n\n<p>Use consts or enums instead of 1 or 2 for xory here and in calls to here.</p>\n\n<pre><code>public void changeDirection(int xory) {\n if (xory == 1) direction -= (direction-270)*2;\n if (xory == 2) direction -= (direction-180)*2;\n}\n</code></pre>\n\n<p>As already commented, these are strange direction expressions.\nThey are technically correct for x-axis reflection and y-axis reflection,\nbut a very roundabout way of expressing:</p>\n\n<pre><code>direction = ((xory==1) ? 180 : 0) - direction;\n</code></pre>\n\n<h2>Brick Class</h2>\n\n<p>NEVER CALLED:</p>\n\n<pre><code>public static int getBricksRemaining() {\n return bricksRemaining;\n}\n</code></pre>\n\n<p>bricksRemaining, decreaseBricks, et. al. should probably be handled by the main Breakout class, so that Brick does not need to depend on Ball.</p>\n\n<h2>Paddle class</h2>\n\n<pre><code>//// These should be static consts.\n double minAngle = 160;\n double maxAngle = 20;\n double angleRange = maxAngle - minAngle;\n\n\n\npublic void checkForPrize(Prize prize, double x, double y) {\n if ((y >= PADDLE_Y) && (y <= PADDLE_Y + PADDLE_HEIGHT) && x > getX() && x < getX() + paddleWidth) {\n prize.pickUp();\n//// Moving the next statement into Prize::pickUp makes the purpose of the Prize \n//// more self-evident within its class and would allow different prizes to have\n//// different effects.\n widen();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T12:27:49.630",
"Id": "12478",
"Score": "0",
"body": "My answer assumed support for negative direction angles -- I haven't checked the ACM doc. @David Wallace gives a much better approach of hard-coding function names rather than hard-coding option flags for the bounce functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T02:08:36.093",
"Id": "7877",
"ParentId": "7865",
"Score": "3"
}
},
{
"body": "<p>Split changeDirection in the Ball class into two methods, and simplify the mathematics in each of them. Something like</p>\n\n<pre><code>public void bounceVertical(){\n direction = 540 - direction;\n}\n\npublic void bounceHorizontal(){\n direction = 360 - direction;\n}\n</code></pre>\n\n<p>plus all the good suggestions made by the other respondents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T12:22:47.627",
"Id": "12477",
"Score": "0",
"body": "To me, 'bounceVertical' sounds like a function that switches the vertical component and leaves the horizontal alone. So an angle of 60 becomes 360 - 60 = 300 (a.k.a. -60), even though this is what happens when bouncing off a _horizontal_ surface. So I'd have switched the 2 names/formulas or called them bounceAgainstHorizontal et. al. Also, `(540 - direction) % 360` would keep angles < 180 in range."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T10:12:45.740",
"Id": "7881",
"ParentId": "7865",
"Score": "2"
}
},
{
"body": "<p>There is a fair amount of redundant code. In addition to things already pointed out, you can add at the very least</p>\n\n<pre><code> direction = rgen.nextDouble(220,320);\n direction = 290;\n</code></pre>\n\n<p>where the first line is redundant, and is the only thing which calls <code>rgen</code>, so that can be removed too.</p>\n\n<pre><code>public void run() { \n while(gameOver != true) {\n pause(20);\n checkCollision(ball);\n ball.move();\n\n if (prize != null) {\n prize.drop();\n if (prize.leftScreen()) remove(prize);\n }\n }\n addMouseListeners();\n} \n</code></pre>\n\n<p>Why add mouse listeners after the game is over?</p>\n\n<p>As a corollary to Josay's comment about <code>if (won == true)</code>, you can rewrite <code>while(gameOver != true)</code> as <code>while(!gameOver)</code>, which is more idiomatic.</p>\n\n<p>A point specifically on game implementation: your timing loop is slightly off. You're going to get a bit under 50fps, but without much consistency. If you want a smooth game you should time how long things take and then take that into account. Using nanosecond timing for accuracy,</p>\n\n<pre><code>while (!gameOver) {\n long start = System.nanoTime();\n\n ... do physics and rendering\n\n long end = System.nanoTime();\n long delay = (1000000000L / DESIRED_FPS) - (end - start);\n if (delay > 0) Thread.sleep(delay / 1000000, (int)(delay % 1000000));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T18:08:58.670",
"Id": "12574",
"Score": "0",
"body": "Thanks! I hadn't even heard of nanosecond timing, nor had I thought of timing the performance. I'll do that in the future :) The direction = 290 was there as a test, but I supposed it's a great lesson on not forgetting test code in my programs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T13:30:01.727",
"Id": "7888",
"ParentId": "7865",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T15:08:35.563",
"Id": "7865",
"Score": "4",
"Tags": [
"java",
"beginner",
"game"
],
"Title": "Building a Breakout game from scratch"
}
|
7865
|
<p>I have the following .net-page. I hope it is ok that it is only an example, describing my problem(s) pretty well.</p>
<pre class="lang-html prettyprint-override"><code><form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="textBox1"></asp:TextBox>
<asp:TextBox runat="server" ID="textBox2"></asp:TextBox>
<asp:Calendar runat="server" ID="calendar1"></asp:Calendar>
</div>
</form>
</code></pre>
<pre class="lang-c# prettyprint-override"><code>public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
textBox1.Text = "Hello";
textBox2.Text = "User";
DateTime yesterday = DateTime.Now.Date.AddDays(-1);
calendar1.SelectedDate = yesterday;
}
}
}
</code></pre>
<p>The <code>Page_Load-routine</code> fills two textboxes with some text and sets the selected date of a calendar control to yesterday.</p>
<p>My questions are:</p>
<ol>
<li>Do I need to or is it recommended to outsource any code into separate routines? I could f.ex. outsource the "calendar part" of the code into a routine <code>SetCalendar</code>, but is it best practice? (It is clear that I would outsource the code if needed on several places in the page class, but this is not the case here.)</li>
<li>Do you think the routine conforms with the Single Responsibility Principle? (A routine should have one and only one responsibility) Is the principle of any importance in a module of this type (event)?</li>
<li>I read that a routine should be as generic as possible. If I had to outsource the "calendar part", would it be good to hand over the date as a parameter, even if I never set the calendar to any other date than yesterday?</li>
</ol>
|
[] |
[
{
"body": "<ul>\n<li>I don't see any reason to refactor that code, at least not in its current state.</li>\n<li>Yes, the routine has a single responsibility at this stage, namely to initialise the fields in the form. If you add another responsibility to the method, you can put the initialisation code in a separate method.</li>\n<li>If you would make a general method to set the calendar date, it would take the calendar reference and the date, so you would just make a method to encapsulate the property setter, which is completely pointless.</li>\n</ul>\n\n<p>You could refactor the code if you choose to see the responsibilities based on separate form fields rather than the form as a whole. However, you should then consider a more object oriented approach rather than just moving the code into separate methods. You can make classes that have the responsibility for initialising, validating and reading a type of form field.</p>\n\n<p>Note: The property calls <code>DateTime.Now.Date</code> already exists as the property <code>DateTime.Today</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T07:54:41.137",
"Id": "7951",
"ParentId": "7866",
"Score": "2"
}
},
{
"body": "<p>I would do something like this:</p>\n\n<pre><code>public partial class WebForm1 : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n if (Page.IsPostBack) return;\n\n InitGreetingMessage();\n InitCalendar();\n } \n\n private void InitGreetingMessage()\n {\n textBox1.Text = \"Hello\";\n textBox2.Text = \"User\";\n }\n\n private void InitCalendar()\n {\n var yesterday = DateTime.Today.AddDays(-1);\n calendar1.SelectedDate = yesterday;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T12:49:50.333",
"Id": "7963",
"ParentId": "7866",
"Score": "1"
}
},
{
"body": "<p>My own approach looks like this and is based on the answers of the users so far.</p>\n\n<pre><code>public class FormInitializer\n{\n public void SetCalendarDate(Calendar c, DateTime date)\n {\n c.SelectedDate = date;\n }\n\n public void SetTextBoxText(TextBox tb, string text)\n {\n Check.NotNullOrEmpty(text, String.Format(\"No text provided for TextBox with ID {0}\", tb.ID.ToString()));\n tb.Text = text;\n }\n}\n\npublic partial class WebForm2 : System.Web.UI.Page\n{\n FormInitializer formInitializer = new FormInitializer();\n\n protected void Page_Load(object sender, EventArgs e)\n { \n if (!Page.IsPostBack)\n {\n formInitializer.SetTextBoxText(textBox1, \"Hello\");\n formInitializer.SetTextBoxText(textBox2, \"User\");\n formInitializer.SetCalendarDate(calendar1, DateTime.Today.AddDays(-1));\n }\n } \n}\n</code></pre>\n\n<p>I like some things about this approach. </p>\n\n<ul>\n<li>It improves readability -> it is much clearer to the reader what the module Page_Load is assigned to do, because I can influence the naming of modules;</li>\n<li>I have fine-grained control about business rules; f.ex. if the user wants to insert text, he can not do so with a String.Empty;</li>\n<li>as the modules are put into a specialized class, this improves code reusability</li>\n</ul>\n\n<p>It is true that the SetCalendarDate module only sets one property, but I can live with it because of the other advantages I get and for the sake of the unity of the concept. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:23:05.980",
"Id": "7964",
"ParentId": "7866",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T15:37:38.230",
"Id": "7866",
"Score": "2",
"Tags": [
"c#",
"html",
".net",
"datetime"
],
"Title": "Page_Load-routine"
}
|
7866
|
<p>Can someone take a look over my bootstrap file and see if you believe it's doing too much or the logic could be better.</p>
<pre><code><?php
/*
* ------------------------------------
* Autoloader for classes/files
* ------------------------------------
*/
function __autoload($class) {
if(file_exists($file = str_replace("\\","/",str_replace("baremvc\\","",$class)).".php")){
require_once $file;
}else{
throw new Exception($file);
}
}
/*
* ------------------------------------
* Get commonly used namespaces
* ------------------------------------
*/
use \baremvc\core\library\exception as ex;
use \baremvc\core\configuration as config;
/*
* ------------------------------------
* Enable session if set in the configuration file
* ------------------------------------
*/
!config::enable_sessions ?: session_start();
/*
* ------------------------------------
* Enable debug information if set in the configuration file
* ------------------------------------
*/
error_reporting(config::debug_level);
ini_set('display_errors', intval(config::debug_enabled));
/*
* ------------------------------------
* Try and load the specified class/method
* ------------------------------------
*/
$router = new \baremvc\core\library\router;
$url_object = $router->parse_request_url(@$_SERVER['REDIRECT_URL']);
try{
$namespace = "\\baremvc\\controllers\\{$url_object->Controller}";
$class = new $namespace;
if(method_exists($class,$url_object->Method)){
if(!empty($url_object->Get)){
call_user_func_array(array($class, $url_object->Method), $url_object->Get);
}else{
call_user_func(array($class, $url_object->Method));
}
}else{
throw new Exception($url_object->Method);
}
}catch(Exception $e){
echo ex::show_404($e->getMessage());
}
</code></pre>
<p><code>parse_request_url</code> takes the requested url (e.g. domain.com/this/is/my/request) and checks to see if a controller exists with that name (can be in directories or file).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T20:02:46.180",
"Id": "12460",
"Score": "1",
"body": "I'd recommend using DIRECTORY_SEPARATOR instead of just assuming that file paths use / as the separator (I'd also recommending aliasing it to something shorter ;) ). Also, I'd replace file_exists with is_file as file_exists would return true if the item exists but isn't a file. Finally, spl_autoload_register is a better choice than __autoload as it will still work even if another autoloader has been defined. I treat __autoload as if it's deprecated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-09T01:16:12.323",
"Id": "29295",
"Score": "0",
"body": "Actually there is no need for DIRECTORY_SEPARATOR as long as one uses the forward slash /. Windows doesn't mind and *nix system already use the forward slash.\n@source http://alanhogan.com/tips/php/directory-separator-not-necessary"
}
] |
[
{
"body": "<p>Generally this is very good code, but I try to be thorough when reviewing so I've listed every minor point that I could think of.</p>\n\n<p>It looks like you write OO code in other places, but you chose to make your bootstrap procedural. Believe it or not <strong>there are benefits to an OO bootsrap!</strong> You can define methods for different parts of the system that you want to bring up. There will always be some procedural code required to call the bootstrap, but it could look more like this:</p>\n\n<pre><code>$bootstrap = new Bootstrap();\n$bootstrap->initializeAutoload();\n$bootstrap->initializeErrorReporting();\n$bootstrap->initializeRouter();\n</code></pre>\n\n<p>As GordonM said, use spl_autoload_register.</p>\n\n<p>You are tightly bound to the config class by your static calls to it. This makes it hard to test your bootstrap. It is understandable in the bootstrap as you have only just brought the autoload up. Keep reading and at the end I'll tell you what I recommend on that.</p>\n\n<p>Personally I don't like the error control operator @. I find it hard to understand what will happen when your server redirect url is not defined. This is very minor, but I would use:</p>\n\n<pre><code>if (isset($_SERVER['REDIRECT_URL']))\n{\n $url_object = $router->parse_request_url($_SERVER['REDIRECT_URL']);\n}\nelse\n{\n $url_object = $router->parse_request_url('');\n\n}\n</code></pre>\n\n<p><code>$namespace</code> and <code>$class</code> are misleading to me, I would rewrite those:</p>\n\n<pre><code>$class_name = '\\baremvc\\controllers\\\\' . $url_object->Controller;\n$controller = new $class_name;\n</code></pre>\n\n<p><code>ex::show_404</code> couples your code tightly to the ex class. This makes it harder for you to test this code as now you require a stub for ex as well as config. You also call new to create a variable controller class, that would make it hard to test.</p>\n\n<p>Other good things that you can do in the bootstrap are: <a href=\"http://php.net/manual/en/function.set-error-handler.php\">set_error_handler</a>, <a href=\"http://php.net/manual/en/function.set-exception-handler.php\">set_exception_handler</a>, <a href=\"http://php.net/manual/en/function.register-shutdown-function.php\">register_shutdown_function</a>.</p>\n\n<p>Now about some of the coupling in this code (to config, ex and the variable controller class). This is an issue if you want to test this code or have it so that it is reusable (You are going to need config and ex if you want to reuse it as it is). You may be happy enough to leave it as it is. That would be a valid choice and one many people would take. Many people should stop reading now (I won't be offended if you also ignore the following).</p>\n\n<p>Now, if you want to get around it a little. All static calls and calls to <code>new</code> bind the calling code to the class that they are calling. Look at the following and answer for yourself how tightly they bind the code to the class:</p>\n\n<pre><code>config::enable_sessions\n$object->enable_sessions\n$configObject = new Config();\n$configObject = $container->getNew('Config');\n</code></pre>\n\n<p>I believe the tightness of coupling is - High (need config class with enable_sessions), Low (need any object with enable_sessions), High (need config class), Low (need an object with getNew).</p>\n\n<p>My recommendation would be that if you are going to bind your Bootstrap to anything it should be a container class, because from that you can get any other object that you need. This means you will only have to stub one class (the container) when you test, which should be simple.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T14:46:34.357",
"Id": "12560",
"Score": "0",
"body": "Thank you VERY much for all of your suggestions - very clear and some good ideas that I will be implementing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T03:29:06.960",
"Id": "12586",
"Score": "0",
"body": "No problems, welcome to code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T13:16:10.113",
"Id": "92248",
"Score": "0",
"body": "Somehow I always thought that bootstrap files were supposed to be procedural, but your suggestion of making it OO looks very good and logical when it comes to OOP. I made an [attempt of my own](http://codereview.stackexchange.com/questions/52543/converting-bootstrap-file-from-procedural-code-to-oop?lq=1), if you're interested to review it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T12:10:18.280",
"Id": "7918",
"ParentId": "7867",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7918",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T15:56:51.480",
"Id": "7867",
"Score": "3",
"Tags": [
"php"
],
"Title": "Bootstrap file - safe and correct"
}
|
7867
|
<p>As my <a href="https://codereview.stackexchange.com/q/7684/15094">parallel mergesort implementation</a> was very memory dependent, I wanted to write a parallel quicksort one. Here it comes:</p>
<pre><code>template<class In>
In partition(In b, In e) {
// create uniform distribuiton for random engine
std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));
// call static random engine to get index of random pivot
tbb::spin_mutex::scoped_lock lock;
lock.acquire(mutex);
auto rand_pivot_index = rand_distribution(rand_engine);
lock.release();
// put pivot to last place in range
std::swap(*(b + rand_pivot_index), *(e - 1));
// save pivot value
auto pivot = *(e - 1);
auto pivotiterator = b;
// sort the range
for(auto it = b; it != e - 1; ++it) {
if(*it < pivot) {
std::swap(*it, *pivotiterator);
++pivotiterator;
}
}
// put pivot to its according position and return position
std::swap(*(pivotiterator), *(e - 1));
return pivotiterator;
}
template<class In>
void quick_sort_parallel(In b, In e) {
if (b != e) {
In m = partition(b, e);
// switch to different sort on worst case or smaller ranges
if(std::distance(b, m) > 500) {
tbb::parallel_invoke([&] { quick_sort_parallel(b, m); },
[&] { quick_sort_parallel(m + 1, e); });
}
else
merge_sort_parallel(b, e); //defined somewhere else, pretty standard
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Code</h2>\n\n<p>I would suggest using RAII for your lock.</p>\n\n<p>Instead of:</p>\n\n<pre><code>std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));\n\n// call static random engine to get index of random pivot\ntbb::spin_mutex::scoped_lock lock;\nlock.acquire(mutex);\nauto rand_pivot_index = rand_distribution(rand_engine);\nlock.release();\n\n// put pivot to last place in range\nstd::swap(*(b + rand_pivot_index), *(e - 1));\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>std::uniform_int_distribution<int> rand_distribution(0, std::distance(b, e - 1));\n\n// call static random engine to get index of random pivot\nint rand_pivot_index;\n{\n tbb::spin_mutex::scoped_lock lock(mutex);\n rand_pivot_index = rand_distribution(rand_engine);\n}\n\n// put pivot to last place in range\nstd::swap(*(b + rand_pivot_index), *(e - 1));\n</code></pre>\n\n<p>This ensures that if rand_distribution throws, the lock is released correctly.</p>\n\n<h2>Algorithm</h2>\n\n<p>Choice of pivot is important in any quick-sort algorithm, and even more so in the parallel case, when you want to garuntee a good distribution of load over cores by avoiding unbalanced recursion.</p>\n\n<p>A good basic strategy is to choose the median of k random elements as your pivot.</p>\n\n<p>Taking this further, using a <a href=\"http://en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithm_-_Median_of_Medians_algorithm\">median of medians algorithm</a> can guarantee your quicksort a O(n log n) running time.</p>\n\n<p>The correct approach and value of k will largely depend on the inputs your function will expect to take (e.g. adapt k based on size on input).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T07:54:23.670",
"Id": "17308",
"Score": "0",
"body": "Of course RAII is the way to manage locks. Today I would do it all a little bit different anyway. Concerning the median of median thing, I don't understand how you can guarantee O(n log n) on an array of only dupes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T09:22:45.557",
"Id": "17310",
"Score": "0",
"body": "If your input can have non distinct elements then you also need your partition step to split into three. 1: (< pivot), 2: (= pivot), 3: (> pivot). Then recurse on 1 and 3. This will get you to O(n log n)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T13:50:13.530",
"Id": "134626",
"Score": "0",
"body": "from where `rand_engine` come from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T17:27:46.513",
"Id": "134691",
"Score": "0",
"body": "@MORTAL from the original question - it's an unimportant implementation detail."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-13T13:12:36.630",
"Id": "10862",
"ParentId": "7870",
"Score": "6"
}
},
{
"body": "<p>Actually, how your pseudo-random number generator is declared does matter, for depending on how it is declared, you may avoid using a lock to generate random numbers. Generating a random number is alreadu an expensive operation, so locking them makes it really expensive.</p>\n\n<p>If you make your pseudo-random number generator <code>thread_local</code>, you don't need to lock anything anymore before generating a random number, it will be inherently thread-safe:</p>\n\n<pre><code>thread_local std::random_device rd;\nthread_local std::mt19937 gen(rd());\n</code></pre>\n\n<p>Moreover, if you also make <code>thread_local</code> your <code>std::uniform_int_distribution</code>, you won't have to update it every time you call <code>partition</code>, but only once in each thread. That said, you can't initialize it with its \"range\" anymore, you have to pass it when you call it:</p>\n\n<pre><code>// Initialize it once\nthread_local std::uniform_int_distribution<int> rand_distribution{};\n\n// Call it\nusing param_type = std::uniform_int_distribution<int>::param_type;\nauto rand_pivot_index = rand_distribution(gen, {0, std::distance(b, e - 1)});\n</code></pre>\n\n<p>If I didn't make any error while writing the code (untested), this should be thread-safe, lock-free and faster than your original solution :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-06T14:00:18.083",
"Id": "232988",
"Score": "0",
"body": "That's a good idea these days. Guess `thread_local` wasn't even supported back in 2012."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-06T14:01:41.977",
"Id": "232990",
"Score": "0",
"body": "@inf Oh yeah, the question is becoming a bit old. I know that GCC and CLang have supported an almost equivalent `__thread` for a while, but I guess it took a bit longer to MSVC :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-06T13:56:28.667",
"Id": "124951",
"ParentId": "7870",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T17:56:45.147",
"Id": "7870",
"Score": "12",
"Tags": [
"c++",
"multithreading",
"c++11",
"quick-sort",
"sorting"
],
"Title": "Parallel Quicksort"
}
|
7870
|
<p>I'm looking for some assistance with a PHP script I'm writing. It creates a table that is then exported to an Excel file for download.</p>
<p>The issues as I see them are as follows:</p>
<p><code>$students</code> contains 559 items and the <code>$classes</code> has 22 items and <code>$attributes</code> has 6 items:</p>
<pre><code><tbody>
<?php foreach($students as $student){
$pupil = Students::retrieveByPK($student['adno']); ?>
<tr>
<td><?php echo strtoupper($pupil->surname); ?></td>
<td><?php echo $pupil->first_name; ?></td>
<td><?php echo $pupil->year_group; ?></td>
<?php foreach($classes as $class){
$shortYear = str_replace('Year ', '',$pupil->year_group);
$slashPos = strpos($class['class_name'],'/');
$className = $shortYear.substr($class['class_name'],1);
$classId = Classes::idFromClassName($className);
foreach($attributes as $attribute){
$attr = AttributeResults::getExportAttribute($pupil->adno, $classId, $attribute['attribute_id']); ?>
<td align="center"><?php echo $attr[0]['attribute_value']; ?></td>
<?php } ?>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</code></pre>
<p>I'm essentially running the <code>AttributeResults::getExportAttribute</code> method in the region of 74000 times. Is there a better way of bringing this data back?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T09:25:57.030",
"Id": "12481",
"Score": "0",
"body": "Depends, where is all that data coming from? Is each of your static class calls a database query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T09:33:04.403",
"Id": "12482",
"Score": "0",
"body": "Yes at the moment they are"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T09:34:24.717",
"Id": "12483",
"Score": "2",
"body": "Then you should use one big SQL query to get the data instead of 74000 tiny ones."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T09:37:28.817",
"Id": "12484",
"Score": "0",
"body": "I think I still need to run for each of the $classes as the next level of info ($attributes) comes specifically from the id's I get in the $classes, so essentially you would suggest running 22 larger queries?"
}
] |
[
{
"body": "<p>I think what your better off doing is to have a join on your database call, so that the class data and student data is returned in one object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T09:27:47.373",
"Id": "7884",
"ParentId": "7883",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "7884",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T09:23:42.947",
"Id": "7883",
"Score": "3",
"Tags": [
"php",
"mysql"
],
"Title": "Creating a table for use in Excel"
}
|
7883
|
<p>I am trying to get my dictionary to iterate seven times after the <code>dateTime</code> is found. I want to iterate through the next week of objects in my dictionary <code>pagesInRange</code>. I figured out how to do it, but I am sure this is not good code. I am wondering if someone could point me in the direction of what I can do to improve this code. </p>
<p>I could not figure out how to iterate through the range I want, so instead I iterate through the entire dictionary and have a bunch of it statements to find the values I am looking for. Here is my code. I know I can use a <code>switch</code> statement to improve the code, but I wondering if there is a way given the first value to iterate over the next seven values.</p>
<pre><code>Console.WriteLine("Please enter a date in the following formate MM/DD/YYYY");
string date = Console.ReadLine();
DateTime dt = Convert.ToDateTime(date);
DateTime end1 = dt.AddDays(1);
DateTime end2 = dt.AddDays(2);
DateTime end3 = dt.AddDays(3);
DateTime end4 = dt.AddDays(4);
DateTime end5 = dt.AddDays(5);
DateTime end6 = dt.AddDays(6);
int i = 0;
foreach (var pair in pagesInRange)
{
if (pair.Key.ToString("d")==date)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
} else if (pair.Key == end1)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
}
else if (pair.Key == end2)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
}
else if (pair.Key == end3)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
}
else if (pair.Key == end4)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
}
else if (pair.Key == end5)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
}
else if (pair.Key == end6)
{
Console.WriteLine(pair.Key.ToString("d") + " " + pair.Value);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T04:56:52.513",
"Id": "12485",
"Score": "0",
"body": "`Dictionary<TKey, TValue>` is not appropriate for sorted searches. Something like the .NET 4 `SortedDictionary` would likely be a better fit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:02:53.413",
"Id": "12487",
"Score": "0",
"body": "pagesInRange as something I forgot to delete. The dictionary I am using is sorted by date."
}
] |
[
{
"body": "<p>You might want to consider using a switch statement since you have so many else if cases. The switch statement I believe can be slightly faster due to the way the compiler uses the test conditions. Though you would have to declare end1 through n as const.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:07:19.527",
"Id": "12488",
"Score": "0",
"body": "Thanks, I am wondering if there is anything I do for a range of consecutive values. Can I do something were I get my dictionary to start at this value and iterate over the next seven consecutive values"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:10:50.297",
"Id": "12489",
"Score": "0",
"body": "Perhaps use the switch to figure out how to increment the date and then add to the date the user inputs?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T04:59:03.650",
"Id": "7886",
"ParentId": "7885",
"Score": "2"
}
},
{
"body": "<p>If I understand your intent:</p>\n\n<pre><code>Console.WriteLine(\"Please enter a date in the following formate MM/DD/YYYY\");\nstring date = Console.ReadLine();\nDateTime startRange = Convert.ToDateTime(date);\nDateTime endRange = startRange.AddDays(6);\n\nforeach (var pair in pagesInRange)\n if (pair.Key >= startRange && pair.Key <= endRange)\n Console.WriteLine(pair.Key.ToString(\"d\") + \" \" + pair.Value);\n</code></pre>\n\n<p>This does not take advantage of the fact that the dictionary is sorted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:16:56.543",
"Id": "12490",
"Score": "0",
"body": "Thanks, I could not think of that one line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:39:40.377",
"Id": "12491",
"Score": "0",
"body": "@Aaron, please see revision, should have been `&&`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T05:11:54.707",
"Id": "7887",
"ParentId": "7885",
"Score": "5"
}
},
{
"body": "<p>Using LINQ you could query like this:</p>\n\n<pre><code>SortedDictionary<DateTime, Page> dict = new SortedDictionary<DateTime, Page>();\n\n...\n\nvar query = dict\n .SkipWhile(pair => pair.Key < startDate)\n .TakeWhile(pair => pair.Key <= endDate);\n\nforeach (var pair in query) {\n Console.WriteLine(\"{0} {1}\", pair.Key, pair.Value);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T20:36:16.350",
"Id": "7938",
"ParentId": "7885",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7887",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T04:52:50.143",
"Id": "7885",
"Score": "3",
"Tags": [
"c#",
"homework"
],
"Title": "Iterating through a dictionary in C#"
}
|
7885
|
<p>I have about 6 of these, but I'm only posting two. Essentially I have a bunch of options with a "yes" or "no" radio button. If "no" is selected, I want a form to popup.</p>
<pre><code>$('#Option1').live('change', function() {
if ($('input[name=Option1]:checked').val() == "False") {
$('#formDiv').show();
} else {
$('#formDiv').hide();
}
});
$('#Option2').live('change', function() {
if ($('input[name=Option2]:checked').val() == "False") {
$('#formDiv').show();
} else {
$('#formDiv').hide();
}
});
</code></pre>
<p>How can I make this more efficient, or even consolidate it? Or is having a function for each pair of radio buttons necessary?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:35:52.230",
"Id": "12494",
"Score": "1",
"body": "This belongs on codereview, but when you post it there, please include your HTML. Only by seeing the repeated parts of the HTML can people offer the best way to do the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:40:42.730",
"Id": "12495",
"Score": "0",
"body": "Also, you should be switching to [`$.on()`](http://api.jquery.com/on/) and/or [`$.delegate()`](http://api.jquery.com/delegate/), as [`$.live()`](http://api.jquery.com/live/) is deprecated."
}
] |
[
{
"body": "<p>This should work:</p>\n\n<pre><code>$('#Option1, #Option2').live('change', function() {\n if ($('input[name=' + $(this).attr('id') + ']:checked').val() == 'False') {\n $('#formDiv').show();\n else {\n $('#formDiv').hide();\n }\n\n });\n</code></pre>\n\n<p>Or, if whatever has the id <code>option1</code> is the same page element as the input with the name <code>option1</code>, you could do:</p>\n\n<pre><code>$('#Option1, #Option2').live('change', function() {\n if ($(this).val() == 'False')\n $('#formDiv').show();\n else {\n $('#formDiv').hide();\n }\n\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T14:29:04.557",
"Id": "12497",
"Score": "0",
"body": "`.show` and `.hide` could be replaced to a `.toggle($(this).val()=='False')` statement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:35:07.530",
"Id": "7891",
"ParentId": "7890",
"Score": "3"
}
},
{
"body": "<p>I'd recommend setting up a listener on all your radio buttons then using '<a href=\"http://remysharp.com/2007/04/12/jquerys-this-demystified/\" rel=\"nofollow\">this</a>' to reference the radio button that is selected. If you are writing six identical functions, you're not adhering to DRY.</p>\n\n<p>Without the HTML to back this up, it's a little tricky to see exactly what's going on. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:35:59.260",
"Id": "7892",
"ParentId": "7890",
"Score": "0"
}
},
{
"body": "<p>You could bind the selection change to a class instead of the id, this way you will have a generic function valid for all the select elements.\nSomething like : </p>\n\n<pre><code>$('.mySelect').live('change', function() { \n var selectedOptionValue = $(this).val();\n if ($('input[name='+selectedOptionValue+']:checked').val() == \"False\") {\n $('#formDiv').show();\n }\n else {\n $('#formDiv').hide();\n }\n\n\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:39:40.270",
"Id": "7893",
"ParentId": "7890",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7891",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:30:22.933",
"Id": "7890",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"form",
"event-handling"
],
"Title": "Options with a \"yes\" or \"no\" radio button"
}
|
7890
|
<p>So i got the grip on the basic MVC patterns in java using Observer / Observable method. Now in interest of keeping it clean and readable i would like some pointers before i move on regarding how to well organize my View as this is where my Classes get most filled up. We been told in school to keep file size per class bellow 20kb to keep it readable and later easier maintainable.</p>
<p>Here is my view:</p>
<pre><code>package view;
import model.*;
import helper.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Observable;
import java.util.Observer;
import net.miginfocom.swing.MigLayout;
public class View extends JFrame implements Observer
{
private Model model;
private JPanel left = new JPanel(new MigLayout());
private JPanel center = new JPanel(new MigLayout());
private JPanel right = new JPanel(new MigLayout());
private void setConstraints()
{
this.left.setMinimumSize(new Dimension(252, 540));
this.left.setMaximumSize(new Dimension(252, 37500));
this.center.setMinimumSize(new Dimension(298, 540));
this.right.setMinimumSize(new Dimension(250, 540));
this.right.setMaximumSize(new Dimension(250, 37500));
}
//Left panel contents
private Towers box = new Towers();
private Modules tree = new Modules();
private JPanel setupLeft()
{
this.left.add(this.box, "growx, pushx, wrap");
this.left.add(new JScrollPane(this.tree), "grow, push");
return this.left;
}
//Center panel contents
private Browser browser = new Browser();
private JPanel setupCenter()
{
this.center.add(new JScrollPane(this.browser), "grow, push");
return this.center;
}
//Right panel contents
private JLabel tower = new JLabel("No tower selected.");
private JLabel cap = new JLabel("Capacitor");
private JLabel cpu = new JLabel("CPU");
private JLabel shield = new JLabel("0");
private JLabel armor = new JLabel("0");
private JLabel em = new JLabel("0.0");
private JLabel th = new JLabel("0.0");
private JLabel kn = new JLabel("0.0");
private JLabel ex = new JLabel("0.0");
private JPanel setupRight()
{
this.right.add(this.tower, "span, wrap");
this.right.add(this.cap, "span, wrap");
this.right.add(this.cpu, "span, wrap");
this.right.add(this.shield, "span, wrap");
this.right.add(this.armor, "span, wrap");
this.right.add(this.em, "span, wrap");
this.right.add(this.th, "span, wrap");
this.right.add(this.kn, "span, wrap");
this.right.add(this.ex, "span, wrap");
return this.right;
}
public View(Model ui_model)
{
model = ui_model;
this.setTitle("MVC Experiment 6");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setMinimumSize(new Dimension(800, 600));
this.setLayout(new MigLayout());
this.setConstraints();
this.add(this.setupLeft(), "dock west");
this.add(this.setupCenter(), "dock center");
this.add(this.setupRight(), "dock east");
}
//Left panel contents - Listeners and methods for addressing JComponents
public void xTowersBrowser(ActionListener event)
{
this.box.addActionListener(event);
}
public void xModulesBrowser(MouseListener event)
{
this.tree.addMouseListener(event);
}
public Towers getTowersBrowser()
{
return this.box;
}
public Modules getModulesBrowser()
{
return this.tree;
}
//Left panel - END
//Center panel - components :: listeners and methods
public void xBrowser(MouseListener event)
{
this.browser.addMouseListener(event);
}
public Browser getBrowser()
{
return this.browser;
}
//Center panel - END
public void update(Observable o, Object arg)
{
}
}
</code></pre>
<p>Any suggestions on what to separate in new classes or how to minimize the code are helpful. This is just a cut out of my main View class there are still a lot of JComponents missing so it will get more messy.</p>
|
[] |
[
{
"body": "<p>Just a quick note: according to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-141855.html#3043\" rel=\"nofollow\">Code Conventions for the Java Programming Language, File Organization</a> instance variables should be placed before constructors and methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T21:57:18.977",
"Id": "7900",
"ParentId": "7896",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T21:03:25.273",
"Id": "7896",
"Score": "2",
"Tags": [
"java",
"mvc",
"swing"
],
"Title": "How can i clean and organize up my View (MVC) better"
}
|
7896
|
<p>This is a question I have in regards to my implementation of the MVC design paradigm that I came up with. The MVC type I am using is where everything must go through the controller. No communication happens between the model and the View. This is what I saw apple doing when I played with some iPhone stuff so I wanted to work through it, even though I had to put my iPhone stuff on hold.</p>
<p>So the issue I am having is I am seeing a lot of what I see as dirty, unnecessary looking code due to me trying to maintain this paradigm and because of this I have a feeling I am going about this quite incorrectly. So I thought I would seek some advice from you guys, who have much more experience in this sort of thing.</p>
<p>Here is an example of code that just gets handed from class to class just so that it passes through the controller:</p>
<p>I have a ViewController JFrame that holds all of the panels for my GUI. It also contains the <code>next</code> and <code>previous</code> buttons required for navigating through them.</p>
<p>So.. This is going to look scary but it is just a LOT of repeated code, I am going to put these in order of how they are called.</p>
<p>NextButton is pressed: </p>
<p><strong>(ViewManager.java):</strong></p>
<pre><code>private void nextButtonActionPerformed(java.awt.event.ActionEvent evt)
{
controller.nextPanelRequested();
}
</code></pre>
<p><strong>(Controller.java):</strong></p>
<pre><code>public void nextPanelRequested()
{
model.readPanel(); // Only following this chain
...
}
</code></pre>
<p><strong>(Model.java):</strong></p>
<pre><code>public void readPanel()
{
...
//LOGIC TO DETERMINE WHICH PANEL WE ARE ON, WHICH DETERMINES WHICH 'FETCH' TO USE:
case PANELX:
controller.fetchPanelInfo(panelList[PANELX]);
break;
....
}
</code></pre>
<p><strong>(Controller.java [Again]):</strong></p>
<pre><code>public void fetchPanelInfo(Panel currentPanel)
{
...
else if (currentPanel.equals(Panel.PANELX))
{
viewManager.getPANELXInfo();
}
}
</code></pre>
<p><strong>(ViewManager.java [Again]):</strong></p>
<pre><code>public void getPANELXInfo()
{
// This calls down to a specific JPanel and gets it to collect input and send.
panelX.collectAndSendPanelInfo();
}
</code></pre>
<p><strong>(PanelX.java):</strong></p>
<pre><code>public void collectAndSendPanelInfo()
{
viewManager.sendPanelXData(double1, double2, double3, ..., double 15);
}
</code></pre>
<p><strong>(ViewManager.java [Again x2]):</strong></p>
<pre><code>public void sentPanelXData(double1 double1In, ..., double15 double 15In)
{
controller.sendPanelXData(double1In, ..., double15In);
}
</code></pre>
<p><strong>(Controller.java [Again x2]):</strong></p>
<pre><code>public void sentPanelXData(double1 double1In, ..., double15 double 15In)
{
model.receivePanelXData(double1In, ..., double15In);
}
</code></pre>
<p><strong>(Model.java [Again x2]):</strong></p>
<pre><code>public void receivePanelXData(double1 double1In, ..., double15 double 15In)
{
instanceVariable = new AppropriateObject(double1In, ..., double2In);
}
</code></pre>
<p>Okay... I hope I don't get too much flak for the length of this question, I rewrote everything to simplify it and hide my specific code.</p>
<p>I want you to see exactly what I am seeing, and this redundancy is what is making me uneasy.</p>
<p>*Sigh*. It works. The issue is that each panel has a different number, and different set of types of inputs, so I cannot simply make one method that could transport them all. So I have about 8 calls that appear in EVERY one of those 4 classes. </p>
<p>If there is some solution to my disgusting implementation of MVC I could delete around 30 methods and make future programmer's lives about 30x easier.. tracing through that line of code is terrible. And I CODED IT. :(</p>
<p><strong>So Question:</strong> Should my model be asking the view directly for the panel info rather than going through the controller?</p>
<p><strong>And:</strong> Should the model be transmitting its collected info in a better manner that goes directly to the model?</p>
<p>In the past I have seen a similar construct transmit the user input with beans, I was uncomfortable with this approach because they needed them for transmitting over a network, and I am just on one screen with one application. </p>
<p>All the handoffs I am doing here are not expensive.. They don't even factor in when I profile the performance of each method. I know the post is insane, but I would have killed for a post like this with an answer when I was programming this beast. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T21:21:34.213",
"Id": "12523",
"Score": "0",
"body": "If you are flexible, switch to Griffon. It handles the boilerplate of MVC for you and lets you just worry about the meat of the models, views, and controllers. While it's built in Groovy, it works just find for straight Java as well (much uglier, but that's just the nature of Java desktop development)"
}
] |
[
{
"body": "<p>If you are sending everything through the controller, it's not exactly MVC. </p>\n\n<p>The beauty of MVC is that most of your views \"listen\" to changes in the model, which means the controller doesn't need to \"update\" the views for regular data changes. That limits the controller's updating of views to cases where the view needs to be laid out again (such as changing screens, layout, etc).</p>\n\n<p>Models that model changing elements (like clocks) don't even involve the controller. The model calls a (typically) private \"changed(...)\" method which signals all of the listening views. The views then fetch the data they are interested in (might be different depending on the view), and the view then invalidates itself (to schedule a redraw of itself).</p>\n\n<p>One clock \"view\" might be a digital clock, another might be a changing non-editable text label, a third a \"solar\" representation of the sun / moon in different phases (dawn, morning, noon, etc).</p>\n\n<p>Your solution could probably be fixed pretty easily. Initialize the views with a reference to their viewed model and cut out the controller \"updating\" the view for any data-related stuff. Normally the controller will still have to update the view for certain items, mostly for presentation (which view is visible, etc). Have the assignment of a model to a view cause the view to \"unlisten\" to the old model and \"listen\" to the new model. In the model, have any data change notify all the \"listeners\" of that model object's data change. The \"listeners\" then need to re-pull whatever data they might be interested in.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T15:49:47.317",
"Id": "12564",
"Score": "0",
"body": "Okay, I've cleaned up my code quite a significant bit by handing each of my Panels their own copy of the 1 model that exists. Now when they are called upon to collect & send their info they simply call model.receivedPanelXInfo(...) and that eliminated a lot of redundant hand-offs. I also made my controller implement ActionListener and now it handles next/previous button presses itself; which allowed me to keep a lot of control flow still emanating from the controller which I like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T15:52:55.067",
"Id": "12565",
"Score": "0",
"body": "One question I have - And I feel like the way I implemented this is still avoiding doing what you are suggesting - is when you say \"listen\" and \"unlisten\" for different classes.. How? With what methodology? Like I am doing; say a view calling a model's method? Or is their some higher intelligence implementation where you can actually set a model to listen to a view through some kind of set-up.. I know I've seen notify() kicking around the posts on this I read but I don't know if that works this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T17:37:14.893",
"Id": "12570",
"Score": "1",
"body": "@Alex, Typically the view \"knows\" how to display a particular model, and the model knows nothing of how the information is displayed. The model \"knows\" which views are interested at any given time, and after the model changes, it \"notify\"s the each of the currently interested views that the model changed. Then each view queries the model(s) it is working with to determine if it needs to recalculate or change the display data, and if so, it schedules itself for being redrawn. In such a setup (which is only part of MVC) the model might call \"notify\" on the views to notify them of change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T17:41:24.840",
"Id": "12571",
"Score": "1",
"body": "@Alex, under a setup as described above, the controller is critical for building / maintaining the model (at initialization and as a side-effect of the input), displaying the appropriate view(s), and telling the views what models they are attached to. This means that if you have to \"customer\" model classes, and a few \"views\" that display certain aspects of a \"customer\", a button click to \"go to the next customer\" might be handled in the controller as simply as telling all the appropriate views that they have a new (different) customer \"model\": like `nameAgeSexView.setModel(selectedCustomer)`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T21:50:12.180",
"Id": "7902",
"ParentId": "7901",
"Score": "4"
}
},
{
"body": "<p>Regarding the implementation of MVC my co-workers and myself are against the view accessing to the model and should therefore always go through a controller. Still, if you feel it like having a direct link from view to model you're welcome to do it.</p>\n\n<p>Regarding your 30 methods you should add another layer on top of these and use polymorphism. Create a abstract class where your panels will inherit from or you could implement an interface.</p>\n\n<p>Hope this helped.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T22:44:05.860",
"Id": "12528",
"Score": "2",
"body": "MVC is not an opinion. It is a technique. Your technique might work well for you, but that hardly makes it MVC if the descriptions of the two techniques are not compatible. Your views don't listen to your model. You might have a good GUI framework, but because your views don't listen to your model, it isn't MVC."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T22:03:19.020",
"Id": "7904",
"ParentId": "7901",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7902",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T21:12:53.583",
"Id": "7901",
"Score": "3",
"Tags": [
"java",
"mvc"
],
"Title": "Java: Worries about my implementation of MVC in a GUI Application"
}
|
7901
|
<p>I have just 'wrote' a linked list implementation of Disjoint Sets. This is the changed version of <a href="https://stackoverflow.com/a/4522532/675100">Bob Tian's implememnation</a>. Can you take a look and tell me if there is something missing ? For instance memory leaks while destroying <code>nodes</code>. And please judge it also in performance matter.</p>
<p>I would like to change the <code>long NodeAddress[9999] = {0};</code> to something better but:
this implementation is used for <a href="http://en.wikipedia.org/wiki/Connected-component_labeling" rel="nofollow noreferrer">Connected-component labeling</a> so every time I examine the pixel that needs to be added to labels array I add it. But in the end I do not know how many of them will be there and I need some way to access them (in case i would need to use them later on - for instance <code>union</code> it with another label)</p>
<pre><code>#include <iostream>
using namespace std;
long NodeAddress[9999] = {0};
int n=0;
class ListSet {
private:
struct Item;
struct node {
int val;
node *next;
Item *itemPtr;
};
struct Item {
node *hd, *tl;
};
public:
ListSet() { }
long makeset(int a);
long find (long a);
void Union (long s1, long s2);
};
long ListSet::makeset (int a) {
Item *newSet = new Item;
newSet->hd = new node;
newSet->tl = newSet->hd;
node *shd = newSet->hd;
NodeAddress[a] = (long) shd;
shd->val = a;
shd->itemPtr = newSet;
shd->next = 0;
return (long) newSet;
}
long ListSet::find (long a) {
node *ptr = (node*)a;
return (long)(ptr->itemPtr);
}
void ListSet::Union (long s1, long s2) {
node *ptr1 = (node*)s1;
node *ptr2 = (node*)s2;
Item *set2 = ptr1->itemPtr;
node *cur = set2->hd;
Item *set1 = ptr2->itemPtr;
while (cur != 0) {
cur->itemPtr = set1;
cur = cur->next;
}
//join the tail of the set to head of the input set
(set1->tl)->next = set2->hd;
set1->tl = set2->tl;
delete set2;
}
int main () {
ListSet a;
long s1, s2, s3, s4;
s1 = a.makeset(13);
s2 = a.makeset(25);
s3 = a.makeset(45);
s4 = a.makeset(65);
cout<<s1<<' '<<s2<<' '<<s3<<' '<<s4<<endl;
cout<<"a.find(NodeAddress[65]): "<<a.find(NodeAddress[65]) <<endl;
cout<<"a.find(NodeAddress[45]): "<<a.find(NodeAddress[45]) <<endl;
cout<<"a.Union(NodeAddress[65], NodeAddress[45]) "<<endl;
a.Union(NodeAddress[65], NodeAddress[45]);
cout<<"a.find(NodeAddress[65]): "<<a.find(NodeAddress[65]) <<endl;
cout<<"a.find(NodeAddress[45]): "<<a.find(NodeAddress[45]) <<endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T02:25:48.710",
"Id": "12536",
"Score": "1",
"body": "Your code does not show any nodes being deleted. Assuming that you do not want to leak them all like this, do you intend to delete them and then continue to have calls to find and union operate correctly on remaining nodes, or do you only need to delete all the nodes after the last call to find or union?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T02:57:03.293",
"Id": "12538",
"Score": "0",
"body": "@PaulMartel I want to continue using them. This will be just a part of bigger function so I do not know if wrapping it up in a class is worth it but on the other hand I will have a memory leak anyway. Can you suggest a way how this can be implemented ? (code snippet)"
}
] |
[
{
"body": "<p>The first thing that meets my eye is all this C-style casting, and in particular you are casting long to pointers and back. Why is the code not typesafe? If you want a pointer use a pointer. If you want a number use a number.</p>\n\n<p>Your node class. Well it's \"struct\" but that just means the members are all public. It doesn't mean you can't put the logic within the class itself - how they are created, how they manage their data, etc.</p>\n\n<p>Actually there were other things that caught my eye first like using namespace std; Get rid of that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T11:35:37.667",
"Id": "7917",
"ParentId": "7905",
"Score": "2"
}
},
{
"body": "<pre><code>#include <assert.h> // for assert\n#include <string.h> // for memset\n\n#include <iostream>\n\nusing namespace std;\n</code></pre>\n\n<p>// OMIT these as not very useful. Anyway, don't needlessly expose globals.</p>\n\n<pre><code>long NodeAddress[9999] = {0};\nint n=0;\n</code></pre>\n\n<p>/* I've kept the class names for now, for the sake of recognition, but\n they've each got different problems.</p>\n\n<p>ListSet does a poor job of describing the class' purpose.\nSince its purpose is to generate, find, and merge disjoint sets, \ncall it something like DisjointSetSource.</p>\n\n<p>Item is too generic and not very descriptive of the class' function. It represents a disjoint set, but to reserve the name DisjointSet for its exported opaque equivalent, just call it Set, or since it's represented as a linked list of member nodes, maybe SetNodeList or SetMemberList. </p>\n\n<p>node is also very generic, but it's a little more apt. Also, it's name should be capitalized by convention and for consistency. So, Node is OK, but better might be Member or since it's main features are to refer to its parent list and successor, call it ListMember. \n*/</p>\n\n<pre><code>class ListSet {\nprivate:\n typedef int ValueType;\n struct Item;\n</code></pre>\n\n<p>/* There's a non-trivial smattering of node and item processing cluttering up the ListMember methods. They really want to be full-fledged classes with a constructor, (possibly) destructor, and (possibly) mutators. Item needs write access to node::next and ListMember needs write access to itemPtr, so I'd keep the node members public. */</p>\n\n<pre><code> struct node {\n ValueType val;\n node *next;\n Item *itemPtr;\n</code></pre>\n\n<p>// So, add:</p>\n\n<pre><code> node (const ValueType& a);\n ~node ();\n };\n\n struct Item {\n</code></pre>\n\n<p>// So, add:</p>\n\n<pre><code> Item(node *shd) : hd(shd), tl(shd) {}\n void append(const Item*);\n // returns head node as \"sign of life\"\n node* remove(node* old);\n private:\n node *hd, *tl;\n };\n</code></pre>\n\n<p>/* Avoid exposing nodeAddress, especially as a global. It SHOULD use std::vec for dynamic growth or std::map if values are sparse. Wrap this in accessors to stay flexible, especially WRT ValueType, opening the door for (re)templatizing as in the originally posted code. */</p>\n\n<pre><code>private:\n node* nodeAddress[9999];\n\npublic:\n\n void setNodeAddress(const ValueType& a, node* shd) {\n nodeAddress[a] = shd;\n }\n\n node* getNodeAddress(const ValueType& a) {\n return nodeAddress[a];\n }\n\n // removeAll requires or maybe IS a third form of nodeAddress accessor\n</code></pre>\n\n<p>/* Why does a ListSet object ever need to be created?\n When the original implementation used the global NodeAddress as its state, \n all functions could be static and no ListSet instance ever created.\n This would also be true if NodeAddress was a static member.</p>\n\n<p>Yet, it was easy enough to improve on the design by making nodeAddress a normal data member. This provides a useful purpose for multiple ListSet instances.<br>\n Each managing its own disjoint sets, completely independently.\n All the more reason to pull NodeAddress out of the API, where it is just noise. See main.\n*/</p>\n\n<pre><code> ListSet() {\n // zero out nodeAddress in some type appropriate way\n memset(nodeAddress, 0, sizeof(nodeAddress));\n }\n\n ~ListSet() {\n removeAll();\n }\n</code></pre>\n\n<p>/* \"long\" is too general a type to use for \"handles\" like the return type, here. Better to make up a unique fictitious type:\n*/</p>\n\n<pre><code> class DisjointSet;\n\n DisjointSet* exportSet(Item* result) { return (DisjointSet*) result; }\n Item* importSet(DisjointSet* input) { return (Item*) input; }\n</code></pre>\n\n<p>/* Use camelCase or under_scoring to makemultiwordnamesreadable. */</p>\n\n<pre><code> DisjointSet* makeSet(const ValueType& a);\n DisjointSet* find (const ValueType& a);\n void remove(const ValueType& a);\n void removeAll();\n</code></pre>\n\n<p>// Use suffix word rather than breaking lowercase convention to get around reserved words</p>\n\n<pre><code> void unionSets (const ValueType& a1, const ValueType& a2) {\n DisjointSet* s1 = find(a1);\n DisjointSet* s2 = find(a2);\n if (s1 && s2) {\n (void) unionSets(s1, s2);\n }\n // else error?\n }\n\n DisjointSet* unionSets (DisjointSet* s1, DisjointSet* s2);\n};\n\nListSet::DisjointSet* ListSet::makeSet (const ValueType& a) {\n assert(!getNodeAddress(a));\n node *shd = new node(a);\n Item *newSet = new Item(shd);\n setNodeAddress(a, shd);\n shd->itemPtr = newSet;\n return exportSet(newSet);\n}\n\nListSet::DisjointSet* ListSet::find (const ValueType& a) {\n node* ptr = getNodeAddress(a);\n if (ptr)\n return exportSet(ptr->itemPtr);\n // else error?\n return 0;\n}\n</code></pre>\n\n<p>/* This used to be needlessly confusing with lines like:</p>\n\n<pre><code>Item *set2 = ptr1->itemPtr;\nItem *set1 = ptr2->itemPtr;\n</code></pre>\n\n<p>I'm really still not sure the revision, below maintains the original intent, because of the set1/set2 naming confusion, but it does what the old code did.</p>\n\n<p>Aside from avoiding such confused naming, use of an Item method\nmakes this code much easier to read. */</p>\n\n<pre><code>ListSet::DisjointSet* ListSet::unionSets (DisjointSet* s1, DisjointSet* s2) {\n Item *set1 = importSet(s1);\n Item *set2 = importSet(s2);\n\n set2->append(set1);\n delete set1;\n}\n\nvoid ListSet::Item::append (const Item* other) {\n //join the tail of the set to head of the other set\n tl->next = other->hd;\n tl = other->tl;\n for (node* cur = other->hd; cur; cur = cur->next) {\n cur->itemPtr = this;\n }\n}\n\nListSet::node::node (const ValueType& a) : val(a), next(0), itemPtr(0) \n{ }\n</code></pre>\n\n<p>/* Here's mutator code that allows values to be incrementally dropped as operations continue. \nNote that after \"union(1,2); union(2,3); remove(2);\", \n1 and 3 are still considered to be in the same set. \n*/</p>\n\n<pre><code>// Returns hd as a sign of life -- null if empty/dead.\nListSet::node* ListSet::Item::remove(node* old) {\n if (old == hd) {\n if (old == tl) {\n assert(! old->next);\n return 0;\n }\n assert(old->next);\n hd = old->next;\n } else {\n node* prev;\n for (prev = hd; prev->next != old; prev = prev->next) {\n assert(prev->next);\n ;\n }\n if (old == tl) {\n assert(! old->next);\n //\n tl = prev;\n prev->next = 0;\n } else {\n assert(old->next);\n prev->next = old->next;\n }\n }\n return hd;\n}\n\nListSet::node::~node() {\n if (itemPtr) {\n if (! itemPtr->remove(this)) {\n // Don't leak an empty set.\n delete itemPtr;\n }\n }\n}\n\nvoid ListSet::remove(const ValueType& a) {\n node* ptr = getNodeAddress(a);\n if (ptr) {\n setNodeAddress(a, 0);\n delete ptr;\n }\n // else error?\n}\n\nvoid ListSet::removeAll() {\n assert( 0 ); // TBD\n // This just needs to iterate over nodeAddress\n // and call delete on each remaining node*.\n}\n</code></pre>\n\n<p>/* There's no reason to expose anything other than the original elements\n (raw numbers), the ListSet and the DisjointSets it returned. \n So don't clutter the interface with Item*s disguised as longs, \n node*s disguised (indistinguishably) as longs, or NodeAddress.\n A cleaner, safer API results:</p>\n\n<pre><code>int main () {\n\n ListSet a;\n ListSet::DisjointSet *s1, *s2, *s3, *s4;\n s1 = a.makeSet(13); \n s2 = a.makeSet(25); \n s3 = a.makeSet(45); \n s4 = a.makeSet(65);\n\n /* If this really needs to work, either define a stream io operator \n for our DisjointSet type or let it get dumped as a hex value. */\n cout<<s1<<' '<<s2<<' '<<s3<<' '<<s4 <<endl;\n\n cout<<\"a.find(65): \"<<a.find(65) <<endl;\n cout<<\"a.find(45): \"<<a.find(45) <<endl;\n cout<<\"a.Union(65, 45) \"<<endl;\n\n // The next line is a safer way to express a.unionSets(s3, s4);\n // which may crash if s3 or s4 had been previously merged/deleted, \n // but it's also a little slower.\n a.unionSets(65, 45); \n\n cout<<\"a.find(65): \"<<a.find(65) <<endl;\n cout<<\"a.find(45): \"<<a.find(45) <<endl;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T16:17:06.063",
"Id": "12934",
"Score": "0",
"body": "Thanks A LOT for your answer you have helped a lot but IMHO you are a bit mixing the names too much. Can you post a comment or edit your answer so that it is more clear in some places like e.g. I do not understand what `DisjointSet` serves for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T17:43:46.850",
"Id": "12940",
"Score": "0",
"body": "I have removed the top-level `typedef ListSet::DisjointSet* DisjointSet;` so that there is only one \"definition\" of DisjointSet, the one within ListSet. So now main has to explicitly use `ListSet::DisjointSet *` in its decl's -- not sure that's an improvement. Maybe `typedef ListSet::DisjointSet* DisjointSetHandle;` would be clearer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T18:10:34.327",
"Id": "12942",
"Score": "0",
"body": "The remaining DisjointSet is purposely not a true definition but just a declaration. It's intended as an opaque handle so callers can do useful things like `s1 == s2`, `cout<<s1`, `a.unionSets(s1,s2)` but not make mistakes like `3*s1+s2` which would be legal using `long`. DisjointSet* is (secretly) just Item*. But Items are a (hidden) implementation detail. In the real world, when I put ListSet in a header, I'd remove the nesting of Node and Item. That leaves a clean ListSet API passing `DisjointSet*s` and raw (int) values. Node and Item can then hide completely in ListSet.cpp."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T03:09:56.977",
"Id": "7945",
"ParentId": "7905",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "7945",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T22:48:02.123",
"Id": "7905",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"linked-list",
"union-find"
],
"Title": "Disjoint set implementation as linked list"
}
|
7905
|
<p>I have the following code that checks for three different properties. Unfortunately each call can throw up to four exceptions that I all have to catch. Can I some how make the code more readable by reducing the amount of try/catch?</p>
<pre><code>public void retrieveSourceCode() {
try {
fileName = RestServices.getInstance().getClassName(getSourceCodeURI());
} catch (ClientProtocolException e) {
fileName = "not available";
e.printStackTrace();
} catch (IOException e) {
fileName = "not available";
e.printStackTrace();
} catch (RestServicesException e) {
fileName = "not available";
e.printStackTrace();
}
if (!(fileName.endsWith(".jar") || fileName.endsWith(".svn-base"))) {
try {
sourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getSourceCodeURI());
} catch (ClientProtocolException e) {
sourceCode = "not available";
e.printStackTrace();
} catch (IOException e) {
sourceCode = "not available";
e.printStackTrace();
} catch (RestServicesException e) {
sourceCode = "not available";
e.printStackTrace();
}
if (before == null) {
beforeSourceCode = "no before source code available";
} else {
try {
beforeSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getBeforeVersionURI());
} catch (ClientProtocolException e) {
beforeSourceCode = "no before source code available";
e.printStackTrace();
} catch (IOException e) {
beforeSourceCode = "no before source code available";
e.printStackTrace();
} catch (RestServicesException e) {
beforeSourceCode = "no before source code available";
e.printStackTrace();
}
}
if (after == null) {
afterSourceCode = "no after source code available";
} else {
try {
afterSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getAfterVersionURI());
} catch (ClientProtocolException e) {
afterSourceCode = "no after source code available";
e.printStackTrace();
} catch (IOException e) {
afterSourceCode = "no after source code available";
e.printStackTrace();
} catch (RestServicesException e) {
afterSourceCode = "no after source code available";
e.printStackTrace();
}
}
}
getChangeSet().addAffectedFile(getFileName());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-09T13:44:45.517",
"Id": "17110",
"Score": "1",
"body": "Someone should of pointed out that ClientProtocolException is an IOException making catching ClientProtocolException pointless in this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-09T15:31:43.097",
"Id": "17115",
"Score": "0",
"body": "You may not have control over it, but needing to check \"before\" and \"after\" for null is a little smelly to me."
}
] |
[
{
"body": "<p>If you upgrade to Java 7, you can use the new Multi-catch syntax. You could change the first block to:</p>\n\n<pre><code> try {\n fileName = RestServices.getInstance().getClassName(getSourceCodeURI()); \n } catch (ClientProtocolException | IOException | RestServicesException e) {\n fileName = \"not available\";\n e.printStackTrace();\n }\n</code></pre>\n\n<p>Essentially if there are many exceptions you catch and handle in the same way, you can use multi-catch</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T17:49:20.667",
"Id": "12846",
"Score": "3",
"body": "That's rather nifty. C# needs this. A lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T09:39:38.523",
"Id": "7911",
"ParentId": "7909",
"Score": "18"
}
},
{
"body": "<p>These unhandled exceptions <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a> very bad. Storing error messages in the place of data also is not a good sign (like <code>fileName = \"not available\"</code>).</p>\n\n<p>Anyway, some notes:</p>\n\n<ol>\n<li><p>You could extract out a </p>\n\n<pre><code>RestServices restServices = RestServices.getInstance();\n</code></pre>\n\n<p>variable.</p></li>\n<li><p>You should create constants from repeating Strings, like <code>\"not available\"</code>, <code>\"no before source code available\"</code> etc.</p></li>\n<li><p>I'd extract out <code>getFileName</code> method for the first <code>try-catch</code> block, a <code>getSourceCode</code> for the second, and so on.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T18:42:30.140",
"Id": "12575",
"Score": "2",
"body": "Agreed - What's the point of catching an exception if you don't deal with it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T10:50:26.990",
"Id": "7915",
"ParentId": "7909",
"Score": "12"
}
},
{
"body": "<p>Considering that you do literally the exact same thing regardless of the type of exception, you can cut down the catch statements by catching type <code>Exception</code> instead of a specific subclass:</p>\n\n<pre><code>public void retrieveSourceCode() {\n try {\n fileName = RestServices.getInstance().getClassName(getSourceCodeURI()); \n } catch (Exception e) {\n fileName = \"not available\";\n e.printStackTrace();\n }\n\n if (!(fileName.endsWith(\".jar\") || fileName.endsWith(\".svn-base\"))) {\n try {\n sourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getSourceCodeURI());\n } catch (Exception e) {\n sourceCode = \"not available\";\n e.printStackTrace();\n } \n\n if (before == null) {\n beforeSourceCode = \"no before source code available\";\n } else {\n try {\n beforeSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getBeforeVersionURI());\n } catch (Exception e) {\n beforeSourceCode = \"no before source code available\";\n e.printStackTrace();\n } \n }\n\n if (after == null) {\n afterSourceCode = \"no after source code available\";\n } else {\n try {\n afterSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getAfterVersionURI());\n } catch (Exception e) {\n afterSourceCode = \"no after source code available\";\n e.printStackTrace();\n } \n }\n }\n getChangeSet().addAffectedFile(getFileName());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T11:35:50.243",
"Id": "13286",
"Score": "2",
"body": "But keep in mind that this will also catch unchecked RuntimeExceptions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T04:12:27.043",
"Id": "7948",
"ParentId": "7909",
"Score": "3"
}
},
{
"body": "<p>A <code>try</code> and <code>catch</code> block should be in their own method so as not to interrupt logic in another method.</p>\n\n<pre><code>private void getClassName(T URI, String error){\n T2 className;\n try{\n className = RestServices.getInstance().getClassName(URI);\n } catch (Exception e){\n className = error;\n e.printStackTrace();\n } finally{\n return className;\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>private void sendGetRequestJsonTextToString(T URI, String error){\n T2 reply;\n try {\n reply = RestServices.getInstance().sendGetRequestJsonTextToString(URI));\n } catch(Exception e){\n reply = error;\n e.printStackTrace();\n } finally{\n return reply;\n }\n}\n</code></pre>\n\n<p>This method now has no <code>try-catch</code> block interrupting the logic. Also, <a href=\"http://c2.com/cgi/wiki?GuardClause\" rel=\"nofollow\">guard clause</a> can be used in place of nested <code>if</code>s.</p>\n\n<pre><code>public void retrieveSourceCode(){\n String error;\n error = \"not available\";\n filename = getClassName(getSourceCodeURI(), error);\n\n // this conditional can be extracted to a method, giving more readability\n // say, if(!isSourcecode(filename))\n if(fileName.endsWith(\".jar\") || !fileName.endsWith(\".svn-base\"))){\n return;\n }\n\n error = \"not available\";\n sourceCode = sendGetRequestJsonTextToString(getSourceCodeURI(), error);\n\n\n error = \"no before source code available\";\n if(before == null){\n beforeSourceCode = error;\n } else {\n beforeSourceCode = sendGetRequestJsonTextToString(getBeforeVersionURI(), error);\n }\n\n\n error = \"no after source code available\";\n if(after == null){\n afterSourceCode = error;\n } else {\n afterSourceCode = sendGetRequestJsonTextToString(getAfterVersionURI(), error);\n }\n\n\n getChangeSet().addAffectedFile(getFileName());\n}\n</code></pre>\n\n<p>This still has some <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smells</a> (as mentioned in another answer), but it does what the questions asking for: to simplify the <code>try-catch</code> block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-09T16:04:08.813",
"Id": "17118",
"Score": "0",
"body": "You've declared `getClassName` and `sendGetRequestJsonTextToString` as `void`, but then `return` values from them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T10:02:48.127",
"Id": "8491",
"ParentId": "7909",
"Score": "5"
}
},
{
"body": "<p>Java 7 syntax wins.</p>\n\n<p>For Java < 7, catching the <code>Exception</code> base class works but it's unfortunate to stop unrelated exceptions from propagating. Here's a workaround to consider:</p>\n\n<pre><code>String getFileName() {\n try {\n return RestServices.getInstance().getClassName(getSourceCodeURI());\n } catch (ClientProtocolException e) {\n } catch (IOException e) {\n } catch (RestServicesException) {\n }\n return \"not available\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T14:06:56.440",
"Id": "20875",
"Score": "0",
"body": "Note that you'll lose the stack trace."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T18:32:20.430",
"Id": "12899",
"ParentId": "7909",
"Score": "1"
}
},
{
"body": "<p>You could use an <code>if</code> statement inside your <code>catch</code>. It could get ugly if you're trying to catch a lot of different exception types but it should be fine for a handful. Sorry for any errors in my syntax. It's been a while since I've used Java.</p>\n\n<pre><code>try {\n fileName = RestServices.getInstance().getClassName(getSourceCodeURI()); \n}catch (Exception e){\n if (e instanceof ClientProtocolException || e instanceof IOException || e instanceof RestServicesException) {\n fileName = \"not available\";\n e.printStackTrace();\n }else{\n throw e;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T15:35:01.007",
"Id": "74459",
"Score": "0",
"body": "Welcome to Code Review! I'm glad you post an answer and hope you'll stay around. I'm not a big fan of this approach, this should get the job done, but is a lot of \"boiler\" plate IMHO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T16:31:02.537",
"Id": "74466",
"Score": "0",
"body": "I mostly agree, hence why I'd only use it with a small number of exceptions. Otherwise multiple catch blocks is probably the way to go, although it looks like the latest Java version has solved this problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T14:18:43.913",
"Id": "43140",
"ParentId": "7909",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T08:12:00.550",
"Id": "7909",
"Score": "11",
"Tags": [
"java",
"error-handling"
],
"Title": "Retrieving multiple versions of source code for a file"
}
|
7909
|
<p>I use the DefaultCodeFormatter of the core Java package to prettify my code. Unfortunately I want to look my code very different from the default settings. That why, I have to explicitly define a lot of values:</p>
<pre><code>public static String makeSourceCodeLookingMoreSexy(String source) {
Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE, DefaultCodeFormatterConstants.INDENT_ON_COLUMN));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_DEFAULT));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_DEFAULT));
options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_DEFAULT));
final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
final TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, System.getProperty("line.separator"));
IDocument document = new Document(source);
try {
edit.apply(document);
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return document.get();
}
</code></pre>
<p>That are not even all options that I want to set. Actually it is way more, maybe about 50. As you can imagine the code gets very long. So is there a better way to do this than I'm actually doing it?</p>
|
[] |
[
{
"body": "<p>I'd extract it out to a helper method:</p>\n\n<pre><code>private static Map<String, String> getOptionsMap() {\n final Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();\n\n options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);\n options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_6);\n options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);\n\n // TODO: rename the variable\n final String aligment0 = DefaultCodeFormatterConstants.createAlignmentValue(true,\n DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE, \n DefaultCodeFormatterConstants.INDENT_ON_COLUMN);\n options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS, aligment0);\n\n // TODO: rename the variable\n final String aligment1 = DefaultCodeFormatterConstants.createAlignmentValue(false, \n DefaultCodeFormatterConstants.WRAP_NO_SPLIT,\n DefaultCodeFormatterConstants.INDENT_DEFAULT);\n options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, aligment1);\n options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION, aligment1);\n options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION, aligment1);\n return Collections.unmodifiableMap(options);\n}\n</code></pre>\n\n<p>Maybe you can split it up to two or more methods. The <code>aligment0</code> and <code>aligment1</code> variables should be renamed to a proper name. Note that you can reuse the <code>Map</code>, since <code>Collections.unmodifiableMap()</code> ensures that it cannot be changed by clients.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T09:43:22.670",
"Id": "7913",
"ParentId": "7910",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T08:15:22.153",
"Id": "7910",
"Score": "3",
"Tags": [
"java",
"formatting"
],
"Title": "Passing many configuration options to Java code formatter"
}
|
7910
|
<p>I am relatively new to C and would like some feedback on a function that I have written, if it adheres to C standards or if there are some other things which I could have done better/differently.</p>
<pre><code>/* Function to find DB matches and store them in a glycopeptide structure */
/* Written by Bas Jansen, 18-01-2012, Leiden University Medical Center */
glycopeptide*
databasereader (float precursor, float massaccuracy, MYSQL *connection) {
float prec_lower = precursor - massaccuracy; /* define lower border by substracting mass accuracy from given precursor */
float prec_higher = precursor + massaccuracy; /* define upper border by adding mass accuracy to given precursor */
glycopeptide* glycan; /* define a pointer to the structure glycopeptide as glycan */
char querystring[MAX_SIZE_LARGE]; /* define a variable to contain the SQL query */
sprintf(querystring,"select precursor.mzValue as 'M/z Value', glycoPeptide.description as 'Description', spectrum.spectrum as 'Data Type', binaryDataArray.arrayData as 'Data (encoded)', binaryDataArray.arrayLength as 'Array length', binaryDataArray.compLength as 'Compressed length' from glycoPeptide, spectrum, binaryDataArray, run, precursor where run.glycoPeptide = glycoPeptide.id AND spectrum.run = run.id AND precursor.run = run.id AND binaryDataArray.spectrum = spectrum.id AND precursor.mzValue between %f and %f ORDER BY glycoPeptide.description, spectrum.spectrum", prec_lower, prec_higher); /* convert the border values into strings and put them in the SQL query */
if (mysql_query (connection, querystring) != 0) { /* checks if query gives any results */
printf("Made it to the query part, but no hits\n"); /* give a message if the query gave no hits */
} else { /* if query gives hits do... */
glycan = malloc(sizeof(glycopeptide)*1000); /* allocate memory for the glycan structure */
int teller = 0; /* implements a counter to count and walk through the daughters of glycan */
MYSQL_RES *result_set; /* defines a result_set structure */
result_set = mysql_store_result (connection); /* stores result from sql query in result_set structure */
if (result_set == NULL) { /* checks if result from the query got stored */
printf("mysql_store_result() failed"); /* print error if no result was stored */
} else { /* if query was successful... */
MYSQL_ROW row; /* defines a row structure */
int i; /* defines a int to use in a for loop */
while ((row = mysql_fetch_row (result_set)) != NULL) { /* as long as there are rows in result set do... */
for (i = 0; i < mysql_num_fields (result_set); i++) { /* for each field in result row */
if (i == 0) { /* if field is 'M/z Value' do... */
float buffer = atof(row[i]); /* convert string in to the float buffer variable */
(glycan+teller)->prec = buffer; /* assign the float buffer variable to the structure */
} /* closes the if field is (M/z Value) do... */
if (i == 1) { /* if field is 'Description' do... */
(glycan+teller)->desc = malloc(sizeof(char)*MAX_SIZE_SMALL); /* allocate memory for the description */
(glycan+teller)->desc = row[i]; /* assign the string in field[i] to the structure */
} /* closes the if field is 'Description' do... */
if (i == 2) { /* if field is 'Data Type' do... */
(glycan+teller)->datatype = malloc(sizeof(char)*MAX_SIZE_TINY); /* allocate memory for the datatype */
(glycan+teller)->datatype = row[i]; /* assign the string in field[i] to the structure */
} /* closes the if field is 'Data Type' do... */
if (i == 3) { /* if field is 'Data (encoded)' do... */
(glycan+teller)->binary = malloc(sizeof(char)*MAX_SIZE_LARGE); /* allocate memory for the binary data */
(glycan+teller)->binary = row[i]; /* assign the string in field[i] to the structure */
} /* closes the if field is 'Data (encoded) do... */
if (i == 4) { /* if field is 'Array length' do... */
int buffer = atoi(row[i]); /* convert string in to the int buffer variable */
(glycan+teller)->array_length = buffer; /* assign the int buffer variable to the structure */
} /* closes the if field is 'Array length' do... */
if (i == 5) { /* if field is 'Compressed length' do... */
int buffer = atoi(row[i]); /* convert string in to the int buffer variable */
(glycan+teller)->compressed_length = buffer; /* assign the int buffer variable to the structure */
} /* closes the if field is 'Compressed length' do... */
} /* closes for loop */
teller++; /* increments counter that counts and walks through the daughters of glycan */
} /* closes while loop */
/* Freeing memory */
return(glycan); /* returns the structure back to main */
for (i = 0; i < teller; i++) { /* for loop that walks through all daughters of glycan */
free((glycan+i)->desc); /* free the memory allocated to description of this particular daughter */
free((glycan+i)->datatype); /* free the memory allocated to datatype of this particular daughter */
free((glycan+i)->binary); /* free the memory allocated to binary of this particular daughter */
}
for (i = teller; i > 0; i--) { /* for loop that walks (backwards) through all daughters of glycan */
(glycan+i)->desc=NULL; /* sets the pointer to description to NULL of this particular daughter */
(glycan+i)->datatype=NULL; /* sets the pointer to datatype to NULL of this particular daughter */
(glycan+i)->binary=NULL; /* sets the pointer to binary to NULL of this particular daughter */
}
free(glycan); /* free the memory allocated for glycan */
glycan = NULL; /* sets the pointer to glycan to NULL */
} /* closes the else, belonging to result_set */
} /* closes the else, belonging to mysql_query */
} /* closes the function */
</code></pre>
<p>Here are my <code>struct</code>s and <code>#define</code>s:</p>
<pre><code>#define MAX_SIZE_TINY 128
#define MAX_SIZE_SMALL 512
#define MAX_SIZE_LARGE 1024
typedef struct {
float prec;
char* desc;
char* datatype;
char* binary;
int array_length;
int compressed_length;
} glycopeptide;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T16:11:46.220",
"Id": "12566",
"Score": "2",
"body": "That is absolutely the worst commenting I have **ever** seen. Comment your code to describe **what** you are trying to achieve. The code describes **how** you don't need to echo the how in comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:53:05.997",
"Id": "12617",
"Score": "0",
"body": "It was a bit redundant yeah, just threw in comments on what every line did while I was coding it and didn't think about 'tidying' up once it was 'done'."
}
] |
[
{
"body": "<p>I'm not too familiar with C, so just some notes.</p>\n\n<ol>\n<li><p>Comments like these are redundant, so they are unnecessary:</p>\n\n<pre><code>MYSQL_ROW row; /* defines a row structure */\nfree(glycan); /* free the memory allocated for glycan */\n</code></pre></li>\n<li><p>Statements after <code>return</code> look unreachable:</p>\n\n<pre><code>return (glycan);\nfor (i = 0; i < teller; i++) {\n</code></pre>\n\n<p>So, this loop never runs.</p>\n\n<p>On the other hand freeing resources at the end of the function looks unnecessary, since the function returns with <code>glycan</code> and clients probably need this data.</p></li>\n<li><p>Instead of the else branches like</p>\n\n<pre><code>if (mysql_query (connection, querystring) != 0) {\n printf(\"Made it to the query part, but no hits\\n\");\n} else { \n glycan = malloc(sizeof(glycopeptide)*1000);\n ...\n</code></pre>\n\n<p>I'd return immediately:</p>\n\n<pre><code>if (mysql_query (connection, querystring) != 0) {\n printf(\"Made it to the query part, but no hits\\n\");\n return; // a return value maybe neccesary\n}\nglycan = malloc(sizeof(glycopeptide) * 1000);\n</code></pre>\n\n<p>It helps <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">flatten the code</a>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T10:33:29.433",
"Id": "12549",
"Score": "1",
"body": "@palascint I will go over your points in order; 1. Valid point, I will remove some of the comments and will have to decide on which are really required, 2. Valid point again, didn't think about it when I wrote this, 3. That is a neat trick, I am definitely going to use that :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T10:23:47.113",
"Id": "7914",
"ParentId": "7912",
"Score": "3"
}
},
{
"body": "<h3>Comments:</h3>\n\n<ul>\n<li>Terrible comments (can not express that enough)</li>\n<li><p>In C one of the hard points is cordinating ownership of dynamically allocated memory.</p>\n\n<ul>\n<li>You should have a big comment at the top of the function explaining that the returned pointer is dynamically allocated with detailed instructions on how to make sure it is de-allocated. </li>\n<li>I would avoid asking the user to call free() as this binds your interface to providing memory allocated from malloc/calloc/realloc and this may be stiffling in future versions. A better alternative is to provide a free function that when passed the result of this function correctly tides up the pointer (and all sub pointers).</li>\n</ul></li>\n<li><p>If the function is expected to return a value you must return a value.</p>\n\n<ul>\n<li>It looks like there are several ways to fall out of your code without returning anything. This is undefined behavior, you must return something even if it is NULL.</li>\n</ul></li>\n<li>Your error messages are not accurate:\n<ul>\n<li><code>printf(\"Made it to the query part, but no hits\\n\");</code><br>\nHere your query failed. This does not mean there are not hits it means there was some form of failure in the query.</li>\n</ul></li>\n<li>Useless statement: <code>glycan = NULL;</code> (glycan goes out of scope the next statement).</li>\n<li>This works <code>(glycan+teller)->STUFF</code> but is a little hard to read.\n<ul>\n<li>I find the form <code>glycan[teller].STUFF</code> is a little more intuitive to read. </li>\n</ul></li>\n<li><p>It helps when you line up the code consistently:</p>\n\n<pre><code> } /* closes for loop */\n teller++; /* increments counter that counts and walks through the daughters of glycan */\n } /* closes while loop */\n</code></pre>\n\n<ul>\n<li>The Line <code>teller++</code> should be indented another 4 character.<br>\nThis is making the code hard to read.</li>\n</ul></li>\n<li>Your code assumes that number of rows read from the DB is exactly dividable by 6.\n<ul>\n<li>If this does not hold then you free statements are freeing pointers that have not been allocated (and have not previously set to NULL).</li>\n</ul></li>\n<li><p>In this section:</p>\n\n<pre><code> for (i = 0; i < teller; i++) { /* for loop that walks through all daughters of glycan */\n free((glycan+i)->desc); /* free the memory allocated to description of this particular daughter */\n free((glycan+i)->datatype); /* free the memory allocated to datatype of this particular daughter */\n free((glycan+i)->binary); /* free the memory allocated to binary of this particular daughter */\n }\n for (i = teller; i > 0; i--) { /* for loop that walks (backwards) through all daughters of glycan */\n (glycan+i)->desc=NULL; /* sets the pointer to description to NULL of this particular daughter */\n (glycan+i)->datatype=NULL; /* sets the pointer to datatype to NULL of this particular daughter */\n (glycan+i)->binary=NULL; /* sets the pointer to binary to NULL of this particular daughter */\n }\n</code></pre>\n\n<ul>\n<li>There is no point in doing two loops.<br>\nYou should have initialized all the pointers to NULL on allocation. (calloc may help)<br>\nThen in the above code you should be setting only the used pointers back to NULL (as the others are already NULL). Here you have the worst of all worlds, you are resetting the unused ones and freeing but not resetting the used ones. Its a good job this code is unreachable.</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:14:38.413",
"Id": "12613",
"Score": "0",
"body": "Thank you for the feedback, some questions however. I was re-writing this snippet during the evening and am now 'abusing' the memory allocated by the mysql API (so not allocating any memory myself) which means that all memory is freed by doing a single free(struct) line in the main. I guess the free_mem function will have like 3 lines of code, I do see the point you are making of not making the user think about memory allocation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:14:43.827",
"Id": "12614",
"Score": "0",
"body": "I have corrected the error messages because of your feedback as well. I am just unsure why you state that 'Your code assumes that number of rows read from the DB is exactly dividable by 6', I have been testing the function on a query that retrieves 3 rows and one that retrieves 11 rows without any problems? I thought that the second for loop (setting pointers to NULL) is something that should make dangling pointer problems less likely as the pointers are still pointing to a (now free'd) memory block, am I right in thinking that you are saying there is a better way to do this?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T16:34:58.337",
"Id": "7932",
"ParentId": "7912",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7914",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T09:41:30.673",
"Id": "7912",
"Score": "6",
"Tags": [
"beginner",
"c",
"mysql",
"bioinformatics"
],
"Title": "Finding database matches and storing them in a glycopeptide structure"
}
|
7912
|
<p>I created a function that compares two hashes and returns a report on whether the subtraction of their values is negative or not.</p>
<p>The problem comes down to having a cost hash for a building and a current resources hash like:</p>
<pre><code>cost = {:wood => 300, :stone => 200, :gold => 100}
reqs = {:wood => 200, :stone => 220, :gold => 90}
</code></pre>
<p>This one should return a report hash like:</p>
<pre><code>report = { :has_resources => false, :has_wood => true, :has_stone => false, :has_gold => true }
</code></pre>
<p>Now, in the cost hash, <code>:gold</code>, <code>:stone</code> or <code>:wood</code> can be nil, i.e. non-existent. </p>
<p>My first attempt is definitely not the Ruby way and I don't like the function. It works, but I want to find a way to write it in a better manner:</p>
<pre><code>def has_resources?(cost)
report = { :has_resources => true, :has_wood => true, :has_stone => true, :has_gold => true }
if not cost[:wood].nil?
if self.wood < cost[:wood]
report[:has_wood] = false
report[:has_resources] = false
end
end
if not cost[:stone].nil?
if self.stone < cost[:stone]
report[:has_stone] = false
report[:has_resources] = false
end
end
if not cost[:gold].nil?
if self.gold < cost[:gold]
report[:has_gold] = false
report[:has_resources] = false
end
end
end
</code></pre>
<p>How should I rewrite this? I don't like the <code>.nil?</code> checks here, but I have to include them since the <code><</code> operator does not work on nil objects. I also don't like having so many <code>if</code>s.</p>
|
[] |
[
{
"body": "<p>Here's a version that is a bit more <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">DRY</a>. It also makes use of ruby's default value for hashes, and I threw in a dummy class in order to make the tests actually run.</p>\n\n<p>This could probably be done even better, but one thing you really should try to achieve when writing ruby code (or any code at all, for that matter) is to try not to repeat yourself too much. That's where DRY come in.</p>\n\n<pre><code>class CostCalculation\n attr_accessor :wood, :stone, :gold\n\n def initialize(reqs)\n self.wood = reqs[:wood] || 0\n self.stone = reqs[:stone] || 0\n self.gold = reqs[:gold] || 0\n end \n\n def has_resources?(cost)\n report = Hash.new(true)\n cost.default = 0 \n\n attributes.each do |key, value|\n report[:\"has_#{key}\"] = cost[key] <= value\n end \n\n if report.values.include?(false)\n report[:has_resources] = false\n end \n\n report\n end \n\n def attributes\n { wood: self.wood, stone: self.stone, gold: self.gold } \n end \nend\n</code></pre>\n\n<p>...and here are some specs for it as well:</p>\n\n<pre><code>describe CostCalculation do\n it \"has enough resources for something that's free\" do\n report = CostCalculation.new({}).has_resources?({})\n report[:has_resources].should == true\n end \n\n %w[wood stone gold].each do |resource| \n it \"does not have enough resources if #{resource} is missing\" do\n cost = {resource.to_sym => 1}\n report = CostCalculation.new({wood: 0, stone: 0, gold: 0}).has_resources?(cost)\n\n report[:has_resources].should == false\n report[:\"has_#{resource}\"].should == false\n end \n end \nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T00:47:43.680",
"Id": "12553",
"Score": "1",
"body": "Although, one thing that I'd really like to do with this, is that since the method name ends with a question mark, I'd want it to return a boolean, so that it returns false in the cases where the current version returns something with `report[:has_resources] == false`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T01:03:51.710",
"Id": "12554",
"Score": "0",
"body": "The only thing I don't like about this is `report = Hash.new(true)`, I'd prefer `report[:pancakes]` to be `nil` (which would hopefully cause something to explode and fall over) rather than `true`. Altering `cost` might be an issue as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T02:49:30.433",
"Id": "12555",
"Score": "0",
"body": "yeah, the question mark is a remainder actually, from my previous version, which return true or false. The new one should return a hash :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T10:12:57.447",
"Id": "12556",
"Score": "1",
"body": "Hm... Now that you mention it, @muistooshort, I actually agree with you. The part of modifying `cost` can be fixed by just cloning `cost` and modifying the clone. You could also do something similar with `report`, or just do `report.default = nil` before returning it, and also make sure to always set a value for `report[:has_resources]`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T00:45:14.363",
"Id": "7923",
"ParentId": "7920",
"Score": "6"
}
},
{
"body": "<p>First of all, you're repeating yourself through copy'n'paste code \nso that should be converted to some sort of iteration. Then bust \nit up into little pieces that can be nicely named and you'll have\nsomething compact and readable:</p>\n\n<pre><code>MATERIALS = [ :wood, :stone, :gold ]\n\ndef resource_availability(costs)\n MATERIALS.reject(&have_enough_for(costs)).\n each_with_object(base_report, &not_enough) \nend\n\nprivate\n\ndef have_enough_for(costs)\n ->(material) { costs[material].nil? || costs[material] < self.send(material) }\nend\n\ndef has_sym(material)\n ('has_' + material.to_s).to_sym\nend\n\ndef base_report\n MATERIALS.each_with_object({ :has_resources => true }) { |m, h| h[has_sym(m)] = true }\nend\n\ndef not_enough\n ->(material, report) do\n report[has_sym(material)] = false\n report[:has_resources ] = false\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T01:01:00.293",
"Id": "7924",
"ParentId": "7920",
"Score": "1"
}
},
{
"body": "<p>Here is my version: Tested Working under ruby 1.8.7-p334</p>\n\n<p>Assume inputs are:</p>\n\n<pre><code>cost = {:wood => 300, :stone => 200, :gold => 100}\nreqs = {:wood => 200, :stone => 220, :gold => 90}\n</code></pre>\n\n<p>and in the cost hash,:gold, :stone or :wood can be nil.</p>\n\n<pre><code>def has_resources?(cost,reqs)\n result = cost.merge(reqs) { |key, cst, rqs| cst.nil?||(cst - rqs) > 0 ? true : false }\n result[:has_resources] = !result.has_value?(false)\n return result\nend\n</code></pre>\n\n<p>It will return the result of:</p>\n\n<pre><code>{ :has_resources => false, :wood => true, :stone => false, :gold => true } \n</code></pre>\n\n<p>If you really want the result to have \"has_wood\",\"has_stone\",\"has_gold\" as key, you may need to modify the code to rename the key in result Hash. But I think it's not needed.</p>\n\n<p>In case people ask why merge method? here is the <a href=\"http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge\" rel=\"nofollow\">Ruby Hash Merge documentation</a>\nWhen compare two hash with same key, I think \"merge\" method is the simple way.</p>\n\n<p>Thanks</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T01:24:32.733",
"Id": "7925",
"ParentId": "7920",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T23:45:35.257",
"Id": "7920",
"Score": "5",
"Tags": [
"ruby"
],
"Title": "How do I compare two integer value hashes?"
}
|
7920
|
<p>I have a collection (Child Collection) on which I am performing some operation to make another collection (Parent Collection). But that I do in a dirty <code>foreach</code> loop. I want to do it in an elegant way.</p>
<pre><code>GroupInfo grpInfo;
List<GroupInfo> lstGroupInfo = new List<GroupInfo>();
foreach (AddressInfo addressInfo in subDetails)
{
if (lstGroupInfo.Where(u => u.Addres1 == addressInfo.Address1).Count() > 0)
{
grpInfo = lstGroupInfo.Where(u => u.Addres1 == addressInfo.Address1).SingleOrDefault();
if (addressInfo.Rural)
grpInfo.Rural = true;
else if (addressInfo.Urban)
grpInfo.Urban = true;
grpInfo.SubDetails.Add(addressInfo);
}
else
{
grpInfo = new GroupInfo();
grpInfo.AddressID = addressInfo.AddressID;
grpInfo.LocationID = addressInfo.NamedLocationID;
if (addressInfo.Rural)
grpInfo.Rural = true;
else if (addressInfo.Urban)
grpInfo.Urban = true;
}
}
</code></pre>
<p><code>GroupInfo</code> class is:</p>
<pre><code>public class GroupInfo
{
public string Address1
{
get;
set;
}
public int AddressID
{
get;
set;
}
public int? LocationID
{
get;
set;
}
}
</code></pre>
<p>I want to do it in LINQ lambda way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T14:11:21.460",
"Id": "12559",
"Score": "0",
"body": "You need to tidy up the code sample, it's very difficult to figure out what some of the variables are.\n\nFor example, what type is lstGroupInfo? or tripAddressInfo?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T04:06:21.043",
"Id": "12587",
"Score": "0",
"body": "Thanks for analyzing the query, i have updated the code. Kindly tell me if i could help me more."
}
] |
[
{
"body": "<p>There's quite a lot of logic in there, so I doubt you will get there completely by using LINQ, and, more importantly, if it would actually be <strong><em>more</em></strong> elegant.</p>\n\n<p>I would rewrite as follows, and be done with it:</p>\n\n<pre><code> foreach (AddressInfo addressInfo in subDetails)\n {\n grpInfo = lstGroupInfo.SingleOrDefault(x => x.Address1 == addressInfo.Address1);\n if (grpInfo != null)\n {\n grpInfo.Rural = addressInfo.Rural;\n grpInfo.Urban = addressInfo.Urban;\n grpInfo.SubDetails.Add(addressInfo);\n }\n else\n {\n grpInfo = new GroupInfo();\n grpInfo.AddressID = addressInfo.AddressID;\n grpInfo.LocationID = addressInfo.NamedLocationID;\n grpInfo.Rural = addressInfo.Rural;\n grpInfo.Urban = addressInfo.Urban;\n }\n }\n</code></pre>\n\n<p>In addition, it seems to me that <code>Rural</code> and <code>Urban</code> are mutually exclusive, so why not define an enumeration that contains those two (or more) values, or declare one boolean property <code>IsRural</code> to indicate if it's \"Rural\", and if not, it's urban. That would bring the code down to:</p>\n\n<pre><code> foreach (AddressInfo addressInfo in subDetails)\n {\n grpInfo = lstGroupInfo.SingleOrDefault(x => x.Address1 == addressInfo.Address1);\n if (grpInfo != null)\n {\n grpInfo.IsRural = addressInfo.IsRural;\n grpInfo.SubDetails.Add(addressInfo);\n }\n else\n {\n grpInfo = new GroupInfo();\n grpInfo.AddressID = addressInfo.AddressID;\n grpInfo.LocationID = addressInfo.NamedLocationID;\n grpInfo.IsRural = addressInfo.IsRural;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:12:02.457",
"Id": "12595",
"Score": "0",
"body": "Shouldnt the first if-clause state if(grpInfo != null) ? It will now generate an NullReferenceException if grpInfo actually is null. Good refactoring though, makes it much more readable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:46:26.097",
"Id": "12598",
"Score": "0",
"body": "Thanks Willem, but this is not exactly as expected, if you look at my more carefully, I intentially write IF condition on IsRural and IsUrban property, in your scenario it will be true or false as per the last addressInfo, but i want it to remains true if it is set to true once through out the process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:55:36.213",
"Id": "12599",
"Score": "0",
"body": "@Manvinder: MaybeI'm missing something, but I think yours will also reflect the state of the last AddressInfo in the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:14:43.673",
"Id": "12604",
"Score": "0",
"body": "yes but it will update only if the value is true and not false"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:20:08.170",
"Id": "12605",
"Score": "0",
"body": "@Manvinder: Ah yes, I see. Then you'd need to bring those checks back in. It also leads to the second part of my answer: Why is there a Rural and Urban property? They seem mutually exclusive (can they both be false btw?). An enumeration or one boolean property seems more appropriate. But I don't have the design, nor the requirements, so I can't really tell."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T07:52:19.670",
"Id": "7950",
"ParentId": "7926",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T13:19:27.173",
"Id": "7926",
"Score": "2",
"Tags": [
"c#",
"linq"
],
"Title": "Improve grouping in LINQ"
}
|
7926
|
<p>I'm building some code with an inheritance heirarchy, and I want to validate the resulting instances. At present I have a method in the base class can override to return a list of the problems (see the code).</p>
<p>My problem here is that this works, provided the inheriting classes remember to get the base results first, before returning their own. It works, but I'm not sure it's the best design?</p>
<pre><code>using System;
using System.Linq;
using System.Collections.Generic;
namespace Query
{
/// <summary>
/// Root class with mehtod
/// </summary>
public abstract class baseClass
{
/// <summary>
/// Is the object valid?
/// </summary>
/// <returns></returns>
public bool IsValid()
{
return (!GetValidationIssues().Any());
}
/// <summary>
/// Return list of validation issues
/// </summary>
/// <returns></returns>
public virtual List<string> GetValidationIssues()
{
var result = new List<string>();
if (Quantity < 0) result.Add("Quantity is invalid");
return result;
}
public int Quantity { get; set; }
}
/// <summary>
/// First child class, adds a new property and more validation
/// </summary>
public abstract class productBase : baseClass
{
public override List<string> GetValidationIssues()
{
// we must get any base results first!!
var result = base.GetValidationIssues();
// do checks for this class
if (string.IsNullOrWhiteSpace(Name)) result.Add("Name not specified");
return result;
}
public string Name { get; set; }
}
/// <summary>
/// Final instance
/// </summary>
public class Product : productBase
{
public override List<string> GetValidationIssues()
{
// remember to get the base results first
var result = base.GetValidationIssues();
// do checks for this class
if (Price <= 0) result.Add("Price is not valid");
return result;
}
public decimal Price { get; set; }
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:41:10.350",
"Id": "12597",
"Score": "0",
"body": "I don't think it is bad that the inheriting classes have to remember to call base.GetValidationIssues(). To help developers out you might want to put a comment on the base implementation to tell them that it is expected of them to call base.GetValidationIssues() though."
}
] |
[
{
"body": "<p>If you don't trust your client classes (maybe they don't call <code>baseClass.GetValidationIssues</code>) you can force it with the <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">Template method pattern</a>.</p>\n\n<pre><code>public abstract class BaseClass {\n\n public final List<String> getValidationIssues() {\n final List<String> issues = doGetBaseValidationIssues();\n final List<String> childIssues = doGetValidationIssues();\n issues.addAll(childIssues);\n return issues;\n }\n\n private List<String> doGetBaseValidationIssues() {\n return null;\n }\n\n protected abstract List<String> doGetValidationIssues();\n}\n</code></pre>\n\n<p>It's Java code, but I suppose it's very similar in C# too. Note the <code>final</code> keyword on <code>getValidationIssues</code>, so client classes are unable to override it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T15:08:47.380",
"Id": "12562",
"Score": "0",
"body": "Thanks for the reply. This would work for the base class and the final instance, but would not pick up the intermediate classes, but it's something to consider."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T15:36:41.750",
"Id": "12563",
"Score": "0",
"body": "The intermediate classes also could implement this pattern but with a few levels it would look terrible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T11:34:44.850",
"Id": "12826",
"Score": "0",
"body": "Funny thing about java and C#. In C# you can only override methods that have the virtual keyword, although you can hide non-virtual base methods using the new keyword. Completely opposite solution to the final keyword in java. :) (C# only have sealed classes for non-ineritables)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T14:45:06.857",
"Id": "7928",
"ParentId": "7927",
"Score": "0"
}
},
{
"body": "<p>Here's a C# version using a cross of the template method pattern and the collector pattern.\nIt'll pick up any issues from any derivative implementing the AddValidationIssues method.</p>\n\n<pre><code>public abstract class BaseClass\n{\n public List<string> GetValidationIssues()\n {\n var result = new List<String>();\n if (Quantity < 0) result.Add(\"Quantity is invalid\"); \n AddValidationIssues(result);\n return result;\n }\n\n protected virtual void AddValidationIssues(List<string> result)\n {\n }\n}\n\npublic class ProductBase : BaseClass\n{\n protected override void AddValidationIssues(List<string> result)\n {\n if (string.IsNullOrWhiteSpace(Name)) result.Add(\"Name not specified\"); \n }\n}\n</code></pre>\n\n<p>As a sidenote, I'd look for another name than \"BaseClass\". It doesn't say anything about what it does.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T18:16:14.030",
"Id": "8166",
"ParentId": "7927",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T14:03:22.127",
"Id": "7927",
"Score": "2",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Getting validation from inherited classes"
}
|
7927
|
<p>I'm starting to look at Python and its facilities. I've just tried to make one simple program using some base libraries. </p>
<p>I would like to hear some comments about anything you've noticed - style, readability, safety, etc.</p>
<pre><code>#!/usr/bin/python2.6 -u
import urllib2
import simplejson
import zlib
from optparse import OptionParser
class StackOverflowFetcher:
"""Simple SO fetcher"""
def getUserInfo( self, userId ):
response = urllib2.urlopen( 'http://api.stackoverflow.com/1.1/users/' + str(userId) )
response = response.read()
jsonData = zlib.decompress( response, 16+zlib.MAX_WBITS )
return simplejson.loads( jsonData )
def getUserDisplayName( self, userId ):
return self.getUserInfo( userId )['users'][0]['display_name']
def getUserViewCount( self, userId ):
return self.getUserInfo( userId )['users'][0]['view_count']
def getUserReputation( self, userId ):
return self.getUserInfo( userId )['users'][0]['reputation']
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-u", "--userId", dest="userId", help="Set userId (default is 1)", default=1 )
parser.add_option("-n", "--display-name", action="store_true", dest="show_display_name", default=False, help="Show user's display name")
parser.add_option("-v", "--view_count", action="store_true", dest="show_view_count", default=False, help="Show user's profile page view count")
parser.add_option("-r", "--reputation", action="store_true", dest="show_reputation", default=False, help="Show user's reputation")
(options, args) = parser.parse_args()
userId = options.userId
show_display_name = options.show_display_name
show_view_count = options.show_view_count
show_reputation = options.show_reputation
if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ):
show_display_name = show_view_count = show_reputation = True
fetcher = StackOverflowFetcher()
if ( show_display_name ) : print fetcher.getUserDisplayName( userId )
if ( show_view_count) : print fetcher.getUserViewCount( userId )
if ( show_reputation ) : print fetcher.getUserReputation( userId )
</code></pre>
<p>Python version 2.6</p>
|
[] |
[
{
"body": "<p>I think your naming scheme is good and on first sight its very easy to see what the code does without having to study it too much.</p>\n\n<p>However, if I would pick on something I would say:</p>\n\n<ul>\n<li><p>Remove the unnecessary whitespace, ex. if ( condition ), or self.getUserInfo( userId ). This is of course a matter of taste, but I find it more consistent with regular coding style to not 'bloat' with whitespace.</p></li>\n<li><p>optparser was deprecated in 2.7: <a href=\"http://docs.python.org/library/optparse.html\">http://docs.python.org/library/optparse.html</a></p></li>\n<li><p>in parser.add.option() you could remove the word \"show\" from the dest name and rather do the following, hence eliminating the need for all the declarations of show_display_name and still keep easy code readability.</p>\n\n<pre><code>...\nparser.add.option(parser.add_option(\"-r\", \"--reputation\", action=\"store_true\", dest=\"reputation\", default=False, help=\"Show user's reputation\")\n(show, args) = parser.parse_args()\n\nfetch = StackOverflowFetcher()\nif(show.reputation) : print fetch.getUserReputation(show.userId)\n</code></pre></li>\n<li><p>I don't really see what the point of the following line which sets everything to true, it seems a bit weird since you use store_true as action if the option parsed is set.</p>\n\n<pre><code>if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ):\nshow_display_name = show_view_count = show_reputation = True\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T21:30:02.987",
"Id": "12580",
"Score": "0",
"body": "I could removing \"show\" from dest names, but then what about userId option?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:04:57.930",
"Id": "12611",
"Score": "0",
"body": "You could just use show.UserId in fetch.getUserReputation. It doesn't break consistency in any major way, you are just showing/providing UserId to get getUserReputation method. If its very important for you, you could always do as you did at first: userId = show.userId, but again, I don't really see the need."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T16:21:13.350",
"Id": "7931",
"ParentId": "7930",
"Score": "7"
}
},
{
"body": "<p><a href=\"http://api.stackoverflow.com/1.1/users/string_id\">http://api.stackoverflow.com/1.1/users/string_id</a> returns</p>\n\n<pre><code>{\n \"error\": {\n \"code\": 404,\n \"message\": \"The server has not found anything matching the Request-URI.\"\n }\n}\n</code></pre>\n\n<p>and will raise <code>KeyError</code>s here:</p>\n\n<pre><code>def getUserDisplayName( self, userId ):\n return self.getUserInfo( userId )['users'][0]['display_name']\n\ndef getUserViewCount( self, userId ):\n return self.getUserInfo( userId )['users'][0]['view_count']\n\ndef getUserReputation( self, userId ):\n return self.getUserInfo( userId )['users'][0]['reputation']\n</code></pre>\n\n<hr>\n\n<p><a href=\"http://api.stackoverflow.com/1.1/users/9924\">http://api.stackoverflow.com/1.1/users/9924</a> returns</p>\n\n<pre><code>{\n \"total\": 0,\n \"page\": 1,\n \"pagesize\": 30,\n \"users\": []\n}\n</code></pre>\n\n<p>and will raise <code>IndexError</code>s here:</p>\n\n<pre><code>def getUserDisplayName( self, userId ):\n return self.getUserInfo( userId )['users'][0]['display_name']\n\ndef getUserViewCount( self, userId ):\n return self.getUserInfo( userId )['users'][0]['view_count']\n\ndef getUserReputation( self, userId ):\n return self.getUserInfo( userId )['users'][0]['reputation']\n</code></pre>\n\n<hr>\n\n<p>And since you are using <code>userId</code> as an argument to every method, and the <code>StackOverflowFetcher</code> instance is used only for 1 <code>userId</code> – it might me a good idea to add <code>__init__</code> method:</p>\n\n<pre><code>__init__(self, userId):\n # some userId validation\n self.userId = userId\n</code></pre>\n\n<p>and save yourself a bit of passing <code>userId</code> around.</p>\n\n<hr>\n\n<p>UPD:</p>\n\n<hr>\n\n<p>If all options are set to <code>True</code>, this will call <code>getUserInfo</code> and, therefore, query api 3 times:</p>\n\n<pre><code>if ( show_display_name ) : print fetcher.getUserDisplayName( userId )\nif ( show_view_count) : print fetcher.getUserViewCount( userId )\nif ( show_reputation ) : print fetcher.getUserReputation( userId )\n</code></pre>\n\n<p>Since you call it at least once any way, you better call it in the <code>__init__()</code>, or just store retrieved value in an instance attribute and use it like this:</p>\n\n<pre><code>def __init__(self, userId):\n #...\n self.userInfo = None\n\ndef getUserReputation(self):\n if self.userInfo is None:\n self.userInfo = self.getUserInfo()\n\n return self.userInfo['users'][0]['reputation']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T12:09:43.893",
"Id": "7962",
"ParentId": "7930",
"Score": "7"
}
},
{
"body": "<pre><code>#!/usr/bin/python2.6 -u\n\nimport urllib2\nimport simplejson\nimport zlib\nfrom optparse import OptionParser\n\nclass StackOverflowFetcher:\n \"\"\"Simple SO fetcher\"\"\"\n def getUserInfo( self, userId ):\n</code></pre>\n\n<p>The python style guide recommends words_with_underscores for function names and parameter names.</p>\n\n<pre><code> response = urllib2.urlopen( 'http://api.stackoverflow.com/1.1/users/' + str(userId) )\n</code></pre>\n\n<p>I'd consider moving the API into a global constant</p>\n\n<pre><code> response = response.read()\n jsonData = zlib.decompress( response, 16+zlib.MAX_WBITS )\n</code></pre>\n\n<p>I'd combine the previous two lines</p>\n\n<pre><code> return simplejson.loads( jsonData )\n\n def getUserDisplayName( self, userId ):\n return self.getUserInfo( userId )['users'][0]['display_name']\n\n def getUserViewCount( self, userId ):\n return self.getUserInfo( userId )['users'][0]['view_count']\n\n def getUserReputation( self, userId ):\n return self.getUserInfo( userId )['users'][0]['reputation']\n</code></pre>\n\n<p>There three functions share most of their code. Why don't you modify getUserInfo to do the ['users'][0] itself instead?</p>\n\n<pre><code>if __name__ == '__main__':\n parser = OptionParser()\n parser.add_option(\"-u\", \"--userId\", dest=\"userId\", help=\"Set userId (default is 1)\", default=1 )\n parser.add_option(\"-n\", \"--display-name\", action=\"store_true\", dest=\"show_display_name\", default=False, help=\"Show user's display name\")\n parser.add_option(\"-v\", \"--view_count\", action=\"store_true\", dest=\"show_view_count\", default=False, help=\"Show user's profile page view count\")\n parser.add_option(\"-r\", \"--reputation\", action=\"store_true\", dest=\"show_reputation\", default=False, help=\"Show user's reputation\")\n (options, args) = parser.parse_args()\n\n userId = options.userId\n show_display_name = options.show_display_name\n show_view_count = options.show_view_count\n show_reputation = options.show_reputation\n\n if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ):\n</code></pre>\n\n<p>None of those parentheses are necessary. I'd probably go with <code>if not (show_display_name or show_view_count or show_reputation):</code> as I think that mostly clear states what you are doing.\n show_display_name = show_view_count = show_reputation = True</p>\n\n<pre><code> fetcher = StackOverflowFetcher()\n if ( show_display_name ) : print fetcher.getUserDisplayName( userId )\n if ( show_view_count) : print fetcher.getUserViewCount( userId )\n if ( show_reputation ) : print fetcher.getUserReputation( userId )\n</code></pre>\n\n<p>Firstly, the ifs don't need the parens. Secondly, the way your code is written each call goes back to the server. So you'll three calls to the stackoverflow server which you could have gotten with one. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T16:04:00.387",
"Id": "7970",
"ParentId": "7930",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "7970",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-18T15:43:16.380",
"Id": "7930",
"Score": "10",
"Tags": [
"python",
"json",
"stackexchange",
"python-2.x"
],
"Title": "Stack Overflow user info fetcher"
}
|
7930
|
<p>I've been getting into plugin development for jQuery and my first creation is a tooltip plugin. I've been reading a lot about plugin development especially with the use of JavaScript prototyping. I'm just looking for any tips to further improve my plugin development (only 144 lines of code).</p>
<p>Two questions in particular:</p>
<ol>
<li><p>The tooltip accepts "settings" options which I extend the standard jQuery way. Should I be passing only the necessary properties into the "Tip" object for each tooltip rather than the whole settings object, which right now I'm just doing out of convenience and simplicity?</p></li>
<li><p>I also pass the event scheduler to the "Tip" object out of convenience, but should I be passing this into the function calls separately rather than keeping it as part of each tooltip object?</p></li>
</ol>
<p>demo: <a href="http://websanova.com/plugins/tooltips/jquery#wtip" rel="nofollow">http://websanova.com/plugins/tooltips/jquery#wtip</a></p>
<p>code (also at <a href="http://websanova.com/a/plugins/websanova/tooltip/wTip.1.0.js" rel="nofollow">http://websanova.com/a/plugins/websanova/tooltip/wTip.1.0.js</a>):</p>
<pre><code>/******************************************
* Websanova.com
*
* Resources for web entrepreneurs
*
* @author Websanova
* @copyright Copyright (c) 2012 Websanova.
* @license This wTip jQuery plug-in is dual licensed under the MIT and GPL licenses.
* @link http://www.websanova.com
* @docs http://www.websanova.com/plugins/websanova/tooltip
* @version Version 1.0
*
******************************************/
(function($)
{
$.fn.wTip = function(settings)
{
var defaultSettings = {
color : 'cream', // allow custom with #FFAACC
opacity : 0.8, // opacity level
title : null, // manually set title
fadeIn : 0, // time before tooltip appears in milliseconds
fadeOut : 0, // time before tooltip fades in milliseconds
delayIn : 0, // time before tooltip displays in milliseconds
delayOut : 0, // time before tooltip begins to dissapear in milliseconds
offsetX : 8, // x offset of mouse position
offsetY : 15 // y offset of mouse position
}
var supportedColors = ['red','green','blue','white','black','cream','yellow','orange','plum'];
settings = $.extend(defaultSettings,settings);
return this.each(function()
{
var elem = $(this);
settings.title = settings.title || elem.attr('title') || 'No title set';
var scheduleEvent = new eventScheduler();
var tip = new Tip(settings, scheduleEvent);
$('body').append(tip.generate());
elem
//hover on/off triggers
.hover(function()
{
tip.hover = true;
scheduleEvent.set(function(){ tip.show(); }, settings.delayIn);
},function()
{
tip.hover = false;
if(tip.shown) tip.hide();
})
//move tooltip with mouse poitner
.mousemove(function(e)
{
tip.move(e);
})
//remove title attribute so that we don't have the browser title showing up
.removeAttr('title');
});
}
/**
* Event scheduler class definition
*/
function eventScheduler(){}
eventScheduler.prototype =
{
set: function (func, timeout)
{
this.timer = setTimeout(func, timeout);
},
clear: function()
{
clearTimeout(this.timer);
}
}
/**
* Tip class definition
*/
function Tip(settings, scheduleEvent)
{
this.hover = false;
this.shown = false;
this.settings = settings;
this.scheduleEvent = scheduleEvent;
}
Tip.prototype =
{
generate: function()
{
if(this.tip) return this.tip;
this.tip =
$('<div class="_wTip_holder"><div class="_wTip_outer"><div class="_wTip_bg"></div><div class="_wTip_inner">' + this.settings.title + '</div></div></div>')
.css({display: 'none', position: 'absolute', opacity: this.settings.opacity})
.addClass('_wTip_' + this.settings.color);
return this.tip;
},
show: function()
{
var $this = this;
this.tip.fadeIn(this.settings.fadeIn, function()
{
$this.shown = true;
if(!$this.hover) $this.hide();
});
},
move: function(e)
{
this.tip.css({left: e.pageX + this.settings.offsetX, top: e.pageY + this.settings.offsetY});
},
hide: function()
{
var $this = this;
this.scheduleEvent.set(function()
{
$this.tip.fadeOut($this.settings.fadeOut, function()
{
$this.shown = false;
});
},
this.settings.delayOut);
}
}
})(jQuery);
</code></pre>
<p>Any tips or pointers in the right direction appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T19:56:31.407",
"Id": "12576",
"Score": "2",
"body": "for future reference: [Please include the code in the question, not a link to it](http://codereview.stackexchange.com/faq#questions)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-26T15:40:43.117",
"Id": "12991",
"Score": "0",
"body": "I'm kind of curious why you picked a tooltip plugin, with so many of those (e.g. qTip) already in existence?"
}
] |
[
{
"body": "<p><strong>You ask:</strong></p>\n\n<blockquote>\n <ol>\n <li>The tooltip accepts \"settings\" options which I extend the standard jQuery way. Should I be passing only the necessary properties into the \"Tip\" object for each tooltip rather than the whole settings object, which right now I'm just doing out of convenience and simplicity?</li>\n </ol>\n</blockquote>\n\n<p><strong>A:</strong></p>\n\n<p>No. If you filter out any \"extra\" settings and someone comes along to extend your code they will have trouble if they want to add extra settings. There doesn't seem to be any reason to remove them. </p>\n\n<p>Also on this point</p>\n\n<pre><code>settings = $.extend(defaultSettings,settings);\n</code></pre>\n\n<p>is normally </p>\n\n<pre><code>settings = $.extend({}, defaultSettings, settings || {});\n</code></pre>\n\n<p>This allows settings to be optional and defaultSettings won't be overridden.</p>\n\n<p>I would also move <code>var defaultSettings</code> outside your <code>$.fn.wTip</code> function (but still in your closure <code>(function($){</code>) this will mean its not created every time.</p>\n\n<p>While it is not necessary, I would <code>return this</code> in your <code>eventScheduler</code> class</p>\n\n<pre><code>function eventScheduler()\n{\n return this;\n} \n</code></pre>\n\n<p>Its easier to understand that it is a class. (Also most class are Capitalized but thats just a style). </p>\n\n<p>Overall I would say you have a nice clean coding style. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T00:48:33.113",
"Id": "12819",
"Score": "0",
"body": "Thanks man, those are great tips. I also moved the $('body').append(tip.generate()); call into the generate function itself, which seemed to make more sense to me as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T03:54:57.110",
"Id": "7947",
"ParentId": "7934",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T19:05:08.090",
"Id": "7934",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery tooltip plugin"
}
|
7934
|
<p>I'm writing a program to convert integers to Roman numerals (naively -- it doesn't know how to do the subtraction trick yet). What I have is functional, but it is not "Good Ruby". </p>
<pre><code>VALUES = [
["M", 1000],
["D", 500],
["C", 100],
["L", 50],
["X", 10],
["V", 5],
["I", 1],
]
def romanize n
roman = ""
VALUES.each do |pair|
letter = pair[0]
value = pair[1]
roman += letter*(n / value)
n = n % value
end
return roman
end
</code></pre>
<p>Perhaps a hash makes more sense than the array of arrays, but the way I update <code>n</code>, order matters. Passing in <code>pair</code> to the block is dumb, but passing <code>letter, value</code> didn't work in the way I expected.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T21:22:33.530",
"Id": "12578",
"Score": "2",
"body": "With ruby 1.9 hashes are also ordered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T11:45:28.040",
"Id": "12663",
"Score": "1",
"body": "No kidding! That's good to know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T02:00:08.330",
"Id": "12771",
"Score": "0",
"body": "I'm unsure why 'passing letter, value didn't work in the way [you] expected'; it worked well for me in Ruby 1.8.7p352 and 1.9.2p290."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T22:17:56.143",
"Id": "13091",
"Score": "3",
"body": "\"With ruby 1.9 hashes are also ordered\". Hashes are not ordered, they are remembered in their insertion order. It's a subtle difference."
}
] |
[
{
"body": "<p>I don't know what you mean about 'good ruby'. I show you a object-oriented version. \nInstead of </p>\n\n<pre><code>romanize(4)\n</code></pre>\n\n<p>you can call</p>\n\n<pre><code>4.roman\n</code></pre>\n\n<p>My solution is similar to your solution. It is Hash-oriented, so you need ruby 1.9.</p>\n\n<p>I also tried to use a array in array solution with <code>ROMAN_NUMBERS.each do |value, letter|</code> without any problem (I'm not sure if it is only ruby 1.9).</p>\n\n<pre><code>class Fixnum\n ROMAN_NUMBERS = {\n 1000 => \"M\", \n 900 => \"CM\", \n 500 => \"D\", \n 400 => \"CD\",\n 100 => \"C\", \n 90 => \"XC\", \n 50 => \"L\", \n 40 => \"XL\", \n 10 => \"X\", \n 9 => \"IX\", \n 5 => \"V\", \n 4 => \"IV\", \n 1 => \"I\", \n }\n\n def roman\n n = self\n roman = \"\"\n ROMAN_NUMBERS.each do |value, letter|\n roman << letter*(n / value)\n n = n % value\n end\n return roman\n end\nend\n</code></pre>\n\n<p>With ruby 1.8 you may add use <code>ROMAN_NUMBERS.sort.each</code>.</p>\n\n<p>As an alternative, you can use a recursive solution:</p>\n\n<pre><code>class Fixnum\n ROMAN_NUMBERS = {\n 1000 => \"M\", \n 900 => \"CM\", \n 500 => \"D\", \n 400 => \"CD\",\n 100 => \"C\", \n 90 => \"XC\", \n 50 => \"L\", \n 40 => \"XL\", \n 10 => \"X\", \n 9 => \"IX\", \n 5 => \"V\", \n 4 => \"IV\", \n 1 => \"I\", \n 0 => \"\", \n }\n def roman\n return '' if self == 0\n ROMAN_NUMBERS.each do |value, letter|\n return ( letter * (self / value)) << (self % value).roman if value <= self\n end\n return (self % value).roman\n end\nend\n</code></pre>\n\n<p>I don't recommend the recursive solution. Each number must start again with <code>M</code>.</p>\n\n<hr>\n\n<p>A little testcode, to check the results:</p>\n\n<pre><code>require 'test/unit'\n\nclass NumberTest < Test::Unit::TestCase\n def test_0; assert_equal('',0.roman); end\n def test_1; assert_equal('I',1.roman); end\n def test_2; assert_equal('II',2.roman); end\n def test_3; assert_equal('III',3.roman); end\n def test_4; assert_equal('IV',4.roman); end\n def test_5; assert_equal('V',5.roman); end\n def test_6; assert_equal('VI',6.roman); end\n def test_7; assert_equal('VII',7.roman); end\n def test_8; assert_equal('VIII',8.roman); end\n def test_9; assert_equal('IX',9.roman); end\n def test_10; assert_equal('X',10.roman); end\n def test_11; assert_equal('XI',11.roman); end\n def test_12; assert_equal('XII',12.roman); end\n def test_13; assert_equal('XIII',13.roman); end\n def test_14; assert_equal('XIV',14.roman); end\n def test_15; assert_equal('XV',15.roman); end\n def test_16; assert_equal('XVI',16.roman); end\n def test_20; assert_equal('XX',20.roman); end\n def test_30; assert_equal('XXX',30.roman); end\n def test_40; assert_equal('XL',40.roman); end\n def test_50; assert_equal('L',50.roman); end\n def test_60; assert_equal('LX',60.roman); end\n def test_70; assert_equal('LXX',70.roman); end\n def test_80; assert_equal('LXXX',80.roman); end\n def test_90; assert_equal('XC',90.roman); end\n def test_99; assert_equal('XCIX',99.roman); end\n def test_100; assert_equal('C',100.roman); end\n def test_200; assert_equal('CC',200.roman); end\n def test_300; assert_equal('CCC',300.roman); end\n def test_400; assert_equal('CD',400.roman); end\n def test_500; assert_equal('D',500.roman); end\n def test_600; assert_equal('DC',600.roman); end\n def test_900; assert_equal('CM',900.roman); end\n def test_1000; assert_equal('M',1000.roman); end\n def test_2000; assert_equal('MM',2000.roman); end\n def test_2003; assert_equal('MMIII',2003.roman); end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T22:59:50.283",
"Id": "7939",
"ParentId": "7937",
"Score": "12"
}
},
{
"body": "<p>Regardless of whether your code works completely, converted to the Ruby way it perhaps would be:</p>\n\n<pre><code>letters = %w[ M D C L X V I ]\nvalues = [ 1000, 500, 100, 50, 10, 5, 1 ]\nLETTERS = letters.zip values\n\ndef romanize number\n n=number\n c=0 # Avoid reallocating count.\n LETTERS.map{|l,v| c, n = n.divmod v; l*c}.join ''\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-16T08:58:29.953",
"Id": "140731",
"Score": "1",
"body": "It's wrong \nTry this:\np romanize(4);\n\nResult will be:\n\"IIII\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-18T12:40:46.500",
"Id": "171057",
"Score": "0",
"body": "@AHK it's not so wrong, in the sophisticated and venerable sense of [Why Do Some Clocks Use Roman Numeral IIII?](http://mentalfloss.com/article/24578/why-do-some-clocks-use-roman-numeral-iiii) and the Alternative forms section of Wikipedia's article on [Roman_numerals](https://en.wikipedia.org/w/index.php?title=Roman_numerals&oldid=665276268#Alternative_forms)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-19T13:48:27.283",
"Id": "171318",
"Score": "0",
"body": "Oh! i didn't know that @Mark"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T19:52:08.413",
"Id": "8168",
"ParentId": "7937",
"Score": "3"
}
},
{
"body": "<p>MarkDBlackwell's use of <code>divmod</code> and <code>map</code> works with the hash containing the 4s & 9s from knut's answer.</p>\n\n<p>Franken-solution cobbled together from their answers below:</p>\n\n<pre><code>ROMAN_NUMS = {\n \"M\" => 1000,\n \"CM\" => 900, \"D\" => 500, \"CD\" => 400, \"C\" => 100,\n \"XC\" => 90, \"L\" => 50, \"XL\" => 40, \"X\" => 10,\n \"IX\" => 9, \"V\" => 5, \"IV\" => 4, \"I\" => 1\n}\n\ndef romanize(num)\n ROMAN_NUMS.map do |ltr, val| \n amt, num = num.divmod(val)\n ltr * amt\n end.join\nend\n</code></pre>\n\n<p>Also works as a version closer to knut's original answer.</p>\n\n<pre><code>class Fixnum\n\n ROMAN_NUMS = {\n \"M\" => 1000,\n \"CM\" => 900, \"D\" => 500, \"CD\" => 400, \"C\" => 100,\n \"XC\" => 90, \"L\" => 50, \"XL\" => 40, \"X\" => 10,\n \"IX\" => 9, \"V\" => 5, \"IV\" => 4, \"I\" => 1\n }\n\n def roman\n num = self\n ROMAN_NUMS.map do |ltr, val| \n amt, num = num.divmod(val)\n ltr * amt\n end.join\n end\n\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-02T00:39:55.170",
"Id": "174217",
"Score": "2",
"body": "When you're posting an answer on Code Review, please make sure it's a code review, not other code that does the same thing, or a code dump of the \"better\" code. Instead, please include a list of the changes you made alongside the modified code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-02T00:33:01.647",
"Id": "95514",
"ParentId": "7937",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T20:24:18.563",
"Id": "7937",
"Score": "9",
"Tags": [
"ruby",
"roman-numerals"
],
"Title": "Roman numeral converter"
}
|
7937
|
<p>I've updated the previous version to be more object oriented as suggested.</p>
<pre><code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
* A class containing a single record. Each record contains the Quora answer
* ID and the predictor vector. If the record is a training example then the
* target classification is also included.
*/
private class Record {
private final Vector predictor;
private final double target;
private final String answerId;
/**
* Constructor for test records
*/
public Record(Vector predictor, String answerId) {
this.predictor = predictor;
this.answerId = answerId;
this.target = 0;
}
/**
* Constructor for training records
*/
public Record(Vector predictor, String answerId, double target) {
this.predictor = predictor;
this.answerId = answerId;
this.target = target;
}
public Vector getPredictor() {
return predictor;
}
public double getTarget() {
return target;
}
public String getAnswerId() {
return answerId;
}
}
/**
* Class for storing a list of records. The constructor reads the records from
* the training or test sections of the input file as appropriate
*/
private class RecordList extends ArrayList<Record> {
private static final long serialVersionUID = 1L;
private final int numFeatures; // number of features in predictor
/**
* Constructor which loads records from training part of input file
*
* @param sc
* scanner to read training data from
*/
public RecordList(Scanner sc) {
String[] dimString = sc.nextLine().split("\\s");
int numRecords = Integer.parseInt(dimString[0]);
numFeatures = Integer.parseInt(dimString[1]);
for (int i = 0; i < numRecords; i++) {
Vector predictor = new Vector(numFeatures);
String[] recordString = sc.nextLine().split("\\s");
// read Quora answer ID
String answerId = recordString[0];
// read training targets and convert from -1/+1 to 0/1
double target = (Double.parseDouble(recordString[1]) + 1) / 2;
// read predictor vector
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
String featureString = recordString[2 + fIndex];
predictor.set(fIndex, Double.parseDouble(featureString
.substring(featureString.indexOf(":") + 1)));
}
add(new Record(predictor, answerId, target));
}
}
/**
* Constructor which loads records from test part of input file
*
* @param sc
* scanner from which test data will be read
*/
public RecordList(Scanner sc, int numFeatures) {
this.numFeatures = numFeatures;
String[] dimString = sc.nextLine().split("\\s");
int numRecords = Integer.parseInt(dimString[0]);
for (int i = 0; i < numRecords; i++) {
Vector predictor = new Vector(numFeatures);
String[] recordString = sc.nextLine().split("\\s");
// read Quora answer ID
String answerId = recordString[0];
// read predictor vector
for (int fIndex = 0; fIndex < numFeatures; fIndex++) {
String featureString = recordString[1 + fIndex];
predictor.set(fIndex, Double.parseDouble(featureString
.substring(featureString.indexOf(":") + 1)));
}
add(new Record(predictor, answerId));
}
}
public int getNumFeatures() {
return numFeatures;
}
}
/**
* Class which supports normalization of records
*/
private class Normalizer {
private final Vector mean;
private final Vector varSqrt;
/**
* Constructor normalizes supplied recordList and calculates elementwise
* mean and variance
*/
public Normalizer(RecordList recordList) {
// calculate mean of each feature
mean = new Vector(recordList.getNumFeatures());
for (Record record : recordList) {
mean.add(record.getPredictor());
}
mean.divide(recordList.size());
// normalize recordList by feature means
for (Record record : recordList) {
record.getPredictor().subtract(mean);
}
// calculate variance of each feature
varSqrt = new Vector(recordList.getNumFeatures());
Vector predictorSquared = new Vector(recordList.getNumFeatures());
for (Record record : recordList) {
predictorSquared.set(record.getPredictor());
predictorSquared.elementwiseSquare();
varSqrt.add(predictorSquared);
}
varSqrt.divide(recordList.size());
varSqrt.sqrt();
// normalize recordList by feature variances
for (Record record : recordList) {
record.getPredictor().divide(varSqrt);
}
}
/**
* Normalize a Vector using the mean and variance calculated from supplied
* recordList during instantiation
*
* @param vector
* Vector to be normalized
*/
public void normalize(Vector vector) {
vector.subtract(mean);
vector.divide(varSqrt);
}
}
/**
* Class for training of a classifier
*/
private class Trainer {
// training rate for stochastic gradient descent
private final double trainingRate;
public Trainer(double trainingRate) {
this.trainingRate = trainingRate;
}
/**
* Train logistic regression coefficients using provided test records
*/
public void train(Classifier classifier, RecordList testRecords) {
for (Record record : testRecords) {
// classify test record
double estimate = classifier.classify(record.getPredictor());
// determine classification error
double estError = estimate - record.getTarget();
// update regression coefficients using SGD
Vector deltaTheta = record.getPredictor().clone();
deltaTheta.multiply(-estError * trainingRate / testRecords.size());
classifier.getRegressionCoeffs().add(deltaTheta);
}
}
}
/**
* A class which implements classification using logistic regression
*/
private class Classifier {
// regression coefficients, trained using Trainer
private final Vector regressionCoeffs;
// normalizer used to normalize predictor vectors
private final Normalizer normalizer;
// number of features in predictor vector
private final int numFeatures;
/**
* Instantiates a classifier with a particular training set. A normalizer
* will be instantiated, storing the mean and variance of the training set
* for future use during classification
*/
public Classifier(RecordList trainingSet) {
normalizer = new Normalizer(trainingSet);
numFeatures = trainingSet.getNumFeatures();
regressionCoeffs = new Vector(numFeatures);
}
/**
* Classify a predictor vector
*
* @param predictor
* predictor vector to be classified
* @return soft classification
*/
public double classify(Vector predictor) {
Vector normalizedPredictor = predictor.clone();
normalizer.normalize(normalizedPredictor);
normalizedPredictor.multiply(regressionCoeffs);
return sigmoid(normalizedPredictor.elementSum());
}
/**
* Sigmoid function
*
* @param z
* a double
*/
private double sigmoid(double z) {
return 1.0 / (1.0 + Math.exp(-z));
}
/**
* Return regression coefficients
*
* @return regression coefficient vector
*/
public Vector getRegressionCoeffs() {
return regressionCoeffs;
}
/**
* Run classification for a set of queries and output the result to
* System.out
*
* @param sc
* Scanner for reading queries
*/
public void classifyQueries(Scanner sc) {
RecordList classificationSet = new RecordList(sc, numFeatures);
for (Record record : classificationSet) {
// classify
double classification = classify(record.getPredictor());
// output result to System.out
if (classification > 0.5) {
System.out.printf("%s +1\n", record.getAnswerId());
} else {
System.out.printf("%s -1\n", record.getAnswerId());
}
}
}
}
</code></pre>
<p>Here's an example of a typical run</p>
<pre><code>public static void main(String[] args) throws FileNotFoundException {
Scanner sc; // input file
if (args.length > 0) { // input stream from file (for testing)
BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
sc = new Scanner(in);
} else { // input streamed from System.in (used in competition)
sc = new Scanner(System.in);
}
// run classification
QuoraClassifier classifier = new QuoraClassifier();
double trainingRate = 5.0;
RecordList trainingSet = new RecordList(sc);
Classifier classifier = new Classifier(trainingSet);
Trainer trainer = new Trainer(trainingRate);
trainer.train(classifier, trainingSet);
classifier.classifyQueries(sc);
}
</code></pre>
|
[] |
[
{
"body": "<p>I just looked briefly but this looks good. I would try to be more expressive with some of your variable names and break the methods up a little more. Also, I think you can get away without using clone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-11T23:05:34.617",
"Id": "8897",
"ParentId": "7941",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8897",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T00:12:45.203",
"Id": "7941",
"Score": "7",
"Tags": [
"java"
],
"Title": "Classification Problem from CodeSprint 2012 (Updated)"
}
|
7941
|
<p>This is a solution from the CodeSprint 2012 coding competition. Any suggestions on ways to improve the object orientation or general style would be much appreciated. The code takes several text documents, encodes them into feature vectors using TF-IDF, and then applies k-means clustering to group documents with similar topics/themes.</p>
<pre><code>/**
* Class containing an individual document
*/
private class Document implements Comparable<Document> {
// document title, contents and ID
private final String title;
private final String contents;
private final long id;
// whether document has been allocated to a cluster
private boolean allocated;
// document word histogram
private Vector histogram;
// encoded document vector (TF-IDF)
private Vector vector;
// precalculated document vector norms
private double norm;
public Document(long id, String title, String contents) {
this.id = id;
this.title = title;
this.contents = contents;
}
public void setVector(Vector vector) {
this.vector = vector;
}
public boolean isAllocated() {
return allocated;
}
/**
* Mark document as having been allocated to a cluster
*/
public void setIsAllocated() {
allocated = true;
}
/**
* Mark document as not being allocated to a cluster
*/
public void clearIsAllocated() {
allocated = false;
}
public long getId() {
return id;
}
public String getContents() {
return contents;
}
public Vector getVector() {
return vector;
}
public Vector getHistogram() {
return histogram;
}
public void setHistogram(Vector histogram) {
this.histogram = histogram;
}
public void setNorm(double norm) {
this.norm = norm;
}
public double getNorm() {
return norm;
}
/**
* Allow documents to be sorted by ID
*/
public int compareTo(Document document) {
if (id > document.getId()) {
return 1;
} else if (id < document.getId()) {
return -1;
} else {
return 0;
}
}
}
/**
* Class storing a collection of documents to be clustered
*/
private class DocumentList extends ArrayList<Document> {
/**
* Parse input string into document ID, document title and contents then
* encode into feature vector using encoder
*
* @param input
* String containing document fields
* @param encoder
* Encoder to use for encoding document into feature vector
*/
public DocumentList(String input) {
StringTokenizer st = new StringTokenizer(input, "{");
int numDocuments = st.countTokens() - 1;
String record = st.nextToken(); // skip empty split to left of {
Pattern pattern =
Pattern
.compile("\"content\": \"(.*)\", \"id\": (.*), \"title\": \"(.*)\"");
for (int i = 0; i < numDocuments; i++) {
record = st.nextToken();
Matcher matcher = pattern.matcher(record);
if (matcher.find()) {
long documentID = Long.parseLong(matcher.group(2));
String title = matcher.group(3);
String contents = matcher.group(1);
add(new Document(documentID, title, contents));
}
}
}
/**
* Mark all documents as not being allocated to a cluster
*/
public void clearIsAllocated() {
for (Document document : this) {
document.clearIsAllocated();
}
}
}
/**
* Interface for encoders which encode documents into feature vectors
*/
private interface Encoder {
public void encode(DocumentList documentList);
}
/**
* Implementation of Encoder which uses Term Frequency - Inverse Document
* Frequency (TF-IDF) encoding
*/
private class TfIdfEncoder implements Encoder {
// number of features to be used in feature vector
private final int numFeatures;
// inverse document frequency used for normalization of feature vectors
private Vector inverseDocumentFrequency = null;
public TfIdfEncoder(int numFeatures) {
this.numFeatures = numFeatures;
}
/**
* Calculate word histogram for document and store in histogram field
*/
private void calcHistogram(Document document) {
// Calculate word histogram for document
String[] words = document.getContents().split("[^\\w]+");
Vector histogram = new Vector(numFeatures);
for (int i = 0; i < words.length; i++) {
int hashCode = hashWord(words[i]);
histogram.increment(hashCode);
}
document.setHistogram(histogram);
}
/**
* Calculate word histogram for all documents in a DocumentList
*/
private void calcHistogram(DocumentList documentList) {
for (Document document : documentList) {
calcHistogram(document);
}
}
/**
* Calculate inverse document frequency for DocumentList. Assumes word
* histograms for constituent documents have already been calculated
*/
private void calcInverseDocumentFrequency(DocumentList documentList) {
inverseDocumentFrequency = new Vector(numFeatures);
for (Document document : documentList) {
for (int i = 0; i < numFeatures; i++) {
if (document.getHistogram().get(i) > 0) {
inverseDocumentFrequency.increment(i);
}
}
}
inverseDocumentFrequency.invert();
inverseDocumentFrequency.multiply(documentList.size());
inverseDocumentFrequency.log();
}
/**
* Encode document using Term Frequency - Inverse Document Frequency
*/
private void encode(Document document) {
// Normalize word histogram by maximum word frequency
Vector vector = document.getHistogram().clone();
// Allow histogram to be deallocated as it is no longer needed
document.setHistogram(null);
vector.divide(vector.max());
// Normalize by inverseDocumentFrequency
vector.multiply(inverseDocumentFrequency);
// Store feature vecotr in document
document.setVector(vector);
// Precalculate norm for use in distance calculations
document.setNorm(vector.norm());
}
/**
* Hash word into integer between 0 and numFeatures-1. Used to form document
* feature vector
*
* @param word
* String to be hashed
* @return hashed integer
*/
private int hashWord(String word) {
return Math.abs(word.hashCode()) % numFeatures;
}
/**
* Encode all documents within a DocumentList
*/
public void encode(DocumentList documentList) {
calcHistogram(documentList);
calcInverseDocumentFrequency(documentList);
for (Document document : documentList) {
encode(document);
}
}
}
/**
* Class representing a cluster of Documents
*/
private class Cluster extends ArrayList<Document> implements
Comparable<Cluster> {
// cluster centroid
private Vector centroid;
// norm of cluster centroid
private double centroidNorm;
/**
* Instantiate a cluster with a single member document
*/
public Cluster(Document document) {
super();
add(document);
centroid = document.getVector().clone();
centroidNorm = centroid.norm();
}
/**
* Allows sorting of Clusters by comparing ID of first document
*/
public int compareTo(Cluster cluster) {
return get(0).compareTo(cluster.get(0));
}
/**
* Add document to cluster and mark document as allocated
*/
public boolean add(Document document) {
super.add(document);
document.setIsAllocated();
return true;
}
/**
* Update centroids and centroidNorms for a specific cluster
*
* @param clusterIndex
* cluster to update
*/
private void updateCentroid() {
centroid = null;
for (Document document : this) {
if (centroid == null) {
centroid = document.getVector().clone();
} else {
centroid.add(document.getVector());
}
}
centroid.divide(size());
centroidNorm = centroid.norm();
}
public Vector getCentroid() {
return centroid;
}
public double getCentroidNorm() {
return centroidNorm;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < this.size(); i++) {
sb.append(this.get(i).getId());
if (i < this.size() - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
/**
* Class representing a list of clusters. This is the output of the clustering
* process
*/
private class ClusterList extends ArrayList<Cluster> {
/**
* Instantiate a list of clusters with a given initial capacity
*
* @param initialCapacity
*/
public ClusterList(int initialCapacity) {
super(initialCapacity);
}
/**
* Update centroids of all clusters within ClusterList
*/
public void updateCentroids() {
for (Cluster cluster : this) {
cluster.updateCentroid();
}
}
/**
* Find document with maximum distance to clusters in ClusterList. Distance
* to ClusterList is defined as the minimum of the distances to each
* constituent Cluster's centroid. This method is used during the cluster
* initialization in k means clustering
*
* @param distance
* distance measure to use
* @param documentList
* list of documents to search
* @return furthest document
*/
public Document findFurthestDocument(Distance distance,
DocumentList documentList) {
double furthestDistance = Double.MIN_VALUE;
Document furthestDocument = null;
for (Document document : documentList) {
if (!document.isAllocated()) {
double documentDistance = distance.calcDistance(document, this);
if (documentDistance > furthestDistance) {
furthestDistance = documentDistance;
furthestDocument = document;
}
}
}
return furthestDocument;
}
/**
* Clear out documents from within each cluster. Used to cleanup at the end
* of each iteration of k means
*/
private void emptyClusters() {
for (Cluster cluster : this) {
cluster.clear();
}
}
/**
* Find cluster whose centroid is closest to a document
*
* @param distance
* distance measure to use
* @param document
* @return Cluster closest to document
*/
private Cluster findNearestCluster(Distance distance, Document document) {
Cluster nearestCluster = null;
double nearestDistance = Double.MAX_VALUE;
for (Cluster cluster : this) {
double clusterDistance = distance.calcDistance(document, cluster);
if (clusterDistance < nearestDistance) {
nearestDistance = clusterDistance;
nearestCluster = cluster;
}
}
return nearestCluster;
}
/**
* Calculate ratio of average intracluster distance to average intercluster
* distance. Used to optimize number of clusters k
*
* @return ratio of average intracluster distance to average intercluster
* distance
*/
private double calcIntraInterDistanceRatio(Distance distance) {
if (this.size() > 1) {
double interDist = calcInterClusterDistance(distance);
if (interDist > 0.0) {
return calcIntraClusterDistance(distance) / interDist;
} else {
return Double.MAX_VALUE;
}
} else {
return Double.MAX_VALUE;
}
}
/**
* Calculate average intracluster distance, which is the average distance
* between the constituent documents in a cluster and the cluster centroid
*
* @param distance
* distance measure to use
*/
private double calcIntraClusterDistance(Distance distance) {
double avgIntraDist = 0.0;
int numDocuments = 0;
for (Cluster cluster : this) {
double clusterIntraDist = 0.0;
for (Document document : cluster) {
clusterIntraDist += distance.calcDistance(document, cluster);
}
numDocuments += cluster.size();
avgIntraDist += clusterIntraDist;
}
return avgIntraDist / numDocuments;
}
/**
* Calculate average intercluster distance, which is the distance between
* cluster centroids
*
* @param distance
* distance measure to use
*/
private double calcInterClusterDistance(Distance distance) {
if (this.size() > 1) {
double avgInterDist = 0.0;
for (Cluster cluster1 : this) {
for (Cluster cluster2 : this) {
if (cluster1 != cluster2) {
avgInterDist += distance.calcDistance(cluster1, cluster2);
}
}
}
// there are N*N-1 unique pairs of clusters
avgInterDist /= (this.size() * (this.size() - 1));
return avgInterDist;
} else {
return 0.0;
}
}
/**
* Sort order of documents within each cluster, then sort order of clusters
* within ClusterList
*/
public void sort() {
for (Cluster cluster : this) {
Collections.sort(cluster);
}
Collections.sort(this);
}
/**
* Display clusters in sorted order
*/
public String toString() {
sort();
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < this.size(); i++) {
sb.append(this.get(i));
if (i < this.size() - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
/**
* Class for measuring the distance between documents, clusters and
* clusterLists
*/
private abstract class Distance {
public double calcDistance(Document document, Cluster cluster) {
return calcDistance(document.getVector(), cluster.getCentroid(),
document.getNorm(), cluster.getCentroidNorm());
}
/**
* Calculate minimum of the distances between a document and the centroids
* of the clusters within a clusterList
*/
public double calcDistance(Document document, ClusterList clusterList) {
double distance = Double.MAX_VALUE;
for (Cluster cluster : clusterList) {
distance = Math.min(distance, calcDistance(document, cluster));
}
return distance;
}
public double calcDistance(Cluster cluster1, Cluster cluster2) {
return calcDistance(cluster1.getCentroid(), cluster2.getCentroid(),
cluster1.getCentroidNorm(), cluster2.getCentroidNorm());
}
public abstract double calcDistance(Vector vector1, Vector vector2,
double norm1, double norm2);
}
/**
* Class for calculating cosine distance between two vectors
*/
private class CosineDistance extends Distance {
public double calcDistance(Vector vector1, Vector vector2, double norm1,
double norm2) {
return 1.0 - vector1.innerProduct(vector2) / norm1 / norm2;
}
}
/**
* Class for caculating Jaccard distance between vectors
*/
@SuppressWarnings("unused")
private class JaccardDistance extends Distance {
public double calcDistance(Vector vector1, Vector vector2, double norm1,
double norm2) {
double innerProduct = vector1.innerProduct(vector2);
return Math.abs(1.0 - innerProduct / (norm1 + norm2 - innerProduct));
}
}
/**
* Class for a clusterer which clusters the documents within a DocumentList
* into a ClusterList
*/
private abstract class Clusterer {
// distance measure to use when evaluating distance between documents
Distance distance;
public abstract ClusterList cluster(DocumentList documentList);
}
/**
* An k means clustering implementation of the Clusterer class
*/
private class KMeansClusterer extends Clusterer {
// threshold used to determine number of clusters k
private final double clusteringThreshold;
// number of iterations to use in k means clustering
private final int clusteringIterations;
public KMeansClusterer(Distance distance, double clusteringThreshold,
int clusteringIterations) {
this.distance = distance;
this.clusteringThreshold = clusteringThreshold;
this.clusteringIterations = clusteringIterations;
}
/**
* Run k means clustering on documentList. Number of clusters k is set to
* the lowest value that ensures the intracluster to intercluster distance
* ratio is above clusteringThreshold
*
* @return ClusterList containing the clusters
*/
public ClusterList cluster(DocumentList documentList) {
ClusterList clusterList = null;
for (int k = 1; k <= documentList.size(); k++) {
clusterList = runKMeansClustering(documentList, k);
if (clusterList.calcIntraInterDistanceRatio(distance) < clusteringThreshold) {
break;
}
}
return clusterList;
}
/**
* Run k means clustering on documentList for a fixed number of clusters k
*
* @param documentList
* documents to be clustered
* @param k
* target number of clusters
* @return ClusterList containing the clusters
*/
private ClusterList runKMeansClustering(DocumentList documentList, int k) {
ClusterList clusterList = new ClusterList(k);
documentList.clearIsAllocated();
// create 1st cluster using a random document
Random rnd = new Random();
int rndDocIndex = rnd.nextInt(k);
Cluster initialCluster = new Cluster(documentList.get(rndDocIndex));
clusterList.add(initialCluster);
// create k-1 more clusters
while (clusterList.size() < k) {
// create new cluster containing furthest doc from existing clusters
Document furthestDocument =
clusterList.findFurthestDocument(distance, documentList);
Cluster nextCluster = new Cluster(furthestDocument);
clusterList.add(nextCluster);
}
// add remaining documents to one of the k existing clusters
for (int iter = 0; iter < clusteringIterations; iter++) {
for (Document document : documentList) {
if (!document.isAllocated()) {
Cluster nearestCluster =
clusterList.findNearestCluster(distance, document);
nearestCluster.add(document);
}
}
// update centroids and centroidNorms
clusterList.updateCentroids();
// prepare for reallocation in next iteration
if (iter < clusteringIterations - 1) {
documentList.clearIsAllocated();
clusterList.emptyClusters();
}
}
return clusterList;
}
}
</code></pre>
<p>Here's an example of a typical clustering:</p>
<pre><code>public static void main(String[] args) throws IOException {
String input;
if (args.length > 0) {
BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
input = in.readLine();
} else {
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
}
DocumentList documentList = new DocumentList(input);
Encoder encoder = new TfIdfEncoder(10000);
encoder.encode(documentList);
Distance distance = new CosineDistance();
Clusterer clusterer = new KMeansClusterer(distance, 0.4, 3);
ClusterList clusterList = clusterer.cluster(documentList);
System.out.println(clusterList.toString());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T05:54:53.633",
"Id": "12589",
"Score": "0",
"body": "possible duplicate of [General Java Style Suggestions - Classification Problem from CodeSprint 2012 (Updated)](http://codereview.stackexchange.com/questions/7941/general-java-style-suggestions-classification-problem-from-codesprint-2012-up)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T07:22:54.203",
"Id": "12592",
"Score": "0",
"body": "This may look similar at the top due to the Vector class but it's very much a different program and I think that different issues come into play."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T07:40:13.920",
"Id": "12593",
"Score": "2",
"body": "@cendrillon Maybe you should factor `Vector` out into its own class (which you could ask about separately) to avoid duplication between the questions. As far as I can tell it shouldn't be a nested class anyway (style tip 1: classes that don't need to share state, should not be defined as (non-static) nested classes)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T16:56:47.677",
"Id": "12627",
"Score": "0",
"body": "Thanks Sepp. The single class is a bit of a quirk of the competition (CodeSprint). They require you to cut and paste a single class which contains the solution into their site which then goes off and runs unit tests to see if the code is valid. Anyway, I'll take the Vector class out here to avoid the duplication."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ol>\n<li><p>This comment is unnecessary:</p>\n\n<pre><code>// document title, contents and ID\nprivate final String title;\nprivate final String contents;\nprivate final long id;\n</code></pre>\n\n<p>Since they are inside the <code>Document</code> class, it's obvious that the <code>title</code> is a title of a document, and so on.</p></li>\n<li><pre><code>// whether document has been allocated to a cluster\nprivate boolean allocated;\n</code></pre>\n\n<p>Here I'd rename the variable to <code>allocatedToCluster</code> and remove the comment. It would make the code more readable since you don't have to check the declaration to figure out what it is allocated to.</p></li>\n<li><p>For the same reason as above,</p>\n\n<ul>\n<li><code>histogram</code> should be <code>wordHistogram</code>,</li>\n<li><code>vector</code> should be <code>encodedDocumentVector</code>,</li>\n</ul>\n\n<p>etc.</p></li>\n<li><p>Input check is missing in the constructor:</p>\n\n<pre><code>public Document(long id, String title, String contents) {\n this.id = id;\n this.title = title;\n this.contents = contents;\n}\n</code></pre>\n\n<p>Does it make sense to have a <code>Document</code> with <code>null</code> or empty String <code>title</code> or <code>contents</code>? If not, check it and throw an <code>IllegalArgumentException</code>. (<em>Effective Java, Second Edition</em>, <em>Item 38: Check parameters for validity</em>)</p></li>\n<li><p></p>\n\n<pre><code>if (id > document.getId()) {\n return 1;\n} else if (id < document.getId()) {\n return -1;\n} else {\n return 0;\n}\n</code></pre>\n\n<p>Instead of this code I'd use <a href=\"http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/ObjectUtils.html#compare%28java.lang.Comparable,%20java.lang.Comparable%29\" rel=\"nofollow\"><code>ObjectUtils.compare</code></a> from <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow\">Apache Commons Lang</a>.</p></li>\n<li><pre><code>class DocumentList extends ArrayList<Document> \n</code></pre>\n\n<p>Check <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em>.</p></li>\n<li><p>Sometimes comments should be method names:</p>\n\n<pre><code>// add remaining documents to one of the k existing clusters\nfor (int iter = 0; iter < clusteringIterations; iter++) {\n</code></pre>\n\n<p>Create an <code>addRemainingDocuments...</code> method and move the <code>for</code> loop in it instead of the comment.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-16T22:54:46.703",
"Id": "9065",
"ParentId": "7942",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "9065",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T00:29:09.727",
"Id": "7942",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"clustering"
],
"Title": "Document clustering / NLP"
}
|
7942
|
<p>I have the follow function:</p>
<pre><code>Download.prototype.fundamentals = function(exchanges, cb){
if (!(exchange = exchanges.pop())) return
var that = this;
this.login(function(err){
if (err) return cb(true, exchange.code)
var path = util.format(that.eoddata.fundamentals['path'], that.token, exchange.code)
that.get(that.eoddata.fundamentals['host'], path, function(err, data){
if (err) return cb(true, exchange.code)
that.xml(data, function(err, data){
if (err || data['@'].Message != 'Success') return cb(true, exchange.code)
var stocks = data['FUNDAMENTALS']['FUNDAMENTAL']
that.insert(stocks, exchange, function(){
cb(false, exchange.code)
})
that.fundamentals(exchanges, cb)
})
})
})
}
</code></pre>
<p>I think it easy to understand, I <code>pop()</code> an element to a list and then do other operations, and then recall the function to <code>pop()</code> another element.</p>
<p>I have a doubt regarding the writing of the function, now it works, but it does not seem very optimized. Example: I do not like <code>var that = this</code>.</p>
<p>How could I rewrite it better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T23:24:01.077",
"Id": "12584",
"Score": "1",
"body": "This might be a better fit on [codereview.se]; I've flagged for moderator attention to migrate, we'll see if they agree you'll do better there. (You can flag too, if you want it higher up the moderator queue.)"
}
] |
[
{
"body": "<p>Firstly, you are missing a <code>var exchange;</code> in your function.</p>\n\n<p>Heavily nested callbacks are no fun for anyone. I would consider using the async library to try to simplify the callbacks.</p>\n\n<p><a href=\"https://github.com/caolan/async#waterfall\" rel=\"nofollow\">https://github.com/caolan/async#waterfall</a></p>\n\n<p>Something like this. The callbacks passed to waterfall are called in series, and any arguments passed to each <code>callback</code> function after the <code>err</code> argument, are passed as the first parameters of the next function.</p>\n\n<p><code>var that = this</code> is just something you kind of have to get used to. In some cases you can avoid it by using various methods to bind the value of 'this' to the proper value.</p>\n\n<pre><code>Download.prototype.fundamentals = function(exchanges, cb) {\n\n var that = this,\n exchange = exchanges.pop();\n\n if (!exchange) return;\n\n async.waterfall([\n function(callback) {\n that.login(callback);\n },\n function(callback) {\n var path = util.format(that.eoddata.fundamentals['path'], that.token, exchange.code)\n that.get(that.eoddata.fundamentals['host'], path, callback);\n },\n function(data, callback) {\n that.xml(data, function(err, xmldata) {\n err = err || xmldata['@'].Message != 'Success';\n callback(err, xmldata);\n });\n },\n function(xmldata, callback) {\n var stocks = xmldata['FUNDAMENTALS']['FUNDAMENTAL']\n that.insert(stocks, exchange, callback);\n that.fundamentals(exchanges, cb);\n }\n ], function(err) {\n cb(err, exchange.code);\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T00:36:52.000",
"Id": "7944",
"ParentId": "7943",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T23:17:56.483",
"Id": "7943",
"Score": "2",
"Tags": [
"javascript",
"optimization",
"node.js"
],
"Title": "Optimize Node.js function"
}
|
7943
|
<p>I have a package called <code>pkg_crypto</code>.</p>
<p>My select looks like this:</p>
<pre><code>SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM MYTABLE
ORDER BY "SEQ" DESC
</code></pre>
<p>This takes about 3 seconds for a few thousand records. (Average of 10 runs is 3.032s.)</p>
<p>Now, if I change it to either of the following, the query completes in about 0.2 seconds (average of 10 runs is 0.203s):</p>
<pre><code>SELECT "SEQ", "NAME", "TEL"
FROM MYTABLE
ORDER BY "SEQ" DESC
SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM MYTABLE
</code></pre>
<p>What seems to be happening is that if I use the <code>decrypt</code> and <code>order by</code> on the same command, it will re-sort the records and ignore the index that exists on "SEQ". </p>
<p>I suspect this may be a problem with the implementation of the <code>pkg_crypto</code> package that I am using. Its code is as follows:</p>
<pre><code>CREATE OR REPLACE PACKAGE PKG_CRYPTO AS
FUNCTION encrypt (
input_string IN VARCHAR2 ,
key_data IN VARCHAR2 := 'DEFDB'
) RETURN RAW;
FUNCTION decrypt (
input_string IN VARCHAR2 ,
key_data IN VARCHAR2 := 'DEFDB'
) RETURN VARCHAR2;
END PKG_CRYPTO;PACKAGE BODY pkg_crypto
IS
-- .. .... error code . message . .. .. .. ...
SQLERRMSG VARCHAR2(255);
SQLERRCDE NUMBER;
-- ... .. .. key_data . .... .. .. default . 12345678 . ....
FUNCTION encrypt (input_string IN VARCHAR2 , key_data IN VARCHAR2 := 'DEFDB')
RETURN RAW
IS
key_data_raw RAW(2000);
converted_raw RAW(2000);
encrypted_raw RAW(2000);
BEGIN
-- ... data . .... .. RAW . .....
converted_raw := UTL_I18N.STRING_TO_RAW(input_string, 'AL32UTF8');
key_data_raw := UTL_I18N.STRING_TO_RAW(key_data, 'AL32UTF8');
-- DBMS_CRYPTO.ENCRYPT . ... .. encrypted_raw . ...
encrypted_raw :=
DBMS_CRYPTO.ENCRYPT(
src => converted_raw ,
-- typ ... .... ... ..... ... . ...
--., key value bype . . ... .... ...
typ => DBMS_CRYPTO.DES_CBC_PKCS5 ,
key => key_data_raw ,
iv => NULL);
RETURN encrypted_raw;
END encrypt;
FUNCTION decrypt (input_string IN VARCHAR2 , key_data IN VARCHAR2 := 'DEFDB')
RETURN VARCHAR2
IS
converted_string VARCHAR2(2000);
key_data_raw RAW(2000);
decrypted_raw VARCHAR2(2000);
BEGIN
key_data_raw := UTL_I18N.STRING_TO_RAW(key_data, 'AL32UTF8');
decrypted_raw :=
DBMS_CRYPTO.DECRYPT(
src => input_string ,
typ => DBMS_CRYPTO.DES_CBC_PKCS5 ,
key => key_data_raw ,
iv => NULL);
-- DBMS_CRYPTO.DECRYPT .. .. .. .... raw data . varchar2 . .... .!
converted_string := UTL_I18N.RAW_TO_CHAR(decrypted_raw, 'AL32UTF8');
RETURN converted_string;
END decrypt ;
END pkg_crypto;
</code></pre>
<p>I've also attempted changing the query around a bit, but it hasn't been fruitful: the following take the same 3 seconds:</p>
<pre><code>SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM
(
SELECT "SEQ", "NAME", "TEL" FROM MYTABLE ORDER BY "SEQ" DESC
)
</code></pre>
<p>and</p>
<pre><code>SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM
(
SELECT "SEQ", "NAME", "TEL" FROM MYTABLE
)
ORDER BY "SEQ" DESC
</code></pre>
|
[] |
[
{
"body": "<p>have you tried this one?</p>\n\n<pre><code>SELECT MYTABLE_ALIAS.\"SEQ\", MYTABLE_ALIAS.\"NAME\", MYTABLE_ALIAS.\"TEL\"\nFROM (\n SELECT \"SEQ\", pkg_crypto.decrypt(\"NAME\", 'secret') NAME, pkg_crypto.decrypt(\"TEL\", 'secret') TEL\n FROM MYTABLE) MYTABLE_ALIAS\nORDER BY \"SEQ\" DESC\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T19:55:38.380",
"Id": "8289",
"ParentId": "7946",
"Score": "0"
}
},
{
"body": "<p>I've found that the reason that decryption xor sorting is fast, but decryption and sorting is slow:</p>\n\n<ul>\n<li>Decryption will only grab the first 100 or so records, decrypt them, and display them. Fast.</li>\n<li>Sorting will grab the first 100 or so records (utilizing the pk index) and display them. Fast.</li>\n<li>Decryption and sorting will force a table scan, resulting in decrypting several thousand records, and then sorting them all. </li>\n</ul>\n\n<p>In other words, the \"fast\" queries are only fast because they're doing very little work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T20:47:12.813",
"Id": "8291",
"ParentId": "7946",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8291",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T03:49:59.177",
"Id": "7946",
"Score": "3",
"Tags": [
"performance",
"sql",
"oracle",
"plsql"
],
"Title": "Oracle PL/SQL decryption function breaking index?"
}
|
7946
|
<p>In a custom Ant task, I have the following constants:</p>
<pre><code>private static final String _REVISION = ".revision";
private static final String _CODEBASE_INFO = ".codebase";
private static final String _DIFF = ".diff";
private static final String _TYPE_GIT = "git";
private static final String _TYPE_SVN = "svn";
private static final String[] _COMMAND_REV_GIT =
{"git", "rev-parse", "HEAD"};
private static final String[] _COMMAND_REV_SVN =
{"svn", "info"};
private static final String[][] _COMMAND_CODEBASEINFO_GIT = {
{"git", "branch", "-v"},
{"git", "remote", "-v"},
{"git", "log", "--max-count=1"},
{"git", "status"}};
private static final String[][] _COMMAND_CODEBASEINFO_SVN = {
_COMMAND_REV_SVN,
{"svn", "status"}};
private static final String[][] _COMMAND_DIFF_GIT = {
{"git", "diff", "HEAD"},
{"git", "diff", "HEAD", "--no-prefix"}};
private static final String[][] _COMMAND_DIFF_SVN = {
{"svn", "diff"}};
private static final Map<String, Object> _COMMANDS;
static {
Map<String, Object> map = new HashMap<>();
map.put(_TYPE_GIT + _REVISION, _COMMAND_REV_GIT);
map.put(_TYPE_SVN + _REVISION, _COMMAND_REV_SVN);
map.put(_TYPE_GIT + _DIFF, _COMMAND_DIFF_GIT);
map.put(_TYPE_SVN + _DIFF, _COMMAND_DIFF_SVN);
map.put(_TYPE_GIT + _CODEBASE_INFO, _COMMAND_CODEBASEINFO_GIT);
map.put(_TYPE_SVN + _CODEBASE_INFO, _COMMAND_CODEBASEINFO_SVN);
_COMMANDS = Collections.unmodifiableMap(map);
}
</code></pre>
<p>What the task should do is to run commands according to a given version control type. For example if I give it <code>git</code> then it will run commands in <code>_COMMAND_REV_GIT</code>, <code>_COMMAND_CODEBASEINFO_GIT</code> and <code>_COMMAND_DIFF_GIT</code>. </p>
<p>The reason I separate them into three constants is that the outputs of them have to be handled in different ways.</p>
<p><strong>The reason I use a map is that I don't want to use a lot of "if" or "switch-case" in my code.</strong> In the map there are keys like <code>git.revision</code>, <code>git.codebase</code>, etc. If <code>git</code> is given when running this task, <code>_COMMAND_REV_GIT</code> will be fetched from the map using the key <code>git.revision</code> in the method handling running the revision command:</p>
<pre><code>String[] command = _COMMANDS.get(_givenType + _REVISION);
</code></pre>
<p>But these constants looks really complicated, and I think the types of version control should be <code>Enum</code> rather than <code>String</code>, so is the suffixes indicating the types of the commands. <strong>So how should I modify these codes to make it clear, safe and elegant?</strong> </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T07:56:03.910",
"Id": "12594",
"Score": "1",
"body": "Would you find your code more or less readable if all of these values were inlined? That is, if there were no constants other than the map itself, and you just use the String literals everywhere. I'm not saying this is necessarily a good idea; just wondering whether you'd find the result more readable, and what reasons you had for using constants in the first place. Otherwise, using an Enum for the vc type and another Enum for the suffix sounds like a great idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:31:01.423",
"Id": "12606",
"Score": "0",
"body": "What I want to achieve are: 1, reduce the number of if or switch-case statements, and currently I am using a static map to make it possible; 2, avoid using Strings for limited possiblities (as few as two or three). Those command arrays never changes during runtime so they are defined as constants. Directly defining them inline may not be as readable. What I concern is not a problem about \"readable\", but a better way, because I think the strings and the static map are ugly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:37:41.917",
"Id": "12609",
"Score": "0",
"body": "Yeah, I see. I've just +1'ed palacsint's answer anyway - he/she has got it exactly right."
}
] |
[
{
"body": "<p>You should create an <code>ScmCommands</code> interface like this:</p>\n\n<pre><code>public interface ScmCommands {\n public String[] getRevisionCommand();\n\n public List<String[]> getDiffCommand();\n\n public List<String[]> getCodebaseInfoCommand();\n}\n</code></pre>\n\n<p>and two implementations: <code>SvnCommands</code>, <code>GitCommands</code>.</p>\n\n<p>It would improve type safety a lot. (With a <code>Map<String, Object></code> you usually have to cast the values which is error-prone). Furthermore, it eliminates the magic constants. It's easy to call <code>Map.get()</code> with a mistyped key. With the interface the compiler warns you if the method name is wrong.</p>\n\n<hr>\n\n<p>Edit: I've changed the return types. Sample implementations are the following:</p>\n\n<pre><code>public class GitCommands implements ScmCommands {\n\n private static final String GIT_COMMAND = \"git\";\n\n public GitCommands() {\n }\n\n @Override\n public String[] getRevisionCommand() {\n return new String[] { GIT_COMMAND, \"rev-parse\", \"HEAD\" };\n }\n\n @Override\n public List<String[]> getDiffCommand() {\n final List<String[]> result = new ArrayList<String[]>();\n result.add(new String[] { GIT_COMMAND, \"diff\", \"HEAD\" });\n result.add(new String[] { GIT_COMMAND, \"diff\", \"HEAD\", \"--no-prefix\" });\n return result;\n }\n\n @Override\n public List<String[]> getCodebaseInfoCommand() {\n final List<String[]> result = new ArrayList<String[]>();\n result.add(new String[] { GIT_COMMAND, \"branch\", \"-v\" });\n result.add(new String[] { GIT_COMMAND, \"remote\", \"-v\" });\n result.add(new String[] { GIT_COMMAND, \"log\", \"--max-count=1\" });\n result.add(new String[] { GIT_COMMAND, \"status\" });\n return result;\n }\n}\n</code></pre>\n\n\n\n<pre><code>public class SvnCommands implements ScmCommands {\n\n private static final String SVN_COMMAND = \"svn\";\n\n public SvnCommands() {\n }\n\n @Override\n public String[] getRevisionCommand() {\n return new String[] { SVN_COMMAND, \"info\" };\n }\n\n @Override\n public List<String[]> getDiffCommand() {\n final List<String[]> result = new ArrayList<String[]>();\n result.add(new String[] {SVN_COMMAND, \"diff\"});\n return result;\n }\n\n @Override\n public List<String[]> getCodebaseInfoCommand() {\n final List<String[]> result = new ArrayList<String[]>();\n result.add(new String[] { SVN_COMMAND, \"status\" });\n return result;\n }\n\n}\n</code></pre>\n\n<p>It fits well to <code>ProcessBuilder</code> but I'd consider extracting out all SCM related methods to an interface (for example <code>Scm</code>), and move the code to SCM-specific classes which implement the <code>Scm</code> interface, like <code>GitScm</code>, <code>SubversionScm</code> etc. Calling command line executables doesn't <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a> good, maybe it would be better to use native Subversion and Git Java libraries.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:42:04.730",
"Id": "12610",
"Score": "0",
"body": "+1 It looks nice! But within the implementations, what should I use to store the commands? Please note that I have one command (with its params) for revision, two commands for git diff while one for svn diff, and four commands for git's codebase info while two for svn's. And since I am using ProcessBuilder to execute the commands, they should (at last) be passed to the ProcessBuilder in an array or a list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T20:47:12.437",
"Id": "12631",
"Score": "0",
"body": "Why do you have two or more command to the same task? (Check the update too :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T01:49:21.180",
"Id": "12645",
"Score": "0",
"body": "For things like codebase info, we want to collect the necessary information of the version control. We may have to run multiple commands to do that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:23:16.950",
"Id": "7958",
"ParentId": "7949",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "7958",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T04:14:11.500",
"Id": "7949",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"constants"
],
"Title": "Looking for a better way to define and use constants"
}
|
7949
|
<p>I'm newish to obj-c and I have some code that works, but I'm thinking I may be leaking memory as I have two <code>retain</code> statements and no <code>release</code> statements.</p>
<p>In both cases if I remove the <code>retain</code> I get a bad access error on <code>[btPairedDevices count]</code></p>
<p>Am I doing this right or is there a better way?</p>
<pre><code>//===================================================================================================
- (id)init
{
self = [super init];
if (self) {
indexDeviceSearch = 0;
// Grab a list of paired devices
btPairedDevices = [IOBluetoothDevice pairedDevices];
[btPairedDevices retain];
}
return self;
}
//===================================================================================================
- (void) applicationDidFinishLaunching:(NSNotification *)notification
{
if(IOBluetoothValidateHardwareWithDescription(nil, nil) != kIOReturnSuccess)
{
[NSApp terminate:self];
}
NSLog(@"Application up an running");
// Start our timer looking for paired phones
timerDeviceSearch = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerDeviceSearchFired)
userInfo:nil
repeats:YES];
}
//===================================================================================================
- (void) timerDeviceSearchFired
{
// Check out the device
if (indexDeviceSearch < [btPairedDevices count])
{
IOBluetoothDevice *device = [btPairedDevices objectAtIndex:indexDeviceSearch];
if ([device deviceClassMajor] == kBluetoothDeviceClassMajorPhone)
{
// Found a phone
[self addNewDeviceIfAcceptable:device];
}
}
// Update the list of devices just in case the use
// paired something while we are running
btPairedDevices = [IOBluetoothDevice pairedDevices];
[btPairedDevices retain];
// Inc the index
indexDeviceSearch++;
if (indexDeviceSearch >= [btPairedDevices count])
indexDeviceSearch = 0;
}
//===========================================================================================================================
-(BOOL)addNewDeviceIfAcceptable:(IOBluetoothDevice*)device
{
NSEnumerator *enumerator;
IOBluetoothDevice *tmpDevice;
const BluetoothDeviceAddress *newDeviceAddress = [device getAddress];
// Allocate our array of monitored devices
if(!btMonitoredDevices)
{
btMonitoredDevices = [[NSMutableArray alloc] initWithCapacity:1];
if(!btMonitoredDevices)
return(FALSE);
[btMonitoredDevices retain];
}
// Walk the devices in the array.
enumerator = [btMonitoredDevices objectEnumerator];
if(enumerator)
{
const BluetoothDeviceAddress* tempAddress = NULL;
while((tmpDevice = [enumerator nextObject]))
{
tempAddress = [tmpDevice getAddress];
if(memcmp(newDeviceAddress, tempAddress, sizeof(BluetoothDeviceAddress)) == 0 )
{
// Already have it.
return(FALSE);
}
}
}
// Add new device to array
NSLog(@"Monitoring new device: %@", [device nameOrAddress]);
[btMonitoredDevices addObject:device];
// Return that we haven't seen it.
return(TRUE);
}
</code></pre>
|
[] |
[
{
"body": "<p>You should definitely be releasing both <code>btMonitoredDevices</code> and <code>btPairedDevices</code> in the <code>dealloc</code>. But it appears that this is your appDelegate so it matters little outside of correctness. I'd do it anyhow.</p>\n\n<p>You shouldn't need the <code>retain</code> on <code>btMonitoredDevices</code> since you're calling <code>alloc</code> on it. So you already have a <code>retain</code> count of one on it. By calling <code>retain</code> on it you actually have a <code>retain</code> count of two. </p>\n\n<p>So to sum up make sure you're releasing both in your <code>dealloc</code> and get rid of the <code>[btMonitedDecices retain];</code> and you should be good. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T15:12:39.283",
"Id": "7968",
"ParentId": "7952",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7968",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:43:04.947",
"Id": "7952",
"Score": "6",
"Tags": [
"objective-c"
],
"Title": "Is there a memory leak in here?"
}
|
7952
|
<p>Given:</p>
<pre><code>k = {'MASTER_HOST': '10.178.226.196', 'MASTER_PORT': 9999}
</code></pre>
<p>I want to flatten into the string:</p>
<pre><code>"MASTER_HOST='10.178.226.196', MASTER_PORT=9999"
</code></pre>
<p>This is the ugly way that I'm achieving this right now:</p>
<pre><code>result = []
for i,j in k.iteritems():
if isinstance(j, int):
result.append('%s=%d' % (i,j))
else:
result.append("%s='%s'" % (i,j))
', '.join(result)
</code></pre>
<p>I'm sure my developer colleagues are going to chastize me for this code. Surely there is a better way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:00:09.547",
"Id": "12600",
"Score": "0",
"body": "I don't think it's that bad, unless perhaps you also have Boolean values in your dict, because `isinstance(False, int)` returns `True`, so instead of `flag='False'`, you'd get `flag=0` (both of which are not optimal)."
}
] |
[
{
"body": "<p>For python 3.0+ (as @Serdalis suggested)</p>\n\n<pre><code>', '.join(\"{!s}={!r}\".format(key,val) for (key,val) in k.items())\n</code></pre>\n\n<p>Older versions:</p>\n\n<pre><code>', '.join(\"%s=%r\" % (key,val) for (key,val) in k.iteritems())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:53:40.223",
"Id": "12601",
"Score": "1",
"body": "Close but no cigar. I don't want quotes around 9999 for `MASTER_PORT` in the final result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:57:21.373",
"Id": "12602",
"Score": "1",
"body": "@BonAmi You're right. I replaced the second `%s` with `%r` to achieve that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:31:08.100",
"Id": "12607",
"Score": "0",
"body": "Instead of the `(key,val)` you could simply write `item`. iteritems returns tuples, and if you have multiple replacements in a string, you replace those using a tuple. You drop a second temporary variable and imo, you gain some readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:34:00.343",
"Id": "12608",
"Score": "0",
"body": "@Elmer That's interesting you say that, because I think novice pythoners might get more readability by using `(key,val)`, since it explains better what happens. But I guess that's a matter of taste. I do agree your way is more efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-18T06:35:11.730",
"Id": "192174",
"Score": "0",
"body": "I know it's a dictionary and .iteritems returns `(key, val)`, so unless you have better variable names that warrant creating temporary variables, like `(food_name, price)`, you can save yourself the characters. It's all about increasing your signal to noise, and `(k,v)` or `(key, value)` is mostly noise."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:50:03.863",
"Id": "7954",
"ParentId": "7953",
"Score": "33"
}
},
{
"body": "<p>If you want exactly that output format, your way is quite OK imo. Because you want your keys unquoted and your values quoted if they're strings and unquoted if they're just numbers, there is no 'easy way' I think</p>\n\n<p>In general str(k) will return a string like <code>{'MASTER_HOST': '10.178.226.196', 'MASTER_PORT': 9999}</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:54:15.603",
"Id": "7955",
"ParentId": "7953",
"Score": "1"
}
},
{
"body": "<p>Dor Shemer's method is very good, however since 3.0+ came out, pythoneque? language is moving towards:</p>\n\n<pre><code>', '.join(\"{!s}={!r}\".format(k,v) for (k,v) in k.items())\n</code></pre>\n\n<p>using <code>.format</code> instead of <code>% ()</code> to format a string.</p>\n\n<p>both will give the same result and are correct.</p>\n\n<p>I used <code>items</code> for python 3.0+, but for python 2.x use <code>iteritems</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:00:34.707",
"Id": "12603",
"Score": "0",
"body": "You're right. I keep thinking with python 2.6"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T20:18:57.007",
"Id": "292282",
"Score": "2",
"body": "new syntax 3.6: `f\"this is a string {variable}\"`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:58:44.917",
"Id": "7956",
"ParentId": "7953",
"Score": "9"
}
},
{
"body": "<p>For python 3.6+ you can use <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a>:</p>\n<pre><code>', '.join(f'{k}_{v}' for k, v in my_dict.items())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T00:38:52.000",
"Id": "505622",
"Score": "1",
"body": "Nice! Do you think you can improve the efficiency a little?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T23:41:19.277",
"Id": "256164",
"ParentId": "7953",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T08:47:59.230",
"Id": "7953",
"Score": "20",
"Tags": [
"python",
"strings"
],
"Title": "Flattening a dictionary into a string"
}
|
7953
|
<p>Is this a good way to design a class so I can prevent values being changed/ the state must remain as it was when it was intantiated...</p>
<p>This code would be normally instantiated after a call from the database.</p>
<pre><code>public class InstructionWorkflow : IStageWorkflow
{
private readonly int _companyID;
public InstructionWorkflow(int instructionid, int progressid, int companyID, InstructionKeyInfoDTO keyInfo, InstructionStageProgress currentStage)
{
_companyID = companyID;
CurrentStage = currentStage;
KeyInfo = keyInfo;
ProgressID = progressid;
InstructionID = instructionid;
}
public int InstructionID { get; private set; }
public int ProgressID { get; private set; }
public InstructionKeyInfoDTO KeyInfo { get; private set; }
private InstructionStageProgress CurrentStage { get; set; }
public bool IsMyCompanyOwnerOfStage
{
get { return CurrentStage.StageOwnerID == _companyID; }
}
/// <summary>
/// #1 stage cannot be ticked as completed
/// #2 stage must be initiated by the user, this will mean stage is open
/// This is the best way so we can code against opening and closing a stage elsewhere,
/// that will have a lot of rules on its own
/// #3 stage must be owned by loggedon users company
/// </summary>
public bool IsStageOpenForUpdates
{
get { return IsMyCompanyOwnerOfStage && !CurrentStage.IsCompleted && CurrentStage.DateInitiated != null; }
}
public int? StageOwnerID
{
get { return CurrentStage.StageOwnerID; }
}
}
public interface IStageWorkflow
{
bool IsMyCompanyOwnerOfStage { get; }
bool IsStageOpenForUpdates { get; }
int? StageOwnerID { get; }
int ProgressID { get; }
int InstructionID { get; }
InstructionKeyInfoDTO KeyInfo { get; }
}
</code></pre>
<p><strong>Update</strong>: As per suggestions</p>
<pre><code>public class InstructionWorkflow : IStageWorkflow
{
private readonly IUserSession _userSession;
private readonly IReadOnlySession _readOnlySession;
public InstructionWorkflow(int instructionid, int progressid, IUserSession userSession, IReadOnlySession readOnlySession)
{
_userSession = userSession;
_readOnlySession = readOnlySession;
ProgressID = progressid;
InstructionID = instructionid;
CurrentStage = ResolveWorkflow();
}
public int InstructionID { get; private set; }
public int ProgressID { get; private set; }
public InstructionKeyInfoDTO KeyInfo { get; private set; }
private InstructionStageProgress CurrentStage { get; set; }
public bool MyCompanyIsOwnerOfStage
{
get { return CurrentStage.StageOwnerID == _userSession.MyProfile.CompanyID; }
}
/* NOTES:
* #1 stage cannot be ticked as completed
* #2 stage must be initiated by the user, this will mean stage is open
* This is the best way so we can code against opening and closing a stage elsewhere,
* that will have a lot of rules on its own
* #3 stage must be owned by loggedon users company
*/
public bool StageIsOpenForUpdates
{
get { return MyCompanyIsOwnerOfStage && !CurrentStage.IsCompleted && CurrentStage.DateInitiated != null; }
}
public int? StageOwnerID
{
get { return CurrentStage.StageOwnerID; }
}
private InstructionStageProgress ResolveWorkflow()
{
var currentStage = _readOnlySession.Single<InstructionStageProgress>(
x => x.ProgressID == ProgressID && x.InstructionID == InstructionID);
if (currentStage == null)
throw new NoAccessException(string.Format("workflow stage progress not found for instruction #{0} and progressid#{1}",
InstructionID, ProgressID));
KeyInfo = null; //set here similar to currentstage above...
return currentStage;
}
}
</code></pre>
<p><em>Additional Info: Origincal IUserSession</em></p>
<pre><code>public interface IUserSession
{
void SetClientStore(string loginID, string identifier);
void Logout();
string LoginID { get; set; }
string CompanyIdentifier { get; set; }
UserProfile MyProfile { get; }
}
</code></pre>
<p>//new user session</p>
<pre><code>public interface IUserSession
{
void SetClientStore(string loginID, string identifier);
void Logout();
string LoginID { get; set; }
int UserID { get; set; }
RoleName Role { get; set; }
string CompanyIdentifier { get; set; }
int CompanyID { get; set; }
CompanyType CompanyType { get; set; }
string CompanyFriendlyName { get; set; }
PricePlanType PricePlan { get; set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>The way you're implementing a read-only object looks fine, except for <code>CurrentStage</code> being mutable. Are you sure you want it that way? It seems counter-intuitive with the rest of the class. Seeing as it is a private member anyway, why not make it <code>readonly</code> just like <code>_companyID</code>?</p>\n\n<p>Other comments:</p>\n\n<ul>\n<li>You are not checking for whether <code>currentStage</code> and <code>keyInfo</code> are <code>null</code> when you read them. It may be better to fail early if you detect this (even if you're sure that it will never happen, a <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.assert.aspx\" rel=\"nofollow\"><code>Debug.Assert</code></a> call could be compiled out in release mode and provides valuable feedback).</li>\n<li>The way you're providing <code>KeyInfo</code> to the rest of the world is prone to breaking the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">Law of Demeter</a>. This may be the least bad solution, but are you sure you shouldn't provide some wrappers around it just like you did for <code>CurrentStage</code>?</li>\n<li><s>Does implementing the public members as properties instead of <code>readonly</code> values really win you anything? The latter would make sure you don't accidentally change it from within the class; on the other hand, the former could (maybe?) work better with reflection.</s> After looking into this further, a property is indeed preferrable; however, perhaps give it an explicit <code>readonly</code> backing variable and make it <code>get</code>-only?</li>\n<li>The properties <code>IsMyCompanyOwnerOfStage</code> and <code>IsStageOpenForUpdates</code> both begin with a verb; this sounds off for something that acts like a data member, and I would advise <code>MyCompanyIsOwnerOfStage</code> and <code>StageIsOpenForUpdates</code> respectively.</li>\n<li>I think your class would be readable if you grouped member variables and automatic properties together; as things are, you have to jump around to see what's declared how.</li>\n<li>In my experience, having such long summaries of members leads to unreadable mouseover text; take a look at how much you really gain from putting it all there as opposed to in a <code>remarks</code> (or similar) section.</li>\n</ul>\n\n<p>Comments on updated code:</p>\n\n<ul>\n<li>I like the way things have been split out to <code>ResolveWorkflow</code>, although I would still advise checking <code>userSession</code> and <code>readonlySession</code> for <code>null</code>.</li>\n<li>I am iffy about <code>_userSession.MyProfile.CompanyId</code> in <code>MyCompanyIsOwnerOfStage</code> -- are you sure this is a valid violation of the aforementioned Law of Demeter? Should an <code>IUserSession</code> really not provide a <code>CompanyID</code> field itself?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:30:57.993",
"Id": "12615",
"Score": "0",
"body": "Thanks for your advise, I have updated my quote to reflect more clearly what I want to do, I have updated with some of your suggestions, could you please comment? Should I check if IUserSession is null + IReadOnlySession?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:47:25.937",
"Id": "12616",
"Score": "0",
"body": "@Haroon: Edited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:54:01.420",
"Id": "12618",
"Score": "0",
"body": "I have added a Guard.ArgumentNotNull(userSession, \"usersession\"); inside my constructor for both user session + readonlysession"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:58:19.367",
"Id": "12619",
"Score": "0",
"body": "Updated to show my IUserSession, I get what you are saying, but I dont understand why I did that... Maybe it was because this class was being used everywhere else, there is no real reason to be honest with you, it is read only anyway... and it should only ever be accessed by an interface..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:14:17.520",
"Id": "7960",
"ParentId": "7959",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7960",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T09:52:28.897",
"Id": "7959",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"classes"
],
"Title": "Best way to Structure class + Instantiation"
}
|
7959
|
<p>I need a bit of help on if I have coded this class correctly.</p>
<p>I want to handle the setting of client cookie/client store.</p>
<pre><code>public class UserSession : IUserSession
{
private readonly IReadOnlySession _repo;
public UserSession(IReadOnlySession repo)
{
_repo = repo;
}
private string _loginId;
public string LoginID
{
get { return HttpContext.Current.User.Identity.Name; }
set { _loginId = value; }
}
private string _companyIdentifier;
public string CompanyIdentifier
{
get { return AuthenticateCookie.GetCompanyIdentifierFromTicket(LoginID); }
set { _companyIdentifier = value; }
}
/// <summary>
/// when the client store is set, this means the user has been changed
/// </summary>
/// <param name="loginId"></param>
/// <param name="identifier"></param>
public void SetClientStore(string loginId, string identifier)
{
MyProfile = null;
AuthenticateCookie.AddDetailsToCookie(loginId, identifier);
LoginID = loginId;
CompanyIdentifier = identifier;
}
public void Logout()
{
// we could throw an exception here?
MyProfile = null;
HttpContext.Current.User = null;
FormsAuthentication.SignOut();
//clear cookie values too?
}
private UserProfile _myprofile;
public UserProfile MyProfile
{
get { return SetupProfile(); }
private set { _myprofile = value; }
}
private UserProfile SetupProfile()
{
if (_myprofile == null)
{
if (string.IsNullOrEmpty(LoginID) || string.IsNullOrEmpty(CompanyIdentifier))
{
Logout();
return null;
}
//call repo to get object...
_myprofile = _repo.All<User>()
.Where(x => x.Login == LoginID)
.Join(_repo.All<Profile>().Where(x => x.IsActive),
x => x.UserID, y => y.UserID,
(x, y) =>
new
{
x.UserID, y.CompanyID, y.RoleID,
})
.Join(_repo.All<Company>()
.Where(x => x.IsActive && x.Identifier == CompanyIdentifier),
x => x.CompanyID, y => y.CompanyID,
(x, y) =>
new
{
x.UserID, y.CompanyID, x.RoleID, x.IsSurveyor,
CompanyFriendlyName = y.Name,
CompanyType = y.Type
})
.Join(_repo.All<Role>(), x => x.RoleID, y => y.RoleID,
(x, y) =>
new
{
x.UserID, x.CompanyID, y.RoleName, x.CompanyFriendlyName, x.CompanyType
})
.Join(_repo.All<Subscription>(),
x => x.CompanyID, y => y.CompanyID,
(x, y) =>
new UserProfile
{
UserID = x.UserID,
CompanyID = x.CompanyID,
Role = x.RoleName.Convert<RoleName>(),
CompanyFriendlyName = x.CompanyFriendlyName,
LoginID = LoginID,
Identifier = CompanyIdentifier,
PricePlan = y.Name.Convert<PricePlanType>(),
CompanyType = x.CompanyType.Convert<CompanyType>()
})
.SingleOrDefault();
if (_myprofile == null)
Logout();
}
return _myprofile;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T13:55:25.117",
"Id": "12620",
"Score": "0",
"body": "The Linq in SetupProfile is very confusing to understand as it is. I would really rather see that written in query syntax. Joins and groups using method syntax never make for readable code!"
}
] |
[
{
"body": "<p>It's great that you separated the ASP.NET specific implementation from the interface. Two things to watch:</p>\n\n<ol>\n<li>Don't forget to call <code>Session.Abandon();Session.Clear();</code> in the <code>Logout</code> method.</li>\n<li><code>SetupProfile</code> contains a lot of code. This seems like business logic to me. Try to extract this code to its own class. An <code>IUserService</code> for instance. Or perhaps explicitly define <a href=\"http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92\" rel=\"nofollow\">Query Objects</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T13:21:31.233",
"Id": "7999",
"ParentId": "7961",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T11:20:58.317",
"Id": "7961",
"Score": "3",
"Tags": [
"c#",
"asp.net"
],
"Title": "Creating an IUserSession that is used throughout my code"
}
|
7961
|
<p>I'm writing some code to perform some simple form validation and I would like to display error messages inside the actual relevant textarea by means of a text fadeout/fadein effect.</p>
<p>To achieve this I am using jQquery UI to do the following:</p>
<ul>
<li>Step 1: Animate the color to match the background colour</li>
<li>Step 2: Modify the text to show the error message then fade it in</li>
<li>Step 3: Fade the error message out, change the text back to its
previous content</li>
<li>Step 4: Fade the text back in </li>
<li>Step 5: Finally, Focus the textarea and put the cursor at the
end</li>
</ul>
<p>This works fine, however to do this I have had to nest a lot of anonymous function which is something I really don't like to do.</p>
<p>Is there a better way of achieving the same effect?</p>
<pre><code>if (replyto == body) {
$textarea.prop("disabled", true).animate({ color: 'rgb(41, 41, 41)'},500, function(){
$textarea.text('Please enter your reply here')
.animate({ color: 'white'},500, function(){
$textarea.delay('1000')
.animate({ color: 'rgb(41, 41, 41)'},500, function(){
$textarea.text(body)
.animate({ color: '#a7a7a7'},500)
.prop("disabled", false)
.focus()
.putCursorAtEnd();
});
});
});
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>Pull it out to a function?</p>\n\n<pre><code>$.fn.textFadeSwap = function(newText, body, customColor) {\n var $this= $(this), \n transparentColor = $this.css('background-color') || 'transparent',\n originalColor = $this.css('color') || '#000',\n customColor = customColor || '#000';\n\n $this.animate({ color: originalColor, 500, function(){ \n $this.text(newText)\n .animate({ color: transparentColor},500, function(){\n $this.delay('1000')\n .animate({ color: originalColor},500, function(){\n $(this).text(body)\n .animate({ color: customColor},500)\n .focus()\n .putCursorAtEnd();\n });\n });\n }); \n}\n\n\nif (replyto == body) {\n $('textarea').textFadeSwap(\"Please enter your reply here\", body, '#a7a7a7')\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:31:55.810",
"Id": "12622",
"Score": "0",
"body": "Thanks for the quick answer kyle, great answer and a good suggestion, i'll definately do just that. Is there any way to achieve the effect withou the serious nesting however? Or would you say it doesn't matter and is the only way to achieve the effect?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:46:43.633",
"Id": "12623",
"Score": "0",
"body": "For what you're working with, the nesting about right... You can kind of hybrid it with the other answer here, if you want."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:26:16.460",
"Id": "7966",
"ParentId": "7965",
"Score": "5"
}
},
{
"body": "<p>You could create a function that will set up the animation of text or color and then just call it a few times to set up your animation:</p>\n\n<pre><code>$.fn.animateIt = function(color, text) {\n var that = $(this);\n if (text) {\n that.queue(function(next) {\n that.text(text);\n next();\n });\n }\n if (color) {\n that.animate({\n color: color\n }, 500);\n }\n return that;\n};\n\n$textarea.animateIt('rgb(41, 41, 41)')\n .animateIt('#FFF', 'Please enter your reply here')\n .delay('1000')\n .animateIt('rgb(41, 41, 41)')\n .animateIt('#a7a7a7', body)\n .queue(function(next) {\n $textarea.focus().putCursorAtEnd();\n next();\n });\n</code></pre>\n\n<p>Gets rid of the nested functions.</p>\n\n<p><a href=\"http://jsfiddle.net/petersendidit/LYsQM/1/\">http://jsfiddle.net/petersendidit/LYsQM/1/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:48:24.377",
"Id": "12624",
"Score": "0",
"body": "Thanks mate thats a great solution... I'm going to use a combination of both answers given. I'm going to leave Kyle with the 'answer' however as he beat you to it. Hope you're okay with that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T15:10:07.293",
"Id": "12625",
"Score": "1",
"body": "+1 - nesting anonymous functions should be on the top list of antipatterns on the first page of any jQuery tutorial."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:43:41.670",
"Id": "7967",
"ParentId": "7965",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "7966",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T14:07:41.080",
"Id": "7965",
"Score": "10",
"Tags": [
"javascript",
"jquery",
"animation",
"jquery-ui"
],
"Title": "Is there a better way to write this jQuery UI effect animation?"
}
|
7965
|
<p>I have inherited the Java function below, and it works the way it should, but you have to look at it for a minute to figure out exactly what is going on. Is there a more succinct or elegant way to encode this logic?</p>
<pre><code>private Float applyFactors(Float originalValue, Float localFactor, Float globalFactor){
if (globalFactor == null || globalFactor == 0){
if (localFactor == null || localFactor == 0){
return null;
} else {
return localFactor * originalValue;
}
} else {
if (localFactor == null || localFactor == 0){
return globalFactor * originalValue;
} else {
return localFactor * originalValue * globalFactor;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>What I like to do in this sort of complicated conditional situation is to do the comparisons upfront and give them names. This makes it easier to reason about the code, and doesn't have any drawback if the conditional expressions are cheap.</p>\n\n<p>I then go ahead and replace the conditional expressions with the named booleans, and it usually becomes more obvious how to simplify the code. Here's what I ended up with:</p>\n\n<pre><code>private Float applyFactors(Float originalValue, Float localFactor, Float globalFactor) {\n Float result = null;\n\n boolean hasGlobalFactor = ((globalFactor != null) && (globalFactor != 0));\n boolean hasLocalFactor = ((localFactor != null) && (localFactor != 0));\n\n if (hasGlobalFactor && hasLocalFactor) {\n result = localFactor * globalFactor * originalValue;\n }\n else if (hasGlobalFactor) {\n result = globalFactor * originalValue;\n }\n else if (hasLocalFactor) {\n result = localFactor * originalValue;\n }\n\n return result;\n}\n</code></pre>\n\n<p>This approach also makes the code more readable as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T21:03:45.407",
"Id": "12632",
"Score": "1",
"body": "+1. (I'd change the `else { return null; }` to `return null;`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T23:05:53.403",
"Id": "12641",
"Score": "0",
"body": "Is it safe to use != 0 when you are using Float objects? There may be a different Float object representing 0, so you should be using the ``equals`` method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T23:13:19.550",
"Id": "12642",
"Score": "0",
"body": "@luketorjussen That is a good point. I transposed the original code, but I don't have enough familiarity with Java to be able to answer that definitively. However, `equals` does seem like it would be the safer bet."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T19:39:38.883",
"Id": "7975",
"ParentId": "7972",
"Score": "2"
}
},
{
"body": "<p>I prefer to break up the logic into pieces, removing the repeated arithmetic. This is how I'd have done it:</p>\n\n<pre><code>private Boolean nullOrZero(Float value) {\n return value == null || value.equals(0);\n}\n\nprivate Float oneIfInvalid(Float value) {\n return nullOrZero(value) ? new Float(1) : value;\n}\n\nprivate Float applyFactors(Float originalValue, Float localFactor, Float globalFactor) {\n if(nullOrZero(globalFactor) && nullOrZero(localFactor)) {\n return null;\n }\n return oneIfInvalid(localFactor) * oneIfInvalid(globalFactor) * originalValue;\n}\n</code></pre>\n\n<p>There are more method calls, and <code>nullOrZero()</code> will be repeated once for each value when the first condition fails, but I believe improved readability is more important than premature micro optimization. </p>\n\n<p>Another thing becomes noticeable in this code, which in my opinion was not obvious in the other versions; <code>originalValue</code> is never checked for null or zero. (Whether or not this was your intent is another matter.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T07:07:12.697",
"Id": "7985",
"ParentId": "7972",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7975",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T17:21:45.910",
"Id": "7972",
"Score": "2",
"Tags": [
"java"
],
"Title": "applyFactors refactoring"
}
|
7972
|
<p>I was wondering if this was a decent way of handling this function. Please take a look.</p>
<pre><code>// Use Less Mixins from Theme Options to adjust Stylesheets before Parsing Less to CSS
add_filter( 'less_vars', 'wellies_less_vars', 10, 2 );
function wellies_less_vars( $vars, $handle ) {
//Necessary for UpTheme Framework
global $up_options;
//Grab Theme option and check if it's empty and default to color if it is.
$linkcolor = empty($up_options->linkcolor) ? '#08c' : $up_options->linkcolor;
$linkcolorhover = empty($up_options->linkcolorhover) ? '#03c' : $up_options->linkcolorhover;
$networknavstart = empty($up_options->networknavstartcolor) ? '#333' :$up_options->networknavstartcolor;
$networknavend = empty($up_options->networknavendcolor) ? '#222' :$up_options->networknavendcolor;
$sitenavstart = empty($up_options->sitenavstartcolor) ? '#333' :$up_options->sitenavstartcolor;
$sitenavend = empty($up_options->sitenavendcolor) ? '#222' :$up_options->sitenavendcolor;
//Set Less Mixins to Variables above
$vars = array(
'linkColor' => $linkcolor,
'linkColorHover' => $linkcolorhover,
'networkNavBarStart' => $networknavstart,
'networkNavBarEnd' => $networknavend,
'siteNavBarStart' => $sitenavstart,
'siteNavBarEnd' => $sitenavend,
);
return $vars;
}
//Enqueue Stylesheets if not on dashboard.
function wellies_css_loader() {
if ( ! is_admin() )
wp_enqueue_style('bootstrap', get_bloginfo('template_directory').'/library/css/lib/bootstrap.less', array(), '', 'screen, projection');
wp_enqueue_style('themes', get_bloginfo('template_directory').'/library/css/theme.less', array(), '', 'screen, projection');
}
add_action('wp', 'wellies_css_loader');
</code></pre>
<p>It is currently working but I don't want to have it slow down the site if I can optimize it somehow.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-29T16:27:27.630",
"Id": "13179",
"Score": "0",
"body": "Try to be more specific in your title and question. E.g Efficient how? I do not see any use of caching. Additionally there is a Wordpress stack exchange as well"
}
] |
[
{
"body": "<p>No, this can be written a lot easier. There is no need to create variables when you are not going to vary the value. It actually only makes things harder to read. Assuming you are using PHP 5.3+ consider this:</p>\n\n<pre><code>// It is odd that you aren't using $vars in your method.\n// I'll ignore that for now.\nfunction wellies_less_vars( $vars, $handle ) {\n\n //Necessary for UpTheme Framework\n // This is not nice, but I'll ignore that too. \n global $up_options;\n\n //Set Less Mixins to Variables above\n // Grab Theme option and check if it's set and use that, otherwise use a\n // default value.\n // Now there is beauty in the alignment IMO.\n return array(\n 'linkColor' => $up_options->linkcolor ?: '#08c',\n 'linkColorHover' => $up_options->linkcolorhover ?: '#03c',\n 'networkNavBarStart' => $up_options->networknavstartcolor ?: '#333',\n 'networkNavBarEnd' => $up_options->networknavendcolor ?: '#222',\n 'siteNavBarStart' => $up_options->sitenavstartcolor ?: '#333',\n 'siteNavBarEnd' => $up_options->sitenavendcolor ?: '#222');\n}\n</code></pre>\n\n<p>There is a small difference in functionality, but a large difference in readability. The <code>?:</code> uses the value on the left if it evaluates to true (generally a set variable except false), or the value on the right if it is not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T07:01:11.733",
"Id": "10523",
"ParentId": "7974",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T19:17:55.843",
"Id": "7974",
"Score": "4",
"Tags": [
"performance",
"css",
"php5"
],
"Title": "Repetitive wordpress PHP styling"
}
|
7974
|
<p>I have several lists of objects which are stored in different locations, based on what they are and who needs them - the system, or the user, for example. There are times where I am only given an ID and need to find the name, type, or description, but I would like a very succinct, efficient way to do so. Since I'm also trying to improve the quality of my code, I want to ensure I'm doing things the best way possible. </p>
<p>Is there a better way to do this? I first was passing in the object and using <code>instanceof</code>, but I thought this was a better way. </p>
<pre><code>/**
* This method searches all known types / locations to find the object name based on ID.
* @param whatClass The type of the object you are searching for
* @param id ID of the object for which you are searching.
* @return The string name or type. Returns null if no match is found.
*/
public static <T> String nameByID(Class<?> whatClass, int id) {
if (whatClass == ProjectCode.class) {
for (ProjectCode c : User.getInstance().getProjects()) {
if (c.getProjCdId() == id) {
return c.getProjNm();
}
}
} else if (whatClass == TransactionType.class) {
for (TransactionType type : Session.getInstance().getTransactionTypes()) {
if (type.getTransactionTypeId() == id) {
return type.getTransactionNm();
}
}
} else if (whatClass == CurrencyType.class) {
for (CurrencyType currencyType : Session.getInstance().getCurrencies()) {
if (currencyType.getCurrencyTypeId() == id) {
return currencyType.getCurrencyTypeNm();
}
}
}
// no matches found
return null;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T03:30:51.230",
"Id": "12646",
"Score": "0",
"body": "Off hand, I'd guess that instanceof may provide a more robust solution in the context of derived classes. Can you show the instanceof alternative and also give examples of how you would typically call the two different functions?"
}
] |
[
{
"body": "<p>It just doesn't <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smell</a> good. Maybe you should post more code. This kind of searches looks weird to me.</p>\n\n<p>Anyway, the <code>User</code> class should have a <code>getProjNameById(final int id)</code> method, the <code>Session</code> class should have <code>getTransactionNameByTransactionTypeId(final int id)</code> and <code>getCurrencyTypeNameByCurrencyTypeId(final int id)</code> methods as well. It would result higher cohesion and easier maintenance.</p>\n\n<p>Note that the Singleton pattern is an antipattern nowadays. (<a href=\"https://softwareengineering.stackexchange.com/questions/37249/the-singleton-pattern\">The Singleton Pattern</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T15:32:12.317",
"Id": "12675",
"Score": "0",
"body": "I agree this is a good approach, but I believe a generic approach results in a still more flexible and concise implementation of `nameById()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T15:55:38.890",
"Id": "12677",
"Score": "0",
"body": "I almost agree. I'd say `User` should have a `getProjectNameById(final int id)` method and `Session` should have `getTransactionNameByTransactionTypeId(final int id)` and `getCurrencyTypeNameByCurrencyTypeId(final int id)` methods. In general, avoid abbreviations; it is likely that your abbreviations will be meaningless gibberish to the next person to work on that code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T16:10:50.213",
"Id": "12678",
"Score": "0",
"body": "My first and original implementation DOES in fact have methods like this in the `Session` / `User` class, but I thought it would be better to have one method being called. Preferably, I wouldn't want to hard-code anything, but have everything determined dynamically..I'm just unsure how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T17:46:14.090",
"Id": "12682",
"Score": "0",
"body": "Thanks @DwB, I agree, I forgot this. I've updated the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T04:11:09.310",
"Id": "7981",
"ParentId": "7976",
"Score": "1"
}
},
{
"body": "<p>If you're going to hard-code conditions for each class you want to support, there isn't much point to using a generic type. You don't even reference <code>T</code> within the method body, so it isn't any different from:</p>\n\n<pre><code>private static String nameById(Class whatClass, int id) {\n if(ProjectCode.class == whatClass) {\n // ...\n } else if(TransactionType.class == whatClass) {\n // ...\n }\n else if(CurrencyType.class == whatClass) {\n // ...\n }\n return null;\n}\n</code></pre>\n\n<p>To write this method so it's reusable with a generic type, you'll need to also abstract both your methods for obtaining a collection, and your getters for obtaining instances' name and Id.</p>\n\n<p>e.g.</p>\n\n<ol>\n<li><p>Some <code>getObjects<T></code> method, called like <code>getObjects<TransactionType>()</code> instead of <code>getTransactionTypes()</code></p></li>\n<li><p>The ability to access object properties polymorphically, through some interface that requires each class to have <code>getId()</code> and <code>getName()</code> instead of separate methods such as <code>getTransactionTypeId()</code>, <code>getProjCdId()</code>, etc. </p></li>\n</ol>\n\n<p>Then your code could be rewritten to take advantage of a generic type parameter:</p>\n\n<pre><code>public static <T extends IInterfaceName> String nameByID(int id) {\n for (T obj : getObjects<T>()) {\n if(obj.getId().equals(id)) {\n return obj.getName();\n }\n }\n return null;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T07:53:02.780",
"Id": "7986",
"ParentId": "7976",
"Score": "2"
}
},
{
"body": "<p>Why would you ever combine all this functionality into one method? Each case does completely different things. The \"name\" that the method retrieves from the ID has completely different content based on what it's looking for. Having three methods with the following signatures makes much, much more sense to me:</p>\n\n<pre><code>public static String getProjectName(int id)\npublic static String getTransactionName(int id)\npublic static String getCurrencyName(int id)\n</code></pre>\n\n<p>If you <em>really</em> want to keep it all in one method for some reason, use an <code>enum</code> as a valid option selector.</p>\n\n<pre><code>public enum NameType {\n PROJECT, TRANSACTION, CURRENCY;\n}\n\npublic static String getNameByID(NameType type, int id) {\n switch(type) {\n case PROJECT:\n for(ProjectCode code : User.getInstance().getProjects()) {\n if(code.getProjCdId == id) return code.getProjNm();\n }\n break;\n case TRANSACTION:\n for(TransactionType type : Session.getInstance().getTransactionTypes()) {\n if(type.getTransactionTypeId() == id) return type.getTransactionNm();\n }\n break;\n case CURRENCY:\n for(CurrencyType type : Session.getInstance().getCurrencies()) {\n if (type.getCurrencyTypeId() == id) return type.getCurrencyTypeNm();\n }\n break;\n }\n return null;\n}\n</code></pre>\n\n<p>I don't see the use of generics at all here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T19:57:01.563",
"Id": "31867",
"ParentId": "7976",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7981",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T20:46:40.160",
"Id": "7976",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"search"
],
"Title": "Is there a better, more object oriented way to write this Finder method?"
}
|
7976
|
<p>I have a method that ascends an inheritance tree and returns the element at the root, progressively yielding the elements if appropriate:</p>
<pre><code># Finds the root of the hierarchy.
def root
element = self
until element.root?
yield element if block_given?
element = element.parent
end
yield element if block_given?
element
end
# Walks the inheritance tree, yielding each element from self to #root.
alias until_root root
</code></pre>
<p>If I have a hierarchy like:</p>
<pre><code>1 > 2 > 3
</code></pre>
<p><code>3.root</code> should return <code>1</code> and <code>3.until_root &block</code> should yield <code>3</code>, then <code>2</code>, then <code>1</code>, and finally return <code>1</code>.</p>
<p>The line which yields elements appears twice in order to yield the actual root element, something I would've liked to accomplish <em>inside</em> the loop.</p>
<p>How can I improve this algorithm?</p>
|
[] |
[
{
"body": "<p>One way to only have one <code>yield</code> statement would be to recursion instead of a loop:</p>\n\n<pre><code>def root(&blk)\n yield self if blk\n if root?\n self\n else\n parent.root(&blk)\n end\nend\n</code></pre>\n\n<p>Of course the usual caveats regarding recursion in ruby apply, so this isn't necessarily a good idea: It is somewhat expensive and can lead to stack overflows if you recurse deep enough (though it's rather unlikely, you'd encounter a tree deep enough to reach that limit).</p>\n\n<hr>\n\n<p>Unrelated to this, the name <code>until_root</code> seems somewhat clunky to me. I would recommend <code>each_ancestor</code> instead. In fact I think it would be good idea to have the method return an enumerable of ancestors when no block is given. Then it could just be called <code>ancestors</code>. Of course that would require separating <code>ancestors</code> and <code>root</code> into two separate methods. <code>root</code> could then just be defined as <code>ancestors.last</code>:</p>\n\n<pre><code># Returns an Enumerable containing the ancestors of this node, starting with\n# the node itself and ending with the root.\n# If a block is supplied, each ancestor will be yielded to the block instead\n# of returning an enumerable.\ndef ancestors\n return enum_for(:ancestors) unless block_given?\n\n element = self\n until element.root?\n yield element\n element = element.parent\n end\n yield element\nend\n\ndef root\n ancestors.last\nend\n</code></pre>\n\n<p>If you do it that way, you can also leave out the <code>if block_given?</code> part of the <code>yield</code> statements because it will return early when no block was given.</p>\n\n<p>As a matter of fact, you can now remove the second <code>yield</code> completely by changing the loop to loop while <code>element</code> is not nil instead of until the root is reached (assuming <code>element.parent</code> will return nil if the element is the root):</p>\n\n<pre><code>def ancestors\n return enum_for(:ancestors) unless block_given?\n\n element = self\n while element\n yield element\n element = element.parent\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T19:48:34.473",
"Id": "12685",
"Score": "0",
"body": "Awesome! I'd been wondering how to return enumerators for a while. Also, just a small thought: I chose the name `until_root` because it starts from `self` and stops at `root`. If I were to use `ancestors` or `each_ancestor`, wouldn't it be inconsistent if the method yielded `self`? Should I create another method to resolve this conflict?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T19:52:12.227",
"Id": "12686",
"Score": "0",
"body": "@MatheusMoreira Hm, you're right that `ancestors` containing `self` is a bit strange now that I think about it. Leaving the name as `until_root` might be best then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T19:55:38.553",
"Id": "12687",
"Score": "0",
"body": "@MatheusMoreira On second thought `ancestors` should be fine. `Class#ancestors` also includes the class itself, so there is some precedence for `ancestors` to also include the current node."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:06:10.590",
"Id": "12688",
"Score": "0",
"body": "Very well. I also think `ancestors` is much clearer, but now that you mentioned `Class#ancestors`, another issue has arisen... These elements are actually classes and the root element is actually the class which initially inherited from a certain class in my library. Using that name means overriding the `Class` method. Would `each_ancestor` or `parents` be appropriate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:11:09.807",
"Id": "12689",
"Score": "0",
"body": "@MatheusMoreira In that case I'd rather call it something like `foo_ancestors` where `foo` is the name of the \"certain class\" you mentioned. `parents` doesn't fit because your parent's parent is not your parent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:16:57.220",
"Id": "12691",
"Score": "0",
"body": "Awesome solution, wish I could give you +10 on this one. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T18:32:26.927",
"Id": "12847",
"Score": "0",
"body": "Isn't it complicated overkill to return ancestors recursively in an enumerator? Each element's ancestor list seems fixed, and keeping it simple would suggest using an array.\n\nThere are duplicate `yield element` statements, unless you take the `nil` route. A nitpick, but checking for `nil` locks you into an implementation of method, `parent`. E.g., what if your class somehow in the future were to evolve into needing every element's parent to be valid? such as the parents of all roots being in an array somewhere?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T18:36:43.003",
"Id": "12848",
"Score": "0",
"body": "@MarkDBlackwell What do you mean by every parent needing to be valid? The root by definition doesn't have a parent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T18:47:27.383",
"Id": "12850",
"Score": "0",
"body": "@MarkDBlackwell Regarding the enumerator being overkill: Maybe, but given that the OP also used an iterator-method instead of an array, I just stuck with that approach and just added the `enum_for` to get an enumerable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-24T05:18:17.807",
"Id": "12866",
"Score": "0",
"body": "@sepp2k, there could be many trees with their roots stored in some array, such as webpage DOM trees for browser tabs. Yet, you are probably right."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T16:55:53.683",
"Id": "8005",
"ParentId": "7982",
"Score": "3"
}
},
{
"body": "<p>Essentially, you can use <code>break</code> to remove the duplication, as below.</p>\n\n<p>See also <a href=\"http://www.skorks.com/2009/09/a-wealth-of-ruby-loops-and-iterators/\" rel=\"nofollow\">A Wealth Of Ruby Loops And Iterators</a> and <a href=\"http://www.tutorialspoint.com/ruby/ruby_loops.htm\" rel=\"nofollow\">Ruby Loops - while, for, until</a>.</p>\n\n<pre><code># Walks the inheritance tree, remembering each element, from self to the root.\ndef ancestors\n result=[]\n element=self\n loop do\n result.push element\n break if element.root?\n element=element.parent\n end\n result\nend\n\n# Walks the inheritance tree, yielding at each element, from self to the root,\n# returning the root.\ndef until_root\n a=ancestors\n a.each{|e| yield e} if block_given?\n a.last\nend\n\n# Finds the root of the hierarchy, without yielding.\ndef root\n ancestors.last\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T17:05:04.843",
"Id": "8221",
"ParentId": "7982",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8005",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T04:38:00.367",
"Id": "7982",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Is there a better way to traverse an inheritance tree?"
}
|
7982
|
<p>I am pretty new to JavaScript and learning the intricacies of this language. I wanted a unique collection which will overwrite while adding if an item already exists else add. Rest of the behavior should be just like any other collection. I had written the type and its as below. Instead of using an array internally, I have used JavaScript's notion of storing an object as key-value pair to store the items.</p>
<p>My question is, is this implementation valid? Are there any disadvantage with this implementation over using an array internally to hold the collection items instead of an object? </p>
<p>Why I chose objects to store items over array is:</p>
<ol>
<li>To avoid iterating through the array while adding an item, so that I don't have to check if objects exists(instead of adding a duplicate). </li>
<li>To avoid iterating while retrieving or deleting an item.</li>
</ol>
<p></p>
<pre><code>function isValid(obj) {
return (obj != undefined && obj != null && typeof (obj) != 'undefined');
}
function uniqueCollection() {
var collection = {};
var length = 0;
return {
removeItem: function (item) {
if (isValid(collection[item])) {
delete collection[item];
--length;
}
},
addItem: function (item) {
if (!isValid(collection[item])) {
collection[item] = item;
++length;
}
},
getLength: function () {
return length;
},
clear: function () {
collection = {};
length = 0;
},
exists: function (item) {
if (isValid(collection[item])) {
return true;
}
return false;
},
getItems: function () {
var items = [];
var i = 0;
for (var o in collection) {
if (collection.hasOwnProperty(o)) {
items[i] = o.toString();
i++;
}
}
if (i !== length) {
alert("Error occurred while returning items");
}
return items;
}
};//end of object literal
};//end of function
</code></pre>
|
[] |
[
{
"body": "<p>This mostly seems like a layer of sugar coating that just adds overhead and doesn't add any improved functionality over what a javascript object already has. The only new functionality I see is keeping track of a length, but this is a lot of extra overhead just for that. The length could be calculated at any time on a plain javascript object.</p>\n\n<p>Here are the analogs to your methods:</p>\n\n<pre><code>var collection = {};\n\naddItem:\n collection[key] = value;\n\nremoveItem: \n delete collection[key]\n\nclear:\n collection = {};\n\nexists:\n if (key in collection)\n\ngetItems:\n collection.keys()\n\ngetLength:\n collection.keys().length\n</code></pre>\n\n<p>So, all you're getting out of your implementation is a slightly more efficient length and every other operation is less efficient than just using the native code way of doing it. Is this collection really useful?</p>\n\n<p>There are some older browsers that don't offer the .keys() method, but there's a <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys\">pretty simple shim</a> that implements it if not available.</p>\n\n<p>In addition, your implementation loses functionality that a plain javascript object has. For example, you can't pass your collection to any function that expects a javascript object with the keys and values on it because those are hidden inside, they aren't actually properties of the collection object itself. Then further, you can't do custom iteration of the keys and values without first creating an array of all the keys because you've hidden the natural ability to iterate the keys of a javascript object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T06:42:54.160",
"Id": "12650",
"Score": "0",
"body": "@jsfriend00, Thanks ... I agree with you, but are there any disadvantage over using object instead of an array for storing items internally?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T06:50:11.903",
"Id": "12651",
"Score": "1",
"body": "@JeeZ - Arrays and Objects each have different advantages and disadvantages. Arrays have a defined order - Objects do not. Arrays have a built-in length - Objects do not. Objects have a fast lookup by key - Arrays do not. Objects accept a string as indexes into the data structure - Arrays accept sequential numbers as indexes into the array. An Array can also have object-like properties - An Object does not have Array-like properties. They are different data types with many differences. One should select the type most appropriate to the task at hand. I regularly use both."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T06:02:50.733",
"Id": "7984",
"ParentId": "7983",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "7984",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T05:41:40.783",
"Id": "7983",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"collections"
],
"Title": "Implementation of a unique collection"
}
|
7983
|
<p>I've been working on this elevator program for quite some time now and finally finished it and made it work and I'm pretty proud of myself, but I'd like to see ways how to optimize my code so I can learn for the future. By optimizing, I mean making the code look better, maybe by using fewer lines of code.</p>
<pre><code>import java.awt.geom.*;
public class elevator
{
static int floor = 0, choice1, person = 0;
public static void main(String args[])
{
floor = ((int) (Math.random() * 10 + 1));
System.out.println("The elevator is now on floor " +floor);
System.out.print("Which floor are you at now (0-10) where 0 = basement: ");
choice1 = Keyboard.readInt();
if(floor == choice1)
{
System.out.println("Enter the elevator");
}
else if(floor > choice1)
{
ElevatorDown();
}
else if(floor < choice1)
{
ElevatorUp();
}
System.out.println("To which floor would you want to go (0-10) where 0 = basement");
choice1 = Keyboard.readInt();
if(floor > choice1)
{
ElevatorDown();
}
else if(floor < choice1)
{
ElevatorUp();
}
}
public static void ElevatorUp()
{
System.out.println("The elevator is on it's way up...");
for (person = choice1; choice1>=floor; floor++)
System.out.println(floor);
System.out.println("The elevator has arrived");
}
public static void ElevatorDown()
{
System.out.println("The elevator is on it's way down...");
for (person = choice1; choice1<=floor; floor--)
System.out.println(floor);
System.out.println("The elevator has arrived");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:06:35.393",
"Id": "12652",
"Score": "1",
"body": "Maybe you could post the complete code of your class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:07:22.460",
"Id": "12653",
"Score": "1",
"body": "And please post `Keyboard`, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:14:50.160",
"Id": "12654",
"Score": "0",
"body": "I've posted my whole code now and I uploaded the Keyboard.class to speedyshare, not sure if there's a better place to upload it.\n\nhttp://speedy.sh/pGMx8/Keyboard.class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:17:55.587",
"Id": "12656",
"Score": "0",
"body": "Well, because I don't have the source file to the Keyboard.class but I uploaded what I could read from the class file onto pastebin. http://pastebin.com/MMyQvAA3 I hope that's enough, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:18:18.403",
"Id": "12657",
"Score": "0",
"body": "This still doesn't work: the imports from `java.awt.geom.*` are unused while `Keyboard` is not imported."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:20:23.927",
"Id": "12658",
"Score": "0",
"body": "I'm afraid I don't follow you, it's working great on my end. All I've to do is adding the Keyboard.class file to my bin folder in Eclipse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:53:00.880",
"Id": "12660",
"Score": "0",
"body": "Not an optimisation as such; but almost all Java programmers begin class names with capital letters and method names with lower case letters. This is actually a standard that was recommended by Sun (when they were still Sun), and it will make your code more readable to just about everyone who ever sees it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:55:49.330",
"Id": "12661",
"Score": "0",
"body": "And what exactly is the `person` variable for? It looks to me like you assign it, but never actually use it. Could you remove this variable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T10:31:28.227",
"Id": "12718",
"Score": "0",
"body": "You never actually check the value of the floor, yet you say you limit it from 0 to 10. You should have some \"checkInputIsValid\" method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T19:23:05.417",
"Id": "12852",
"Score": "2",
"body": "Making the code look better (more readable) and using less lines of code are usually opposite aims in Java."
}
] |
[
{
"body": "<pre><code>import java.awt.geom.*;\n\npublic class elevator\n</code></pre>\n\n<p>Class names are typically capitalized</p>\n\n<pre><code>{\n\n static int floor = 0, choice1, person = 0;\n</code></pre>\n\n<p>Prefer local variables to statics like this. Person doesn't appear to be used.</p>\n\n<pre><code> public static void main(String args[])\n {\n\n floor = ((int) (Math.random() * 10 + 1));\n</code></pre>\n\n<p>You've got an extra pair of parens that you don't need.</p>\n\n<pre><code> System.out.println(\"The elevator is now on floor \" +floor);\n System.out.print(\"Which floor are you at now (0-10) where 0 = basement: \");\n choice1 = Keyboard.readInt();\n\n if(floor == choice1)\n {\n System.out.println(\"Enter the elevator\");\n }\n\n else if(floor > choice1)\n {\n ElevatorDown();\n }\n\n else if(floor < choice1)\n {\n ElevatorUp();\n }\n</code></pre>\n\n<p>Rather then keeping your choice in a static variable. Pass it as a parameter to your ElevatorUp()/ElevatorDown() Movement functions.</p>\n\n<pre><code> System.out.println(\"To which floor would you want to go (0-10) where 0 = basement\");\n choice1 = Keyboard.readInt();\n\n if(floor > choice1)\n {\n ElevatorDown();\n }\n\n else if(floor < choice1)\n {\n ElevatorUp();\n }\n</code></pre>\n\n<p>This is repeated from before. Write an ElevatorMove() function that decides whether to call ElevatorUp or ElevatorDown.</p>\n\n<pre><code> }\n\n public static void ElevatorUp()\n {\n System.out.println(\"The elevator is on it's way up...\");\n\n for (person = choice1; choice1>=floor; floor++)\n</code></pre>\n\n<p>Declare for loop variables in the loop not some other random place. And <code>person</code>? What does person have to do with it? In fact person=choice1 does nothing. I'd make this a while loop.</p>\n\n<pre><code> System.out.println(floor);\n\n System.out.println(\"The elevator has arrived\");\n }\n\n public static void ElevatorDown()\n {\n System.out.println(\"The elevator is on it's way down...\");\n for (person = choice1; choice1<=floor; floor--)\n\n System.out.println(floor);\n\n System.out.println(\"The elevator has arrived\");\n }\n</code></pre>\n\n<p>These two functions are similiar. They can be combined. \n }</p>\n\n<p>My reworking of your code:</p>\n\n<pre><code>import java.awt.geom.*;\n\npublic class elevator\n{\n\n static int floor;\n\n public static void main(String args[])\n {\n\n floor = (int) (Math.random() * 10 + 1);\n\n System.out.println(\"The elevator is now on floor \" +floor);\n System.out.print(\"Which floor are you at now (0-10) where 0 = basement: \");\n int current_floor = Keyboard.readInt();\n\n if(floor == current_floor)\n {\n System.out.println(\"Enter the elevator\");\n }\n else\n {\n MoveElevator(current_floor);\n }\n\n\n System.out.println(\"To which floor would you want to go (0-10) where 0 = basement\");\n int target_floor = Keyboard.readInt();\n\n MoveElevator(target_floor);\n }\n\n public static void MoveElevator(int target_floor)\n {\n int direction;\n if( target_floor > floor )\n {\n System.out.println(\"The elevator is on it's way up...\");\n direction = 1;\n }else{\n System.out.println(\"The elevator is on it's way down...\");\n direction = -1;\n }\n\n while(target_floor != floor)\n {\n floor += direction;\n System.out.println(floor);\n }\n\n System.out.println(\"The elevator has arrived\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T19:00:07.960",
"Id": "8009",
"ParentId": "7990",
"Score": "11"
}
},
{
"body": "<p>In object oriented programming, you typically ask yourself: which objects do I operate with, what can I do with them, and what are their properties? In your case:</p>\n\n<ul>\n<li>There is <em>an elevator</em>, and there could possibly be many elevators, which are all similar.</li>\n<li>An elevator always has a <em>current floor</em> where it currently is.</li>\n<li>That <em>current floor</em> can change when the elevator is in action.</li>\n<li>One typical action is <em>to move up</em>.</li>\n<li>Another typical action is <em>to move down</em>.</li>\n<li>When a person wants to use the elevator, the elevator moves to the floor where the person is. In general, the elevator <em>moves to a certain floor</em>.</li>\n</ul>\n\n<p>And here is the code, based on the description above:</p>\n\n<pre><code>public class Elevator {\n\n private int currentFloor;\n\n public void run() {\n currentFloor = 1 + ((int) (Math.random() * 10));\n\n System.out.println(\"The elevator is now on floor \" + currentFloor);\n System.out.print(\"Which floor are you at now (0-10) where 0 = basement: \");\n int personFloor = Keyboard.readInt();\n moveTo(personFloor);\n System.out.println(\"Enter the elevator\");\n\n System.out.println(\"To which floor do you want to go (0-10) where 0 = basement\");\n int destinationFloor = Keyboard.readInt();\n moveTo(destinationFloor);\n System.out.println(\"Leave the elevator\");\n }\n\n private void moveTo(int destinationFloor) {\n if (destinationFloor == currentFloor) {\n /* nothing to do */\n } else if (destinationFloor > currentFloor) {\n moveUpTo(destinationFloor);\n } else {\n moveDownTo(destinationFloor);\n }\n }\n\n private void moveUpTo(int destinationFloor) {\n System.out.println(\"The elevator is on its way up ...\");\n while (currentFloor < destinationFloor) {\n currentFloor++;\n System.out.println(currentFloor);\n }\n System.out.println(\"The elevator has arrived\");\n }\n\n private void moveDownTo(int destinationFloor) {\n System.out.println(\"The elevator is on its way down ...\");\n while (currentFloor > destinationFloor) {\n currentFloor--;\n System.out.println(currentFloor);\n }\n System.out.println(\"The elevator has arrived\");\n }\n\n public static void main(String[] args) {\n new Elevator().run();\n }\n\n}\n</code></pre>\n\n<p>By the way, the elevator is on <em>its</em> way, not on <em>it's</em> way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T00:21:06.710",
"Id": "10422",
"ParentId": "7990",
"Score": "2"
}
},
{
"body": "<p>You should separate the <code>main</code> method from the <code>Elevator</code> class, so that your <code>Elevator</code> class truly represents an elevator! You could have, let's say, a <code>Program</code> class, that'll call your <code>Elevator</code> class.</p>\n\n<p>Second, your methods and fields shouldn't be static. Usually, when your class has a state (such as the current floor), your object shouldn't be static. This way, you could have 2 (or more) <code>Elevator</code> instances, and they won't collide together.</p>\n\n<p>The elevator shouldn't start at a random floor, imagine a real elevator. At it's first use, there's a big possibility that it starts at the bottom floor (at least, I guess, I'm no elevator expert!). Let's start this elevator at floor 0 (the basement).</p>\n\n<p>So right now, I assume your elevator is used by only one person, because a real elevator might not come and get you if it isn't going in the direction you want to go.</p>\n\n<p>Your class name should be capitalized and your method named should be camelCased so : </p>\n\n<p><code>Elevator</code> instead of <code>elevator</code></p>\n\n<p><code>elevatorUp</code> instead of <code>elevatorUp</code></p>\n\n<p><code>elevatorDown</code> instead of <code>elevatorDown</code></p>\n\n<p>Also, the Java convention specifies that your brackets should be \"egyptian style\". Which means : </p>\n\n<pre><code>//Good\nif{\n}\n\n//Less good\nif\n{\n}\n</code></pre>\n\n<p>There goes the resume of my explanations : </p>\n\n<pre><code>public class Elevator {\n private int floor = 0, choice1, person = 0;\n\n public void callFrom(int floor){\n System.out.println(\"Elevator is coming\");\n goTo(floor);\n }\n\n public void goTo(int floor){\n if(floor == choice1) {\n System.out.println(\"Enter the elevator\");\n }\n else if(floor > choice1) {\n elevatorDown();\n }\n\n else if(floor < choice1){\n elevatorUp();\n }\n }\n\n private void elevatorUp() {\n System.out.println(\"The elevator is on it's way up...\");\n\n for (person = choice1; choice1>=floor; floor++)\n\n System.out.println(floor);\n\n System.out.println(\"The elevator has arrived\");\n }\n\n private void elevatorDown() {\n System.out.println(\"The elevator is on it's way down...\");\n for (person = choice1; choice1<=floor; floor--)\n\n System.out.println(floor);\n\n System.out.println(\"The elevator has arrived\");\n }\n}\n</code></pre>\n\n<p>I wasn't sure about the <code>goTo</code> and <code>callFrom</code>, but I thought it was important to split them since if you ever want to make your elevator even more complex (dealing with multiple calls etc..) you'll need to have them splitted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-18T04:21:04.637",
"Id": "178009",
"Score": "0",
"body": "This is the best answer \"for the future\" (quoting the OP). Other answers demonstrate better Java this one included, but this answer is the only one addressing better software."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-17T14:16:46.007",
"Id": "97235",
"ParentId": "7990",
"Score": "3"
}
},
{
"body": "<p>This is my code review. I don't read others much of others answers, it's likely they have point almost the same issues. </p>\n\n<ol>\n<li>Name conventions: you have to pay attention of Java widely used name conventions: <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow\">Java code conventions</a></li>\n</ol>\n\n<p>In this case, your class name should start with uppercases and your methods with lowercases. </p>\n\n<ol start=\"2\">\n<li><p>is this import used?</p>\n\n<ul>\n<li>import java.awt.geom.*;</li>\n</ul></li>\n<li><p>your implementation is to much procedural. You do all in the main method. You should put the logic in Elevator class and call it via main method, after instantiating the Elevator object. You should\navoid static members, too. </p></li>\n<li><p>your implementation have to much ifs, that let your code bigger and polluted. see <a href=\"http://antiifcampaign.com/\" rel=\"nofollow\">anti-if</a>.</p></li>\n<li><p>elevatorUp and elevatorDown methods are almost the same. you should avoid code duplication. See <a href=\"https://pt.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>. </p></li>\n</ol>\n\n<p>I made an re-implementation of your elevator simulator. I change the methods elevatorUp and elevatorDown to \none unique method, to avoid code repetition and to put off some ifs. </p>\n\n<pre><code>public class Elevator {\n private static final String DOWN = \"down\";\n private static final String UP = \"up\";\n private final Random rand = new Random();\n private int floor = rand.nextInt(10) + 1;\n\n public void simulateElevator() {\n System.out.println(\"The elevator is now on floor \" + floor);\n System.out.print(\"Which floor are you at now (0-10) where 0 = basement: \");\n int destinationFloor = readDestinationFloor();\n int movement = getMovementDirection(destinationFloor);\n if (movement == 0) {\n System.out.println(\"Enter the elevator\");\n } else {\n moveElevator(destinationFloor, movement);\n }\n }\n\n private int readDestinationFloor() {\n return Keyboard.readInt();\n }\n\n /* determine if movement needed is to up or to down */\n private int getMovementDirection(int destinationFloor) {\n int dif = destinationFloor - floor;\n if (dif == 0) {\n return 0;\n }\n return dif / Math.abs(dif);\n }\n\n\n private String getMovementName(int movement) {\n return movement < 0 ? DOWN : UP;\n }\n\n private void moveElevator(int destination, int moveDirection) {\n String movementName = getMovementName(moveDirection);\n System.out.println(\"The elevator is on it's way \".concat(movementName).concat(\"...\"));\n while (floor != destination) {\n floor += moveDirection;\n System.out.println(floor);\n }\n System.out.println(\"The elevator has arrived\");\n }\n\n public static void main(String[] args) {\n new Elevator().simulateElevator();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-17T15:29:25.240",
"Id": "97248",
"ParentId": "7990",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T09:57:51.030",
"Id": "7990",
"Score": "6",
"Tags": [
"java"
],
"Title": "Elevator program"
}
|
7990
|
<p>I have the following code with switch case statement:</p>
<pre><code>public string IrregularCouponLabel
{
get
{
switch ((ctrl.IrregularCouponFirst ? 10 : 0) + (ctrl.IrregularCouponLast ? 1 : 0))
{
case 11: return LocalString.Evaluate("label.Both");
case 10: return LocalString.Evaluate("label.First");
case 1: return LocalString.Evaluate("label.Last");
default: return LocalString.Evaluate("label.None");
}
}
}
</code></pre>
<p>How should I refactor this code to be more clear and readable or how could I otherwise improve this code snippet?</p>
<p><strong>UPDATE</strong>
According to valuable answers
I have updated the code in the following way, </p>
<pre><code> public string IrregularCouponLabel
{
get
{
return LocalString.Evaluate("label." + GetIrregularCouponValue());
}
}
private string GetIrregularCouponValue()
{
bool first = ctrl.IrregularCouponFirst;
bool last = ctrl.IrregularCouponLast;
bool both = first && last;
return both ? "Both" :
first ? "First" :
last ? "Last" :
"None";
}
</code></pre>
<p>What do you think about this? Is it readable or not?</p>
|
[] |
[
{
"body": "<p>I'd write something like this:</p>\n\n<pre><code>string labelName;\nif (ctrl.IrregularCouponFirst && ctrl.IrregularCouponLast) {\n labelName = \"label.Both\"\n} else if (ctrl.IrregularCouponFirst) {\n labelName = \"label.First\";\n} else if (ctrl.IrregularCouponLast) {\n labelName = \"label.Last\";\n} else {\n labelName = \"label.None\";\n}\nreturn LocalString.Evaluate(labelName);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T13:31:34.413",
"Id": "12793",
"Score": "3",
"body": "This is the easiest answer to follow IMO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T13:34:48.567",
"Id": "12834",
"Score": "0",
"body": "What does it mean IMO?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T13:47:46.143",
"Id": "12835",
"Score": "1",
"body": "\"in my opinion\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:35:13.920",
"Id": "7992",
"ParentId": "7991",
"Score": "15"
}
},
{
"body": "<p>You can use an <code>if</code> statement and the conditional operator:</p>\n\n<pre><code>string label;\nif (ctrl.IrregularCouponFirst) {\n label = ctrl.IrregularCouponLast ? \"label.Both\" : \"label.First\";\n} else {\n label = ctrl.IrregularCouponLast ? \"label.Last\" : \"label.None\";\n}\nreturn LocalString.Evaluate(label);\n</code></pre>\n\n<p>You can also use only conditional operators. This way of chaining conditional operators checks take a bit of work to grasp the first time, but it's very compact:</p>\n\n<pre><code>return LocalString.Evaluate(\n ctrl.IrregularCouponFirst && ctrl.IrregularCouponLast ? \"label.Both\" :\n ctrl.IrregularCouponFirst ? \"label.First\" :\n ctrl.IrregularCouponLast ? \"label.Last\" :\n \"label.None\"\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T14:50:29.380",
"Id": "12670",
"Score": "4",
"body": "+1 for the second version as it completely describes intent and keeps a good bunch of mechanism on the sidelines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T13:34:03.620",
"Id": "12833",
"Score": "0",
"body": "Yes I agree the second one is short and clear thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T11:33:23.070",
"Id": "7993",
"ParentId": "7991",
"Score": "17"
}
},
{
"body": "<p>I'd use enums.</p>\n\n<p>My suggestion presumes you are able to refactor your existing code a bit. If your control can be modified to keep the position value in one property of the following enum type, this will work.</p>\n\n<pre><code>[Flags]\npublic enum LabelEnum\n{\n None = 0,\n First = 1,\n Last = 2,\n Both = 3\n}\n\n//....\nctrl.IrregularCoupon = LabelEnum.Both;\n// or\nctrl.IrregularCoupon = LabelEnum.First | LabelEnum.Last\n\nlabelName = \"label.\" + ctrl.IrregularCoupon.ToString();\n</code></pre>\n\n<p>This might be off topic, but if you use switch statements for more complex functionality, you should read this before going further.\n<a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\">http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-26T17:42:54.717",
"Id": "12999",
"Score": "0",
"body": "Wish I could upvote more than once. Enums are far more readable than magic numbers and if the code can be refactored to just use a single enum value then you end up with the clear `ToString` operation on the value itself, no conditional parsing needed. My first thought when reading the code was Enum."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T11:49:07.450",
"Id": "7995",
"ParentId": "7991",
"Score": "11"
}
},
{
"body": "<p>I think I would store the <code>IrregularCouponFirst</code> and <code>IrregularCouponLast</code> as flag-enums to improve readability.</p>\n\n<p>So first define the enum:</p>\n\n<pre><code>[Flags]\nenum Position\n{\n None = 0,\n First = 1,\n Last = 2,\n Both = 3\n}\n</code></pre>\n\n<p>Then to keep compatibility with previous code, I'd consider implementing properties for <code>IrregularCouponFirst</code> and <code>IrregularCouponLast</code> like this:</p>\n\n<pre><code>public Position IrregularCouponPosition;\n\npublic bool IrregularCouponFirst\n{\n get { return _irregularCouponPosition & Position.First != 0; }\n set { _irregularCouponPosition |= Postion.First; }\n}\n\npublic bool IrregularCouponLast\n{\n get { return _irregularCouponPosition & Position.Last != 0; }\n set { _irregularCouponPosition |= Postion.Last; }\n}\n</code></pre>\n\n<p>And finally your switch would look like this:</p>\n\n<pre><code>public string IrregularCouponLabel\n{\n get\n {\n switch (ctrl.IrregularCouponPosition)\n {\n case Position.First: return LocalString.Evaluate(\"label.First\");\n case Position.Last: return LocalString.Evaluate(\"label.Last\");\n case Position.Both: return LocalString.Evaluate(\"label.Both\");\n default: return LocalString.Evaluate(\"label.None\");\n }\n }\n}\n</code></pre>\n\n<p>Which is pretty much the same switch you had to begin with. Though I find it a bit more readable now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T23:31:24.860",
"Id": "12817",
"Score": "1",
"body": "If you were going to do it this way, I think you'd want to use your enum constants in the switch statement - not the \"magic\" constants 1, 2, and 3."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T12:24:17.977",
"Id": "7997",
"ParentId": "7991",
"Score": "5"
}
},
{
"body": "<p>I would likely use:</p>\n\n<pre><code>string type=\"None\";\nif (false) {\n}else if (ctrl.IrregularCouponFirst && ctrl.IrregularCouponLast){type=\"Both\";\n}else if (ctrl.IrregularCouponFirst ){type=\"First\";\n}else if (ctrl.IrregularCouponLast ){type=\"Last\";\n}\nreturn LocalString.Evaluate(\"label.\"+type);\n</code></pre>\n\n<p>But then there is always:</p>\n\n<pre><code>var types = new Dictionary<int, string> {\n { 0, \"None\" }\n ,{ 1, \"Last\" }\n ,{ 10, \"First\" }\n ,{ 11, \"Both\" }\n};\n\nint key=(ctrl.IrregularCouponFirst ? 10 : 0) + (ctrl.IrregularCouponLast ? 1 : 0);\nreturn LocalString.Evaluate(\"label.\"+types[key]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T17:20:37.997",
"Id": "13069",
"Score": "0",
"body": "-1: convoluted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-29T16:58:14.530",
"Id": "13180",
"Score": "0",
"body": "Oh yes, convoluted on this scale. But truth tables work wonders for larger applications."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T05:25:36.080",
"Id": "8208",
"ParentId": "7991",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:23:31.593",
"Id": "7991",
"Score": "17",
"Tags": [
"c#"
],
"Title": "Switch case statement refactoring"
}
|
7991
|
<p>A previous developer had an array of strings like so:</p>
<pre><code>public static const PAGE_ONE:String = 'PageOne';
public static const PAGE_TWO:String = 'PageTwo';
public static const PAGE_THREE:String = 'PageThree';
public static const PAGE_FOUR:String = 'PageFour';
public static const PAGE_FIVE:String = 'PageFive';
public static const PAGE_SIX:String = 'PageSix';
</code></pre>
<p>When he wanted to open a new type of page he would write</p>
<pre><code>switch ($page)
{
case PAGE_ONE:
// Do stuff
break;
...
case PAGE_SIX:
// Do stuff
break;
}
</code></pre>
<p>Which was all well and good, but I thought it could be condensed a little bit, so I created a little more functional approach.</p>
<p>In the constructor, this function is called setting up the table:</p>
<pre><code> private function setDefaultPages() : void {
_pages[PAGE_ONE] = function($xml:XMLList) { return new PageOne( $xml ); }
...
_pages[PAGE_SIX] = function($xml:XMLList) { return new PageSix( $xml ); }
}
</code></pre>
<p>Now, when the time comes to open a page, all I have to write is this:</p>
<pre><code>_nextPage = _pages[$page](xml);
</code></pre>
<p>However, I am worried that I have hurt readability by doing this. Could anybody suggest a good middle-ground if it is so?</p>
|
[] |
[
{
"body": "<p>It seems to me that what you need is the <a href=\"http://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow\">State pattern</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T15:45:04.977",
"Id": "8003",
"ParentId": "7996",
"Score": "2"
}
},
{
"body": "<p>There's a safety issue, here. If you somehow get a bad page name in the original case statement, nothing good happens, but nothing bad happens either. What happens for <code>_nextPage[\"BOGUS\"]($xml);</code> ?</p>\n\n<p>That aside, your change can be broken down into a few steps and each one evaluated separately. Also, the solution has parts that can be teased out for readability.</p>\n\n<p>You seem to be implying that</p>\n\n<pre><code>switch ($page)\n{\n case PAGE_ONE:\n // Do stuff\n break;\n // etc.\n</code></pre>\n\n<p>can be replaced by:</p>\n\n<pre><code>switch ($page)\n{\n case PAGE_ONE:\n _nextPage = new PageOne($xml);\n break;\n // etc.\n</code></pre>\n\n<p>That being the case, you could stop there. </p>\n\n<p>Optionally you could wrap the switch statement in a function:</p>\n\n<pre><code>private function generateNamedPage($page:String, $xml:XMLList) {\n switch ($page)\n {\n case PAGE_ONE:\n return new PageOne($xml);\n break;\n // etc.\n\n_nextPage = generateNamedPage($page, $xml);\n</code></pre>\n\n<p>It's no harder to extend this code than to extend your setDefaultPages code. And it's easier to follow. </p>\n\n<p>Dispatching like this to create new objects of different kinds is a common technique known as the Abstract Factory Pattern. Naming and comments that reference this pattern will help to clarify your intent to anyone familiar with the pattern.</p>\n\n<p>The only benefit I can see to the more sweeping change using <code>setDefaultPages</code> is to enable dynamic reconfiguration, e.g. from anywhere else in the code after <code>setDefaultPages</code> has run:</p>\n\n<pre><code> if (userHasAdminPrivileges()) {\n // add admin navigation to front page\n _pages[PAGE_ONE] = function($xml:XMLList) { return new PageOneForAdmins( $xml );}\n\n // add access to admin pages\n _pages[PAGE_SEVEN] = function($xml:XMLList) { return new PageSeven( $xml ); }\n _pages[PAGE_EIGHT] = function($xml:XMLList) { return new PageEight( $xml ); }\n }\n</code></pre>\n\n<p>If you don't need this kind of dynamism, keep it simple with the switch statement.</p>\n\n<p>On the other hand, if the more dynamic original solution is desired, its parts can be packaged to improve readability, much like the wrapping of the switch statement above. Caveat: I don't know as3, but if I did, I might declare specific return types for these functions.</p>\n\n<pre><code>// return a function\n// This may be overkill if it's only ever used by generateNamedPage.\nprivate function getNamedPageGenerator($page:String) {\n // probably want to guard against bogus $page, returning a dummy page generator function\n return _pages[$page];\n}\n\n// return a new page\nprivate function generateNamedPage($page:String, $xml:XMLList) {\n return getNamedPageGenerator($page)($xml);\n // OR, to be more explicit:\n // var generatePage = getNamedPageGenerator($page);\n // return generatePage($xml);\n}\n...\n_nextPage = generateNamedPage($page, $xml);\n</code></pre>\n\n<p>The name <code>_pages</code> probably adds to the confusion because it is not a collection of pages at all, but a collection of page-generator functions. Maybe calling it <code>_pageGenerator</code> or <code>_pageFactory</code> would be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T17:29:10.900",
"Id": "12680",
"Score": "0",
"body": "Some excellent tipps, I didn't realize that this pattern had a name :D Yes, I actually do dynamically change the pages like you are describing, which was one of the catalysts for the change. I thought it would be a little easier to extend than the previous version, although I suppose palacsint would be the end-all overkill solution to this problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T17:21:06.490",
"Id": "8007",
"ParentId": "7996",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T12:11:04.897",
"Id": "7996",
"Score": "1",
"Tags": [
"actionscript-3"
],
"Title": "Is this possibly confusing code?"
}
|
7996
|
<p>I am implementing Unix sort in Clojure. This is my first program, and I would like some feedback regarding any non-idiomatic, harmful code and any other best practices I can include in future versions. I tried my best to follow the coding standards, but went with <code>camelCase</code> instead of <code>hyphen-case</code> for variable and function names.</p>
<p>Main class: <code>sort.core</code></p>
<pre><code>(ns sort.core
(:gen-class)
(:use clojure.contrib.core)
(:use clojure.tools.cli)
(:require [sort.lib :as lib]))
(defn -main [& args]
(let [[options args banner] (cli args
["-h" "--help" "Show help" :default false :flag true]
["-i" "--input" "The input file" :default nil]
["-d" "--delim" "The delimitter" :default ","]
["-f" "--field" "The column to parse(1 indexed)" :parse-fn #(Integer. %)])
{:keys [delim field input]} options]
(lib/help options args banner)
(when (= (lib/fileKind input) "file")
(lib/printOutVector delim
(lib/sortVector field
(lib/splitFile input delim ))))
(System/exit 0)))
</code></pre>
<p>Library: <code>sort.lib</code></p>
<pre><code>(ns sort.lib
(:require [clojure.string :as str])
(:import java.io.File))
(defn splitFile
"splits a file into a 2d array"
[s delim]
(pmap #(str/split % (re-pattern delim))
(str/split(slurp s) #"\n")))
(defn printOutVector
"prints out the 2dVector formatted by the delim arg"
[delim coll]
(println
(apply str
(interpose "\n" (map #(apply str (interpose delim %)) coll)))))
(defn sortVector
"sorts a 2d vector by the given index"
[index coll]
(sort-by #(nth % index) coll))
(defn help
"custom help message for sort.core"
[opts args banner]
(when (:help opts)
(println (str "input: " (:input opts)))
(println (str "field: " (:field opts)))
(println (str "delim: " (:delim opts)))
(println banner)
(System/exit 0)))
(defn fileKind [filename]
(let [f (File. filename)]
(cond
(.isFile f) "file"
(.isDirectory f) "directory"
(.exists f) "other"
:else "(non-existent)" )))
</code></pre>
|
[] |
[
{
"body": "<p>You should use namespace-qualified keywords instead of strings in the fileKind function:</p>\n\n<pre><code>(defn fileKind [filename]\n (let [f (File. filename)]\n (cond\n (.isFile f) ::file\n (.isDirectory f) ::directory\n (.exists f) ::other \n :else ::non-existent)))\n</code></pre>\n\n<p>... which would require the following change in the -main function:</p>\n\n<pre><code>(= (lib/fileKind input) :lib/file)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T22:04:29.097",
"Id": "13262",
"Score": "0",
"body": "looks like you're gonna win the bounty, have anything else to say?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T09:06:33.810",
"Id": "13282",
"Score": "0",
"body": "Not really, I don't think I'd do it very differently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T09:15:10.257",
"Id": "13283",
"Score": "1",
"body": "I guess your usage of pmap is a bit clumsy and could lead to decreased performance for large files due to the extra overhead. You might want to take a look at this: http://www.fatvat.co.uk/2009/05/jvisualvm-and-clojure.html"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T10:39:03.220",
"Id": "8447",
"ParentId": "8000",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8447",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T14:24:04.640",
"Id": "8000",
"Score": "7",
"Tags": [
"clojure"
],
"Title": "Unix sort in Clojure"
}
|
8000
|
Adobe ActionScript 3 is the open source object oriented programming (OOP) language of the Adobe Flash and Air Platforms. AS3 is widely used for RIAs, mobile apps, and desktop applications. (ActionScript 3 is a dialect of ECMAScript.)
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T14:51:54.487",
"Id": "8002",
"Score": "0",
"Tags": null,
"Title": null
}
|
8002
|
<p>I have a workflow; within the workflow I can have many stages. I want to open and close a stage based on some business rules. E.g., stage 7 cannot be opened, because stage 5 + 6 need to be closed first; or, check whether key data x is filled out: if so, you can close stage 4.</p>
<p>How can I optimize or improve my code, below? Are there any guidelines or help?</p>
<pre><code>public interface IHigherLevelWorkflow
{
int InstructionID { get; }
int DashboardID { get; }
string Name { get; }
string Description { get; }
int CurrentStage { get; }
IList<DashboardStageDetailDTO> Stages { get; }
InstructionStageProgress CloseStage(int progressId);
InstructionStageProgress OpenStage(int progressId);
}
public class Workflow : IHigherLevelWorkflow
{
private readonly IReadOnlySession _readOnlySession;
private readonly IUserSession _userSession;
public Workflow (Instruction instruction, IReadOnlySession readOnlySession, IUserSession userSession)
{
Guard.ArgumentNotNull(instruction, "instruction");
InstructionID = instruction.InstructionID;
MyInstruction = instruction;
Guard.ArgumentNotNull(readOnlySession, "readOnlySession");
_readOnlySession = readOnlySession;
_userSession = userSession;
Guard.ArgumentNotNull(userSession, "usersession");
MyWorkflow = ResolveDashboard();
}
public Instruction MyInstruction { get; private set; }
public int InstructionID { get; private set; }
public int DashboardID
{
get { return MyWorkflow.DashboardID; }
}
public string Name
{
get { return MyWorkflow.Name; }
}
public string Description
{
get { return MyWorkflow.Description; }
}
public int CurrentStage
{
get { return MyWorkflow.CurrentStage; }
}
public IList<DashboardStageDetailDTO> Stages
{
get {return MyWorkflow.Stages; }
}
public InstructionStageProgress CloseStage(int progressId)
{
//user wants to close a stage...
//is stage valid?
var stage = Stages.FirstOrDefault(x => x.ProgressID == progressId);
if(stage == null)
throw new NoAccessException(string.Format("stage progress #{0} does not exist",progressId));
//what kind of stage is it? do some rules and checks...
//if ok, save to db - do we require a update session? Should we return the object and allow caller to save?
//where will notifications be generated?
var mystage = _readOnlySession.Single<InstructionStageProgress>(x => x.ProgressID == progressId);
if (mystage == null)
throw new NoAccessException(string.Format("stage progress #{0} does not exist", progressId));
mystage.IsCompleted = true;
mystage.DateCompleted = DateTime.Now;
mystage.CompletedByID = _userSession.UserID;
return mystage;
}
private static void OpenStageRules(DashboardStageDetailDTO stageDetail)
{
//depending on what stage it is, we will allow the opening of the stage...
var rules = new RulesException<DashboardStageDetailDTO>();
switch (stageDetail.ViewHook)
{
case StageViewHook.NoView: //first and last stage can never be opened, this is down to the system
rules.ErrorForModel("this stage cannot be opened");
break;
case StageViewHook.Quotes:
rules.ErrorForModel("this stage cannot be opened");
break;
case StageViewHook.Configure:
break;
case StageViewHook.Report:
rules.ErrorForModel("this stage cannot be opened");
break;
case StageViewHook.Check:
rules.ErrorForModel("this stage cannot be opened");
break;
}
if(rules.Errors.Any())
throw rules;
}
public InstructionStageProgress OpenStage(int progressId)
{
//user wants to open a stage...
//is stage valid?
var stage = Stages.FirstOrDefault(x => x.ProgressID == progressId);
if (stage == null)
throw new NoAccessException(string.Format("stage progress #{0} does not exist", progressId));
//what kind of stage is it? do some rules and checks...
OpenStageRules(stage);
//if ok, save to db - do we require a update session? Should we return the object and allow caller to save?
//where will notifications be generated?
var mystage = _readOnlySession.Single<InstructionStageProgress>(x => x.ProgressID == progressId);
if (mystage == null)
throw new NoAccessException(string.Format("stage progress #{0} does not exist", progressId));
mystage.IsCompleted = false;
mystage.DateCompleted = null;
mystage.CompletedByID = null;
mystage.DateInitiated = DateTime.Now;
mystage.InitiatedByID = _userSession.UserID;
return mystage;
}
private WorkflowDTO MyWorkflow { get; set; }
private WorkflowDTO ResolveDashboard()
{
var wf = _readOnlySession.All<Dashboard>()
.GroupJoin(_readOnlySession.All<DashboardStage>(),
x => x.DashboardID,
y => y.DashboardID,
(dash, ds) =>
new
{
Dashboard = dash,
DashboardStages =
ds.DefaultIfEmpty().Join(_readOnlySession.All<InstructionStageProgress>()
.Where(x => x.InstructionID == InstructionID),
x => x.DashboardStageID,
y => y.StageID,
(d, s) => new
{
InstructionStageProgress = s,
DashboardStage = d,
StageOwnerCompany =
_readOnlySession.All<Company>().FirstOrDefault
(
c => c.CompanyID == s.StageOwnerID),
})
})
.Select(dash =>
new WorkflowDTO
{
DashboardID = dash.Dashboard.DashboardID,
Name = dash.Dashboard.Name,
Description = dash.Dashboard.Description,
CurrentStage = dash.DashboardStages
.OrderByDescending(o => o.DashboardStage.SortOrder)
.First(x => x.InstructionStageProgress.IsCompleted).DashboardStage.
DashboardStageID,
Stages = dash.DashboardStages
.Select(stage =>
new DashboardStageDetailDTO
{
Name = stage.DashboardStage.Name,
Description = stage.DashboardStage.Description,
StageID = stage.DashboardStage.DashboardStageID,
StageNumber = stage.DashboardStage.SortOrder,
ViewHook =
stage.DashboardStage.StageHook.Convert<StageViewHook>(),
ProgressID = stage.InstructionStageProgress.ProgressID,
StageOwnerID = stage.InstructionStageProgress.StageOwnerID,
StageOwnerCompanyName =
stage.StageOwnerCompany != null
? stage.StageOwnerCompany.Identifier
: string.Empty,
Progress =
new ProgressDTO
{
DateInitiated =
stage.InstructionStageProgress.DateInitiated,
DateCompleted =
stage.InstructionStageProgress.DateCompleted,
IsCompleted =
stage.InstructionStageProgress.IsCompleted,
InitiatedByUserID =
_readOnlySession.All<User>().Single(
u =>
u.UserID ==
stage.InstructionStageProgress.InitiatedByID)
.
Login,
SignedOffByUserID =
_readOnlySession.All<User>().Single(
u =>
u.UserID ==
stage.InstructionStageProgress.CompletedByID)
.
Login,
}
})
.OrderBy(s => s.StageNumber)
.ToList()
})
.FirstOrDefault();
if (wf == null)
throw new NoAccessException(string.Format("dashboard not found for instruction #{0}", InstructionID));
return wf;
}
}
</code></pre>
<p>Here are my stage and progress DTO classes:</p>
<pre><code>public class DashboardStageDetailDTO
{
public int ProgressID { get; set; }
public int StageID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int StageNumber { get; set; }
public StageViewHook ViewHook { get; set; }
public string Url { get; set; }
public bool IsViewAvailable { get; set; }
public ProgressDTO Progress { get; set; }
public int? StageOwnerID { get; set; }
}
public class ProgressDTO
{
public bool IsCompleted { get; set; }
public DateTime? DateInitiated { get; set; }
public string InitiatedByUserID { get; set; }
public DateTime? DateCompleted { get; set; }
public string SignedOffByUserID { get; set; }
}
</code></pre>
<p>Update to my code:</p>
<pre><code>public class Workflow : IHigherLevelWorkflow
{
public Workflow(Instruction instruction, Dashboard dashboard, IEnumerable<StageProgress> progress)
{
Guard.ArgumentNotNull(instruction, "instruction");
InstructionID = instruction.InstructionID;
MyInstruction = instruction;
Guard.ArgumentNotNull(dashboard, "dashboard");
Description = dashboard.Description;
Name = dashboard.Name;
DashboardID = dashboard.DashboardID;
Guard.ArgumentNotNull(progress, "progress");
Progress = progress.OrderBy(x => x.Stages.SortOrder)
.ToDictionary(x => x.Progress.ProgressID, y => y);
}
public Instruction MyInstruction { get; private set; }
public int InstructionID { get; private set; }
public int DashboardID { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public IDictionary<int, StageProgress> Progress { get; private set; }
public int CurrentStage
{
get
{
//get the last stage that was completed
return Progress.Last(x => x.Value.Progress.IsCompleted).Value.Progress.ProgressID;
}
}
}
public class WorkflowService
{
private readonly IReadOnlySession _readOnlySession;
private readonly IUserSession _userSession;
private readonly IUpdateSession _updateSession;
private readonly INotificationService _notificationService;
public WorkflowService(IUserSession userSession, IReadOnlySession readOnlySession, IUpdateSession updateSession)
{
_userSession = userSession;
_readOnlySession = readOnlySession;
_updateSession = updateSession;
_notificationService = new NotificationService();
}
private int InstructionID { get; set; }
private int ProgressId { get; set; }
private DashboardInfo GetMyDashboard()
{
var wf = _readOnlySession.All<Dashboard>()
.GroupJoin(_readOnlySession.All<DashboardStage>(),
x => x.DashboardID,
y => y.DashboardID,
(dash, ds) =>
new
{
Dashboard = dash,
DashboardStages = ds.DefaultIfEmpty()
.Join(_readOnlySession.All<InstructionStageProgress>()
.Where(x => x.InstructionID == InstructionID),
x => x.DashboardStageID,
y => y.StageID,
(d, s) => new StageProgress
{
Progress = s,
Stages = d,
})
})
.Select(dash =>
new DashboardInfo
{
Dashboard = dash.Dashboard,
Stages = dash.DashboardStages.ToList()
})
.FirstOrDefault();
if (wf == null)
throw new NoAccessException(string.Format("dashboard not found for instruction #{0}", InstructionID));
return wf;
}
/// <summary>
/// we could determine workflow by instruction source?
/// </summary>
/// <param name="instruction"></param>
/// <returns></returns>
private IHigherLevelWorkflow DetermineWorkflow(Instruction instruction)
{
var dashboard = GetMyDashboard();
var wfhandler = new Workflow (instruction, dashboard.Dashboard, dashboard.Stages);
return wfhandler;
}
/// <summary>
/// these rules will be based on the workflow...
/// </summary>
/// <param name="workflow"></param>
/// <returns></returns>
private static IWorkflowStageHandler DetermineWorkflowRules(IHigherLevelWorkflow workflow)
{
return new WorkflowStageHandler();
}
public void CloseWorkflowStage(int instructionid, int progressId)
{
InstructionID = instructionid;
ProgressId = progressId;
var instruction = _readOnlySession.GetData(instructionid, _userSession);
//set up workflow + rules...
var wfhandler = DetermineWorkflow(instruction);
var stageHandler = DetermineWorkflowRules(wfhandler);
StageProgress mystage;
stageHandler.CloseStage(_readOnlySession, _userSession, wfhandler, progressId, out mystage);
//raise notification
//persist...
_updateSession.Update(mystage.Progress);
_notificationService.SaveNotifications(_updateSession);
_updateSession.CommitChanges();
}
public void OpenWorkflowStage(int instructionid, int progressId)
{
InstructionID = instructionid;
ProgressId = progressId;
var instruction = _readOnlySession.GetData(instructionid, _userSession);
//user wants to close a stage...
//is stage valid?
var wfhandler = DetermineWorkflow(instruction);
var stageHandler = DetermineWorkflowRules(wfhandler);
StageProgress mystage;
stageHandler.OpenStage(_readOnlySession, _userSession, wfhandler, progressId, out mystage);
//raise notification//
//persist...
_updateSession.Update(mystage.Progress);
_notificationService.SaveNotifications(_updateSession);
_updateSession.CommitChanges();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T16:16:17.213",
"Id": "12797",
"Score": "0",
"body": "The ResolveDashboard()-method is almost impossible to read due to heavy overusage of LINQ. I would begin with some refactoring there"
}
] |
[
{
"body": "<ul>\n<li>Conceptually you say you open and close stages. Then I'd expect to see open and close methods in a stage class, not in the workflow class.</li>\n<li>Looks like stages are non-trival. I'd expect to see these created w/in some kind of factory pattern</li>\n<li>Wheres the exception handling? Seeing NoAccessException thrown in the example implementation of the interface concerns me. I don't see your higherLevelworkflow code expecting exceptions at all. I like to see the highest level of my application catching exceptions so it can deal with them. Maybe you want to send an email, or put them in a database, or something else or none-of-the-above.</li>\n<li>Generally, I don't see the code design implementing appropriate abstraction levels. </li>\n<li>In terms of \"guidelines\", ResolveDashboard() is violating many: Too many nested levels, too long. It's complex, but no comments. Totally untestable!! It's essentially one massive WTF statement. It either has to all work or not at all.</li>\n<li>Generally, you should pull the code in ResolveDashboard() into a separate class/layer for data fetching. Generally this ultimately makes the various code pieces easier to test also.</li>\n<li>Are there other kinds of concrete workflows? It's odd that the IHigherWorkflow interface has such a generically named implementation.</li>\n<li>Are there \"ILowerLevelWorkflow\"s? If not then consider renaming the interface.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T11:34:52.167",
"Id": "12827",
"Score": "0",
"body": "Yes I have been told there will be different higherlevel workflows - each with its own validation + rules (potentially), hence the need for an interface (I will resolve the higherlevel interface depending on certain variable)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T11:37:08.873",
"Id": "12828",
"Score": "0",
"body": "point3 - handling exceptions: my asp.net mvc application will handle this, not my domain/core project, it is handled inside a filter globally, some errors will show up in UI, some errors will force a 404 - depends on what exception I am throwing, so there is no need to handle anything within these classes (unless it is relevant to the code creating/calling/depending on this class)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T12:24:15.597",
"Id": "12830",
"Score": "0",
"body": "I have refactored, could you please comment?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T23:51:28.133",
"Id": "8205",
"ParentId": "8006",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T17:01:44.740",
"Id": "8006",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"classes"
],
"Title": "C#: Simplfy code using Interfaces + business rules / validation"
}
|
8006
|
<p>I have a routine that can be potentially reduced.</p>
<pre><code>internal ArrayBufferObject GetAccessorArray()
{
ColladaDocument colladaDocument = GetColladaDocument();
ColladaArray colladaArray = colladaDocument.GetSpecialElement<ColladaArray>(Source);
ArrayBufferObject bufferObject;
if (IsSimpleParamsConfiguration() == false)
throw new NotSupportedException("complex accessor params not supported");
string simpleParamsType = Params[0].Type;
if (simpleParamsType == ArrayTypeFloat) {
uint cursorOffset = Offset;
ArrayBufferObject<float> arrayBufferObject = new ArrayBufferObject<float>(BufferObject.Hint.StaticCpuDraw);
for (uint i = 0; i < Count; i++) {
foreach (ColladaParam param in Params) {
if (param.Name != null)
arrayBufferObject[cursorOffset - Offset] = (float) colladaArray[cursorOffset];
cursorOffset++;
}
cursorOffset += Stride - (uint)Params.Count;
}
bufferObject = arrayBufferObject;
} else if (simpleParamsType == ArrayTypeInt) {
uint cursorOffset = Offset;
ArrayBufferObject<int> arrayBufferObject = new ArrayBufferObject<int>(BufferObject.Hint.StaticCpuDraw);
for (uint i = 0; i < Count; i++) {
foreach (ColladaParam param in Params) {
if (param.Name != null)
arrayBufferObject[cursorOffset - Offset] = (int) colladaArray[cursorOffset];
cursorOffset++;
}
cursorOffset += Stride - (uint)Params.Count;
}
bufferObject = arrayBufferObject;
} else
throw new NotSupportedException(String.Format("simple accessor params type {0} not supported", simpleParamsType));
return (bufferObject);
}
</code></pre>
<p>As you can see, there are two <code>if</code> branches that are the same. Essentially they create a generic class using <code>float</code> and <code>int</code> type.</p>
<p>The class <code>ArrayBufferObject</code> is the base of <code>ArrayBufferObject<T></code>, but only the latter implements an indexer (strongly typed). It is implemented as following:</p>
<pre><code>public T this[uint index]
{
get
{
if ((MemoryBuffer == null) || (MemoryBuffer.AlignedBuffer == IntPtr.Zero))
throw new InvalidOperationException("not defined");
if (index >= ItemCount)
throw new ArgumentException("index out of bounds", "index");
return ((T) Marshal.PtrToStructure(new IntPtr(MemoryBuffer.AlignedBuffer.ToInt64() + (index * mItemSize)), typeof(T)));
}
set
{
if ((MemoryBuffer == null) || (MemoryBuffer.AlignedBuffer == IntPtr.Zero))
throw new InvalidOperationException("not defined");
if (index >= ItemCount)
throw new ArgumentException("index out of bounds", "index");
Marshal.StructureToPtr(value, new IntPtr(MemoryBuffer.AlignedBuffer.ToInt64() + (index * mItemSize)), false);
}
}
</code></pre>
<p>The source of the assigned item comes from a <code>ColladaArray</code> class, that is an abstract class wrapping an array of values. To resolve the data accessor I've defined in it a generic numeric accessor like the following:</p>
<pre><code>/// <summary>
/// Access this array.
/// </summary>
/// <param name="i">
/// The index of the element to be accessed.
/// </param>
/// <returns>
/// It returns an equivalent <see cref="System.Double"/> of the value accessed.
/// </returns>
public virtual double this[uint i] { get { throw new NotSupportedException("array accessor not implemented"); } }
</code></pre>
<p>Which is implemented in each derived class returning the real array value casted to double (all arrays contains numeric data... hopefully).</p>
<hr>
<p>How would you suggest to remove the <code>GetAccessorArray</code> routine redundancies? Help! Soon it will grow up with all possible numeric types!</p>
|
[] |
[
{
"body": "<p>Presumably you could pull those sections out into a generic method. </p>\n\n<pre><code>private ArrayBufferObject CreateArrayBuffer<T>(ColladaArray colladaArray)\n{\n uint cursorOffset = Offset;\n\n ArrayBufferObject<T> arrayBufferObject = new ArrayBufferObject<T>(BufferObject.Hint.StaticCpuDraw);\n\n for (uint i = 0; i < Count; i++)\n {\n foreach (ColladaParam param in Params)\n {\n if (param.Name != null)\n arrayBufferObject[cursorOffset - Offset] = (T)Convert.ChangeType(colladaArray[cursorOffset], typeof(T));\n cursorOffset++;\n }\n cursorOffset += Stride - (uint)Params.Count;\n }\n\n return arrayBufferObject;\n}\n</code></pre>\n\n<p>And then replace those sections with a call to that method.</p>\n\n<pre><code>if (simpleParamsType == ArrayTypeFloat)\n return CreateArrayBuffer<float>(colladaArray);\nelse if (simpleParamsType == ArrayTypeInt)\n return CreateArrayBuffer<int>(colladaArray);\nelse\n throw new NotSupportedException(String.Format(\"simple accessor params type {0} not supported\", simpleParamsType));\n</code></pre>\n\n<p>Depending on the types that you're converting to and from, the call to <code>Convert.ChangeType()</code> may have to be changed to something else, but it should be sufficient for the standard numeric types. For more information on type conversion, see <a href=\"http://msdn.microsoft.com/en-us/library/98bbex99.aspx\" rel=\"nofollow\">this.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T08:37:42.437",
"Id": "12714",
"Score": "0",
"body": "I got it too after good sleeping, but I was missing the \"generic cast\"!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T00:02:22.610",
"Id": "8043",
"ParentId": "8008",
"Score": "4"
}
},
{
"body": "<p>Ahhh ... C# and numeric generics. Been <a href=\"http://whathecode.wordpress.com/2011/01/24/interpolation-no-more/\" rel=\"nofollow\">experimenting with that myself</a> quite a bit in order to interpolate any types.</p>\n\n<p>Originally I used <a href=\"http://www.codeproject.com/Articles/8531/Using-generics-for-calculations\" rel=\"nofollow\">the Arithmetic library</a>, which worked practically just as fast as normal math operators.</p>\n\n<p>My latest implementation follows <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html\" rel=\"nofollow\">an idea by Marc Gravell, borrowed from the MiscUtils library</a>. At the moment all the code in my library has been converted to use an <code>Operator</code> class in order to do generic calculations. First benchmarks show it runs just as fast as before when using the Arithmetic library.</p>\n\n<p>There's quite a bit of theory behind it, which I'm not going to explain all here, but Arithmetic and Operator are the two most important sources on the subject. Operator uses expression trees which is only available starting from .NET 3.5, should that be a concern.</p>\n\n<ul>\n<li><a href=\"https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System/Operators/Operator.cs\" rel=\"nofollow\">Example implementation for Operator</a>.</li>\n<li><a href=\"https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System/Arithmetic/Range/Interval.cs\" rel=\"nofollow\">Example implementation using it for an Interval class.</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T02:35:07.570",
"Id": "12706",
"Score": "0",
"body": "The code is quite complex. I'll attempt extracting some relevant portions of it tomorrow."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T02:30:54.723",
"Id": "8046",
"ParentId": "8008",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T18:46:29.130",
"Id": "8008",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Generics for reducing redundancies"
}
|
8008
|
<p>My goal was to make a list dynamically list itself into two columns, no matter the length of the list. I know this is possible by just floating the <code>li</code> nodes, but I wanted to keep the <code>li</code> nodes in the same vertical order. I would really like to hear from people who know more about JavaScript and jQuery than I do if this code looks good or if there is a better or more concise method for implementing this sort of thing.</p>
<p>Demo: <a href="http://jsfiddle.net/mkimitch/ZEL5x/" rel="nofollow">http://jsfiddle.net/mkimitch/ZEL5x/</a></p>
<p>HTML:</p>
<pre><code><ul class="columned">
<li>Australia</li>
<li>Brazil</li>
<li>Canada</li>
<li>Chile</li>
<li>China</li>
<li>France</li>
<li>India</li>
<li>Italy</li>
<li>Malaysia</li>
<li>Norway</li>
<li>Russia</li>
<li>United Kingdom</li>
<li>United States</li>
</ul>
</code></pre>
<p>JavaScript:</p>
<pre><code>var colLength = $('.columned li').length;
var colHeight = $('.columned').height();
var liHeight = $('.columned li').height();
if ($('.columned li').length % 2 != 0) {
var half = (Math.round(colHeight / 2)) + liHeight / 2;
} else {
var half = Math.round(colHeight / 2);
}
var firstrow = Math.ceil(colLength / 2);
var secondrow = firstrow + 1;
$('.columned li:nth-child(-n+' + firstrow + ')').addClass('column1');
$('.columned li:nth-child(n+' + secondrow + ')').addClass('column2');
$('.columned li:nth-child(' + secondrow + ')').css('margin-top', -half);
</code></pre>
|
[] |
[
{
"body": "<p>the best javascript is no javascript ;-)</p>\n\n<p>you could use css3 columns, see <a href=\"http://jsfiddle.net/bjelline/JWnaz/\" rel=\"nofollow\">http://jsfiddle.net/bjelline/JWnaz/</a> for the result</p>\n\n<pre><code>ul {\n-moz-column-count: 2;\n-moz-column-gap: 20px;\n-webkit-column-count: 2;\n-webkit-column-gap: 20px;\ncolumn-count: 2;\ncolumn-gap: 20px;\n</code></pre>\n\n<p>}</p>\n\n<p>if you are worried about browser support: there's a polyfill for that\n<a href=\"http://www.csscripting.com/css-multi-column/\" rel=\"nofollow\">http://www.csscripting.com/css-multi-column/</a>\nthat falls back to javascript if the browser doesn't honor the css yet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:13:31.213",
"Id": "12690",
"Score": "1",
"body": "that jsfiddle link goes to the original demo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:39:03.530",
"Id": "12694",
"Score": "0",
"body": "Thanks, and yes, I am worried about browser support. I've written this code for a global Web site, so users will be using all sorts of browsers to view this, including IE6 (and maybe even IE 5.5). What's more is that the content will be translated into many different languages, and will often be updated by either someone using a WYSIWYG editor, or by someone who doesn't know a whole lot about code, so making the HTML as simple as possible is the goal. I'll definitely look into that polyfill script. Other than the implementation, how does my code look? For jQuery is it well structured?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:08:21.647",
"Id": "8011",
"ParentId": "8010",
"Score": "1"
}
},
{
"body": "<p>For simpler javascript, you can just move the second half of the <code>li</code> elements into a new <code>ul</code> element, and float both of them left, so the structure looks like this:</p>\n\n<pre><code><ul class=\"columned\" style=\"float:left\">\n <li>Australia</li>\n <li>Brazil</li>\n <li>Canada</li>\n <li>Chile</li>\n <li>China</li>\n <li>France</li>\n <li>India</li>\n</ul>\n<ul style=\"float:left\">\n <li>Italy</li>\n <li>Malaysia</li>\n <li>Norway</li>\n <li>Russia</li>\n <li>United Kingdom</li>\n <li>United States</li>\n</ul>\n</code></pre>\n\n<p>JavaScript:</p>\n\n<pre><code>$('.columned').each(function() {\n // divide the children\n var secondColNum = Math.ceil($(this).children('li').length / 2);\n\n // float first ul left\n $(this).css('float', 'left');\n\n // move the children to the second ul\n var secondColChildren = $(this).children('li:nth-child(n+' + secondColNum + ')');\n $('<ul style=\"float:left\"></ul>').insertAfter($(this)).append(secondColChildren);\n});\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/PqWgj/\" rel=\"nofollow\">http://jsfiddle.net/PqWgj/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:18:01.737",
"Id": "8012",
"ParentId": "8010",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T20:00:33.297",
"Id": "8010",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Is there a better or more concise way to do this?"
}
|
8010
|
<p>I am very new to functional programming. I wrote this program where the user can enter an integer and it will print the factorial. If the user enters a negative integer or not an integer at all, it'll give the user a second chance.</p>
<p>This doesn't feel very functional to me. How can I make this code more functional (esp. the main function)? Or is this just fine?</p>
<pre><code>module Main where
import Data.Char
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = product [1..n]
isIntegral :: String -> Bool
isIntegral [] = False
isIntegral st = all isDigit st
main :: IO ()
main = do
putStrLn "Enter a non-negative integer:"
numberStr <- getLine
if isIntegral numberStr
then do
let number = read numberStr :: Integer
if number < 0
then do
main
else do
putStrLn $ show $ factorial number
else do
main
</code></pre>
|
[] |
[
{
"body": "<p>The line <code>factorial 0 = 1</code> is redundant. The product of the empty list is already 1.</p>\n\n<p>When writing a function that only works with strings (instead of arbitrary lists), I'd prefer to use <code>\"\"</code> instead of <code>[]</code> to denote the empty string. This way it's more obvious we're dealing with strings.</p>\n\n<p>Since your <code>isIntegral</code> function will return false for negative numbers (because <code>-</code> is not a digit), you should name it something like <code>isNaturalNumber</code> instead.</p>\n\n<p><s>Instead of applying <code>read</code> to the result of <code>getLine</code>, you can just use <code>readLn</code>.</s> (Edit: since in your latest revision you do error checking on the string before using <code>read</code>, this no longer applies). Likewise you can use <code>print</code> instead of <code>putStrLn</code> and <code>show</code>.</p>\n\n<p>Instead of having multiple <code>$</code>s on the same line, it is usually preferred to combine <code>.</code>s and <code>$</code>s. However using <code>print</code> you only need <code>print $ factorial number</code> anyway.</p>\n\n<p>There is no point in prefixing a single expression with <code>do</code>, so you should remove the <code>do</code>s from your <code>if</code> and <code>else</code>.</p>\n\n<p>Also since your <code>isIntegral</code>/<code>isNaturalNumber</code> function already returns false for negative numbers, there's no need to check whether the result is negative after calling <code>read</code>, so you can get rid of the if-statement and the duplication of calling <code>main</code> recursively from two different places.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:43:34.850",
"Id": "12696",
"Score": "0",
"body": "I have added error checking (see the updated question) so I guess I can't simply use `readLn` anymore. Is there a solution for that? Thanks for all the other tips!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:50:04.220",
"Id": "12697",
"Score": "1",
"body": "@WTP: Yes, I noticed that. I adjusted my answer in response to your edit (and yes, with error checking it's no longer possible to use `readLn`)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:41:02.940",
"Id": "8019",
"ParentId": "8018",
"Score": "7"
}
},
{
"body": "<p>First of all, Haskell is pure functional language, so you can not write anything non-functional in it. However, some improvements can be made:</p>\n\n<ul>\n<li><p>Instead of making a custom check for <code>isIntegral</code> you can use the <code>reads</code> function, which is does the same thing as <code>read</code>, but instead of crashing returns the empty list on failure.</p></li>\n<li><p>Your program consists of two steps: reading a number and printing its factorial. However, the complicated control flow makes it difficult to see. You can make it more explicit.</p></li>\n<li><p>It is often beneficial to bring the amount of code involving <code>IO</code> to the minimum because IO is hard to reason about. You can extract the <code>IO</code>-free code into separate functions. </p></li>\n</ul>\n\n<p>The last two \"improvements\" increase the code size in this case though, so they are not so useful here. Try writing a more complex program and concerns like this will become relevant.</p>\n\n<pre><code>factorial n = product [1..n]\n\nreadNumber :: String -> Maybe Integer\nreadNumber numberStr = case reads numberStr of\n [(number,\"\")] | number >= 0 -> Just number\n _ -> Nothing\n\ngetNumber :: IO Integer\ngetNumber = do\n putStrLn \"Enter a non-negative integer:\"\n numberStr <- getLine\n case readNumber numberStr of\n Nothing -> getNumber\n Just number -> return number\n\nmain :: IO ()\nmain = getNumber >>= print . factorial\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T04:20:29.607",
"Id": "13209",
"Score": "1",
"body": "I'd use a guard in readNumber: `[(number,\"\")] | number >= 0 -> ...`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T01:03:02.167",
"Id": "8044",
"ParentId": "8018",
"Score": "2"
}
},
{
"body": "<p>Reifying a few of sepp2k's suggestions:</p>\n\n<pre><code>module Main where\nimport Data.Char\n\nfactorial :: Integer -> Integer\nfactorial n = product [1..n]\n\nisNat :: String -> Bool\nisNat [] = False\nisNat st = all isDigit st\n\nmain :: IO ()\nmain = do\n putStrLn \"Enter a non-negative integer:\"\n numberStr <- getLine\n if isNat numberStr\n then print . factorial . read $ numberStr\n else main\n</code></pre>\n\n<p>An alternate approach, use <code>Maybe</code>s:</p>\n\n<pre><code>module Main where\nimport Data.Char\n\nfactorial :: Integer -> Integer\nfactorial n = product [1..n]\n\nparseNat :: String -> Maybe Integer\nparseNat [] = Nothing\nparseNat st | all isDigit st = Just $ read st\n | otherwise = Nothing\n\nmain :: IO ()\nmain = do\n putStrLn \"Enter a non-negative integer:\"\n numberStr <- getLine\n case parseNat numberStr of\n Just num -> print $ factorial num\n Nothing -> main\n</code></pre>\n\n<p>For different control flow, you might like <code>unless</code> and <code>when</code> from <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad.html#g:6\" rel=\"nofollow\">Control.Monad</a>.</p>\n\n<p>Also, be aware of <a href=\"http://community.haskell.org/~ndm/hlint/\" rel=\"nofollow\">hlint</a>, which can sometimes give you tips on being more Haskellish.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T02:15:03.220",
"Id": "8045",
"ParentId": "8018",
"Score": "3"
}
},
{
"body": "<p>Consider replacing <code>isIntegral</code> with an inline test:</p>\n\n<pre><code>...\nmain = do\n putStrLn \"Enter a non-negative integer:\"\n numberStr <- getLine\n if not (null numberStr) && all isDigit numberStr\n ...\n</code></pre>\n\n<p>It's hard to explain, both concisely and correctly, what <code>isIntegral</code> (or as some suggested, <code>isNat</code> or <code>isNaturalNumber</code>) does. Sure, you can say it tests if the string contains a non-negative integer. But does it accept hexadecimal syntax? How does it treat octals?</p>\n\n<p>On the other hand, perhaps the definition of <code>isIntegral</code> can be based on purpose, rather than function:</p>\n\n<pre><code>-- | Test if the string is a valid, non-negative integer that can be parsed\n-- with 'read'.\nisIntegral :: String -> Bool\nisIntegral [] = False\nisIntegral st = all isDigit st\n</code></pre>\n\n<p>By this interpretation, keeping <code>isIntegral</code> separate makes it easier to extend later (e.g. to allow hexadecimal syntax, which <code>read :: String -> Integer</code> accepts). It's a matter of fixing a standalone function, rather than modifying code buried in a procedure with broader scope (namely, <code>main</code>).</p>\n\n<p>However, <code>isIntegral</code>'s definition assumes that the caller calls <code>read</code> (or similar) after validating the input with <code>isIntegral</code>. It would be simpler to do the reading and validation in one function. See the <code>readNumber</code> function in <a href=\"https://codereview.stackexchange.com/a/8044/2672\">Rotsor's answer</a>, which uses <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:reads\" rel=\"nofollow noreferrer\"><code>reads</code></a> and a <a href=\"http://en.wikibooks.org/wiki/Haskell/Control_structures#Guards\" rel=\"nofollow noreferrer\">guard</a> to accomplish this.</p>\n\n<h2>Playing with point-free</h2>\n\n<p>Let's see if we can make this more concise:</p>\n\n<pre><code>isIntegral :: String -> Bool\nisIntegral [] = False\nisIntegral st = all isDigit st\n</code></pre>\n\n<p>Or, put another way:</p>\n\n<pre><code>isIntegral st = not (null st) && all isDigit st\n</code></pre>\n\n<p>We can express it in <a href=\"http://www.haskell.org/haskellwiki/Pointfree\" rel=\"nofollow noreferrer\">point-free</a> style (i.e. eliminate variables using combinators like <code>.</code>, <code>flip</code>, <code>uncurry</code>, etc.):</p>\n\n<pre><code>isIntegral = liftA2 (&&) (not . null) (all isDigit)\n</code></pre>\n\n<p>Yes, this is longer and more cryptic. However, with a little practice, it's easy to see that it's combining two predicates, <code>not . null</code> and <code>all isDigit</code>, with the <code>&&</code> operator. Since <code>&&</code> doesn't like functions as arguments, the noisy <code>liftA2</code> (<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Applicative.html#v:liftA2\" rel=\"nofollow noreferrer\">from Control.Applicative</a>) is applied to <code>&&</code> to combine predicates.</p>\n\n<p>Although I would say point-free is overkill here, it's good to practice using it. Here are a couple examples where point-free does make things more concise (in my opinion):</p>\n\n<pre><code>-- Read two lines, and combine their values with (+)\naddLines :: IO Integer\naddLines = (+) <$> readLn <*> readLn\n\n-- Call \"hPutStrLn msg\" on each Handle in the list.\n--\n-- Unfortunately, `hPutStrLn` takes the Handle argument first, so we have to\n-- flip it to use it like we want.\nbroadcast :: String -> [Handle] -> IO ()\nbroadcast = mapM_ . flip hPutStrLn\n</code></pre>\n\n<p>Learning to write in point-free style can help you write programs faster. Here's a script I wrote recently that takes a list of file names, and prints lines present in every file:</p>\n\n<pre><code>import Data.List (foldl1')\nimport System.Environment\n\nimport qualified Data.Set as S\n\nmain :: IO ()\nmain = getArgs\n >>= mapM (fmap (S.fromList . lines) . readFile)\n >>= mapM_ putStrLn . S.toList . foldl1' S.intersection\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T01:16:07.703",
"Id": "8482",
"ParentId": "8018",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:13:49.357",
"Id": "8018",
"Score": "8",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Printing a factorial from an integer"
}
|
8018
|
<p>The basic format of a ternary operator is thus:</p>
<pre><code>condition ? first_expression : second_expression;
</code></pre>
<p>A number of languages have a ternary operator consisting of <code>?</code> and <code>:</code>. The proper name for this operator (at least in C and C-like languages) is the "conditional operator".</p>
<p>As "<a href="http://stackoverflow.com/questions/2997028/other-ternary-operators-besides-ternary-conditional">Other ternary operators besides ternary conditional (?:)</a>" determined, there <em>are</em> other ternary operators in various languages.</p>
<h2>Syntax examples:</h2>
<h3>MySQL</h3>
<p>This is MySQL specific and not SQL standard:</p>
<pre><code> IF(condition,value_when_true,value_when_false);
</code></pre>
<h3>PHP</h3>
<pre><code>(condition) ? value_when_true : value_when_false ;
</code></pre>
<p>or for a single condition, by reversing the condition:</p>
<pre><code>!(condition) ?: value_when_true;
</code></pre>
<h3>Python</h3>
<pre><code>value_when_true if condition else value_when_false
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:06:42.423",
"Id": "8021",
"Score": "0",
"Tags": null,
"Title": null
}
|
8021
|
Normally referring to the conditional operator, represented by the characters ? and :, that form a basic conditional expression in several programming languages, also known as inline if. It is used as follows: (condition) ? (value if true) : (value if false).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:06:42.423",
"Id": "8022",
"Score": "0",
"Tags": null,
"Title": null
}
|
8022
|
ASP.NET is a web application framework developed by Microsoft to allow programmers to build dynamic web sites and web applications.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:11:39.170",
"Id": "8024",
"Score": "0",
"Tags": null,
"Title": null
}
|
8024
|
<p>Object-oriented programming is an approach to designing modular, reusable software systems which models the issue first.</p>
<p>Rather than structuring programs as code and data, an object-oriented system integrates the two using the concept of an "object". An object has a state (data) and a behavior (code).</p>
<p>Objects correspond to things found in the real world. So for example, an online shopping system will have objects such as <em>shopping cart</em>, <em>customer</em>, and <em>product</em>. The shopping system will support behaviors such as <em>place order</em>, <em>make payment</em>, and <em>offer discount</em>. The objects are designed as class hierarchies. So, for example, with the shopping system there might be high level classes such as <em>electronics product</em>, <em>kitchen product</em>, and <em>book</em>. There may be further refinements for example under <em>electronic products</em>: <em>CD Player</em>, <em>DVD player</em>, etc.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:16:43.327",
"Id": "8025",
"Score": "0",
"Tags": null,
"Title": null
}
|
8025
|
<blockquote>
<p>Cascading Style Sheets (CSS) is a style sheet language used for
describing the look and formatting of a document written in a markup
language. While most often used to style web pages and interfaces
written in HTML and XHTML, the language can be applied to any kind of
XML document, including plain XML, SVG and XUL.</p>
</blockquote>
<p>Via <a href="https://en.wikipedia.org/wiki/Cascading_Style_Sheets" rel="nofollow noreferrer">Wikipedia</a></p>
<h2>Specification</h2>
<ul>
<li><a href="http://www.w3.org/Style/CSS/" rel="nofollow noreferrer">W3C: CSS homepage</a></li>
<li><a href="http://www.w3.org/TR/CSS2/" rel="nofollow noreferrer">W3C: CSS2.1</a></li>
<li><a href="http://www.w3.org/TR/WCAG20/" rel="nofollow noreferrer">W3C: Web Content Accessibility Guidelines (WCAG)</a></li>
<li><a href="http://www.w3.org/TR/WCAG20/" rel="nofollow noreferrer">W3C: Media Queries</a></li>
<li><a href="http://www.w3.org/TR/css3-selectors/" rel="nofollow noreferrer">W3C: Selectors Level 3</a></li>
<li><a href="http://www.w3.org/Style/CSS/current-work" rel="nofollow noreferrer">List of other CSS standards</a> (including various parts of CSS3)</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="https://developer.mozilla.org/en/CSS" rel="nofollow noreferrer">Mozilla Developer Network</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/ms531209(v=vs.85).aspx" rel="nofollow noreferrer">Internet Explorer Dev Center</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:17:33.497",
"Id": "8027",
"Score": "0",
"Tags": null,
"Title": null
}
|
8027
|
CSS, short for Cascading Style Sheets, is a language used to control the presentation of HTML and XML documents including colors, layout, and fonts.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:17:33.497",
"Id": "8028",
"Score": "0",
"Tags": null,
"Title": null
}
|
8028
|
<p>A DATABASE is a collection of information organized in such a way that a computer program can quickly select desired pieces of data. You can think of a database as an electronic filing system.</p>
<p>The term <em>database</em> should not be confused with <em>Database Management System</em> (DBMS). A DBMS is the system software used to create and manage databases and provide users and applications with access to the database. A database is to a DBMS as a document is to a Word Processor.</p>
<p>See a more detailed information here: <a href="https://en.wikipedia.org/wiki/Database" rel="nofollow noreferrer">Database</a>.</p>
<hr>
<p><strong>Commonly used specific databases on Code Review:</strong></p>
<p>On Code Review we have a number of specific DBMS tags as well. If your question relates to a specific database, you may want to tag it with that tag only, or perhaps even both.</p>
<p><sup>no particular order</sup></p>
<ul>
<li><a href="/questions/tagged/mysql" class="post-tag" title="show questions tagged 'mysql'" rel="tag">mysql</a></li>
<li><a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged 'oracle'" rel="tag">oracle</a></li>
<li><a href="/questions/tagged/sql-server" class="post-tag" title="show questions tagged 'sql-server'" rel="tag">sql-server</a></li>
<li><a href="/questions/tagged/mongodb" class="post-tag" title="show questions tagged 'mongodb'" rel="tag">mongodb</a></li>
<li><a href="/questions/tagged/postgresql" class="post-tag" title="show questions tagged 'postgresql'" rel="tag">postgresql</a></li>
<li><a href="/questions/tagged/couchdb" class="post-tag" title="show questions tagged 'couchdb'" rel="tag">couchdb</a></li>
<li><a href="/questions/tagged/sqllite" class="post-tag" title="show questions tagged 'sqllite'" rel="tag">sqllite</a></li>
</ul>
<hr>
<p><strong>Other Related Tags:</strong></p>
<p>Additionally, if your question is about a database, you may want to tag your question with:</p>
<ul>
<li><a href="/questions/tagged/sql" class="post-tag" title="show questions tagged 'sql'" rel="tag">sql</a> for your database queries or manipulations (or <a href="/questions/tagged/tsql" class="post-tag" title="show questions tagged 'tsql'" rel="tag">tsql</a> for <a href="/questions/tagged/sql-server" class="post-tag" title="show questions tagged 'sql-server'" rel="tag">sql-server</a>, or <a href="/questions/tagged/plsql" class="post-tag" title="show questions tagged 'plsql'" rel="tag">plsql</a> for <a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged 'oracle'" rel="tag">oracle</a>)</li>
<li><a href="/questions/tagged/jdbc" class="post-tag" title="show questions tagged 'jdbc'" rel="tag">jdbc</a> for <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a> programs that interact with databases</li>
<li><a href="/questions/tagged/mysqli" class="post-tag" title="show questions tagged 'mysqli'" rel="tag">mysqli</a> for accessing <a href="/questions/tagged/mysql" class="post-tag" title="show questions tagged 'mysql'" rel="tag">mysql</a> from <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a></li>
</ul>
<hr>
<p><strong>Free Books</strong></p>
<ul>
<li><a href="http://www.database-books.us/" rel="nofollow noreferrer">Database-Books.us</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:18:43.090",
"Id": "8029",
"Score": "0",
"Tags": null,
"Title": null
}
|
8029
|
<p>A string is a sequence of characters commonly used to represent text; in most languages a string is a data type.</p>
<p>It is also used to represent a sequence of bytes encoding arbitrary binary data.</p>
<p>In the original C representation, a string is an array of characters (which are byte-sized <code>int</code>s) terminated by the "null character" <code>\0</code>. In the context of string implementations (or other programming languages), this implementation is often referred to as a C string.</p>
<p>In most languages, strings can be iterated over, similar to lists or arrays. However, in high-level languages (in which strings are a data type unto themselves), strings are immutable, whereas arrays are mutable.</p>
<p>String uses certain encoding to represent characters as bytes. Newer encodings like UTF-8 use variable number of bytes per character, making less trivial to access the next char, previous char or char at the given index in the string. A byte per char ASCII encoding uses is restricted to Latin alphabet. Some strings (like Java String) use 2 bytes per character.</p>
<p>For more details, see the <a href="http://en.wikipedia.org/wiki/String_(computer_science)" rel="nofollow">Wikipedia entry on String</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:21:07.423",
"Id": "8031",
"Score": "0",
"Tags": null,
"Title": null
}
|
8031
|
A string is a sequence of characters. It is commonly used to represent text or a sequence of bytes. Use this tag along with the appropriate programming language being used.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:21:07.423",
"Id": "8032",
"Score": "0",
"Tags": null,
"Title": null
}
|
8032
|
<h2>Description</h2>
<p>An <a href="http://en.wikipedia.org/wiki/Array_data_type" rel="nofollow noreferrer">array</a> is an ordered data structure consisting of a collection of elements (values or variables), each identified by at least one index, stored in contiguous memory locations. An array is typically stored so that the position of each element can be computed from its index tuple by a mathematical formula. In some languages (C, Java, etc.) the length of the array must be set beforehand. In other languages (Ruby, Python, LISP, etc.) the length of the array grows dynamically as elements are added.</p>
<ul>
<li><p>Elements of an array are generally specified with a 0-first index, for example, <code>myarray[0]</code> would represent the first element of <code>myarray</code>. <code>myarray[l]</code> (where <code>l</code> is the length of the array minus 1) would represent the last element in the array. However, some languages such as old Fortran and Lua use 1 as the initial index.</p></li>
<li><p>Some languages (<a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a>, <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a>, <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged 'c#'" rel="tag">c#</a>) have "basic arrays" and collections. Basic arrays are supported by the compiler directly; have fixed size and only provide element access by index. Collections, like Java's <a href="/questions/tagged/arraylist" class="post-tag" title="show questions tagged 'arraylist'" rel="tag">arraylist</a>, are system library classes implemented on the top of these basic arrays and have a wide range of various methods. In such cases the tag <code>arrays</code> should be used to name the simple arrays.</p></li>
<li><p>Arrays can be statically allocated or dynamically allocated. The way in which you access the array and its type varies based on how it is declared and allocated. </p></li>
</ul>
<h2>Array in specific languages</h2>
<ul>
<li><h3>Ruby</h3>
<p>In <a href="/questions/tagged/ruby" class="post-tag" title="show questions tagged 'ruby'" rel="tag">ruby</a> the normal array class is called an <code>Array</code>.</p></li>
<li><h3>Python</h3>
<p>In <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a> the normal array datatype is called a <code>list</code>, while the <a href="http://en.wikipedia.org/wiki/Array_data_type" rel="nofollow noreferrer"><code>array</code></a> type is used for homogeneous arrays.</p></li>
<li><h3>PHP</h3>
<p>In <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a> arrays are implemented as ordered maps which may contain a mix of numeric or string keys.</p></li>
<li><h3>JavaScript</h3>
<p>In <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a> arrays are just objects with a different prototype (with additional functions more useful for array-like structures), with numerical indexes stored as strings (all JavaScript keys are strings).</p></li>
</ul>
<h2>Tag Guidelines</h2>
<p>When tagging a question with this tag, also tag the question with the programming language being used.</p>
<h2>References</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Array_data_type" rel="nofollow noreferrer">Array Data Type (Wikipedia)</a></li>
<li><a href="http://en.wikipedia.org/wiki/Array_data_structure" rel="nofollow noreferrer">Array Data Structure (Wikipedia)</a></li>
<li><a href="http://introcs.cs.princeton.edu/java/14array/" rel="nofollow noreferrer">Fundamental of Array and Q+A </a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-20T22:22:26.330",
"Id": "8033",
"Score": "0",
"Tags": null,
"Title": null
}
|
8033
|
An array is an ordered data structure consisting of a collection of elements (values or variables), each identified by one (single dimensional array, or vector) or multiple indexes.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:22:26.330",
"Id": "8034",
"Score": "0",
"Tags": null,
"Title": null
}
|
8034
|
<p>Security is important in programming as a single vulnerability can compromise part or the entirety of a system.</p>
<p>Some measures to increase the security of a system include, but are not limited to, access control, awareness training, audit and accountability, risk assessment, penetration testing, vulnerability management, and security assessment and authorization.</p>
<h2>Secure coding</h2>
<p>Securing coding is the practice of developing computer software in a way that guards against the accidental introduction of security vulnerabilities. Techniques include reusing already tested code, data canonicalisation and input validation.</p>
<p>There are standards like <a href="https://www.securecoding.cert.org/confluence/display/seccode/SEI+CERT+Coding+Standards" rel="nofollow noreferrer">CERT</a> to help guide programmers to write secure code.</p>
<p>If your code controls safety-critical systems then you should also see the <a href="https://en.wikipedia.org/wiki/MISRA_C" rel="nofollow noreferrer">MISRA</a> standards and <a href="http://en.wikipedia.org/wiki/The_Power_of_10:_Rules_for_Developing_Safety-Critical_Code" rel="nofollow noreferrer">NASA Rules for Developing Safety Critical Code</a> (which also is relevant to general good practices too).</p>
<h2>Information Security</h2>
<p>Information security, sometimes shortened to infosec, is the practice of protecting information by mitigating information risks. </p>
<p>Key concepts include confidentiality, data integrity, availability, identification, authentication, authorization, reliability and non-repudiation.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-20T22:24:01.133",
"Id": "8035",
"Score": "0",
"Tags": null,
"Title": null
}
|
8035
|
Computer security is security applied to computing devices such as computers and smartphones, as well as to both private and public computer networks, including the whole Internet.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:24:01.133",
"Id": "8036",
"Score": "0",
"Tags": null,
"Title": null
}
|
8036
|
<p>Data structures are ubiquitous in software. Hash tables, balanced trees, and dynamic arrays are essential building blocks for large, complicated systems and almost all programmers have encountered them at some point. More complicated structures like binary heaps can speed up complicated systems, while simpler concepts like stacks and queues make it possible to more elegantly and concisely encode algorithms.</p>
<p>Of course, this is just the tip of the iceberg when it comes to data structures. Theoreticians have been developing progressively better and better data structures over the past years, many of which are used extensively in modern software, and many are only useful from a theoretical perspective.</p>
<p>Data structures are closely related to algorithms. Often, a good choice of data structure can lead to a marked improvement in an algorithm's runtime. For example, Dijkstra's algorithm with a naive implementation of a priority queue runs in quadratic time, but with a fast Fibonacci heap can be shown to run in O(m + n lg n).</p>
<p>Below is a (not at all comprehensive) list of some of the more popular data structures and their variants:</p>
<ul>
<li>Dynamic arrays
<ul>
<li>Dynamic table</li>
<li>Tiered vector</li>
<li>Hashed array tree</li>
<li>Extendible array</li>
</ul></li>
<li>Linked lists
<ul>
<li>Singly-linked lists</li>
<li>Doubly-linked lists</li>
<li>XOR-linked lists</li>
</ul></li>
<li>Hash tables
<ul>
<li>Chained hash tables</li>
<li>Linear probing hash tables</li>
<li>Quadratic probing hash tables</li>
<li>Double hash tables</li>
<li>Cuckoo hash tables</li>
<li>Perfect hash tables</li>
<li>Dynamic perfect hash tables</li>
</ul></li>
<li>Binary trees
<ul>
<li>Red/black trees</li>
<li>AVL trees</li>
<li>AA trees</li>
<li>Splay trees</li>
<li>Scapegoat trees</li>
<li>Treap</li>
</ul></li>
<li>Priority queues
<ul>
<li>Binary heap</li>
<li>Binomial heap</li>
<li>Fibonacci heap</li>
<li>van Emde Boas tree</li>
<li>Skew binomial heap</li>
<li>Brodal queue</li>
</ul></li>
<li>Radix trees
<ul>
<li>Trie</li>
<li>Patricia tree</li>
<li>Ternary search tree</li>
</ul></li>
<li>Multiway trees
<ul>
<li>B tree</li>
<li>B+ tree</li>
<li>B* tree</li>
</ul></li>
<li>Geometric trees
<ul>
<li>Quadtree</li>
<li>Octree</li>
<li>kd-Tree</li>
<li>BSP-tree</li>
<li>R-tree</li>
</ul></li>
<li>Geometric structures
<ul>
<li>Winged-edge</li>
<li>Quadedge</li>
</ul></li>
<li>Network connectivity structures
<ul>
<li>Disjoint-set forest</li>
<li>Link/cut tree</li>
<li>Top tree</li>
</ul></li>
<li>Graphs
<ul>
<li>DAG</li>
<li>Directed graph</li>
<li>Undirected graph</li>
<li>Hypergraph</li>
</ul></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:31:11.993",
"Id": "8037",
"Score": "0",
"Tags": null,
"Title": null
}
|
8037
|
A data structure is a way of organizing data in a fashion that allows particular properties of that data to be queried and/or updated efficiently. THIS TAG IS BEING REMOVED, SO USE A SPECIFIC DATA STRUCTURES TAG INSTEAD.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:31:11.993",
"Id": "8038",
"Score": "0",
"Tags": null,
"Title": null
}
|
8038
|
<p>This is a scraper written in CoffeeScript for NodeJS. It is run in an interval (set to 5 seconds here to dramtically show the leak). Somewhere this code leaks memory. I already tried nulling a few things for manually deleting references. Where is the reference kept that produces the leak?</p>
<pre><code>request = require 'request'
jsdom = require 'jsdom'
util = require 'util'
scrapeURL = 'http://kwlpls.adiwidjaja.com/index.php'
jqueryUrl = 'http://code.jquery.com/jquery-1.6.1.min.js'
scrapeDivId = "cc-m-externalsource-container-m8a3ae44c30fa9708"
scrapeDelay = 5 * 1000 # 5 seconds
data = []
fetch = (callback) ->
request { uri: scrapeURL }, (error, response, body) ->
if error and response and response.statusCode isnt 200
util.log 'Error when contacting #{scrapeURL}'
# Fake Browser
jsdom.env
html: body,
scripts: [jqueryUrl],
(err, window) ->
processPage(window, (result) ->
callback(err, result)
)
processPage = (window, callback) ->
# cleanup
result = {}
result.cities = []
result.parkings = []
$ = window.jQuery
rows = $('table').children()
num = $(rows).size()
rows.each (i, row) ->
if i > 0 and i isnt num - 1 # cut off header and footer
processRow($, row, (item, city) ->
result.parkings.push(item) if item?
result.cities.push(city) if city?
item = null
city = null
callback(result) if i is num - 2
)
processRow = ($, row, callback) ->
elements = $(row).children('td')
item = {}
city = null
nameStr = elements?.eq(0).html()
nameStr ?= ""
item.kind = nameStr.substring 0, 2
item.name = nameStr.substring 3
if elements.size() > 2
free = elements?.eq(2).html()
spaces = elements?.eq(1).html()
item.free = free
item.spaces = spaces
item.status = "open"
else if elements.size() > 0
item.status = "closed"
else
header = $(row).children().first().html()
currentCity = header.split(' ')[1]
city = {}
city.name = currentCity
item.city = currentCity
if item.name is "" or not item.name? then item = null
# cleanup
elements = null
$ = null
callback(item, city)
cacheJson = () ->
fetch(
(err, result) ->
util.log err if err?
data = result ? []
util.log 'Fetched ' + data?.parkings?.length + ' entries'
)
scrapeIntervalId = setInterval cacheJson, scrapeDelay
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:53:52.270",
"Id": "12699",
"Score": "1",
"body": "In coffeescript \\o/. Seriously I can't see a leak in your code which leaves three places jsdom, jQuery and coffeescript"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T23:11:32.210",
"Id": "12701",
"Score": "0",
"body": "I read about a leak adressing the use of jsdom in setInterval [here](https://github.com/joyent/node/issues/1007). But I don't really get it..."
}
] |
[
{
"body": "<p>I got here reading about garbage collection and memory leakage in CS. It's an old post but I 'll give my 2 cents anyway. When emptying an array it's often recommended to avoid using <code>array = []</code>, but use <code>array.length = 0</code>. </p>\n\n<p>Also, in functions that you don't indent to return, perhaps it's better to implicitly return undefined so that to avoid returning functions just because they appear at the very end of your CS function call. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-16T21:57:10.597",
"Id": "17625",
"ParentId": "8039",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:43:04.190",
"Id": "8039",
"Score": "3",
"Tags": [
"jquery",
"node.js",
"memory-management",
"web-scraping",
"coffeescript"
],
"Title": "Memory leak in a scraper"
}
|
8039
|
<p>I'm creating a factory design for math problems. The idea which I have is:</p>
<ul>
<li>When the factory initializes, creates in a list some problems (20 initially)</li>
<li>If the program wants more than 20, the list should grow until reach the requested quantity.</li>
</ul>
<p>For example, if I require 30 problems of the X problem, will generate two times.</p>
<ul>
<li>Some problems must be generated more difficult. I pass in the constructor the level and the factory must generate them.</li>
<li>To do this, I've got an abstract method called <code>ConfigureLevels</code>, where you has to set up.</li>
<li>I set an abstract method called Generate, this one must be implemented in a concrete class.</li>
<li>When the problem is generated, sometimes is not a good problem. When this happen, it must generate another's until gets a good problem. A good problem is according to a CRITERIA. I mean, the problem mustn't exist in the list, if we refer that the factory generates FRACTIONS, must be below than 1, etc. And I haven't done yet this last feature.</li>
</ul>
<p>This is the factory which I'm talking to:</p>
<pre><code>public abstract class Factory<T> where T : IProblem
{
protected static Random rnd;
protected LinkedListNode<T> actualNode;
protected LinkedList<T> problems;
public virtual int TotalProblemsPossible { get; set; }
protected virtual int InitialSize { get; set; }
protected Factory(Levels level)
{
this.InitialSize = 20;
Initialize();
ConfigureLevels(level);
FirstTime();
}
public virtual void FirstTime()
{
if (rnd == null) rnd = new Random(100);
if (problems == null)
{
problems = new LinkedList<T>();
Generate(problems);
}
actualNode = problems.First;
}
public virtual T CreateProblem()
{
if (actualNode.Next == null)
{
Generate(problems);
}
actualNode = actualNode.Next;
return actualNode.Value;
}
private void Generate(LinkedList<T> problems)
{
for (int i = 0; i < InitialSize; i++)
{
T newProblem;
int bucles = 0;
do
{
if (bucles == 50) throw new InvalidOperationException();
newProblem = Generate();
bucles++;
} while (problems.Contains(newProblem));
problems.AddLast(newProblem);
}
}
protected virtual void Initialize()
{
}
protected abstract T Generate();
protected abstract void ConfigureLevels(Levels level);
}
</code></pre>
<p>And here is a concrete class. Check how I'm overriding some methods from the abstract Factory. The factory create times table problems, and it knows how to calculates.</p>
<pre><code>public class TimesTableProblemFactory : Factory<BinaryProblem>
{
private Bound<int> Bound1 { get; set; }
private Bound<int> Bound2 { get; set; }
public TimesTableProblemFactory(Levels level)
: base(level)
{
}
protected override void Initialize()
{
base.Initialize();
}
protected override void ConfigureLevels(Levels level)
{
switch (level)
{
case Levels.Easy:
this.Bound1 = new Bound<int>(2, 6);
this.Bound2 = new Bound<int>(3, 11);
break;
case Levels.Normal:
this.Bound1 = new Bound<int>(3, 13);
this.Bound2 = new Bound<int>(3, 10);
break;
case Levels.Hard:
this.Bound1 = new Bound<int>(6, 13);
this.Bound2 = new Bound<int>(3, 10);
break;
}
}
protected override BinaryProblem Generate()
{
BinaryProblem problem;
int number1 = rnd.Next(Bound1.Min, Bound1.Max);
int number2 = rnd.Next(Bound1.Min, Bound1.Max);
Answer<decimal> correctValue = new Answer<decimal>(number1 * number2);
problem = new BinaryProblem(number1, number2, Operators.Multiplication, correctValue);
return problem;
}
}
</code></pre>
<p>Here is another factory for the same problem, which creates additions and multiplications:</p>
<pre><code>public class BinaryProblemFactory : Factory<BinaryProblem>
{
private Bound<int> _bound;
private LinkedList<Operators> _operatorsList;
private LinkedListNode<Operators> _node;
public BinaryProblemFactory(Levels level)
: base(level)
{
}
protected override void Initialize()
{
_bound = new Bound<int>();
_operatorsList = new LinkedList<Operators>(new List<Operators>() { Operators.Addition, Operators.Multiplication });
base.Initialize();
}
protected override void ConfigureLevels(Levels level)
{
switch (level)
{
case Levels.Easy:
this._bound = new Bound<int>(10, 100);
break;
case Levels.Normal:
this._bound = new Bound<int>(50, 200);
break;
case Levels.Hard:
this._bound = new Bound<int>(100, 10000);
break;
}
}
private Operators NextOperator()
{
if (_node == null || _node.Next == null)
{
_node = _operatorsList.First;
}
else
{
_node = _node.Next;
}
return _node.Value;
}
protected override BinaryProblem Generate()
{
BinaryProblem problem;
int number1 = rnd.Next(_bound.Min, _bound.Max);
int number2 = rnd.Next(_bound.Min, _bound.Max);
Answer<decimal> correctValue = new Answer<decimal>(number1 + number2);
problem = new BinaryProblem(number1, number2, NextOperator(), correctValue);
return problem;
}
}
</code></pre>
<p>I feel is not a well design, so I need a little of help to organize these factories. I'm gonna create around 200 hundreds of it. So, I prefer fix these instead spent pains.</p>
<p><img src="https://i.stack.imgur.com/6K14o.png" alt="enter image description here"></p>
<p>Now I need to know a list of available levels. I guess create three three virtual functions <code>CanConfigureXLevel</code> is not a good way.</p>
<p>Maybe it'll be great create a some dictionary which contains the available levels (Level enum as key) and value should have something like a container of objects useful to generate the problem (for example binary and times tables both needs two bound objects). </p>
<p><a href="http://www.mediafire.com/?tlm7abea14tdeks" rel="nofollow noreferrer">Here is the current project</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T15:11:32.290",
"Id": "13295",
"Score": "0",
"body": "I fail to see the point of `GrowSize`, why don't you just generate problems problems as you need them? It's not like it's going to be faster to generate many problems in a row, right? We're not talking about resizing an array here."
}
] |
[
{
"body": "<p>I think your list factory shouldn't be responsible for creating the concrete problems. How about separating the list factory from the problem factory? That way you can have <code>timeTableProblems</code> and <code>binaryProblems</code> in the same list. (even though that might not be a requirement, it's still a nice separation of concerns)</p>\n\n<p>It actually looks like you've catered for this since you have the <code>IProblem</code> interface.\nThe list factory wouldn't have to be generic either, it'd just keep a list of <code>IProblem</code>s generated by whatever problem factories it's given.</p>\n\n<p>Also, I believe you could apply the <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">template method pattern</a> to some of your methods. There is some repeated code in each of your concretes.</p>\n\n<p>For instance you could pull the <code>ConfigureLevels</code> method up to the base class and call down to <code>ConfigureEasy</code>, <code>ConfigureMedium</code> and <code>ConfigureHard</code>.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Regarding template methods, the point is to remove duplication, and at the same time avoid letting the FirstTime method be overridden for instance. It should call out to an empty OnFirstTime method instead. Derivatives might just forget to call base.FirstTime, and you probably don't want that. (Why not just join it with Initialize() ? )</p>\n\n<p>Here's a stub of a sample of separating the list factory and the problem factories.\nThe point is that these are two different things. A list of problems, and the problems themselves.</p>\n\n<p>Also have a look at this:\n<a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Single_responsibility_principle</a> </p>\n\n<pre><code>public class ProblemListFactory\n{ \n // omitted stuff\n\n protected Factory(ProblemFactory problemFactory) \n { \n // ...\n } \n\n public void Generate()\n {\n for(// ...)\n {\n IProblem problem = problemFactory.Generate();\n if (ProblemExists(problem))\n continue;\n problems.Add(problem);\n }\n }\n}\n\npublic abstract class ProblemFactory\n{\n protected Random Random = new Random();\n\n public abstract IProblem Generate();\n}\n\npublic class BinaryProblemFactory : ProblemFactory\n{\n public BinaryProblemFactory(Level level)\n {\n // ...\n }\n\n public override IProblem Generate()\n {\n // ...\n return new BinaryProblem(x, y, operator, answer);\n }\n}\n\n// ...\nvar binaryProblemListFactory = new ProblemListFactory(new BinaryProblemFactory(Level.Easy));\nvar binaryProblems = binaryProblemListFactory.Generate();\nvar timeTableProblemListFactory = new ProblemListFactory(new TimeTableProblemFactory(Level.Medium));\nvar timeTableProblems = timeTableProblemListFactory.Generate();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T17:48:04.427",
"Id": "12941",
"Score": "0",
"body": "I do not get your point, can you show an example of this (or an interface of it)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T01:16:29.750",
"Id": "13035",
"Score": "0",
"body": "I really do not have idea about the design patterns and it's beautiful your design. In fact right now, I'm studying them. For example, I'm trying to implement a singleton for Random property.\n\nOne doubt, how do you think will be the best way to pass paramaters for configuration. I mean, pass the Bound class of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T09:15:09.117",
"Id": "13044",
"Score": "0",
"body": "Great. :) Just remember not to use a sledge hammer for nails. I don't think you need a singleton for the random property. Just make it static if you want a common seed.\n\nHere's the overview for the siblings of SRP: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\nYou might also be interested in reading the Gang of four Design Patterns book. (google it)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T09:53:26.400",
"Id": "13045",
"Score": "0",
"body": "About the bounds, the factories could either take a dictionary of levels and bounds as parameter, or you could just pass the bounds and ditch the level completely. Although I don't see a problem with having the bounds config in the problem factories as you did with the list factories."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T19:50:16.167",
"Id": "13080",
"Score": "0",
"body": "I think is better because, later I need to show which levels are available, so I guess this is better. I've updated the post and the project, I just want to know how would I need to modified to implement the feature you're telling me (the dictionaries)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T23:55:52.620",
"Id": "13102",
"Score": "0",
"body": "I have an idea. According to your explanation, create a `Dictionary<Levels, IConfiguration> configurations;` in `ProblemFactory` class. At this case, for binary problems we can create `BinaryProblemConfiguration` which contains `Bound1`, `Bound2` and `Operators` (operators is a list if we want to have a mix of additions, substractions, multiplications or divisions). I guess doing this, we don't need `CanConfigureXLevel` and `ConfigureXLevel`, and the idea would just adding values to the dictionary, and here is I don't know what I should have to modify."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-28T01:47:34.317",
"Id": "13107",
"Score": "0",
"body": "I've updated the entire post with the most recently project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-28T22:50:08.033",
"Id": "13147",
"Score": "0",
"body": "I've checked as only and best answer. I just one to know if you can orient me in this part of the project: http://codereview.stackexchange.com/questions/8401/how-to-add-a-random-feature-for-a-factory-design\n\nIs about how to generate the random numbers according to an especific configuration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T23:47:22.607",
"Id": "13268",
"Score": "0",
"body": "See my comment on your linked question. (You should close either one of them I guess.)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T10:08:29.250",
"Id": "8277",
"ParentId": "8041",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "8277",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T23:01:48.327",
"Id": "8041",
"Score": "7",
"Tags": [
"c#",
"factory-method"
],
"Title": "Factory design for math problems"
}
|
8041
|
<p>I've been looking at ways to use asserts in programs that must do some kind of cleanup on fatal errors, and have arrived at the following pattern (PROJECT being replaced by the name of the project):</p>
<pre><code>#include <boost/exception/all.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <string>
#include <iostream>
#include <ostream>
typedef boost::error_info<struct tag_err_info,std::string> err_msg;
struct BaseError : virtual boost::exception, virtual std::exception {};
struct FatalError : BaseError {};
struct AssertionError : FatalError {};
#ifndef NDEBUG
#define PROJECT_ASSERT(expr) do { \
if (expr); \
else { \
std::string error = "Assertion failed: `"; \
error += #expr; \
error += "'."; \
BOOST_THROW_EXCEPTION(AssertionError() << err_msg(error)); \
} \
} while(false)
#else
#define PROJECT_ASSERT(expr) do {} while(false)
#endif
template<typename EXCEPTION>
void print_diagnostic_info(std::ostream& o, EXCEPTION const& e) {
#ifndef NDEBUG
o << boost::diagnostic_information(e) << std::endl;
#else
// Suppress unused parameter warnings
(void)o;
(void)e;
#endif
}
void fail() {
PROJECT_ASSERT(true > 0);
PROJECT_ASSERT(!!!true);
}
int main() {
try {
fail();
}
catch (BaseError& e) {
print_diagnostic_info(std::cerr, e);
if (std::string const* err_msg_p = boost::get_error_info<err_msg>(e))
std::cerr << "Error: " << *err_msg_p << std::endl;
// Cleanup goes here
}
}
</code></pre>
<p>Running this gives</p>
<pre><code>exception.cpp(39): Throw in function void fail()
Dynamic exception type: boost::exception_detail::clone_impl<AssertionError>
std::exception::what: std::exception
[tag_err_info*] = Assertion failed: `!!!true'.
Error: Assertion failed: `!!!true'.
</code></pre>
<p>What are the possible problems with this approach, and are there any improvements to be made?</p>
<p>One part I'm not sure about is defining <code>error</code> in the assertion. Seeing as this is an inner scope it should always hide out values, shouldn't it? Could this lead to unexpected warnings (maybe glue <code>__LINE__</code> to it?)?</p>
<p>EDIT: With suggestions incorporated:</p>
<pre><code>#include <boost/exception/all.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <string>
#include <iostream>
#include <ostream>
typedef boost::error_info<struct tag_err_info,std::string> err_msg;
struct BaseError : virtual boost::exception, virtual std::exception {};
struct FatalError : BaseError {};
struct AssertionError : FatalError {
AssertionError(std::string const& err) {
std::string error = "Assertion failed: `";
error += err;
error += "'.";
*this << err_msg(error);
}
};
#define PROJECT_ALWAYS_ASSERT(expr) do { \
if (expr); \
else { \
BOOST_THROW_EXCEPTION(AssertionError(#expr)); \
} \
} while(false)
#ifndef NDEBUG
#define PROJECT_ASSERT(expr) PROJECT_ALWAYS_ASSERT(expr)
#else
#define PROJECT_ASSERT(expr)
#endif
template<typename EXCEPTION>
void print_diagnostic_info(std::ostream& o, EXCEPTION const& e) {
#ifndef NDEBUG
o << boost::diagnostic_information(e) << std::endl;
#else
// Suppress unused parameter warnings
(void)o;
(void)e;
#endif
}
void fail() {
PROJECT_ASSERT(true > 0);
PROJECT_ASSERT(1 + 1 > 0);
PROJECT_ASSERT(!!!true);
}
int main() {
try {
fail();
}
catch (BaseError& e) {
print_diagnostic_info(std::cerr, e);
if (std::string const* err_msg_p = boost::get_error_info<err_msg>(e))
std::cerr << "Error: " << *err_msg_p << std::endl;
// Cleanup goes here
}
}
</code></pre>
<p>Commentary: I'm not sure I like the way the case when <code>NDEBUG</code> is defined is handled (I don't like it when expressions are evaluated), but I don't think there's any way of handling both that and the unused variable error.</p>
<p><em>Further Commentary</em>: I've thought about it, and I'm fairly certain I do not want expressions to be evaluated, as that would discourage expensive asserts (which I think is a bad thing, assuming those asserts improve matters).</p>
|
[] |
[
{
"body": "<p>Note: Personal opinions done matter. Just voicing them.</p>\n\n<p>Personally I don't like (runtime) asserts (checks that disappear in production just asking for trouble and if something goes wrong you can't reproduce it in debug mode now). But OK its better than no checks.</p>\n\n<p>Personally I don't like hiding throwing exceptions inside macros.<br>\nAll the work you do to build the exception could be done inside the exception constructor. </p>\n\n<p>I have not seen multiple inheritance in exceptions before. But then again I have not used boost::exception so that may be normal. But I don't see the need for virtual inheritance as they don't have a common root base (as they are both base classes). What does your catch look like that you need to inherit from both?</p>\n\n<p>You are obviously trying to have zero cost when asserts are disabled, yet you are using the function: <code>void print_diagnostic_info(std::ostream& o, EXCEPTION const& e)</code>. To be consistent with your other usage why is this not a macro (god I hate saying that since I hate using macros as function calls when we have template functions to solve that problem, but I think this is a unique type of situation where we are explicitly trying for zero overhead when asserts are disabled).</p>\n\n<p>No point in this:</p>\n\n<pre><code>#else\n#define PROJECT_ASSERT(expr) do {} while(false)\n#endif\n\n// Just do this:\n#else\n#define PROJECT_ASSERT(expr)\n#endif\n</code></pre>\n\n<p>Is there any point in this:</p>\n\n<pre><code>struct BaseError : virtual boost::exception, virtual std::exception {};\nstruct FatalError : BaseError {};\nstruct AssertionError : FatalError {};\n</code></pre>\n\n<p>The only reason to have an <a href=\"https://softwareengineering.stackexchange.com/a/118187/12917\">exception hierarchy</a> is if there is the ability to catch and explicitly recover from particular types of error. As this is an assertion you (by definition) can't recover so there is only the need for one exception type (and the generic one should suffice).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T22:43:31.203",
"Id": "12741",
"Score": "0",
"body": "Would a call to `print_diagnostics_info` really take enough resources for it to be of any harm? Seeing as it's a template, I would expect the compiler to turn it into a no-op in release, and it's only ever called when an exception is caught: wouldn't the output done at that point be far more expensive?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T22:46:40.480",
"Id": "12742",
"Score": "0",
"body": "The point of defining `PROJECT_ASSERT` that way when `NDEBUG` is defined is that there is no unnecessary `;` in the program -- as far as I know, it could cause the compiler to issue a warning. Is this no longer the case? (I can't seem to reproduce it with GCC.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T22:53:21.110",
"Id": "12743",
"Score": "0",
"body": "The reason for deriving virtually is covered here: http://www.boost.org/doc/libs/1_40_0/libs/exception/doc/using_virtual_inheritance_in_exception_types.html . Your advice not to explicitly derive an assertion error and to construct the error string in the constructor are somewhat contradictory: I'd like assertions to be clearly unlike other fatal errors. I can see why having all fatal errors represented by one class would be a good idea, though -- which would you say is more important?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T00:01:41.720",
"Id": "12767",
"Score": "0",
"body": "@AntonGolov: `print_diagnostics_info`: The cost would not be high and I personally would keep it as a function. But I am just making the comment you are attempting to have zero cost assertion stuff and this is not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T00:03:01.670",
"Id": "12768",
"Score": "0",
"body": "Empty statement is completely valid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T00:12:39.393",
"Id": "12769",
"Score": "0",
"body": "When I was trying to say is not to have a large hierarchy (not too not derive the exception type). If you follow the [link I provided](http://programmers.stackexchange.com/a/118187/12917) I go into more detail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T19:14:23.750",
"Id": "12808",
"Score": "0",
"body": "Zero-cost everywhere isn't really my goal, but I see what you mean. I know that an empty statement is valid; I was concerned about unwanted warnings (and legal release code not compiling in debug mode, but that's not as much of an issue), but it seems like compilers don't omit those for empty statements. I think I understand about the exception hierarchy, too. Thanks for the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T17:32:07.307",
"Id": "13697",
"Score": "0",
"body": "Do you always need macros for zero cost? You could have a templated parameter such that Assert<true> does stuff and Assert<false> does is no-op and suddenly we're reducing macro use. A macro that puts in __FILE__ and __LINE__ for you can be nice so we don't eliminate them completely but we do reduce and make our code easier to debug."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T19:28:09.933",
"Id": "8167",
"ParentId": "8047",
"Score": "2"
}
},
{
"body": "<p>I would change the macro to this :</p>\n\n<pre><code>#ifndef NDEBUG\n#define PROJECT_ASSERT(expr) \\\n if (!(expr)) \\\n { \\\n std::string error = \"Assertion failed: `\"; \\\n error += #expr; \\\n error += \"'.\"; \\\n BOOST_THROW_EXCEPTION(AssertionError() << err_msg(error)); \\\n }\n#else\n#define PROJECT_ASSERT(expr) (void)expr;\n#endif\n</code></pre>\n\n<p>to avoid compiler's warnings about unused variables.</p>\n\n<p>But as Loki said, I would leave assertions there.</p>\n\n<hr>\n\n<p>The compiler (if you use maximum warning level) will report warning in next case :</p>\n\n<pre><code>void foo( int a )\n{\n const bool aIsPos = a > 0;\n PROJECT_ASSERT( aIsPos );\n // use a\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T20:19:51.093",
"Id": "12809",
"Score": "0",
"body": "@AntonGolov Right. That was a small bug (fixed now). However, it is possible to get unused variables, like in the edit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T21:04:50.527",
"Id": "12811",
"Score": "0",
"body": "True; I wasn't aware it was common to do that. Thanks, redefining it as specified. About removing/including asserts in release builds: I'm mostly on the fence about that; will edit in a way to keep them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T18:00:27.607",
"Id": "8201",
"ParentId": "8047",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "8167",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T03:29:17.327",
"Id": "8047",
"Score": "6",
"Tags": [
"c++",
"exception-handling"
],
"Title": "Asserting when cleanup is required"
}
|
8047
|
<p>I have this method which sends binary data to server. The code works fine, but still, it's structure is kinda stupid: output and input connections are opened like thousands times (depends on data size), closed only once.</p>
<p>I cannot move the code that opens connection outside of the loop because I'm getting strange errors, like the data was never sent to server.</p>
<p>Please help me to restructure this code so it could still work and have a correct structure: </p>
<pre><code>OutputStream os = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection huc = null;
DataInputStream dis = null;
InputStream in = null;
Path path = null;
byte[] buf = new byte[64 * 1024];
int bytesRead = 0;
try {
path = Paths.get("D:\\testfile.rar");
in = Files.newInputStream(path);
int i = 0;
URL u = new URL(defaultURL);
while ((bytesRead = in.read(buf)) != -1) {
huc = (HttpURLConnection) u.openConnection(); // wrong
huc.setRequestMethod("POST");
huc.setRequestProperty("chunk-number", i + "");
huc.setDoOutput(true); // wrong
huc.setDoInput(true); // wrong
os = huc.getOutputStream(); // wrong
os.write(buf, 0, bytesRead);
os.flush();
System.out.println(i++ + " " + bytesRead);
int ch;
dis = new DataInputStream(huc.getInputStream()); // wrong
long len = huc.getContentLength();
if (len != -1) {
for (int k = 0; k < len; k++)
if ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
else {
// if the content-length is not available
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
}
Thread.sleep(16);
}
dis.close();
huc.disconnect();
int statusCode = huc.getResponseCode();
String message = huc.getResponseMessage();
messagebuffer.append("status code=" + statusCode + "\n");
messagebuffer.append("response message=" + message + "\n");
} catch (Exception ex) {
// throw errors
} finally {
// closing stuff
}
return messagebuffer.toString();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T12:39:52.303",
"Id": "12721",
"Score": "1",
"body": "Could you please show `Path` class?"
}
] |
[
{
"body": "<p>In my opinion the key way to improve this code is decomposition. Actually, methods with more than 15 java lines are usually <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smells</a> for me. So </p>\n\n<pre><code>//There should be other signature depending on what does this method actually do\npublic static String foo(Path path) throws InterruptedException, IOException {\n final StringBuffer messagebuffer = new StringBuffer();\n final byte[] buf = new byte[64 * 1024];\n InputStream in = null;\n try {\n in = Files.newInputStream(path);\n int bytesRead;\n int i = 0;\n while ((bytesRead = in.read(buf)) != -1) {\n dealWithConnection(bytesRead, messagebuffer, buf, i);\n i++;\n Thread.sleep(16);\n }\n } finally {\n closeQuietly(in);\n }\n return messagebuffer.toString();\n}\n\n\nprivate static void dealWithConnection(int bytesRead, StringBuffer messagebuffer, byte[] buf, int i) throws IOException {\n final URL u = new URL(defaultURL);\n HttpURLConnection huc = null;\n try {\n huc = (HttpURLConnection) u.openConnection();// wrong\n init(huc, i);\n send(huc, buf, bytesRead);\n fillData(huc.getInputStream(), huc.getContentLength(), messagebuffer);\n fillResultInfo(huc, messagebuffer);\n } finally {\n if (huc != null) huc.disconnect();\n }\n}\n\nprivate static void send(HttpURLConnection huc, byte[] buf, int bytesRead) throws IOException {\n OutputStream os = null;\n try {\n os = huc.getOutputStream(); // wrong\n os.write(buf, 0, bytesRead);\n os.flush();\n } finally {\n closeQuietly(os);\n }\n}\n\nprivate static void fillResultInfo(HttpURLConnection huc, StringBuffer messagebuffer) throws IOException {\n int statusCode = huc.getResponseCode();\n String message = huc.getResponseMessage();\n messagebuffer.append(\"status code=\").append(statusCode).append(\"\\n\"); //Don't use concatenation when you can append\n messagebuffer.append(\"response message=\" + message + \"\\n\");\n}\n\nprivate static void fillData(InputStream inputStream, int contentLength, StringBuffer messagebuffer) throws IOException {\n DataInputStream dis = null;\n try {\n dis = new DataInputStream(inputStream); // wrong\n\n //if (contentLength != -1) { //we don't need this check actually\n int ch;\n for (int k = 0; k < contentLength; k++)\n if ((ch = dis.read()) != -1)\n messagebuffer.append((char) ch);\n else {\n // if the content-length is not available\n while ((ch = dis.read()) != -1)\n messagebuffer.append((char) ch);\n }\n } finally {\n closeQuietly(dis);\n }\n}\n\n\nprivate static void init(HttpURLConnection huc, int i) throws ProtocolException {\n huc.setRequestMethod(\"POST\");\n huc.setRequestProperty(\"chunk-number\", i + \"\");\n huc.setDoOutput(true);\n huc.setDoInput(true); // wrong\n}\n</code></pre>\n\n<p>If you haven't <code>closeQuietly()</code> in your libs, it can be implemented like </p>\n\n<pre><code>private static void closeQuietly(Closeable closeable) {\n if (closeable == null) return;\n try {\n closeable.close();\n } catch (IOException ignored) {\n }\n}\n</code></pre>\n\n<p>It's not so easy task to figure out what does this code do. So further improvement can be easily done. Personally I would start from variables names. </p>\n\n<p>BTW, comments like <code>if the content-length is not available</code> is good signal that there should be some method/variable for this to make code be self documented.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T06:51:37.767",
"Id": "12778",
"Score": "0",
"body": "the question was not only about restructuring the code, but also keep it working in case you decide to do so. this code that you have provided will not work! the problem is that if you open new connection and close it each time (that's what you do, not the original code) the loop iteration ends - the operating system will soon run out of free ports! That's why i've asked to keep code working!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T08:51:29.413",
"Id": "12788",
"Score": "0",
"body": "@ilja First of all you provided that don't even compiled. Secondly, we don't know what it actually do. Beside I believe that reconstruction by decomposition is key idea to improve this code. This was direction, not end solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T13:18:05.673",
"Id": "8056",
"ParentId": "8051",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T07:59:14.260",
"Id": "8051",
"Score": "3",
"Tags": [
"java"
],
"Title": "Writing to an HttpURLConnection in a loop"
}
|
8051
|
<p>There is HTML that triggers the code below I want to disallow executing the script more than once per 24 hours. I wanted this script to store the last visit time in a table against the user ID in a database, then do a time calculation and back them out until the 24 hour expiry time.</p>
<pre><code><?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$player = $_POST['Player'];
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
//---- This is the connection
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
mysql_select_db($dbname);
$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
$query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
mysql_query($query1);
mysql_query($query2);
$query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
$result = mysql_query($query);
mysql_close($conn);
echo 'Done! Type /redeem in-game to get your diamonds.';
$ip=@$REMOTE_ADDR;
setcookie ("24Hourvote",$ip,time()+86400,'/',true,…
} else {
echo 'You have already voted today! Come back later...'; }
?>
</code></pre>
|
[] |
[
{
"body": "<p><sub>Note: this is intended to be a Community wiki since it was taken from a deleted answer by <a href=\"https://codereview.stackexchange.com/users/4673/yannis\">yannis</a>; The suggestion to do this was <a href=\"https://codereview.meta.stackexchange.com/a/10625/120114\">here</a></sub></p>\n<hr />\n<p><strong>mysql_* functions</strong></p>\n<p>Stop using them, immediately! They are essentially deprecated, as they refer to MySQL before version 4.1. They are not removed as to not brake backward compatibility, but there's no point in using them.</p>\n<p>The drop in replacement is <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">myslqi_* functions</a>, which are based around a newer MySQL driver that works better with MySQL 5.x. You can easily replace most references to myslq_* functions by just adding the extra <strong>i</strong>.</p>\n<p>But a far better solution is <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">PDO</a>, an object oriented database agnostic interface. Since you are starting out in object oriented PHP you'll definitely appreciate the object orient part, and as for the database agnostic part, it means that you can easily switch databases (with minor modifications).</p>\n<p><sub>Verbatim copy from another <a href=\"https://codereview.stackexchange.com/a/7337/4673\">one of my reviews</a>.</sub></p>\n<p><strong>Long if, small else</strong></p>\n<p>Instead of:</p>\n<pre><code>if( condition ) {\n // blah\n // blah \n // blah\n // blah\n // blah\n // blah\n // blah\n // blah\n // blah\n} else {\n // blah\n}\n</code></pre>\n<p>consider refactoring as:</p>\n<pre><code>if( !condition ) {\n // blah \n exit();\n} \n\n// blah\n// blah\n// blah\n</code></pre>\n<p>It's a bit more readable.</p>\n<p><strong>Player, you've been played</strong></p>\n<p>You get <code>$player</code> from a post variable:</p>\n<pre><code>$player = $_POST['Player'];\n</code></pre>\n<p>and then you go and feed it to the database:</p>\n<pre><code>$query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";\n</code></pre>\n<p>and, sooner or later, you're dead. Read everything you can about SQL injection on <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">Wikipedia</a> and the <a href=\"http://php.net/manual/en/security.database.sql-injection.php\" rel=\"nofollow noreferrer\">manual</a>. Tips:</p>\n<ol>\n<li>User input is unsafe, and it includes everything that comes from the environment (<code>$_POST</code>, <code>$_GET</code>, <code>$_SESSION</code>, <code>$_COOKIE</code>, <code>$_SERVER</code>, etc).</li>\n<li>Always validate and sanitize user input. Not only when you feed it to a database, always.</li>\n</ol>\n<p>For this instance, your best bet would be to go with PDO and <a href=\"http://php.net/manual/en/pdo.prepared-statements.php\" rel=\"nofollow noreferrer\">prepared statements</a>, that's how the cool kids do it anyway. Additionally, use the <a href=\"http://www.php.net/manual/en/intro.filter.php\" rel=\"nofollow noreferrer\">Filter extension</a>.</p>\n<p><strong>Error suppression operator</strong></p>\n<pre><code>$ip=@$REMOTE_ADDR;\n</code></pre>\n<p>First of all, where does <code>$REMOTE_ADDR</code> come from and why do you suppress errors? What exactly are you doing there and what can go wrong.</p>\n<p>In any case, forget all about the error suppression operator, <a href=\"https://softwareengineering.stackexchange.com/questions/120378/is-error-suppression-acceptable-in-role-of-logic-mechanism\">it's evil and it must die</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T16:28:22.060",
"Id": "257354",
"ParentId": "8053",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T11:25:59.237",
"Id": "8053",
"Score": "4",
"Tags": [
"php",
"sql",
"mysql"
],
"Title": "Keeping track of voting"
}
|
8053
|
<p>I'm learning functional programming and their concept of <a href="http://en.wikipedia.org/wiki/Monad_%28functional_programming%29">Monads</a>. I've found nothing more effective in learning than writing an implementation in a programming language I have experience with.</p>
<p>I came up with the following implementation in Java. Could someone please suggest improvements?</p>
<p>So, I have an interface, <code>Bindable</code>:</p>
<pre><code>public interface Bindable<T> {
<E> Bindable<E> bind(Function<T, Bindable<E>> function);
}
</code></pre>
<p>And I have the <code>Maybe</code> implementation:</p>
<pre><code>public class Maybe<T> implements Bindable<T> {
private final State<T> state;
public static <T> Maybe<T> just(T value) {
return new Maybe<T>(new Just<T>(value));
}
public static <T> Maybe<T> nothing() {
return new Maybe<T>((State<T>) Nothing.INSTANCE);
}
private Maybe(State<T> state) {
this.state = state;
}
@Override
public <E> Bindable<E> bind(final Function<T, Bindable<E>> function) {
return state.accept(new StateVisitor<T, Bindable<E>>() {
@Override
public Bindable<E> visitJust(T value) {
return function.apply(value);
}
@Override
public Bindable<E> visitNothing() {
return nothing();
}
});
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("state", state)
.toString();
}
private static interface State<T> {
<E> E accept(StateVisitor<T, E> visitor);
}
private static interface StateVisitor<T, E> {
E visitJust(T value);
E visitNothing();
}
private static class Just<T> implements State<T> {
private final T value;
private Just(T value) {
this.value = value;
}
@Override
public <E> E accept(StateVisitor<T, E> visitor) {
return visitor.visitJust(value);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("value", value)
.toString();
}
}
private static enum Nothing implements State<Object> {
INSTANCE;
@Override
public <E> E accept(StateVisitor<Object, E> visitor) {
return visitor.visitNothing();
}
@Override
public String toString() {
return "Nothing";
}
}
}
</code></pre>
<p>My <code>Identity</code> implementation:</p>
<pre><code>public class Identity<T> implements Bindable<T> {
private final T value;
public static <T> Identity<T> create(T value) {
return new Identity<T>(value);
}
private Identity(T value) {
this.value = value;
}
@Override
public <E> Bindable<E> bind(Function<T, Bindable<E>> function) {
return function.apply(value);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("value", value)
.toString();
}
}
</code></pre>
<p>And of <code>BindableSequence</code>:</p>
<pre><code>public class BindableSequence<T> implements Bindable<T> {
private final Iterable<Bindable<T>> sequence;
public static <T> BindableSequence<T> create(Iterable<T> sequence) {
ImmutableList.Builder<Bindable<T>> builder = ImmutableList.builder();
for (T item : sequence) {
builder.add(Identity.create(item));
}
return new BindableSequence<T>(builder.build());
}
public static <T> BindableSequence<T> create(T... sequence) {
return BindableSequence.create(Lists.newArrayList(sequence));
}
private BindableSequence(Iterable<Bindable<T>> sequence) {
this.sequence = sequence;
}
@Override
public <E> Bindable<E> bind(Function<T, Bindable<E>> function) {
List<Bindable<E>> result = Lists.newArrayList();
for (Bindable<T> t : sequence) {
Bindable<E> bind = t.bind(function);
result.add(bind);
}
return new BindableSequence<E>(result);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("sequence", sequence)
.toString();
}
}
</code></pre>
<p>And <code>Sample</code> class of how they can be used</p>
<pre><code>public class Sample {
public static void main(String[] args) {
Bindable<Integer> result = Identity.create(5)
.bind(new Function<Integer, Bindable<Integer>>() {
@Override
public Maybe<Integer> apply(Integer integer) {
return Maybe.just(integer * 10);
}
})
.bind(new Function<Integer, Bindable<Integer>>() {
@Override
public Bindable<Integer> apply(Integer integer) {
return BindableSequence.create(integer, integer + 10);
}
})
.bind(new Function<Integer, Bindable<Integer>>() {
@Override
public Maybe<Integer> apply(Integer integer) {
return Maybe.just(integer + 10);
}
});
System.out.println(result);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:00:44.690",
"Id": "12725",
"Score": "1",
"body": "Note that without having `return` in your interface (which you can't in Java because interfaces can only specify instance methods), you can't do half the things with your Bindable interface that you can do with monads in Haskell (e.g. you won't be able to implement most of the functions from `Control.Monad`) including `sequence`, `mapM` etc. This makes `Bindable` much less useful then monads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T16:10:35.337",
"Id": "12729",
"Score": "0",
"body": "It seems odd to have a \"monad implementation\" that doesn't define anything named \"Monad\". Maybe this reflects the problem cited by @sepp2k ? Is \"Bindable\" that models the \"bind\" part of Monad behavior as close as you can get (without perhaps a radically different approach)? I'm trying to decide how much damage the \"lack of `return`\" argument does -- can you give a small example of what your Bindable definition can do in its current form? Perhaps show some generic code that operates abstractly on Bindable to do something useful/different for each of Maybe, Identity, and BindableSequence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T11:16:55.383",
"Id": "12789",
"Score": "0",
"body": "@PaulMartel I added sample code of how `Bindable` can be used"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T11:30:34.820",
"Id": "12790",
"Score": "1",
"body": "@Mairbek: Note that what you wrote would actually be illegal in Haskell. The function given to `bind` should return the same kind of monad that you're calling `bind` on. I.e. you're not allowed to return an Identity from a function that's given as an argument to `bind` on a `Maybe`. This works in this case, but if you consider for example the list monad, you'll see why this is problematic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T11:34:37.763",
"Id": "12791",
"Score": "1",
"body": "Also note that it's impossible to write methods that work with arbitrary monads in Java since already the type `<M extends Bindable, T, U> M<U> bla(M<T>, Function<T,U>, M<U>)` would be illegal. This makes the interface next to useless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T03:26:02.863",
"Id": "30293",
"Score": "0",
"body": "@sepp2k Where can I read more on topics like \"Note that without having return in your interface (which you can't in Java because interfaces can only specify instance methods), you can't do half the things with your Bindable interface that you can do with monads in Haskell\"? May be you point out links to papers, or blog posts, ... that discuss topics like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T11:28:29.707",
"Id": "30304",
"Score": "0",
"body": "@user1123502 I don't know of any blog posts or papers that specifically discuss the power of monads without `return`, but if you read any introduction to monads, it should become clear why `return` is a fundamental operation. Also if you read the source code of the functions defined in `Control.Monad`, you'll notice that almost all of them either use `return` or another function that uses `return`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:31:36.577",
"Id": "30306",
"Score": "0",
"body": "@sepp2k I am NOT trying to doubt the need of `return` in monad definition. The need is really obvious, so one do not have to read code of `Control.Monad` in order to justify the need. What is not obvious for me -- that \"the type `<M extends Bindable, T, U> M<U> bla(M<T>, Function<T,U>, M<U>)` would be illegal\". Java generics implement parametric polymorphism, just like Haskell. IIRC `C#` generics (that are similar, although not coincide, to Java generics) are known to implement monads in LINQ. So, if you are right, then you mentioned a subtle and interesting point, so I want to dig into it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:56:06.917",
"Id": "30310",
"Score": "0",
"body": "@user1123502 The fact that `<M extends Bindable, T, U> M<U> bla` is illegal is unrelated to the statement about `return` that you quoted earlier. Anyway the reason it's illegal is that all type parameters in Java have kind `*`, i.e. you can't pass around an uninstantiated generic and then instantiate it with different type arguments. The best source for this I could come up with a quick google search is [this SO question](http://stackoverflow.com/questions/876948/higher-kinded-generics-in-java)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-25T12:58:57.790",
"Id": "30311",
"Score": "0",
"body": "@user1123502 Also note that C# generics have the same limitation as Java generics in this regard, so in C# it is also not possible to define most useful methods that work on arbitrary monads. Of course that doesn't prevent you from implementing specific monads and implementing monadic operations on them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-17T15:01:52.290",
"Id": "87992",
"Score": "0",
"body": "Have a look at my attempt: https://code.google.com/p/highj/"
}
] |
[
{
"body": "<p>As mentioned in the comments, the problem with implementing monads in Java is that in an OO language class methods always work on a single instance. Type classes in Haskell are very different, there you can create values \"out of nowhere\" like in\n</p>\n\n<pre><code>class Monad m where\n return :: a -> m a\n -- ...\n</code></pre>\n\n<p>or\n</p>\n\n<pre><code>class Monoid a where\n mempty :: a\n -- ...\n</code></pre>\n\n<p>There is a functional library for Scala called Scalaz, which solves the problem in the following way: Instead of having an object implement an interface such as <code>Bindable</code>, it creates a separate object that carries all the functions of a \"type class\". Unfortunately this requires generic type parameters that take parameters themselves, so called higher-order kinds, which <a href=\"https://stackoverflow.com/q/876948/1333025\">Java doesn't support</a>. If Java had them, we'd write something like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface Monad<M<?>> {\n public <A> M<A> pure(A value); // return is a keyword\n public <A,B> M<B> bind(M<A> v, Function<A,M<B>> f);\n}\n</code></pre>\n\n<p>and then for each monad type you'd define a singleton that implements this interface, such as <code>Monad<Maybe></code>. However, Java doesn't allow this. And another problem is that you have to pass this singleton around in every computation, which is very inconvenient.</p>\n\n<p>If you want to explore such functional concepts in a Java-like language, probably the best bet is to start learning Scala. Scala has <a href=\"http://www.scala-lang.org/node/114\" rel=\"nofollow noreferrer\">implicit parameters</a> which solve the problem with passing singletons around, and also has higher-order type parameters. In Scala you'd do something like</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>trait Monad[M[_]] {\n def pure[A](value: A): M[A];\n def bind[A,B](v: M[A], f: A => M[B]): M[B];\n}\n\nimplicit object OptionMonad extends Monad[Option] {\n override def pure[A](value: A): Option[A]\n = Some(value);\n // in most cases Scala's flatMap corresponds to bind\n override def bind[A,B](v: Option[A], f: A => Option[B]): Option[B]\n = v.flatMap(f);\n}\n\n// Generic monadic computations use implicit parameters:\ndef liftM2[M[_],A,B,C](f: (A,B) => C, x: M[A], y: M[B])\n (implicit m: Monad[M]): M[C] =\n m.bind(x, (x1: A) => m.bind(y, (y1: B) => m.pure(f(x1, y1))))\n\ndef sequence[M[_],A](xs: List[M[A]])(implicit m: Monad[M]): M[List[A]] =\n xs match {\n case Nil => m.pure(Nil)\n case x :: xs => liftM2[M,A,List[A],List[A]](_ :: _, x, sequence(xs))\n }\n\nSystem.out.println(sequence(List[Option[Int]](Some(1), Some(2))))\nSystem.out.println(sequence(List[Option[Int]](Some(1), None)))\n</code></pre>\n\n<p>Note that Scala has it's own concept for dealing with monadic computations using <code>for</code>-comprehensions, but that's out of the scope of this question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-05T20:04:42.263",
"Id": "28177",
"ParentId": "8055",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T12:51:34.487",
"Id": "8055",
"Score": "22",
"Tags": [
"java",
"functional-programming",
"monads"
],
"Title": "Java monad implementation"
}
|
8055
|
<p>I've wrote this class in PHP for my future projects:</p>
<pre><code><?php
/**
* Auth
* This class is used to securely authenticate and register users on a given website.
* This class uses the crypt() function, and PDO database engine.
*
* @package Class Library
* @author Truth
* @copyright 2011
* @version 1.00
* @access public
*/
class Auth {
const HOST = 'localhost'; //Holds the database host. For most cases that would be 'localhost'
const NAME = 'users'; //Holds the database name for the class to use. Assums 'users', change if needed.
const USER = 'root'; //Holds the username for the database. CHANGE IF NEEDED!!
const PASS = ''; //Holds the password for the database. CHANGE IF NEEDED
const TABLE = 'users'; //Holds the name of the table. CHANGE IF NEEDED
#NOTE, THE USER/PASS COMBO MUST HAVE SUFFICIENT PRIVLIGES FOR THE DATABASE IN NAME.
/**
* @var Auth::$db
* Holds pointer to the PDO object
*/
protected static $db;
/**
* @var Auth::$user
* Holds username information in the instance object
*/
protected $user;
/**
* @var Auth::$pass
* Holds password information in the instance object
*/
protected $pass;
/**
* @var Auth::$hash
* Holds the hashed password ready for database storage
*/
protected $hash;
/**
* Auth::__construct()
*
* @param string $user
* @param string $pass
* @return void
*/
public function __construct($user = "", $pass = "") {
if (empty($user) || empty($pass)) {
throw new Exception("Empty username or password.");
}
$this->user = $user;
$this->pass = $pass;
}
/**
* Auth::hash()
* Pass a user/password combination through the crypt algorithm and return the result.
*
* @return string hash Returns the complete hashed string.
*/
private function hash() {
$this->hash = crypt($this->pass, '$2a$10$'.sha1($this->user));
return $this->hash;
}
/**
* Auth::getUname()
* Return the username
*
* @return string The username
*/
public function getUname() {
return $this->user;
}
/**
* Auth::getHash()
* Check if there's a hash, if not, make one, then return the hash.
*
* @return string Hashed password
*/
public function getHash() {
if (empty($this->hash)) {
$this->hash();
}
return $this->hash;
}
public function __toString() {
return $this->getHash();
}
/**
* Auth::databaseConnect()
* Establish connection to database and store the connection on self::$db.
*
* @param PDO $pdo an optional PDO object to have an existing connection instead of a new one
* @return void
*/
public static function databaseConnect($pdo = null) {
#The class accepts an external
if (is_object(self::$db)) {
#Should the connection already been established, an exception will be thrown.
#If you want to start the connection yourself, make sure that this function is called before any other class functions.
throw new Exception('Could not complete operation. Connection was already established.');
}
if (is_object($pdo)) {
if (!($pdo instanceof PDO)) {
throw Exception('Illegal Argument: Supplied argument is not a PDO object.');
}
#The function accepts an external PDO object as an argument.
#WARNING: Do not use an object other then a PDO object, as it might cause unexpected results.
self::$db = $pdo;
return 0;
}
$dsn = "mysql:host=".self::HOST.";dbname=".self::NAME;
try {
self::$db = new PDO($dsn, self::USER, self::PASS); //Connect to the database, and store the pdo object.
self::$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
throw new Exception("There have been an error in the connection: ". $e->getMessage());
}
#Here, connection is established.
}
/**
* Auth::databaseCreate()
* Create a default table (named self::TABLE) on the database.
* Only use from within an installation page or a try/catch statement
*
* @return void
*/
public static function databaseCreate() {
if (!is_object(self::$db)) {
self::databaseConnect();
}
$table = self::TABLE;
$query = <<<EOQ
CREATE TABLE $table(
`uname` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'Holds usernames (who also act as salt)',
`phash` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'Holds hashed passwords',
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Unique user ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin COMMENT='Default user table' AUTO_INCREMENT=1 ;
EOQ;
//var_dump(self::$db);
$stmt = self::$db->prepare($query);
$stmt->execute();
}
/**
* Auth::registerUser()
* Insert a user into the database.
*
* @param Auth $auth The $auth object in question. Escaping is not needed.
* @return void
*/
public static function registerUser(Auth $auth) {
if (!is_object(self::$db)) {
self::databaseConnect();
}
try {
$query = "INSERT INTO ".self::TABLE." (`uname`, `phash`, `id`) VALUES (:uname, :phash, NULL)";
$stmt = self::$db->prepare($query);
$stmt->bindValue(':uname', $auth->getUname());
$stmt->bindValue(':phash', $auth->getHash());
$stmt->execute();
}
catch (PDOException $e) {
echo "There has been an error registering: ". $e->getMessage();
}
}
/**
* Auth::validateAgainstDatabase()
* Validate a user against the database.
* Exceptions detailing the potential error will be thrown. Make sure to catch them!
*
* @param Auth $auth The Auth object in question. No escaping needed.
* @return bool $success Whether the user is valid or not.
*/
public static function validateAgainstDatabase(Auth $auth) {
if (!is_object(self::$db)) {
self::databaseConnect();
}
try {
$query = "SELECT `uname`, `phash` FROM ".self::TABLE." WHERE `uname` = :uname";
$stmt = self::$db->prepare($query);
$stmt->bindValue(':uname', $auth->getUname());
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
throw new Exception('Username does not exist in the system.');
}
if ($row['phash'] != $auth->getHash()) {
throw new Exception('Password does not match username.');
}
return true;
}
catch (PDOException $e) {
echo "There was an error during the fetching: ". $e->getMessage();
}
}
}
?>
</code></pre>
<p>What do you guys think? Can it be improved? Does it look good? Anything to consider?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T21:10:41.133",
"Id": "41347",
"Score": "0",
"body": "Can you descripe or give a sample how you use this class in your page. Maybe with the different pages for login and validate the user against the DB. And use with sessions would be nice"
}
] |
[
{
"body": "<pre><code>public function __construct($user = \"\", $pass = \"\") {\n if (empty($user) || empty($pass)) {\n</code></pre>\n\n<p>Don't use <code>empty</code> when the variable is <em>guaranteed</em> to exist. It just makes it harder to catch typos, since it suppresses PHP's error mechanism when there's no need to. Since you also <em>require</em> arguments for <code>$user</code> and <code>$pass</code>, don't give them default values:</p>\n\n<pre><code>public function __construct($user, $pass) {\n if (!$user || !$pass) {\n</code></pre>\n\n<p>Also, hardcoding the database credentials as constants and the database schema is probably not good. That's something you'll want to configure dynamically without modifying your code. Just pass a <code>PDO</code> instance into the class, since you'll likely want to use that connection in more than just the Auth class. Don't let the Auth class instantiate its own connection or manage the database schema, that's not its job.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T18:21:50.133",
"Id": "12805",
"Score": "0",
"body": "Thanks for your comments! I've improved my code. Anything else you can see there?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T04:14:48.413",
"Id": "8183",
"ParentId": "8059",
"Score": "2"
}
},
{
"body": "<p>I would never write static methods in OO code. Others argue that they are ok in certain circumstances, however I make different design decisions to them. At the very least you should have thought long and hard about why you are making it static and be prepared to be stuck with the static dependency created in every class that will call your static method (and the testing overhead that this will add).</p>\n\n<ol>\n<li>They are very hard to test. See Misko Hevery's article <a href=\"http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/\" rel=\"nofollow\">Static Methods are a death to testability</a>.</li>\n<li>They create a tight coupling in your code. Read nikic's <a href=\"http://nikic.github.com/2011/12/27/Dont-be-STUPID-GRASP-SOLID.html\" rel=\"nofollow\">Don't be STUPID: GRASP SOLID</a> (especially the STU part).</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T07:21:39.497",
"Id": "12779",
"Score": "0",
"body": "Static methods in and of themselves aren't bad, it depends on what they do. Unseen dependencies and unseen state are bad, not the `static` keyword."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T07:29:56.597",
"Id": "12781",
"Score": "0",
"body": "@deceze Calling a static method couples the calling code. Any calls to Auth::databaseConnect would couple the calling code making it depend on an Auth class with a databaseConnect method. There is no good reason to write a static method ever. Just write a global function instead. Give it a namespace if you want. What good can a static method do that a non-static one can't do? (nothing)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T18:13:58.867",
"Id": "12804",
"Score": "0",
"body": "A static method is supposedly a global function, it's just a way to make it more organized and contained in the single class, that's all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T23:08:39.967",
"Id": "12814",
"Score": "1",
"body": "\"No good reason to write a static method ever\"? What about alternative object constructors? For example a static method that initializes an instance of its own class and sets a bunch of `private` properties, for example by restoring the object state from a database record. The only real way to do that is with static methods. `$foo = new Foo` vs. `$foo = Foo::fromDbRecord($pdo, 42)`. There's no more or less coupling going on here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T00:05:07.457",
"Id": "12818",
"Score": "0",
"body": "You are correct, the coupling is only slightly higher with the static (which is a Foo class with method fromDbRecord). What I am arguing for is doing neither of those as both of them create a tight coupling: [as Misko Hevery suggests](http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T01:49:42.590",
"Id": "12820",
"Score": "0",
"body": "I have read that article before and I do not agree with it. Since I'm really interested in this topic, I have moved it [here](http://stackoverflow.com/questions/8966434/static-methods-are-death-to-testability-alternatives-for-alternative-constru). I'd welcome your input in this. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T11:04:06.133",
"Id": "12822",
"Score": "0",
"body": "static is okay if it's to self:: (or static:: in PHP 5.3+) because it's still contained in the same module as the calling code. cross-class statics are definitely bad though."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T05:07:45.300",
"Id": "8184",
"ParentId": "8059",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8184",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T13:58:36.233",
"Id": "8059",
"Score": "3",
"Tags": [
"php",
"classes",
"security"
],
"Title": "Authentication Class"
}
|
8059
|
<p>In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created.</p>
<p>Most languages allow overloading the constructor in that there can be more than one constructor for a class, with differing parameters. Some languages take consideration of some special types of constructors.</p>
<p>Some types of constructors:</p>
<ul>
<li>Default constructors</li>
<li>Copy constructors</li>
<li>Conversion constructors</li>
<li>Move constructors</li>
</ul>
<p><strong>Default constructors</strong></p>
<p>If the programmer does not supply a constructor for an instantiable class, most languages will provide a default constructor. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. In C++ a default constructor is required if an array of class objects is to be created. Other languages (Java, C#, VB .NET) have no such restriction.</p>
<p><strong>Copy constructors</strong></p>
<p>Copy constructors define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor.</p>
<p><strong>Conversion constructors</strong></p>
<p>Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.</p>
<p><strong>Move constructors</strong></p>
<p>In C++, move constructors take an rvalue reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:24:34.193",
"Id": "8060",
"Score": "0",
"Tags": null,
"Title": null
}
|
8060
|
A special type of subroutine called at the creation of an object.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:24:34.193",
"Id": "8061",
"Score": "0",
"Tags": null,
"Title": null
}
|
8061
|
<p>In <a href="http://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow">object-oriented programming</a> (see: <a href="/questions/tagged/oop" class="post-tag" title="show questions tagged 'oop'" rel="tag">oop</a>), a class is a construct that is used as a <strong>blueprint</strong> (or <strong>template</strong>) to create objects of that class. This blueprint describes the <strong>state</strong> and <strong>behavior</strong> that the objects of the class all share. An object of a given class is called an <strong>instance</strong> of the class. The class that contains (and was used to create) that instance can be considered as the <strong>type</strong> of that object, e.g. an object instance of the "Fruit" class would be of the type "Fruit".</p>
<p>A class usually represents a noun, such as a person, place or (possibly quite abstract) thing - it is a model of a concept within a computer program. Fundamentally, it encapsulates the state and behavior of the concept it represents. It encapsulates state through data placeholders called <strong>attributes</strong> (or member variables or instance variables); it encapsulates behavior through reusable sections of code called <strong>methods</strong>.</p>
<p>More technically, a class is a cohesive package that consists of a particular kind of metadata. A class has both an <strong>interface</strong> and a <strong>structure</strong>. The interface describes how to interact with the class and its instances using methods, while the structure describes how the data is partitioned into attributes within an instance. A class may also have a representation (metaobject) at run time, which provides run time support for manipulating the class-related metadata. In object-oriented design, a class is the most specific type of an object in relation to a specific layer.</p>
<p>Example of class declaration in <strong>C#</strong>:</p>
<pre><code>/// <summary>
/// Class which objects will say "Hello" to any target :)
/// </summary>
class HelloAnything
{
/// <summary>
/// Target for "Hello". Private attribute that will be set only once
////when object is created. Only objects of this class can access
/// their own target attribute.
/// </summary>
private readonly string target;
/// <summary>
/// Constructor. Code that will execute when instance of class is created.
/// </summary>
/// <param name="target">Target for "Hello". If nothing specified then
/// will be used default value "World".</param>
public HelloAnything(string target = "World")
{
//Save value in the inner attribute for using in the future.
this.target = target;
}
/// <summary>
/// Returns phrase with greeting to the specified target.
/// </summary>
/// <returns>Text of greeting.</returns>
public string SayHello()
{
return "Hello, " + target + "!";
}
}
</code></pre>
<p>Using example of declared class:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
//Say hello to the specified target.
HelloAnything greeting = new HelloAnything("Stack Overflow");
Console.WriteLine(greeting.SayHello());
//Say hello to the "default" target.
greeting = new HelloAnything();
Console.WriteLine(greeting.SayHello());
}
}
</code></pre>
<p>Output result:</p>
<pre><code>Hello, Stack Overflow!
Hello, World!
</code></pre>
<p>Computer programs usually model aspects of some real or abstract world (the Domain). Because each class models a concept, classes provide a more natural way to create such models. Each class in the model represents a noun in the domain, and the methods of the class represent verbs that may apply to that noun.</p>
<p>For example in a typical business system, various aspects of the business are modeled, using such classes as Customer, Product, Worker, Invoice, Job, etc. An Invoice may have methods like Create, Print or Send, a Job may be Performed or Canceled, etc.</p>
<p>Once the system can model aspects of the business accurately, it can provide users of the system with useful information about those aspects. Classes allow a clear correspondence (mapping) between the model and the domain, making it easier to design, build, modify and understand these models. Classes provide some control over the often challenging complexity of such models.</p>
<p>Classes can accelerate development by reducing redundant program code, testing and bug fixing. If a class has been thoroughly tested and is known to be a 'solid work', it is usually true that using or extending the well-tested class will reduce the number of bugs - as compared to the use of freshly-developed or ad hoc code - in the final output. In addition, efficient class reuse means that many bugs need to be fixed in only one place when problems are discovered.</p>
<p>Another reason for using classes is to simplify the relationships of interrelated data. Rather than writing code to repeatedly call a graphical user interface (GUI) window drawing subroutine on the terminal screen (as would be typical for structured programming), it is more intuitive. With classes, GUI items that are similar to windows (such as dialog boxes) can simply inherit most of their functionality and data structures from the window class. The programmer then need only add code to the dialog class that is unique to its operation. Indeed, GUIs are a very common and useful application of classes, and GUI programming is generally much easier with a good class framework.</p>
<p><em>Source of class explanation: <a href="http://en.wikipedia.org/wiki/Class" rel="nofollow">Wikipedia</a>.</em></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:26:10.757",
"Id": "8062",
"Score": "0",
"Tags": null,
"Title": null
}
|
8062
|
Core to Object-Oriented Programming (OOP), a class is a template for creating new objects that describes the common state(s) and behavior(s).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:26:10.757",
"Id": "8063",
"Score": "0",
"Tags": null,
"Title": null
}
|
8063
|
<p>A loop is a sequence of statements which is specified once, but which may be carried out several times in succession. The code inside the loop (the body of the loop) is executed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely.</p>
<p>In <a href="/questions/tagged/functional" class="post-tag" title="show questions tagged 'functional'" rel="tag">functional</a> programming languages, loops can be expressed by using recursion or fixed point <a href="/questions/tagged/iteration" class="post-tag" title="show questions tagged 'iteration'" rel="tag">iteration</a> rather than explicit looping constructs. Tail recursion is a special case of recursion which can be easily transformed to iteration.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:27:11.833",
"Id": "8064",
"Score": "0",
"Tags": null,
"Title": null
}
|
8064
|
Loops are a type of control flow structure, in which, a series of statements may be executed repeatedly until some condition is met.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:27:11.833",
"Id": "8065",
"Score": "0",
"Tags": null,
"Title": null
}
|
8065
|
<p>Functional programming is a paradigm which attempts to solve computational problems by the chained evaluation of functions whose output is determined by their inputs rather than the programme state. In this style of programming, side effects and mutable data are deprecated and usually strictly isolated.</p>
<p>The disciplines of functional programming can be applied in almost any language, but in many imperative languages the resulting code is inelegant and verbose. A growing set of programming languages have been developed explicitly to enable expressive functional coding, including</p>
<ul>
<li>Lisp and its many dialects (e.g. Scheme, Clojure)</li>
<li>ML/OCaml/SML</li>
<li>Haskell</li>
<li>Erlang</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:28:58.133",
"Id": "8066",
"Score": "0",
"Tags": null,
"Title": null
}
|
8066
|
Functional programming is a paradigm which attempts to solve computational problems by the chained evaluation of functions whose output is determined by their inputs rather than the program state. In this style of programming, side effects and mutable data are deprecated.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:28:58.133",
"Id": "8067",
"Score": "0",
"Tags": null,
"Title": null
}
|
8067
|
<p>There is always the question of whether to work with PHP4 or use PHP5. Unless you're restricted to the earlier version, or you're working with legacy code that would not be compatible, it is <a href="http://stackoverflow.com/questions/716168/php4-vs-php5">always suggested that you work with the latest version</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:29:37.007",
"Id": "8068",
"Score": "0",
"Tags": null,
"Title": null
}
|
8068
|
The fifth version of the PHP: Hypertext Preprocessor (PHP) scripting language. It features the Zend Engine 2, better object model support, and many other improvements over PHP 4.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:29:37.007",
"Id": "8069",
"Score": "0",
"Tags": null,
"Title": null
}
|
8069
|
<p>I have a small library for utility functions for ES5 mainly aimed at OO code organization.</p>
<p>Are there any recommendations for the API or for the code quality / organization? </p>
<ul>
<li><a href="https://github.com/Raynos/pd/blob/master/lib/pd.js" rel="nofollow">github page</a></li>
<li><a href="https://github.com/Raynos/pd/blob/master/docs/styleGuide.md" rel="nofollow">styleGuide it complies to</a></li>
</ul>
<p>Note the library has a few tricks in it for aggressive minification.</p>
<h3>Code inlined</h3>
<pre><code>/*
pd(obj) -> propertyDescriptorsOfObject {
bindAll: function that binds all the methods of an object to the object,
extend: function that extends the first argument with the rest
Name: returns a namespace(anyKey) -> uniqueObject function
}
pd requires ES5. Uses the shimmable subset of ES5.
*/
(function (Object, slice) {
"use strict";
extend(pd, {
bindAll: bindAll,
extend: extend,
Name: Name
});
typeof window !== "undefined" ? window.pd = pd : module.exports = pd;
/*
pd will return all the own propertydescriptors of the object
@param Object object - object to get pds from.
@return Object - A hash of key/propertyDescriptors
*/
function pd(obj, retObj) {
retObj = {};
Object.getOwnPropertyNames(obj).forEach(function(key) {
var pd = Object.getOwnPropertyDescriptor(obj, key);
retObj[key] = pd;
});
return retObj;
}
/*
Extend will extend the firat parameter with any other parameters
passed in. Only the own property names will be extended into
the object
@param Object target - target to be extended
@arguments Array [target, ...] - the rest of the objects passed
in will extended into the target
@return Object - the target
*/
function extend(target) {
slice.call(arguments, 1).forEach(function(source) {
Object.defineProperties(target, pd(source));
});
return target;
}
/*
defines a namespace object. This hides a "privates" object on object
under the "key" namespace
@param Object object - object to hide a privates object on
@param Object key - key to hide it under
@author Gozala : https://gist.github.com/1269991
@return Object privates
*/
function namespace(object, key) {
var privates = Object.create(object),
valueOf = object.valueOf;
Object.defineProperty(object, "valueOf", {
value: function(value) {
return value !== key ? valueOf.apply(this, arguments) : privates;
},
writable: true
});
return privates;
}
/*
Constructs a Name function, when given an object it will return a
privates object.
@author Gozala : https://gist.github.com/1269991
@return Function name
*/
function Name(key) {
key = {};
return name;
function name(object) {
var privates = object.valueOf(key);
return privates !== object ? privates : namespace(object, key)
}
}
/*
bindAll binds all methods to have their context set to the object
@param Object obj - the object to bind methods on
@param Array whitelist - optional whitelist of methods to bind
@return Object - the bound object
*/
function bindAll(obj, whitelist) {
(whitelist || Object.keys(obj).filter(getMethods)).forEach(bindMethods);
return obj;
function getMethods(key) {
return obj[key].call;
}
function bindMethods(name) {
obj[name] = obj[name].bind(obj)
}
}
})(Object, [].slice);
</code></pre>
|
[] |
[
{
"body": "<p>There isn't anything majorly wrong, so these will be mostly minor things.</p>\n\n<p><code>getMethods</code> doesn't really get methods, <code>isMethod</code> (or <code>isBindable</code>) is a more descriptive name for it.</p>\n\n<p>You'd also want to check that <code>.call</code> is in fact the <code>.call</code> inherited from Function\nprototype, or since you are doing the filtering in preparation for <code>.bind</code>, just\ncheck that <code>obj[key].bind === Function.prototype.bind</code> or similar. Also check for truthiness, so you don't try to access <code>null.bind</code>:</p>\n\n<p><code>return obj[key] && obj[key].bind ===</code></p>\n\n<p>If <code>Name</code> is a normal function, it shouldn't be capitalized and be a named like a <em>noun</em>,\nthis is convention for functions that are meant to be invoked as constructors using <code>new</code>.\nSomething like <code>makeName</code> or <code>makeNamespace</code>, a <em>verb</em> that implies a factory, would\nbe a better fit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T15:03:21.320",
"Id": "12728",
"Score": "0",
"body": "`isMethod` and `.bind === Function.prototype.bind` are indeed issues, I've handled those. As for the `pd.Name` name, not sure how to handle that. I don't like `makeName` it'll be either `pd.name` or `pd.Name`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T15:00:43.113",
"Id": "8080",
"ParentId": "8070",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:30:00.767",
"Id": "8070",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "ES5 utility functions implementations"
}
|
8070
|
<p>Here is a short description of Programming Style from <a href="http://en.wikipedia.org/wiki/Programming_style" rel="nofollow">Wikipedia</a>:</p>
<blockquote>
<p>Programming style is a set of rules or guidelines used when writing the source code for a computer program.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:30:45.383",
"Id": "8071",
"Score": "0",
"Tags": null,
"Title": null
}
|
8071
|
A coding style is a set of conventions and practices used in software, such as naming classes, variables, and files.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:30:45.383",
"Id": "8072",
"Score": "0",
"Tags": null,
"Title": null
}
|
8072
|
<p>Developed by <a href="https://www.google.com/" rel="nofollow noreferrer">Google</a> and the <a href="http://www.openhandsetalliance.com/" rel="nofollow noreferrer">Open Handset Alliance</a>.</p>
<ul>
<li><p><a href="http://developer.android.com/" rel="nofollow noreferrer">Android Developers</a> (developer.android.com)<br>
Contains the <a href="http://developer.android.com/sdk/index.html" rel="nofollow noreferrer">SDK downloads</a>, documentation, <a href="http://developer.android.com/reference/packages.html" rel="nofollow noreferrer">class reference</a> and <a href="http://developer.android.com/guide/index.html" rel="nofollow noreferrer">tutorials</a>. Start here.</p></li>
<li><p><a href="http://android-developers.blogspot.com/" rel="nofollow noreferrer">Android Developers Blog</a><br>
Google's blog for Android developers, discussing technical topics as well as those relating to <a href="http://market.android.com/" rel="nofollow noreferrer">Android Market</a>. </p></li>
<li><p><a href="https://plus.google.com/108967384991768947849/posts" rel="nofollow noreferrer">+Android Developers on Google+</a>
News and announcements for developers from the Android team at Google. Also a venue for discussion of recent news and announcements.</p></li>
<li><p><a href="http://twitter.com/AndroidDev" rel="nofollow noreferrer">@AndroidDev on Twitter</a>
News and announcements for developers from the Android team at Google.</p></li>
<li><p><a href="http://groups.google.com/group/android-developers" rel="nofollow noreferrer">Android Developers Google Group</a><br>
Alternative developer discussion forum for Android.</p></li>
<li><p><a href="http://source.android.com/" rel="nofollow noreferrer">Android Open Source Project</a> (a.k.a. AOSP)<br>
Contains all necessary information about the Android source code.</p></li>
<li><p><a href="https://en.wikipedia.org/wiki/Android_(operating_system)" rel="nofollow noreferrer">Android page on Wikipedia</a><br>
Detailed information about the Android OS.</p></li>
<li><p><a href="http://www.android.com/" rel="nofollow noreferrer">Android.com</a><br>
General information about the Android OS.</p></li>
<li><p><a href="http://www.google.com/events/io/2010/" rel="nofollow noreferrer">Google I/O 2010 developer conference</a><br>
Contains detailed videos and slides by Android product engineers</p></li>
<li><p><a href="http://www.google.com/events/io/2011/index-live.html" rel="nofollow noreferrer">Google I/O 2011 developer conference</a><br>
Contains videos and slides by Android product engineers</p></li>
<li><p><a href="https://developers.google.com/events/io/" rel="nofollow noreferrer">Google I/O 2012 developer conference</a><br>
Contains videos and slides by Android product engineers</p></li>
<li><p><a href="http://code.google.com/intl/de-DE/android/add-ons/google-apis/index.html" rel="nofollow noreferrer">Google Maps API</a><br>
The Google Maps API port for Android, which provides many infos on how to use the Maps API on Android (which can not be found on the Android Developer site)</p></li>
</ul>
<p>For non-developer questions, see the <a href="https://android.stackexchange.com">Android Enthusiasts StackExchange</a>.</p>
<blockquote>
<p><strong>Android Development Book Recommendations</strong></p>
</blockquote>
<ul>
<li><p><a href="http://pragprog.com/titles/eband3/hello-android" rel="nofollow noreferrer">Hello, Android</a> by Ed Burnette </p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/1430234466" rel="nofollow noreferrer">Android Apps for Absolute Beginners</a> by Wallace Jackson </p></li>
<li><p><a href="http://commonsware.com/" rel="nofollow noreferrer">The CommonsWare Android Library</a> by <a href="https://stackoverflow.com/users/115145/commonsware">Mark Murphy</a> </p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/0470565527" rel="nofollow noreferrer">Professional Android 2 Application Development</a> by Reto Meier </p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/0321627091" rel="nofollow noreferrer">Android Wireless Application Development</a> by Shane Conder & Lauren Darcy </p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/1430232676" rel="nofollow noreferrer">Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets</a> by Shawn Van Every </p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/0321741234" rel="nofollow noreferrer">The Android Developer's Cookbook: Building Applications with the Android SDK</a> by James Steele & Nelson To </p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/1849513503" rel="nofollow noreferrer">Android Application Testing Guide</a> by Diego Torres Milano</p></li>
<li><p><a href="http://www.apress.com/mobile/android/9781430232971" rel="nofollow noreferrer">Beginning Android 3</a> by Mark L. Murphy</p></li>
<li><p><a href="http://rads.stackoverflow.com/amzn/click/1449389694" rel="nofollow noreferrer">Programming Android</a> by Zigurd Mednieks</p></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:31:55.647",
"Id": "8073",
"Score": "0",
"Tags": null,
"Title": null
}
|
8073
|
Android is Google's software stack for mobile devices. For non-developer questions, see http://android.stackexchange.com
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:31:55.647",
"Id": "8074",
"Score": "0",
"Tags": null,
"Title": null
}
|
8074
|
<h3>Description</h3>
<blockquote>
<p>Ideally, each <a href="http://en.wikipedia.org/wiki/Test_case" rel="nofollow noreferrer">test case</a> is independent from the others: substitutes like <a href="http://en.wikipedia.org/wiki/Method_stub" rel="nofollow noreferrer">method stubs</a>, <a href="http://en.wikipedia.org/wiki/Mock_object" rel="nofollow noreferrer">mock objects</a>, <a href="http://en.wikipedia.org/wiki/Mock_object#Mocks_and_fakes" rel="nofollow noreferrer">fakes</a> and <a href="http://en.wikipedia.org/wiki/Test_harness" rel="nofollow noreferrer">test harnesses</a> can be used to assist testing a module in isolation. Unit tests are typically written and run by software developers to ensure that code meets its design and behaves as intended.<sup><a href="http://en.wikipedia.org/wiki/Unit_testing" rel="nofollow noreferrer">Wikipedia</a></sup></p>
</blockquote>
<h3>Methods</h3>
<ul>
<li><p><strong>Black-box testing</strong></p>
<p>is a method of software testing that examines the functionality of an application without peering into its internal structures or workings</p></li>
<li><p><strong>White-box testing</strong></p>
<p>is a method of software testing that tests internal structures or workings of an application, as opposed to its functionality</p></li>
</ul>
<h3>See Also</h3>
<ul>
<li>Unit testing is closely related to <a href="http://c2.com/cgi/wiki?TestDrivenDevelopment" rel="nofollow noreferrer">Test Driven Development</a>.</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-21T14:39:29.160",
"Id": "8076",
"Score": "0",
"Tags": null,
"Title": null
}
|
8076
|
Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:39:29.160",
"Id": "8077",
"Score": "0",
"Tags": null,
"Title": null
}
|
8077
|
<h2>About</h2>
<p>Parsing is the process your compiler or interpreter goes through to extract meaning from your code. It is also how your browser translates the HTML of this page to a DOM, and in turn to graphics on your screen.</p>
<h2>Parser generators</h2>
<p>There are <a href="https://en.wikipedia.org/wiki/Comparison_of_parser_generators" rel="nofollow noreferrer">tools</a> that generate code for parsers given a grammar file. Most notable is the <a href="http://dinosaur.compilertools.net/" rel="nofollow noreferrer">Yacc + Lex</a> combo.</p>
<h2>Definitions</h2>
<p><a href="https://en.wikipedia.org/wiki/Parsing" rel="nofollow noreferrer">Wikipedia</a>:</p>
<blockquote>
<ul>
<li><p>Within computer science, the term is used in the analysis of computer languages, referring to the syntactic analysis of the input code into its component parts in order to facilitate the writing of compilers and interpreters.</p></li>
<li><p>Within computational linguistics the term is used to refer to the formal analysis by a computer of a sentence or other string of words into its constituents, resulting in a parse tree showing their syntactic relation to each other, which may also contain semantic and other information.</p></li>
</ul>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-21T14:43:28.873",
"Id": "8078",
"Score": "0",
"Tags": null,
"Title": null
}
|
8078
|
Parsing is the process of analysing a string of symbols, either in natural language or in computer languages, conforming to the rules of a formal grammar.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T14:43:28.873",
"Id": "8079",
"Score": "0",
"Tags": null,
"Title": null
}
|
8079
|
<p><a href="http://json.org/" rel="nofollow">JSON</a> (JavaScript Object Notation) is a lightweight data exchange format and is often used with <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a> and RESTful <a href="/questions/tagged/web-services" class="post-tag" title="show questions tagged 'web-services'" rel="tag">web-services</a>.</p>
<p>JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.</p>
<p>JSON is built on two structures:</p>
<ul>
<li>A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.</li>
<li>An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.</li>
</ul>
<p>These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages is also based on these structures.</p>
<p>Its syntax was inspired by a subset of the JavaScript object literal notation.</p>
<pre class="lang-js prettyprint-override"><code>{
"names": { "first": "John", "last": "Doe" },
"languages": [ "javascript", "python", "lisp" ]
}
</code></pre>
<hr>
<p>JSON is <strong>not</strong> <a href="http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/" rel="nofollow">the same thing</a> as JavaScript object literals. Rather, JSON is a common technique to serialize from and deserialize to JavaScript's (and other languages') objects.</p>
<p><strong>See also</strong></p>
<ul>
<li><a href="/questions/tagged/xml" class="post-tag" title="show questions tagged 'xml'" rel="tag">xml</a></li>
<li><a href="/questions/tagged/yaml" class="post-tag" title="show questions tagged 'yaml'" rel="tag">yaml</a></li>
<li><a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a></li>
</ul>
<p><strong>Useful links:</strong></p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/JSON" rel="nofollow">JSON</a></li>
<li><a href="http://json.org/" rel="nofollow">JSON specification</a></li>
<li><a href="http://www.jsonexample.com/" rel="nofollow">JSON Example</a></li>
<li><a href="http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/" rel="nofollow">JSON Example You can download</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/JSON" rel="nofollow">JSON on Mozilla Developer Network</a></li>
<li><a href="http://www.jsondata.com/" rel="nofollow">JSONData</a></li>
<li><a href="http://www.jsonlint.com/" rel="nofollow">JSONLint</a></li>
<li><a href="http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/" rel="nofollow">There is no such thing as a JSON object in JavaScript</a></li>
<li><a href="http://www.w3schools.com/json/default.asp" rel="nofollow">JSON Tutorial For Starters</a> at W3Schools</li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb299886.aspx" rel="nofollow">JSON-Introduction By Microsoft</a> </li>
<li><a href="http://www.webmonkey.com/2010/02/get_started_with_json/" rel="nofollow">Get Started With JSON</a> introduction at Webmonkey</li>
<li><a href="http://echojson.com/" rel="nofollow">Echo JSON</a></li>
<li><a href="https://github.com/douglascrockford/JSON-js" rel="nofollow">JSON library for old browsers</a> (IE8 and below)</li>
<li><a href="http://stackoverflow.com/questions/tagged/json?sort=frequent&pagesize=50">FAQ</a> in Stack Overflow</li>
</ul>
<p><strong>Browser Addons</strong></p>
<ul>
<li><a href="https://chrome.google.com/webstore/detail/pretty-json/ddngkjbldiejbheifcmnfmmfiniimbbg" rel="nofollow">Pretty JSON for Chrome</a></li>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/10869" rel="nofollow">Pretty JSON for Firefox</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T15:23:34.823",
"Id": "8081",
"Score": "0",
"Tags": null,
"Title": null
}
|
8081
|
JSON (JavaScript Object Notation) aka the Fat Free Alternative to XML is a lightweight data exchange format inspired by JavaScript object literals. It is often used with JavaScript, Ajax, and RESTful web services but is completely language independent.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T15:23:34.823",
"Id": "8082",
"Score": "0",
"Tags": null,
"Title": null
}
|
8082
|
<h1>Extensible Markup Language</h1>
<p><a href="https://en.wikipedia.org/wiki/XML" rel="nofollow noreferrer">Wikipedia</a> defines XML as follows:</p>
<blockquote>
<p>XML (Extensible Markup Language) is a set of rules for encoding documents in both human-readable and machine-readable form. It is defined in the XML 1.0 Specification produced by the <a href="https://www.w3.org/" rel="nofollow noreferrer">W3C</a>, and several other related specifications, all gratis open standards.</p>
</blockquote>
<p>In short, XML is:</p>
<ul>
<li>Designed to transport and store data.</li>
<li>A flexible text format derived from SGML (ISO 8879).</li>
</ul>
<p>The design goals of XML emphasize simplicity, generality, and usability over the Internet. It is a textual data format with strong support via Unicode for the languages of the world. Although the design of XML focuses on documents, it is widely used for the representation of arbitrary data structures, such as in web services. XML is also used heavily in Android application development, providing administration and design layout for an app. </p>
<p>Many Application Programming Interfaces (API's) have been developed to aid software developers with processing XML data, and several schema systems exist to aid in the definition of XML-based languages.</p>
<h2>Example Document</h2>
<p>The following text is defined using <a href="https://www.w3.org/TR/xhtml1/" rel="nofollow noreferrer">XHTML</a> and <a href="https://www.w3.org/TR/REC-xml/#dt-entref" rel="nofollow noreferrer">entity references</a>; the text serves as an example of XML syntax and structure:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [
<!ENTITY hello "Hello, World!">
]>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>&hello;</title>
</head>
<body>
<div>&hello;</div>
</body>
</html>
</code></pre>
<h2>Resources</h2>
<p>The following links provide additional information for learning about XML:</p>
<ul>
<li><a href="https://www.w3.org/XML/" rel="nofollow noreferrer">XML introduction</a></li>
<li><a href="https://www.w3.org/TR/REC-xml/" rel="nofollow noreferrer">XML specification</a></li>
<li><a href="http://en.wikipedia.org/wiki/Xml_namespace" rel="nofollow noreferrer">XML namespaces</a></li>
<li><a href="https://www.ibm.com/developerworks/xml/" rel="nofollow noreferrer">XML material in ibm developer works site</a></li>
<li><a href="http://www.jclark.com/xml/" rel="nofollow noreferrer">XML Resource Collection</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T15:24:15.337",
"Id": "8083",
"Score": "0",
"Tags": null,
"Title": null
}
|
8083
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.