body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>As part of my Java learning, I tried solving Part I of problem description <a href="http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/readme" rel="nofollow">here</a>. The only issue that I see now is that I could not close the button of <code>Frame</code>. </p>
<p>Please review and provide your comments on coding style/OOPS aspects.</p>
<p><strong>Ocean.java</strong></p>
<pre><code>/* Ocean.java */
/**
* The Ocean class defines an object that models an ocean full of sharks and
* fish. Descriptions of the methods you must implements appear below. They
* include a constructor of the form
*
* public Ocean(int i, int j, int starveTime);
*
* that creates an empty ocean having width i and height j, in which sharks
* starve after starveTime timesteps.
*
* See the README file accompanying this project for additional details.
*
* @author mohet01
*
*/
public class Ocean {
/**
* Do not rename these constants. WARNING: if you change the numbers, you
* will need to recompile Test4.java. Failure to do so will give you a very
* hard-to-find bug.
*/
public final static int EMPTY = 1;
public final static int SHARK = 2;
public final static int FISH = 3;
/**
* Define any variables associated with an Ocean object here. These
* variables MUST be private.
*
*/
private final static int UNKNOWN = -1; // for unknown return type
private int width;
private int height;
private int[][] oceanMatrix;
private int[][] sharkHungerLevelMatrix; // need to think on optimization
private int starveTime;
/**
* The following methods are required for Part I.
*
*/
/**
* Ocean() is a constructor that creates an empty ocean having width i and
* height j, in which sharks starve after starveTime timesteps.
*
* @param i
* is the width of the ocean.
* @param j
* is the height of the ocean.
* @param starveTime
* is the number of timeSteps sharks survive without food.
*/
public Ocean(int i, int j, int starveTime) {
this.width = i;
this.height = j;
this.oceanMatrix = new int[j][i];
this.sharkHungerLevelMatrix = new int[j][i];
this.starveTime = starveTime;
for (int row = 0; row < j; row++) {
for (int col = 0; col < i; col++) {
oceanMatrix[row][col] = EMPTY;
}
}
for (int row = 0; row < j; row++) {
for (int col = 0; col < i; col++) {
sharkHungerLevelMatrix[row][col] = EMPTY;
}
}
}
/**
* width() returns the width of an ocean Object.
*
* @return the width of the ocean.
*
*/
public int width() {
return this.width;
}
/**
* height() returns the height of an Ocean object.
*
* @return the height of the Ocean.
*/
public int height() {
return this.height;
}
/**
* starveTime() returns the number of timesteps sharks survive without food.
*
* @return the number of timesteps sharks survive without food.
*/
public int starveTime() {
return starveTime;
}
/**
* addFish() places a fish in cell (x,y) if the cell is empty. If the cell
* is already occupied, leave the cell as it is.
*
* @param x
* is the x-coordinate of the cell to place a fish in.
* @param y
* is the y-coordinate of the cell to place a fish in.
*/
public void addFish(int x, int y) {
if (oceanMatrix[x][y] == EMPTY) {
oceanMatrix[x][y] = FISH;
}
}
/**
* addShark() (with two parameters) places a newborn shark in cell (x, y) if
* the cell is empty. A "newborn" shark is equivalent to a shark that has
* just eaten. If the cell is already occupied, leave the cell as it is.
*
* @param x
* is the x-coordinate of the cell to place a shark in.
* @param y
* is the y-coordinate of the cell to place a shark in.
*/
public void addShark(int x, int y) {
if (oceanMatrix[x][y] == EMPTY) {
oceanMatrix[x][y] = SHARK;
}
}
/**
* cellContents() returns EMPTY is cell (x,y) is empty, FISH if it contains
* a fish, and SHARK if it contains a shark.
*
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
*/
public int cellContents(int x, int y) {
return oceanMatrix[x][y];
}
/**
* isFish() checks for the existence of fish in that cell.
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return the boolean value
*/
private boolean isFish(int x, int y){
return (this.oceanMatrix[x][y] == Ocean.FISH);
}
/**
* isShark() checks for the existence of shark in that cell.
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return the boolean value
*/
private boolean isShark(int x, int y){
return (this.oceanMatrix[x][y] == Ocean.SHARK);
}
/**
* isSharkStarving() checks the hunger level of shark, if reached to starveTime level
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return the boolean value
*/
private boolean isSharkStarving(int x, int y){
return (this.sharkHungerLevelMatrix[x][y] == (this.starveTime+1));
}
/**
* checkFish() checks the existence of atleast one fish
* surrounding shark cell
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return returns true on atleast one fish exist otherwise false
*
*/
private boolean checkFish(int x, int y){
for(int i = x-1;i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
if(this.isFish(mod(i,this.height), mod(j,this.width))){
return true;
}
}
}
return false;
}
/**
* countShark() counts the number of sharks surrounding queried cell
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return returns number of sharks surrounding fish cell
*/
private int countShark(int x, int y){
int neighbourSharkCount = 0;
for(int i = x-1;i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
if(this.isShark(mod(i,this.height), mod(j,this.width))){
neighbourSharkCount++;
}
} // end inner for loop
}//end outer for loop
return neighbourSharkCount;
}
/**
* countFish() counts the number of fish surrounding queried cell
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
* @return returns number of sharks surrounding queried cell
*/
private int countFish(int x, int y){
int neighbourFishCount = 0;
for(int i = x-1;i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
if(this.isFish(mod(i,this.height), mod(j,this.width))){
neighbourFishCount++;
}
} // end inner for loop
}//end outer for loop
return neighbourFishCount;
}
/**
* mod() performs the modulo operation using euclidean divison
*
* @param n
* is the numerator
* @param d
* is the denominator
* @return the remainder
*/
private int mod(int n, int d) {
if (n >= 0)
return n % d;
else
return d + ~(~n % d);
}
/**
* timeStep() performs a simulation timestep as described in README.
*
* @return an ocean representing the elapse of one timestep.
*/
public Ocean timeStep() {
Ocean sea = new Ocean(width, height, starveTime);
for (int row = 0; row < this.height; row++) {
for (int col = 0; col < this.width; col++) {
switch(this.oceanMatrix[row][col]){
case Ocean.SHARK:
boolean gotTheFish = false;
//Check all the 8 neighbors of a Shark Cell for fish
if(this.checkFish(row,col)){
gotTheFish = true;
}
//Updating Shark Cell
if(gotTheFish){
/*
* 1) If a cell contains a shark, and any of its neighbors is a fish, then the
* shark eats during the time step, and it remains in the cell at the end of the
* time step. (We may have multiple sharks sharing the same fish. This is fine;
* they all get enough to eat.)
*/
sea.oceanMatrix[row][col] = Ocean.SHARK; // for next time step
}else{
/*
* 2) If a cell contains a shark, and none of its neighbors is a fish, it gets
* hungrier during the time step. If this time step is the (starveTime + 1)th
* time step the shark has gone through without eating, then the shark dies
* (disappears). Otherwise, it remains in the cell.
*/
this.sharkHungerLevelMatrix[row][col]++;
if(this.isSharkStarving(row,col)){
this.oceanMatrix[row][col] = Ocean.EMPTY; // for this time step
this.sharkHungerLevelMatrix[row][col] = Ocean.EMPTY; // for this time step
}
sea.sharkHungerLevelMatrix[row][col] = this.sharkHungerLevelMatrix[row][col]; // for next time step
sea.oceanMatrix[row][col] = this.oceanMatrix[row][col]; // for next time step
}
break;
case Ocean.FISH:
int neighbourSharkCount=0;
//Check all the 8 neighbors of a Fish cell to count for sharks
neighbourSharkCount=countShark(row,col);
//Updating fish cell for current & next time step
if(neighbourSharkCount ==1){
/*
* 4) If a cell contains a fish, and one of its neighbors is a shark, then the
* fish is eaten by a shark, and therefore disappears.
*/
this.oceanMatrix[row][col] = Ocean.EMPTY; //fish disappears this time step
}
else if(neighbourSharkCount > 1){
/*
* 5) If a cell contains a fish, and two or more of its neighbors are sharks, then
* a new shark is born in that cell. Sharks are well-fed at birth; _after_ they
* are born, they can survive an additional starveTime time steps without eating.
*/
sea.oceanMatrix[row][col] = Ocean.SHARK; // new shark for next time step
}
else if(neighbourSharkCount < 1){
/*
* 3) If a cell contains a fish, and all of its neighbors are either empty or are
* other fish, then the fish stays where it is.
*/
sea.oceanMatrix[row][col] = FISH; //for next time step
}
break;
case Ocean.EMPTY:
int fishCount=0;
int sharkCount=0;
//Check all the 8 neighbors of an Empty cell to count sharks and Fish
fishCount = this.countFish(row,col);
sharkCount = this.countShark(row, col);
//Update Empty Cell for current & next time step.
/* (no need to handle this case)
* 6) If a cell is empty, and fewer than two of its neighbors are fish, then the
* cell remains empty.
*/
if((fishCount >= 2) && (sharkCount <=1)){
/*
* 7) If a cell is empty, at least two of its neighbors are fish, and at most one
* of its neighbors is a shark, then a new fish is born in that cell.
*/
this.oceanMatrix[row][col] = FISH;// for current time step
sea.oceanMatrix[row][col] = FISH; //for next time step
}else if((fishCount >= 2) && (sharkCount >= 2)){
/*
* 8) If a cell is empty, at least two of its neighbors are fish, and at least two
* of its neighbors are sharks, then a new shark is born in that cell. (The new
* shark is well-fed at birth, even though it hasn’t eaten a fish yet.)
*/
sea.oceanMatrix[row][col] = Ocean.SHARK; // for next time step
}
break;
}
}//end inner for loop
}//end outer for loop
return sea;
}
/**
* The following method is required for Part II.
*
*
*/
/**
* addShark() (with three parameters) places a shark in cell (x, y) if the
* cell is empty. The shark's hunger is represented by the third parameter.
* If the cell is already occupied, leave the cell as it is, You will need
* this method to help convert run-length encodings to Oceans.
*
* @param x
* is the x-coordinate of the cell to place a shark in.
* @param y
* is the y-coordinate of the cell to place a shark in.
* @param feeding
* is an integer that indicates the shark's hunger. You may
* encode it any way you want; for instance, "feeding" may be the
* last timestep the shark was fed, or the amount of time that
* has passed since the shark was last fed, or the amount of time
* left before the shark will starve. It's upto you, but be
* consistent.
*/
public void addShark(int x, int y, int feeding) {
this.oceanMatrix[x][y] = Ocean.SHARK;
this.sharkHungerLevelMatrix[x][y] = feeding;
}
/**
* The following method is required for Part III.
*/
/**
* sharkFeeding() returns an integer that indicates the hunger of the shark
* in cell (x, y), using the same "feeding" representation as the parameter
* to addShark() described above. If cell (x, y) does not contain a shark,
* then its return value is undefined--that is, anything you want. Normally,
* this method should not be called if cell (x, y) does not contain a shark.
* You will need this method to help convert Oceans to run-length encodings.
*
* @param x
* is the x-coordinate of the cell whose contents are queried.
* @param y
* is the y-coordinate of the cell whose contents are queried.
*
*/
public int sharkFeeding(int x, int y) {
if(this.isShark(x, y)){
return this.sharkHungerLevelMatrix[x][y];
}
return Ocean.UNKNOWN;
}
}
</code></pre>
<p><strong>SimText.java</strong></p>
<pre><code>import java.util.Random;
/* SimText.java */
/* DO NOT CHANGE THIS FILE (except as noted). */
/* (You may wish to make temporary or insert println() statements */
/* while testing your code. when you're finished testing and debugging, */
/* though, make sure your code works with the original version of this file. */
/**
* The SimText class is a program that runs and animates a simulation of Sharks
* and Fish.
*
* The SimText program takes up to four parameters. The first two specify the
* width and height of the ocean. The third parameter specifies the value of
* starveTime. For example, if you run
*
* java SimText 25 25 1
*
* then SimText will animate a 25x25 ocean with a starveTime of 1. If you run
* "java SimText" with no parameters, by default SimText will animate a 50x25
* ocean with a starveTime of 3. With some choices of parameters, the ocean
* quickly dies out; with others, it teems forever.
*
* @author mohet01
*
*/
public class SimText {
/**
* Default parameters. (You may change these if you wish.)
*
*/
private static int i = 50; // Default ocean width
private static int j = 25; // Default ocean height
private static int starveTime = 3; // Default shark starvation time
/**
* paint() prints an Ocean.
*/
public static void paint(Ocean sea) {
if (sea != null) {
int width = sea.width();
int height = sea.height();
/* Draw the ocean */
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
for (int row = 0; row < height; row++) {
System.out.print("|");
for (int col = 0; col < width; col++) {
int contents = sea.cellContents(row, col);
if (contents == Ocean.SHARK) {
System.out.print('S');
} else if (contents == Ocean.FISH) {
System.out.print('F');
} else {
System.out.print(' ');
}
}
System.out.println("|");
}
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
}// end if
} // end paint
/**
* main() reads the parameters and performs the simulation and animation.
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Ocean sea;
/**
* Read the input parameters.
*/
if (args.length > 0) {
try {
i = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out
.println("First argument to SimText is not an number");
}
}
if (args.length > 1) {
try {
j = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.out
.println("Second argument to SimText is not an number");
}
}
if (args.length > 2) {
try {
starveTime = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out
.println("Third argument to SimText is not an number");
}
}
/**
* Create the initial ocean.
*/
sea = new Ocean(i, j, starveTime);
/**
* Visit each cell (in a roundabout order); randomly place a fish,
* shark, or nothing in each. (21.5-15) / (21.5*2) is actually ~.15 so
* this creates sharks 15% of the time. In otherwords random.nextInt()
* will generate a number larger than 1500000000 15% of the time because
* it is capable of generating 2147483647−1500000000 numbers larger than
* 1500000000 out of a total of 2147483647−(−2147483648) numbers in
* total.
*
*/
Random random = new Random(0); // Create a "Random" object with seed 0
int x = 0;
int y = 0;
for (int row = 0; row < j; row++) {
x = (x + 78887) % j; // width - This will visit every x-coordinate
// once
if ((x & 8) == 0) {
for (int col = 0; col < i; col++) {
y = (y + 78887) % i; // height - This will visit every
// y-coordinate once
if ((y & 8) == 0) {
int r = random.nextInt(); // Between -2147483648 and
// 2147483647
if (r < 0) { // 50% of cells start with fish
sea.addFish(x, y); // x - width, y-height
} else if (r > 1500000000) { // ~15% of cells start with
// sharks
sea.addShark(x, y); // x - width, y-height
}
}
}
}
}// end for loop
/**
* Perform timesteps forever.
*/
while (true) { // Loop forever
paint(sea);
// For fun, you might wish to change the delay in the next line.
Thread.sleep(1000); // Wait one second (1000 milliseconds)
sea = sea.timeStep(); // Simulate a timestep
}
}// end main()
} // end Class SimText
</code></pre>
<p><strong>Simulation.java</strong></p>
<pre><code>import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.util.Random;
/* Simulation.java */
/* DO NOT CHANGE THIS FILE (except as noted). */
/* (You may wish to make temporary changes or insert println() statements) */
/* while testing your code. When you're finished testing and debugging, */
/* though, make sure your code works with the original version of this file */
/**
* The Simulation class is a program that runs and animates a simulation of
* Sharks and Fish.
*
* The Simulation program takes up to four parameters. The first two specify
* the width and height of the ocean. The third parameter specifies the value
* of starveTIme. For example, if you run
*
* java Simulation 25 25 1
*
* then Simulation will animate a 25x25 ocean with a starveTime of 1. If you
* run "java Simulation" with no parameters, by default Simulation will animate
* a 50x25 ocean with a starveTime of 3. With some choices of parameters,
* the ocean quickly dies out; with others;, it teems forever.
*
* @author mohet01
*
*/
public class Simulation {
/**
* The constant cellSize determines the size of each cell on the screen
* during animation. (You may change this if you wish).
*/
private static final int cellSize = 4;
/**
* Default parameters. (You may change this of you wish).
*/
private static int i = 50; //Default ocean width
private static int j = 25; //Default ocean height
private static int starveTime = 3; //Default shark starvation time
/**
* drawOcean() adds cell contents as part of graphics
*/
private static void drawOcean(Graphics graphics, Ocean ocean){
if(ocean != null){
int width = ocean.width();
int height = ocean.height();
for(int row = 0; row < height; row++){
for(int col = 0; col < width; col++){
int contents = ocean.cellContents(row, col);
if(contents == Ocean.SHARK){
graphics.setColor(Color.red);
graphics.fillRect(row*cellSize, col*cellSize, cellSize, cellSize);
}else if(contents == Ocean.FISH){
// Draw a green fish
graphics.setColor(Color.green);
graphics.fillRect(row * cellSize, col * cellSize, cellSize, cellSize);
}else{
graphics.clearRect(row, col, cellSize, cellSize);
}
}
}
}
}
/**
* main() reads the parameters and performs the simulation and animation.
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Ocean sea;
/**
* Read the input parameters
*/
if(args.length >0){
try{
i = Integer.parseInt(args[0]);
}catch(NumberFormatException e){
System.out.println("First argument to Simulation is not a number.");
}
}
if(args.length > 1){
try{
j = Integer.parseInt(args[1]);
}catch(NumberFormatException e){
System.out.println("Second argument to Simulation is not a number");
}
}
if(args.length > 2){
try{
starveTime = Integer.parseInt(args[2]);
}catch(NumberFormatException e){
System.out.println("Third argument to Simulation is not a number");
}
}
/**
* Create a window on your screen
*/
Frame frame = new Frame("Sharks and Fish");
frame.setSize(i*cellSize + 10, j*cellSize + 30);
frame.setVisible(true);
/**
* Create a "Canvas" we can draw upon; attach it to the window
*/
Canvas canvas = new Canvas();
canvas.setBackground(Color.white);
canvas.setSize(i*cellSize, j*cellSize);
frame.add(canvas);
Graphics graphics = canvas.getGraphics();
/**
* Create the initial ocean.
*/
sea = new Ocean(i, j, starveTime);
/**
* Visit each cell (in a roundabout order); randomnly place a fish, shark,
* or nothing in each.
*/
Random random = new Random(0);
int x = 0;
int y = 0;
for(int row = 0;row < j; row++){
//This will visit every x-coordinate once.
x = (x + 78887) %j;
if((x & 8) == 0){
for(int col = 0; col < i; col++){
//This will visit every y coordinate once.
y = (y+78887)%i;
if((y & 8) == 0){
int r = random.nextInt();
if(r < 0){
//50% of cells start with fish
//x - width, y - height
sea.addFish(x, y);
}else if(r > 1500000000){
//~15% of cells start with sharks
sea.addShark(x, y);
}
}
}
}
}
/**
* Perform timesteps forever
*/
while (true) {
// Wait one second (1000 milliseconds)
Thread.sleep(1000);
// Draw the current ocean
drawOcean(graphics, sea);
// For fun, you might wish to change the delay in the next line.
// If you make it too short, though, the graphics won't work properly.
// Simulate a timestep
sea = sea.timeStep();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T07:45:34.513",
"Id": "75164",
"Score": "1",
"body": "This is the same simulation they used in AP Computer Science courses over eight years ago..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:27:45.347",
"Id": "75171",
"Score": "0",
"body": "What's the deal with bitwise complements: `d + ~(~n % d)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:38:22.997",
"Id": "75173",
"Score": "0",
"body": "I would like someone disentangle the conditional spaghetti in `timeStep()` method. I suspect it might be essential spaghetti."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:14:58.023",
"Id": "75175",
"Score": "0",
"body": "@abuzittingillifirca 'd + ~(~n % d) ' is used to perform modulo operation with euclidean divison principle when n<0 and java perform real division so it works for positive n only, am sorry what does it mean, when you say, 'what's the deal'? so going back to problem description mentioned in the link above, we are resolving this problem:\"You can also refer to locations such as (4, 0) or (-4, 3.......wrapping around at the edges.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:24:04.617",
"Id": "75177",
"Score": "0",
"body": "@abuzittingillifirca timeStep() looks like spaghetti? am doing only two things uniformly in 3 switch cases one is 'Check 8 neighbours of the cell' and second is 'Update the cell', Please let me know, if the style is different comparing 3 switch cases. Please be specific"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:46:00.300",
"Id": "75181",
"Score": "0",
"body": "@user3317808 You are mixing arithmetic and bitwise operators in `d + ~(~n % d)`. What's wrong with `d + n % d` even `d + -(-n % d)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:50:00.863",
"Id": "75182",
"Score": "1",
"body": "@user3317808 Spaghetti comment is addressed at reviewers and not you. I count 5 levels of nested scopes and 100+ lines. I can't count the cyclomatic complexity by hand. I want to see and learn how other people deal with too many conditionals (= spaghetti conditional)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T07:13:35.783",
"Id": "75369",
"Score": "0",
"body": "@abuzittingillifirca i copied d+~(~n%d) from stackoverflow. Because i still did not understand, How do i think of deriving formulae (d + (n % d)) performing modulo operation using euclidean division(if n<0) instead of remembering that formulae. Please help me on this!!!"
}
] | [
{
"body": "<p>Just a quick comment: Your <code>Ocean</code> class knows/does too many things.</p>\n\n<p>I'd be expecting a <code>Fish</code> class and a <code>Shark</code> class. Creating an ocean requires a <code>starveTime</code> constructor parameter? That's a sign you've broken the <strong>single responsibility principle</strong> (SRP).</p>\n\n<p>Methods like <code>void addFish(int x, int y)</code> would be <code>void addFish(Fish fish)</code> - <em>let the fish know where he is in the ocean, and let the ocean know it has fish</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:30:45.697",
"Id": "75178",
"Score": "0",
"body": "starveTime constructor? I think i set this value in Ocean() constructor. Are you saying that it does not make sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:40:29.697",
"Id": "75180",
"Score": "0",
"body": "Do you mean, I can have an Ocean class and then interface that can subclass Shark Fish etc...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:40:10.927",
"Id": "75214",
"Score": "3",
"body": "@user3317808: The answer is suggesting that your `Ocean` class *contain* `Shark` and `Fish` objects. The sharks would know how hungry they are. The ocean shouldn't care; It's just the stage where your actors play their parts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T07:15:41.993",
"Id": "75370",
"Score": "0",
"body": "@cHao When you say \"Ocean class contain Shark and Fish objects.\" Are you saying, Shark and Fish should be inner class of Ocean? i think they Shark and Fish cannot be subclass of Ocean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:02:00.027",
"Id": "75376",
"Score": "0",
"body": "@user3317808: There's no real need for them to be inner classes. The point is that you'd have a `Fish` class and a `Shark` class somewhere, and an Ocean would contain a collection of `Shark` and `Fish` instances. (Maybe separate, maybe in the same collection.)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:17:38.637",
"Id": "43477",
"ParentId": "43476",
"Score": "19"
}
},
{
"body": "<p><strong>Minor notes</strong> </p>\n\n<p><code>// need to think on optimization</code> this is really not that important, but if you're using an IDE, you could probably use an <code>//TODO</code>. This can be shown in most IDE and is more easily visible IMHO.</p>\n\n<p><strong>Javadoc</strong></p>\n\n<blockquote>\n<pre><code> * Ocean() is a constructor that creates an empty ocean having width i and\n * height j, in which sharks starve after starveTime timesteps.\n</code></pre>\n</blockquote>\n\n<p>I don't like that you use <code>Ocean()</code>, since at first I was thinking that it was a documentation for an empty constructor, when in fact it is not. You could only say :</p>\n\n<pre><code> * Constructor that creates an empty ocean having width i and\n * height j, in which sharks starve after starveTime timesteps.\n</code></pre>\n\n<p>For my personal taste, there is too much documentation. When you add a javadoc for <code>width()</code>, you've been a step too far. This is really my opinion and it all depends on standard that you must follow. </p>\n\n<p><strong>Constant</strong></p>\n\n<p>Good thing, you're using constant! This is a first step in extracting concept in general! But there is still magic numbers in the code.</p>\n\n<blockquote>\n<pre><code>y = (y + 78887)\n</code></pre>\n</blockquote>\n\n<p>Why 78887 ? You're re-using it more than one time, so if you ever need to change it, you need to remember every occurrence of it! This is not the only one so you should look for it. In many case, even if you're using the number only once, it's easier and more readable to name a variable and use it instead!</p>\n\n<p><strong>Naming</strong></p>\n\n<blockquote>\n<pre><code> * @param i\n * is the width of the ocean.\n * @param j\n * is the height of the ocean.\n * @param starveTime\n * is the number of timeSteps sharks survive without food.\n */\n\npublic Ocean(int i, int j, int starveTime) {\n</code></pre>\n</blockquote>\n\n<p>You should not use <code>i</code> and <code>j</code> here. In your documentation you're giving a meaning to those variables, why not use it! Even if they will be use in a loop later, you can name it <code>width</code> and <code>height</code>. If you need to differentiate the argument one from the private one, simply use <code>this</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:37:00.180",
"Id": "75179",
"Score": "2",
"body": "78887 magic number is used in simtext.java and simulation.java which are test programs or driving programs to test Ocean class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:30:37.707",
"Id": "75211",
"Score": "0",
"body": "Well in that case, it could be a static final variable in the class it make more sense to have!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:50:02.513",
"Id": "43478",
"ParentId": "43476",
"Score": "9"
}
},
{
"body": "<p>As I mentioned in <a href=\"https://codereview.stackexchange.com/a/43477/23788\">this answer</a>, your <code>Ocean</code> class is breaking SRP, which makes your code harder to maintain than it needs to be.</p>\n<h3>Memory Usage</h3>\n<p>Let's pretend the ocean is an array of X-Y coordinates with 3 possible values at each intersection: <code>EMPTY</code>, <code>FISH</code> or <code>SHARK</code> (what your code does). If the ocean is 1000x1000 you have 1 million of these values in memory, and unless there's a massive over-population of fish or sharks, the vast majority of these in-memory values are <code>EMPTY</code> and serve no purpose: you have essentially defined an ocean as a... bitmap.</p>\n<h3>Maintainability</h3>\n<p>Let's pretend you have a new requirement, that a fish will move in either direction (randomly) at every unit of time. With your current code, you have a major problem: the ocean needs to "scan" itself entirely, and whenever it finds a <code>FISH</code>, it must compute a new coordinate for that fish and assign a new location... but that's quite tricky to do in a <em>bitmap</em> that you're iterating.</p>\n<p>If you had a base class for anything that can exist at a specific location in the ocean:</p>\n<pre><code>public class Critter\n{\n public Point location; // define getter and setters\n \n public void update()\n {\n // no-op on base class\n }\n}\n</code></pre>\n<p>And then you could have a <code>Fish</code> class:</p>\n<pre><code>public class Fish extends Critter\n{\n @Override\n public void update()\n {\n // compute a new value for the Location property\n }\n}\n</code></pre>\n<p>..And a <code>Shark</code> class:</p>\n<pre><code>public class Shark extends Fish\n{\n public int hungerLevel; // define getter and setters\n\n public Shark()\n {\n hungerLevel = 0;\n }\n\n private void eat(Fish fish)\n {\n hungerLevel = 0;\n // let the ocean know the fish is gone\n }\n\n @Override\n public void update()\n {\n // compute a new location - find nearest fish?\n hungerLevel++;\n }\n}\n</code></pre>\n<p>Now you can have <em>hunting sharks</em>! Better yet, the <code>Ocean</code> class can now focus on <em>being an ocean</em>:</p>\n<pre><code>public class Ocean\n{\n private List<Critter> _critters;\n\n public void update()\n {\n for(Critter critter : _critters)\n {\n critter.update();\n }\n }\n}\n</code></pre>\n<p>Now obviously an updating <code>Shark</code> will want to know if there are any other critters nearby, and an updating <code>Fish</code> will probably want to try to escape a <code>Shark</code> (but the <code>Shark</code> could be moving faster!), so perhaps the <code>Critter.update()</code> method should take an <code>Iterable<Critter></code>:</p>\n<pre><code>public class Fish extends Critter\n{\n public void update(Iterable<Critter> critters)\n {\n // compute a new value for the Location property\n }\n}\n</code></pre>\n<p>So the <code>Ocean</code> could pass in its critters:</p>\n<pre><code>public class Ocean\n{\n private List<Critter> _critters;\n\n public void update()\n {\n for(Critter critter : _critters)\n {\n critter.update(_critters);\n }\n }\n}\n</code></pre>\n<p>And now you can implement the <code>Shark</code>'s hunting behavior, and the <code>Fish</code>'s <em>swim-for-your-life</em> behavior</p>\n<pre><code>public class Shark extends Fish\n{\n public Shark()\n {\n hungerLevel = 0;\n }\n\n public int hungerLevel; // define getter setters\n\n private void eat(Fish fish)\n {\n hungerLevel = 0;\n // let the ocean know the fish is gone\n }\n\n private Fish _currentTarget;\n\n @Override\n public void update(Iterable<Critter> critters)\n {\n // are we hunting a target already?\n if (_currentTarget != null)\n {\n // try to get closer.. and try to eat!\n return;\n }\n else\n {\n // is there a fish nearby?\n for(Critter critter : critters)\n {\n // if there's a fish (viz not a shark) in sight, make it our target.\n if (!(critter instanceof Shark) && canCapture(critter))\n {\n _currentTarget = critter; \n }\n }\n }\n\n // not eating; increment hunger level:\n hungerLevel++;\n }\n}\n</code></pre>\n<p>Obviously this is just food for thought, I'm not going to implement the whole thing here, but you get the idea: now you can decide that a <code>Fish</code> that weighs 20 pounds will have a bigger impact on a <code>Shark</code>'s appetite than a <code>Fish</code> that weighs 2 pounds, for example: the <code>Ocean</code> class couldn't care less about these details - and it's up to you to put that code where it belongs.</p>\n<p>Yes, this might look like it's more code to write. It could very well be. But I've gone overboard here, just to illustrate a point. The bitmap is gone, the ocean doesn't need to scan <em>itself</em> anymore, and you're only storing the data that you need; if there's 1 fish in the entire ocean, finding it will be much, much, <em>much</em> faster that way - and with each class responsible for its own business, extending your simulation and adding more variables and possibly other critters in the food chain, wouldn't be very hard.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:40:46.467",
"Id": "75323",
"Score": "0",
"body": "Can I edit your answer to make it correct in Java's term?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:41:42.453",
"Id": "75325",
"Score": "0",
"body": "@tintinmj sure!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:02:10.707",
"Id": "75332",
"Score": "0",
"body": "Changed `IsInsight` to `canCapture`. One thing also I didn't understand why make `eat` a private method and not include in the base class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:04:40.490",
"Id": "75333",
"Score": "0",
"body": "@tintinmj got caught by the assumption that only `Shark`s can eat - perhaps `eat(Critter critter)` would make it more extensible indeed :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T08:38:59.367",
"Id": "75374",
"Score": "0",
"body": "@tintinmj here is the [link](http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/readme) for problem description, where part I solution is being discussed here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:34:36.860",
"Id": "75381",
"Score": "0",
"body": "@Mat'sMug In your update, I did not understand about Stark extending Fish, i thought Shark extends Critter similar to Fish extending Critter. Shark and Fish are two creatures in ocean. So, What is the idea here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:50:34.887",
"Id": "75391",
"Score": "0",
"body": "@user3317808 you could do that as well, but you'll likely be writing similar code twice... because a shark *is a* fish :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:55:16.377",
"Id": "75392",
"Score": "1",
"body": "Good job at implementing the problem btw - it's just that the exercise isn't object-oriented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T11:48:31.610",
"Id": "75394",
"Score": "0",
"body": "@Mat'sMug Thank you, But i want to chat with you as i have some queries surrounding it. I don't know, How to reach you on chat"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:07:38.070",
"Id": "75397",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13410/discussion-between-mats-mug-and-user3317808)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T10:10:54.327",
"Id": "75980",
"Score": "0",
"body": "@Mat'sMug I would like to dicuss with you on chat further on this. When can i come on chat?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T11:17:34.147",
"Id": "75982",
"Score": "0",
"body": "@Mat'sMug Can we discuss further on the changes as per given [link](http://codereview.stackexchange.com/questions/43921/suggestions-needed-to-fill-timestep-method)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T05:22:54.263",
"Id": "76198",
"Score": "0",
"body": "@Mat'sMug In the Ocean class, How would you maintain all creatures with 'private List<Critter> _critters;\n' Do you think it should be something like 'private Critter[][] oceanMatrix;'? am stuck up here. i need help"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T12:32:05.507",
"Id": "76248",
"Score": "0",
"body": "@user3317808 a `Critter` *has a* `Location` property that encapsulates its X-Y location; all the `Ocean` needs to know is that it *has a* `List<Critter>` - `Ocean` doesn't need to know each critter's location because it's each individual critter that's responsible for its moves (e.g. `this.location.X++`), the `Ocean` merely says \"update\", and the critters run their \"update\" method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:04:38.957",
"Id": "76254",
"Score": "0",
"body": "@Mat'sMug Yes i understand that, But if you carefully see the timeStep() method, we need to check the behaviour of 8 neighbours surrounding each cell. with your recommended design, do u think it is possible? Do you think update() method of each Critter can be implemented for neighbor check, if we just maintain List<Critter> in Ocean? May be i want to chat with you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T13:05:05.340",
"Id": "76255",
"Score": "0",
"body": "http://chat.stackexchange.com/rooms/8595/the-2nd-monitor"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T10:54:03.590",
"Id": "76436",
"Score": "0",
"body": "@Mat'sMug am unable to notify anybody on this query [link](http://codereview.stackexchange.com/questions/43921/suggestions-needed-after-modification-of-simulation-of-an-ocean) I have modified the code with solution, Please help me with review. Please also check, why i did not use 2darray in place of list, i gave my reasoning in comments"
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:57:44.687",
"Id": "43525",
"ParentId": "43476",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:39:07.920",
"Id": "43476",
"Score": "9",
"Tags": [
"java",
"simulation"
],
"Title": "Simulation of an ocean containing sharks and fish"
} | 43476 |
<p>I'm using this JS to sticky website footers at the bottom and I would like to know if is there anything to be optimised?</p>
<pre><code>(function($, window, document){
//Screen_height = Header_height + Main_Content_height + Footer_height + alltoplvlContainersMarginTop_Bottom + alltoplvlContainersPaddingTop_Bottom
$.fn.sticky_footer = function(header,footer,content) {
if(typeof header != undefined && typeof footer != undefined && typeof content != undefined) {
var screen_height = $(window).height(); //Total height of the screen which is rendered within a browser window without having to scroll-down.
var sum_of_top_bottom_props = function(id){ //Returns the sum of float values of padding-top,bottom margin-top,bottom, border-top,bottom-width.
if(typeof id != undefined){
var elem_id = id;
if(elem_id.length>0) { //If id exists in the page, fetch the sum of float values of the properties.
var prop_padding = parseFloat(elem_id.css('padding-top'))+parseFloat(elem_id.css('padding-bottom')),
prop_margin = parseFloat(elem_id.css('margin-top'))+parseFloat(elem_id.css('margin-bottom')),
prop_border = parseFloat(elem_id.css('border-top-width'))+parseFloat(elem_id.css('border-bottom-width'));
return prop_padding+prop_margin+prop_border;
} else{ //If id soesnot exist return 0;
console.error("The id: "+id+" doesn't exists! Pleas enter a valid id.");
return 0;
}
}};
var header_height = (header.length>0) ? header.height():0, //Height of header
footer_height = (footer.length>0) ? footer.height():0, //Height of footer
header_props = sum_of_top_bottom_props(header), //Height of properties that contribute to header's height.
footer_props = sum_of_top_bottom_props(footer), //Height of properties that contribute to footer's height.
main_props = sum_of_top_bottom_props(content), //Height of properties that contribute to content's height.
main_height = screen_height-(header_height + header_props + main_props + footer_props + footer_height);
if(content!= undefined && content.length>0) { content.css('min-height',main_height); return true; }
else return false;
}
else return false;
}
})(jQuery, window, document);
</code></pre>
<p>GitHub: <a href="https://github.com/Elavarasanlee/sticky-footer.js" rel="nofollow">https://github.com/Elavarasanlee/sticky-footer.js</a></p>
| [] | [
{
"body": "<p>From a once over,</p>\n\n<ul>\n<li>I strongly suggest lowerCamelCase: <code>sticky_footer</code> -> <code>stickyFooter</code>, <code>screen_height</code> -> <code>screenHeight</code> etc. etc.</li>\n<li><p>You should compare to <code>undefined</code> with <code>===</code> or use a falsey comparison, I would suggest the falsey comparison:<br></p>\n\n<pre><code>if(header && footer && content) {\n</code></pre></li>\n<li>This: <code>var elem_id = id;</code> makes no sense to me, why not simply keep working with <code>id</code> ?</li>\n<li>If you are going to return the sum of all 6 css values (<code>return prop_padding+prop_margin+prop_border;</code> ), then I would not use the temporary values but just return the actual calculation</li>\n<li>Do not use <code>console.log</code> in production code</li>\n<li><p>That gives something like this:</p>\n\n<pre><code>//Returns the sum of float values of padding-top/bottom,margin-top/bottom, border-top/bottom, \n//if no element is provided, returns 0\nvar sum_of_top_bottom_props = function(id){ \n if(id && id.length){\n return parseFloat(elem_id.css('padding-top')) + \n parseFloat(elem_id.css('padding-bottom')) +\n parseFloat(elem_id.css('margin-top')) + \n parseFloat(elem_id.css('margin-bottom')) +\n parseFloat(elem_id.css('border-top-width')) + \n parseFloat(elem_id.css('border-bottom-width'));\n }\n return 0;\n}};\n</code></pre></li>\n<li><code>else return false</code> is pointless, just do <code>return false</code></li>\n<li>Finally, you require the user of your script to take care of <code>$(window).resize(function(){</code>, your script should take care of that instead.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:10:32.397",
"Id": "43513",
"ParentId": "43484",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T05:18:16.877",
"Id": "43484",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"dom"
],
"Title": "JavaScript Sticky Footer"
} | 43484 |
<p>I've tried to write my <code>Property Container</code> design-pattern implementation.</p>
<p>Could anybody, please, tell me, if this code is really <strong>what I intended</strong> to write (follows the <code>Property Container</code> design-pattern rules)? Is there anything that can be improved?</p>
<pre><code><?php
class PropertyContainer
{
private $PropertyContainer = array();
public function __construct() { }
public function addProperty($k, $v)
{
for($i = 0; $i < count($this->PropertyContainer); $i++) { }
$this->PropertyContainer[$k] = $v;
}
public function setProperty($k, $v)
{
while($this->PropertyContainer)
{
if(key($this->PropertyContainer) == $k) {
$this->PropertyContainer[$k] = $v;
return;
}
next($this->PropertyContainer);
}
echo "Key was not found";
}
public function getProperty($k)
{
//var_dump($this->PropertyContainer);
foreach($this->PropertyContainer as $key => $val)
{
if($key == $k) { return $val; }
}
echo "Key was not found";
return;
}
}
$pc1 = new PropertyContainer();
$pc1->addProperty("myProperty1", 31);
$pc1->addProperty("myProperty2", 32);
$pc1->addProperty("myProperty3", 33);
$pc1->setProperty("myProperty2", 7);
echo $pc1->getProperty("myProperty1") . "<br />";
echo $pc1->getProperty("myProperty2") . "<br />";
echo $pc1->getProperty("myProperty3") . "<br />";
echo "<br />";
$pc2 = new PropertyContainer();
$pc2->addProperty("myProp1", 11);
$pc2->addProperty("myProp2", 11);
$pc2->addProperty("myProperty3", "Some String");
$pc2->setProperty("myProp2", 12);
echo $pc2->getProperty("myProp1") . "<br />";
echo $pc2->getProperty("myProp2") . "<br />";
echo $pc2->getProperty("myProperty3") . "<br />";
echo "<br />" . $pc2->getProperty("myProperty5") . "<br />";
?>
</code></pre>
| [] | [
{
"body": "<p>Yes, you are using this patter correctly here. Its use in PHP (especially as a generic implementation) is greatly reduced though. As the answers in your <a href=\"https://softwareengineering.stackexchange.com/questions/231274/property-container-design-pattern-in-depth-definition\">programmers.stackexchange.com</a> point out: basically it is a hashmap. Now, PHP implements arrays as some form of hash map already. I see this pattern as an anti-pattern too. There are some use-cases of this pattern when you register validators along each property this property has to fullfil when setting. </p>\n\n<p>The php class <code>stdClass</code> basically does what you want to achieve it a more direct way:</p>\n\n<pre><code>$object = new stdClass();\n$object->key = $value;\n</code></pre>\n\n<p>Though I'd recommend not to use this code in production, it is a good way to learn of course. </p>\n\n<p>So my review for your code:</p>\n\n<ul>\n<li><code>$PropertyContainer</code>: It is uncommon in PHP to have variables start in upper case. Most code I do read either starts in lower-case and follow Camel-Case or is snake casing. </li>\n<li><code>public function __construct() { }</code> just fills up space. Not required, therefore remove it.</li>\n<li>You should have a closer look at how to work with arrays in PHP. Your current approach is highly inefficient. Many of the array functions do not relay on the array iterator's state. Currently you force PHP to iterate over the array. If you use dedicated methods instead, PHP doesn't have to iterate (which is much faster of course :))\n\n<ul>\n<li>To add an entry to your array there is no need to iterate over it without doing it first. You can either <code>array_push</code> it at the end or just set it by <code>$this->PropertyContainer[$k] = $v</code>.</li>\n<li>Same goes for checking of existence. Use <code>isset</code> instead. </li>\n<li>And for accessing you can use <code>$this->PropertyContainer[$k]</code> instead of iterating</li>\n</ul></li>\n<li><code>$k</code> and <code>$v</code> are bad parameter names. While they usually are recognized as key and value, there is no harm to call them this way. But this can be improved: you are talking about properties and not keys. So better name them <code>$propertyName</code> and <code>$value</code>. Shorthands should be used in local scope only (if at all).</li>\n<li>While I suppose they are just there for debugging: <code>echo</code>'ing on error is a bad idea. Either return a error code or even better, throw an exception. Of course this requires a method to check if a property exists (e.g. <code>hasProperty</code>).</li>\n<li><code>return;</code> without any value is the default anyway at the end of a method. You can remove this, shorting the code. Elsish after some time another developer might wonder why it was written once: was it located at some other line? was there some return value previously? </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T22:11:50.343",
"Id": "43558",
"ParentId": "43485",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43558",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T05:18:27.767",
"Id": "43485",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"classes",
"php5",
"properties"
],
"Title": "\"Property Container\" design-pattern"
} | 43485 |
<pre><code>import java.math.BigInteger;
import java.util.Random;
public class Primetest {
private static int size=15;
private static Random r=new Random();
private static BigInteger two=new BigInteger("2");
private static BigInteger three=new BigInteger("3");
public static void main(String[] args) {
while(true)
{
BigInteger p=new BigInteger(size,r);
if(isprime(p)==true)
{
System.out.println("prime="+p);
break;
}
}
}
public static boolean isprime(BigInteger n)
{
if(n.compareTo(BigInteger.ONE)==0 || n.compareTo(two)==0)
{
return true;
}
BigInteger half=n.divide(two);
for(BigInteger i=three; i.compareTo(half)<=0;i=i.add(two))
{
if(n.mod(i).equals(BigInteger.ZERO))
{
return false;
}
}
return true;
}
}
</code></pre>
<p>This code selects a random prime <code>BigInteger</code> number. I want a 2048 bit <code>BigInteger</code> prime number, but it only works with 15 bit. Can anybody help me?</p>
| [] | [
{
"body": "<p>This is Code Review, so I will not try to find where it doesn't support 2048 bit BigIntegers, but I will tell you what I see in your code:</p>\n\n<p><strong>Naming Conventions</strong></p>\n\n<p>You should choose your names according to your language's <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow\">naming conventions</a>: <code>Primetest</code> should be <code>PrimeTest</code>, <code>two</code> should be <code>TWO</code> (see also below regarding proper variable scopes), <code>isprime</code> should be <code>isPrime</code>, etc...</p>\n\n<p>Also refrain from single letter names for anything that you use for more than one line of code - <code>r</code>, <code>n</code>, etc.</p>\n\n<p><strong>Proper names</strong></p>\n\n<p>Variable names should clearly state their purpose <code>half</code> means the number 1/2, especially next to <code>one</code> and <code>two</code>. Actually it means half the input number. It is used as the max possible divisor, so call it that - <code>maxDivisor</code>.</p>\n\n<p>Same goes for <code>size</code> - it should be <code>MAX_BITS_RANGE</code> (btw, what happens when you change its value to 2048?)</p>\n\n<p><strong>When things don't change</strong></p>\n\n<p>If you have data which does not change over time (like the number <code>two</code>) - making is <code>static</code> is good, making it a constant (<code>static final</code>) is better:</p>\n\n<pre><code>private static final int MAX_BITS_RANGE=15;\nprivate static final Random GENERATOR=new Random();\nprivate static final BigInteger TWO=new BigInteger(\"2\");\nprivate static final BigInteger THREE=new BigInteger(\"3\");\n</code></pre>\n\n<p><strong>Redundant code</strong></p>\n\n<p><code>if (isPrime(x) == true)</code> is <em>exactly</em> the same as <code>if (isPrime(x))</code>.</p>\n\n<p><strong>Be consistent</strong></p>\n\n<p>In different places in your code you check equality either as <code>n.compareTo(BigInteger.ONE)==0</code> or as <code>n.mod(i).equals(BigInteger.ZERO)</code> - choose one way - and stick to it.</p>\n\n<p>*Adding @Marc-Andre's observation:</p>\n\n<p>You should also be consistent with your indentations and braces locations. Although Oracle's <a href=\"http://www.oracle.com/technetwork/java/codeconventions-141270.html#2991\" rel=\"nofollow\">suggestion</a> is to put the opening brace at the end of the line, </p>\n\n<pre><code>while(true) {\n}\n</code></pre>\n\n<p>not at the start of the next (my preference as well), other styles are also used (<a href=\"http://en.wikipedia.org/wiki/Indent_style#Allman_style\" rel=\"nofollow\">some</a> more widely than <a href=\"http://en.wikipedia.org/wiki/Indent_style#Whitesmiths_style\" rel=\"nofollow\">others</a>):</p>\n\n<pre><code>// Allman Style\nwhile (true)\n{\n}\n\n// Whitesmiths Style\nwhile (true)\n {\n }\n</code></pre>\n\n<p>but you should choose one style and stick with it, to prevent reading errors, and general head-ache by code readers...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:41:52.853",
"Id": "75235",
"Score": "0",
"body": "I won't add an answer for that (since you cover a good part of what I could say ), but you could mention that his indentation is not consistent and that he should decide if he use brackets Java style or not (it's not consistent either)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:58:11.490",
"Id": "75239",
"Score": "0",
"body": "@Marc-Andre - added you observation as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T22:10:47.877",
"Id": "75506",
"Score": "0",
"body": "Pro tip: (BigInteger.compareTo(otherBigInt) == 0) != BigInteger.equals(otherBigInt). One takes precision into account. SO, \"1.00\" will not be the same as \"1.0\" -- but I forget which of those functions bears it out"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:47:44.257",
"Id": "43493",
"ParentId": "43490",
"Score": "5"
}
},
{
"body": "<p>Edit: Your code is working beyond 15 bits, it's just really slow..... More about that later.</p>\n\n<p><strike>I am not sure why your code does not work beyond 15-bit BigIntegers either.... it's not something daft like the fact you have <code>size = 15</code>, now, is it?</strike></p>\n\n<h2>Two suggestions</h2>\n\n<p>Apart from that, there are two items that may interest you:</p>\n\n<ul>\n<li><p>you can probably improve performance by using the two methods:</p>\n\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#nextProbablePrime%28%29\" rel=\"nofollow\">nextProbablePrime()</a></li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#isProbablePrime%28int%29\" rel=\"nofollow\">isProbablePrime()</a></li>\n</ul>\n\n<p>With these methods you can check your candidate prime before you do the hard work... i.e. your first call in the isprime() method can be:</p>\n\n<pre><code>if (!n.isProbablePrime()) {\n return false;\n}\n</code></pre>\n\n<p>Then, if it is probably a prime, you will need to check it, and you can do that in a way that may be faster with:</p>\n\n<pre><code>for(BigInteger i=three; i.compareTo(half)<=0;i=i.nextProbablePrime()) {\n ....\n}\n</code></pre>\n\n<p>This may, or may not be faster. Check it.</p></li>\n<li><p>What will be faster is if you only check to the square-root of n, instead of 'half'. BigInteger does not have a method <code>square-root</code>, but you can get an approximate limit quite fast with just a <a href=\"http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method\" rel=\"nofollow\">few iterations through the Babylonian method</a>. You don't need to find the actual square-root, just some value that is slightly larger than the root. This will save many, many, many potential iterations for when the input value really is prime.</p></li>\n</ul>\n\n<hr>\n\n<h2>Test implementation</h2>\n\n<p>I have put together some example code which shows a few things:</p>\n\n<ol>\n<li>your code is, in fact working....</li>\n<li>when you have large numbers, your prime factoring guesses are going to pretty much take forever.... and I am not sure if forever-running code is working code...</li>\n<li>It uses the faster isProbablyPrime(int) method to short-circuit the slow math.</li>\n<li>It computes an approximate square-root of the input value.</li>\n<li>It uses nextProbablePrime() instead of checking every odd number in the loop.</li>\n</ol>\n\n<p>Note that I think your algorithm could also be optimized by changing the outer loop. If the goal is to find a large random number, then the better way to do it would be to choose a large number randomly, make sure it is odd, and then test it for prime-ness. If it is not prime, then keep adding 2 until the value <strong>is</strong> prime. This will significantly reduce the random hunting for prime values.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>private static int size = 1024;\nprivate static Random r = new Random(1);\nprivate static BigInteger two = new BigInteger(\"2\");\nprivate static BigInteger three = new BigInteger(\"3\");\n\npublic static void main(String[] args) {\n\n while (true) {\n BigInteger p = new BigInteger(size, r);\n System.out.println(\"Processing prime \" + p + \" with input \" + size\n + \" bits\");\n\n if (isprime(p) == true) {\n System.out.println(\"prime=\" + p);\n break;\n }\n }\n}\n\npublic static boolean isprime(BigInteger n) {\n\n if (!n.isProbablePrime(10)) {\n return false;\n }\n\n if (n.compareTo(BigInteger.ONE) == 0 || n.compareTo(two) == 0) {\n return true;\n }\n BigInteger root = appxRoot(n);\n System.out.println(\"Using approximate root \" + root);\n\n int cnt = 0;\n for (BigInteger i = three; i.compareTo(root) <= 0; i = i\n .nextProbablePrime()) {\n cnt++;\n if (cnt % 1000 == 0) {\n System.out.println(cnt + \" Using next prime \" + i);\n }\n if (n.mod(i).equals(BigInteger.ZERO)) {\n return false;\n }\n\n }\n return true;\n\n}\n\nprivate static BigInteger appxRoot(final BigInteger n) {\n BigInteger half = n.shiftRight(1);\n while (half.multiply(half).compareTo(n) > 0) {\n half = half.shiftRight(1);\n }\n return half.shiftLeft(1);\n}\n</code></pre>\n\n<p>And, here is the output</p>\n\n<pre><code>Processing prime 98329376886274465203040498066651959157640182809094020631664385777551847591123638109144698149095205744886312777380124671380640351550097713803874959847367838878126620008205910502904640512240477769179755530216157310355581410760731210073213721673064659778570224177036380289355437254781245378941806708640626915896 with input 1024 bits\nProcessing prime 37646605107187235792943122848905725816642680759921726391069038948580233504043310475106107937453362419670194263133240792533036542339813188374350574945196545621538046755833078747457686689427373500864049860688062396137214885740182673993779980005699518336257562987964318771232237070594662691795239179395907746381 with input 1024 bits\nProcessing prime 125205778308571596366364664578026315265996047681538536772575342694310454438809896771367811860534210488218628994364991251294455216205362342490618659150824104797110134588899854049460243713711039304748274575425927846133394573799688746650452867761117377057477970221094526444104587198668516522314203910650060775297 with input 1024 bits\nProcessing prime 29927154392784343780961536475173096429548596167420203155112563329853022850079385324824305227046118707802338722443720119949840770560558670171973682574167343679095711827324930773450204678598945005042160247713118600168856758838352856602314407651532633576632941646038272135258001495947267516367654449573770447978 with input 1024 bits\nProcessing prime 139243961902015178358905340711072637999780823861985238094201532190345570854225223205633490036395897038352240416702384303956261085630258304397095684303936086294128301544469715824139689002062508603332475411268227340511899314982630226967627021263463712185132048978641948260688280239972303621025851700017991795656 with input 1024 bits\nProcessing prime 122363695497135362876334096986750092237187818163935289528269643131788940948676195886148173694943587069178270471951802290191005226421476324835369279161430725594938044767129988205836293228618396536013056503441398180392306035348529131293104302985721904196513857471448257453900973803574632148674525698706255968469 with input 1024 bits\nProcessing prime 6766841734279494121695202528813564426876102386393672096192548380596947610679150306271345703101761193843898532659901726349258449119163161846636750914151571614552775446973414312295356121082306016346670297986250268817217032557516075488000173517339258842372202954513367225234606811784912645921661651252301210439 with input 1024 bits\nProcessing prime 1244168157289385582197158692756366939639032807157147509726417844315011285784938824776953893721289756574282393714469772808628985336160381884771437651533388861457165174027710304927221871555060351769769251837444763151883211741263529676654328058488380773866083064897587855677058477160609886235025932428799595897 with input 1024 bits\nProcessing prime 132158916583424296773989292524518115815097623427134119856232403777863313269411230253297504275469503273779555561857087644449894885032508020437681301637184423517233528793784318637110731993459739195119489689739447166431101193405592878819600262595536763785155730768337651779977312858406291899622027075197339272533 with input 1024 bits\nProcessing prime 69992427855596672916046274609831358925004102231151217146504934042278719263838690406603474915165537361784459455893083094877744290705302384633321340170916902155546529977673369310451021181970658193490668498069273542381636608842630759935789234533400192866934709438808312038202012904797132388392567889891155748450 with input 1024 bits\nProcessing prime 21158035183654230873794938382538380103022588111151171726822340627470812338126036440129555658534288545561323627229661551179395796822536779689099195780624577722259563387380039125533382285521378162912552760478091032365155104156393389243223430957343814123541441495493412606366108994001798740793143149348566611849 with input 1024 bits\nProcessing prime 15252401507860116139044993701109820472568933087608994119874588139374351833868522812721998308899653583211533913737970680874956499213716249151797416323727562426289207703789447617206459217803392887453871279176965603731348358876019227478462392987492580262414905238078166067132705908043224132942658110708655117575 with input 1024 bits\nProcessing prime 79207591965644170299922757157810677225143754875497695785333916966745459024878221535386104794074683912029219571613935837926395463393267459748825400976839505450111313617312314479345019735666163348592463847785881480127339787201145529464779061029020193892147298882124349322947190382379671430079191833914102173464 with input 1024 bits\nProcessing prime 61030497376329633328073316647655267262303694060711488520514344109326325543945802124423073251577269169186781440230219553617205658081336472411027108746182826458446589150653587257149674878699689258298746835269894603933930803472419590290016677183062036325055276717300539131443014986954057041180792801863470921160 with input 1024 bits\nProcessing prime 169114037779361593124142841783629182425924353804019723914654438093025578377446888507229925252227113606029383048794273249003173542629081468619397107139204307145864334149929493619281837363125251731861465625382815511697458723930987915758447225669236647982784800507786813022174334313252476414285766502413871475837 with input 1024 bits\nUsing approximate root 25226202323750862638468707057345770204269264134797015774704159175996067529790533462300444165020098361223682946889361283140757213132269147109605325588573982\n1000 Using next prime 7927\n2000 Using next prime 17393\n3000 Using next prime 27457\n4000 Using next prime 37831\n</code></pre>\n\n<p>by my estimates, on my machine, it will probably take a few years to test all primes up to <code>25226202323750862638468707057345770204269264134797015774704159175996067529790533462300444165020098361223682946889361283140757213132269147109605325588573982</code> .... but, that is much faster than what it would to calculate all the primes up to half of the test value which is <code>169114037779361593124142841783629182425924353804019723914654438093025578377446888507229925252227113606029383048794273249003173542629081468619397107139204307145864334149929493619281837363125251731861465625382815511697458723930987915758447225669236647982784800507786813022174334313252476414285766502413871475837</code></p>\n\n<p>If you follow my suggestion and loop to find primes using +2 instead of random, then your main method could be:</p>\n\n<pre><code>public static void main(String[] args) {\n\n BigInteger p = new BigInteger(size, r);\n if (testBit(0)) {\n p = p.add(BigInteger.ONE);\n }\n while (true) {\n System.out.println(\"Processing prime \" + p + \" with input \" + size\n + \" bits\");\n\n if (isprime(p) == true) {\n System.out.println(\"prime=\" + p);\n break;\n }\n p = p.add(TWO);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:51:24.953",
"Id": "75218",
"Score": "0",
"body": "You got your links confused a bit... as for the stop condition, how about `for(BigInteger i=three; i.pow(2).compareTo(n)<=0;...`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:05:00.287",
"Id": "75227",
"Score": "0",
"body": "@UriAgassi The stop condition would work, but it is a big calculation to do every time. It is faster to calculate the root just once, and then do a simple compareTo... I am busy building this as an example code anyway... about to post"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:40:06.230",
"Id": "43503",
"ParentId": "43490",
"Score": "8"
}
},
{
"body": "<p>I can suggest you something that can reduce your <code>isPrime</code> code size drastically.</p>\n\n<pre><code>public static boolean isPrime(BigInteger n) {\n BigInteger lessOne = n.subtract(BigInteger.ONE);\n // get the next prime from one less than number and check with the number\n return lessOne.nextProbablePrime().compareTo(n) == 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T18:28:29.837",
"Id": "103073",
"Score": "0",
"body": "Shouldn't the name of this revised function be `isProbablyPrime`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T18:37:21.833",
"Id": "103074",
"Score": "0",
"body": "@DavidK from the docs `\"Returns the first integer greater than this BigInteger that is probably prime. The probability that the number returned by this method is composite does not exceed 2^-100. This method will never skip over a prime when searching: if it returns p, there is no prime q such that this < q < p.\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T18:48:42.863",
"Id": "103076",
"Score": "0",
"body": "Yes, that is why the documented function is named `nextProbablePrime` rather than `nextPrime`. Admittedly 2^-100 is a very small probability, but it was considered important enough to insert the word `Probable` in the function name."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-21T18:15:51.757",
"Id": "57596",
"ParentId": "43490",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:25:18.453",
"Id": "43490",
"Score": "5",
"Tags": [
"java",
"primes",
"random"
],
"Title": "BigInteger prime testing"
} | 43490 |
<p>I am using knockout in my project. I have some models like <code>EmployeeModel</code>, <code>ServiceModel</code> etc which user can update. On UI I give the user a <code>Cancel</code> control button by which he can revert the changes. On cancel I have to revert the model change back to its original state. For this I found these two good approaches by @rniemeyer: </p>
<p><a href="http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html" rel="nofollow">Protected Observable</a></p>
<p>I can't use protected observables because I am using <a href="http://knockoutjs.com/documentation/plugins-mapping.html" rel="nofollow">ko.mapping plugin</a> which will create a knockout models base on server side viewmodels. Yes, I can use mapping option like <em>Create</em>, but I feel its not a good to keep separate observables state. I want solution which will be reusable and can apply to whole model. </p>
<p>And guess what I got, second good approach by same author @rniemeyer:</p>
<p><a href="http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html" rel="nofollow">Simple editor pattern</a></p>
<p>I can't use this also because of the same reason I mentioned above. So I wrote 2 functions copy and reset which will do the job for me:</p>
<p><strong>Copy</strong></p>
<p>Here, <code>source</code> is the object whose current state we want to preserve, and <code>dest</code> keeps the current state. </p>
<pre><code>function copy(source, dest) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
//no need to keep knockout added properties
if (key === "__ko_mapping__")
continue;
//recursive call to copy if property is an object
else if (typeof source[key] === "object") {
dest[key] = {};
copy(source[key], dest[key]);
}
else {
//no need to copy the computed observable value
if (!ko.isComputed(source[key])) {
var value = ko.utils.unwrapObservable(source[key]);
dest[key] = value;
}
}
}
}
//remove all function
for (var key in dest) {
if (typeof dest[key] === "function")
delete dest[key];
}
}
</code></pre>
<p><strong>Reset</strong></p>
<p>Here, <code>source</code> is the previous <code>dest</code> and <code>dest</code> is the previous <code>source</code>. </p>
<pre><code>function reset(source, dest) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
//recursive call to copy if it is an object
if (source[key] !== null && typeof source[key] === "object") {
reset(source[key], dest[key]);
}
else {
if (ko.isObservable(dest[key]))
dest[key](source[key]);
else
dest[key] = source[key];
}
}
}
}
</code></pre>
<p>I want you to please review these function and let me know if these function require any improvement.</p>
| [] | [
{
"body": "<p>From a <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">KISS</a> perspective, I would simply load the model again, then you would not need any of this code.</p>\n\n<p>Other than that the code is clean and maintainable, some nitpicking though:</p>\n\n<ul>\n<li>You declare <code>var key</code> twice in <code>copy</code>, that is not required</li>\n<li>You are not using <code>hasOwnProperty(key)</code> when you delete all the functions in <code>copy</code></li>\n<li>You could have merged <code>source.hasOwnProperty(key)</code> and <code>key === \"__ko_mapping__\"</code> with a <code>&&</code></li>\n<li>You access <code>source[key]</code> a lot, you could have considered a <code>var value = source[key]</code> and then work with <code>value</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:41:04.960",
"Id": "43511",
"ParentId": "43492",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:45:03.627",
"Id": "43492",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"knockout.js"
],
"Title": "Revert knockout model original state back on update cancel?"
} | 43492 |
<p>I'm hoping this is the correct place for this, I'm struggling a little for wording as i'm not sure what you would call this.</p>
<p>Basically, i have a system in place where my datagrid marks cells that have changed with a new background colour, to do this i have a method in the object that contains these properties that receives a string which is the name of the property to check, and then a switch statement that takes that string to check the correct property.</p>
<pre><code>public Color HasChanged(string value)
{
switch (value)
{
case "CILRef":
if (_localShipment.cilRef != _originalShipment.cilRef)
{
return Colors.SkyBlue;
}
else
{
return Colors.White;
}
case "ArrivedAtPortDate":
if (_localShipment.arrivedAtPortDate != _originalShipment.arrivedAtPortDate)
{
return Colors.SkyBlue;
}
else
{
return Colors.White;
}
}
</code></pre>
<p>I've removed the rest of the properties for brevity.</p>
<p>Now i get the nagging sensation that there is a cleaner way to do this string>property without using a switch statement, but i can't for the life of me find anything on google, it's hard to search without some keyword to go on.</p>
<p>I'm also attempting to only save those properties that have changed, i was going to place any changed property name into an array, and then have a loop with yet another switch statement that checked that array and then saved the correct property. However this again seems untidy to me.</p>
<p>is there a cleaner solution to this, hopefully that could handle the addition of new properties without needing to add new code to the switch statements.</p>
<p>I can include the rest of the code that does this checking (namely the WPF binding on the datagrid, and a converter that calls the checking method with the property name as a string parameter) if needed.</p>
<p><strong>EDIT:</strong> </p>
<p>To show the rest of my code, hopefully explaining a few things.</p>
<p>I have a datagrid in xaml that contains these properties. below is an example:</p>
<pre><code><DataGridTemplateColumn Header="CILRef">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding CILRef}">
<TextBlock.Background>
<SolidColorBrush Color="{Binding Converter={StaticResource hasChangedConverter}, ConverterParameter='CILRef'}"/>
</TextBlock.Background>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding CILRef, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</code></pre>
<p>as you can see, by this line : <code><SolidColorBrush Color="{Binding Converter={StaticResource hasChangedConverter}, ConverterParameter='CILRef'}"/></code></p>
<p>The background is bound using a converter, which is:</p>
<pre><code>class HasChangedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
var shipment = value as Shipment;
var property = parameter as string;
return shipment.HasChanged(property);
}
catch (Exception ex)
{
return Colors.HotPink;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
</code></pre>
<p>Hopefully this will explain how the code works better than i've been doing in the comments.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:34:38.847",
"Id": "75193",
"Score": "1",
"body": "That doesn't really change much from the points I mentioned below although as Vogel612 said , you shouldn't use exceptions in expected areas. you should return the Pink value if the variable is null, not do the try block, they are slow and bad practice in logic. Binding is fine but if the values are always the same and they match certain colours...pair them. have a collection of matching enum/colours to values, I would use a dictionary, then your converter can just pull out the right value. Converters are meant to be light weight way's to visualize data differently,not heavy business logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:48:30.190",
"Id": "75196",
"Score": "0",
"body": "I'm still not sure what you mean by this, the design of this is if the value has changed from the original loaded value, it displays skyblue. the colour is simply a representation of data that is dirty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:00:01.527",
"Id": "75199",
"Score": "0",
"body": "@user1412240 please include the full switch-statement in your question. also: Why not do the job with simple JavaScript? `onChange=\"this.style.add('background-color', '#lightblueRGB');\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:04:05.500",
"Id": "75200",
"Score": "0",
"body": "if you look at my own answer below, i have removed the switch statement completely now. also, i was not aware you could use javascript in a WPF application, also that would not be a \"dirty\" flag just a changed flag, which is not what was requested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:11:54.947",
"Id": "75201",
"Score": "0",
"body": "@user1412240 sorry, I'm not experienced with WPF, but I can tell that the difference between a dirty- and changed-flag is only one if-statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:14:55.067",
"Id": "75203",
"Score": "0",
"body": "that is the point, the data must be checked against the previously loaded data, hence the link to the business logic, i had to check it some how. I think however my original question has been answered by my answer below. and this is turning into an extended discussion now. Thank you very much for your time however."
}
] | [
{
"body": "<p>Well it seems to me you have a key and a chunk of code that returns a colour based on some boolean check. </p>\n\n<p>I would probably suggest a Function collection.</p>\n\n<p>e.g</p>\n\n<pre><code>Dictionary<string,Func<Color>> Actions;\n\nvoid InitActions()\n{\n Actions = new Dictionary<string,Func<Color>>();\n\n\n Actions.add(\"CILRef\",()=>\n{\n return _localShipment.cilRef != _originalShipment.cilRef ? Colors.SkyBlue : Color.White;\n});\n\n} \n</code></pre>\n\n<p>and to use it:</p>\n\n<pre><code>public Color HasChanged(string value)\n{\n Color highlightColor = Color.White;\n if(Actions.Contains(value))\n highlightColor = Actions[value];\n\nreturn highlightColor;\n}\n</code></pre>\n\n<p>Although that doesn't really solve your problem. </p>\n\n<p>I usually like to answer a persons question first in case they choose not to do a large refactor but I would take a closer look at what you are trying to do. </p>\n\n<p>You have a number of larger design problems:</p>\n\n<ul>\n<li>You have a lot of repetition. </li>\n<li>Next nested loops/logic are usually good indications of requiring a refactor.</li>\n<li>You have \"Magic Strings\", what if one of those is misspelt, will your whole application break?</li>\n<li>You shouldn't be tying application logic directly to the ui in the first place. </li>\n</ul>\n\n<p>Ideally I imagine you want something more akin to:</p>\n\n<pre><code>void DataGridSelectionChanged(object sender,EventArgs e)\n{\n var grid = sender as Grid; \n if(grid == null) return;\n\n string selectedValue = grid.SelectedValue ?? DefaultValue;\n\n Color highlightColor = GetHighlightColour(selectedValue);\n\n ...\n}\n</code></pre>\n\n<p>In short the prospect of setting the highlight colour should not really be dependent on the raw values, and if indeed it has to be it should be done in a safe manner. as it is there are a number of way's to break your application some accidentally while developing others while using the application by passing invalid data. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T10:40:05.520",
"Id": "75186",
"Score": "0",
"body": "I appreciate your comments, This system was requested by the designer, it highlights changes to the datagrid that will be saved in the next \"save all\", these changes must be data based (different from the loaded data). Also the default on the switch case throws an ArgumentOutOfRangeException. I hope this clears up some of your concerns, and explains why I've chosen to do it this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T10:52:42.383",
"Id": "75188",
"Score": "0",
"body": "@user1412240 one should not use Exceptions for \"expected\" errors. Actually I do that myself more often than I want to admit, but you should instead return a meaningful errorvalue. ;)#"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:06:39.573",
"Id": "75189",
"Score": "0",
"body": "Just to note, the string value that is passed is hard coded, not a parameter that is set by the user. It should only ever error if i've made a mistake during development, never during runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:08:18.113",
"Id": "75190",
"Score": "1",
"body": "@user1412240 which goes back to my original point, why use raw strings that could cause a mistake in the first place? If they are hard coded and never change replace them for const strings and refer to them instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:09:14.243",
"Id": "75191",
"Score": "0",
"body": "I think it would help if i provided the rest of the code, perhaps that will explain better than i can via comments. Please see my edit (in a few mins)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:32:45.597",
"Id": "75204",
"Score": "0",
"body": "`Actions` is a terrible name for that Dictionary. And it shouldn't be `<string, func>`. It should be `<string, Color>` and use it like `Color color = _localShipment.cilRef != _originalShipment.cilRef ? Colors.SkyBlue : Colors.White; myDict.add(myKey, color);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:13:59.700",
"Id": "75209",
"Score": "0",
"body": "@Max agree on the name, but the usage is preference here..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:25:19.063",
"Id": "75210",
"Score": "0",
"body": "It's still sub-par usage. First of all the dictionary has the wrong type as value, second is that for every time he wants to add a new value he will need to do so at several places and clutter the codebase, third his example doesn't even compile... See OP's answer using reflection to accomplish the same thing but much better for his use case"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:51:38.810",
"Id": "75219",
"Score": "0",
"body": "@Max well, to be fair. Originally only half the code was posted and the use case was not clear, Your solution though only applies to cilRef, a new switch would still be required for arrivedAtPortDate != _originalShipment.arrivedAtPortDate.All that aside though now understanding this is simply a data representation in WPF. it is all irrelevant. The ViewModel object that populates in the Binding should contain a color or a converter.this entire question is moot from a design perspective as it defeats the point of WPF binding. (but i'll give you actions being terrible. although myDict is better?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:54:02.377",
"Id": "75220",
"Score": "0",
"body": "@apieceoffruit No I didn't provide a solution - I explained how you should add new entries to your dictionary (adding `Color` instead of `Func`. So of course you would need to handle `arrivedAtPortDate` also since your approach is still using a dictionary. `myDict` wasn't a suggestions, it was just a placeholder example to clarify what object I'm invoking from."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:57:20.407",
"Id": "75223",
"Score": "0",
"body": "@Max then all that suggestion does is add an additional switch statement on top of the dictionary. How does changing the dictionary value from a function to a color benefit anything?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:59:16.210",
"Id": "75224",
"Score": "0",
"body": "It was just a small fix for your solution... It wasn't a proposed solution for OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:02:53.637",
"Id": "75225",
"Score": "0",
"body": "@Max then i don't think you see the point. I added one entry to the dictionary as a test. Each one has a different boolean check. It would exponentially increase the amount of code to switch the dictionary as each new entry is added. How does your suggestion fix my solution?"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T10:34:42.580",
"Id": "43499",
"ParentId": "43495",
"Score": "2"
}
},
{
"body": "<p>Ok, so having spoken to others on stackoverflow, i have change the code, this (i hope) satisfies all the issue's I've pointed out and all the issues pointed out to me.</p>\n\n<p>The HasChanged is now:</p>\n\n<pre><code>public Color HasChanged(string value)\n{\n try\n {\n var data1 = _localShipment.GetType().GetProperty(value, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(_localShipment, null);\n var data2 = _originalShipment.GetType().GetProperty(value, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(_originalShipment, null);\n return data1 != data2 ? Colors.SkyBlue : Colors.White;\n }\n catch (Exception ex)\n {\n return Colors.White;\n } \n}\n</code></pre>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>This has been changed to the following methods:</p>\n\n<pre><code> private object GetPropValue(object src, string propName)\n {\n PropertyInfo p = src.GetType().GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);\n string value = (string)p.GetValue(src, null);\n return value;\n }\n\n public bool HasChanged(string value)\n {\n var data1 = GetPropValue(_localShipment, value);\n var data2 = GetPropValue(_originalShipment, value);\n return data1 != data2 ? true : false;\n }\n #endregion\n}\n</code></pre>\n\n<p>and the converter has been changed to :</p>\n\n<pre><code>class HasChangedConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n if (value == null) { return Colors.White; }\n var shipment = value as Shipment;\n var property = parameter as string;\n if (shipment.HasChanged(property)) { return Colors.SkyBlue; } else { return Colors.White; }\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new Exception(\"The method or operation is not implemented.\");\n }\n}\n</code></pre>\n\n<p>This solves the issues mentioned previously in this question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:01:11.467",
"Id": "75207",
"Score": "1",
"body": "This is basically what I was going to post haha. It looks good except for in your `catch` block you should instead handle the exception. (Unless of course you just want to consume the exception and return a default color...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:04:05.130",
"Id": "75264",
"Score": "0",
"body": "@Max: The part of your comment in parentheses is wrong, but only because the type of the exception is `Exception`. If there's a `StackOverflowException` or an `OutOfMemoryException`, trying to handle it is a very bad idea. No one wants that. This is more for the questioner's benefit than yours, though, since I assume you already know that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:33:18.983",
"Id": "75270",
"Score": "0",
"body": "See the edits above, this has been changed in an attempt to solve the issues people have pointed out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:28:42.043",
"Id": "43502",
"ParentId": "43495",
"Score": "4"
}
},
{
"body": "<ol>\n<li>As you already discovered, if you want to access a member based on a string name, use reflection.</li>\n<li>You shouldn't mix business logic with presentation: <code>HasChanged</code> shouldn't return a <code>Color</code>, it should return a <code>bool</code>. The colors should the be defined separately.</li>\n<li>Use <code>as</code> only when you expect to get the wrong type and in that case, always test for <code>null</code>. If you're not going to do that, just use a cast.</li>\n<li>I don't think that indicating a general exception using a color is a good idea, because it hides all information about what specific exception occurred. If you're expecting only some specific exception, then catch only that.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:54:03.160",
"Id": "75221",
"Score": "0",
"body": "Thanks for this. Much clearer than trying to understand via comments. I've already changed the gas change to return a boil and the converter handles the color. The try catch has been removed. Quick question tho. I've always been under the assumption that using as was faster and cleaner than a cast. That comes from uni and is most likely wrong"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:50:34.350",
"Id": "75237",
"Score": "0",
"body": "Using as and a null check is going to be faster than cast and catch for NullReferenceException, that's probably where the speed argument comes from. But if you're not going to do that, just use a cast. And I think that clearer code is the one that more accurately describes your intentions. And here, that's a cast, not as."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:52:32.000",
"Id": "75238",
"Score": "0",
"body": "Ok, great reply, sorry about the big typos in the original comment, i was attempting to reply via phone for the first time. and it clearly did not go well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:23:25.050",
"Id": "43509",
"ParentId": "43495",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:50:03.603",
"Id": "43495",
"Score": "4",
"Tags": [
"c#",
"wpf"
],
"Title": "Better method for my property Checking, replacement of switch statement"
} | 43495 |
<p>I tried to make a weighted search function in JavaScript. I've been improving my JS lately but still not sure about some best practices, wondering if there's any improvements I could make, or if I've ended up doing it completely wrong.</p>
<p>The intention is to keep it quite flexible so it can take an array of filter functions, each with its own weight, it also takes a property on which to sort items with equal weights.</p>
<p>The search function is</p>
<pre><code>function weightedSearch(array, weightedTests, sortProperty) {
return array.map(function (e) {
return {
element: e, weight: weightedTests.map(function (weightedTest) {
var testResult = weightedTest.test(e);
return testResult * weightedTest.weight;
}).reduce(function (previousValue, currentValue) { return previousValue + currentValue; }, 0)
};
}).filter(function (element) {
return element.weight > 0;
}).sort(function (obj1, obj2) {
//sort first by weight
if (obj1.weight > obj2.weight) {
return -1;
} else if (obj1.weight < obj2.weight) {
return 1;
}
// Else by chosen property
if (obj1.element[sortProperty] < obj2.element[sortProperty]) {
return -1;
} else if (obj1.element[sortProperty] > obj2.element[sortProperty]) {
return 1;
} else {
return 0;
}
}).map(function (e) {
return e.element;
});
}
</code></pre>
<p>A weighted test is an object of the form:</p>
<pre><code>{test: function(element){}, weight: relativeWeightOfTheTest}
</code></pre>
<p>And would be used in a manner such as:</p>
<pre><code>var search = "test";
var results = weightedSearch(arrayToSearch, [
{ test: function (testElement) { return testElement.title.toLowerCase().indexOf(search) >= 0; }, weight: 2 },
{ test: function (testElement) { return testElement.description.toLowerCase().indexOf(search) >= 0; }, weight: 0.5 }
], "title")
</code></pre>
<p>This would return an array where either the title or description contain "test" and ordered by:</p>
<ul>
<li>Appearing in title and description</li>
<li>Appearing in title only</li>
<li>Appearing in description only</li>
</ul>
<p>Any results with the same weighting are then ordered by their title. Obviously this is a simple test case, you could easily have a test that adds up instances of the search string, the test could check it against a list of synonyms before counting etc.</p>
<p>Here's a JSbin with some test data and a quick Knockout usecase.</p>
<p><a href="http://jsbin.com/figay/1/edit?html,js,output">http://jsbin.com/figay/1/edit?html,js,output</a></p>
| [] | [
{
"body": "<p>I like it, from a once over:</p>\n\n<ul>\n<li><code>map</code>, <code>filter</code>, <code>reduce</code> etc. are not the most efficient functions, they make for readable code, not for speedy sorting/searching. See this : <a href=\"http://jsperf.com/arraymap\" rel=\"nofollow\">http://jsperf.com/arraymap</a>, a simply <code>for</code> loop beats everything else every time, this also goes for <code>filter</code>,<code>reduce</code> etc.</li>\n<li><p>I would change around the first block, there is too much happening horizontally:</p>\n\n<pre><code>return array.map(function (e) {\n return {\n element: e, \n weight: weightedTests.map(function (weightedTest) {\n return weightedTest.test(e) * weightedTest.weight;\n }).reduce(function (previousValue, currentValue) { \n return previousValue + currentValue; }, 0)\n };\n })\n</code></pre></li>\n<li><p>The sorting by weight I would do like this:</p>\n\n<pre><code>//sort first by weight if possible\nvar weightDifference = obj2.weight- obj1.weight;\nif (weightDifference) {\n return weightDifference;\n}\n</code></pre></li>\n<li><p>The last <code>return 0</code> does not need to be in an <code>else</code> block</p></li>\n<li><p>Other than that the code runs fine on JsHint, is well commented and easy to follow.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:44:42.930",
"Id": "75390",
"Score": "0",
"body": "Thanks for the comments. I agree completely on the formatting bit I think I just overlooked it after reformatting the bits around it. I like the way you handled the weighting too.\n\nRegarding performance on map/filter/reduce this isn't being used on large datasets so I'll likely keep them for readability purposes however I was under the impression they were supposed to be quite efficient. If I did need high performance what approach should I use here instead and how significant an impact would it have?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:24:08.187",
"Id": "75398",
"Score": "1",
"body": "Updated my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:15:16.260",
"Id": "75454",
"Score": "0",
"body": "Thanks. Useful benchmarks, I think it's helped confirm that it's not a worry unless we vastly increase the datasets we are working with."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:57:30.583",
"Id": "43549",
"ParentId": "43500",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43549",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T10:55:19.227",
"Id": "43500",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"search"
],
"Title": "My attempt at a weighted search in JavaScript"
} | 43500 |
<p>I have a jQuery script and I should explain it line by line. I already do that and I want to make sure that is correct. If someone has any remarks, I will be very appreciative.</p>
<pre><code>//Here we use the jQuery selector ($) to select the servers_id which is located into
//the delivers_id and we attaches a function to run when a change event occurs
$("#delivers #servers").change(function () {
//Here we look if the servers_id value was changed and the value is different of 0
if ($(this).val() != '0') {
//Here we create a new variable sid and we stored the servers_id value in it
var sid = $("#delivers #servers").val();
//Here we use the Ajax $.get to get the sid value and send it by Ajax request then
//we set the data into the o_vmats_id html and empty the vmtas_id
$.get("/deliverability/get_vmtas/" + sid,
function (data) {
$('#o_vmtas').html(data);
$('#vmtas').html('');
});
} else {
//Here the else statement, we select the vmtas_id and set the html content like in the code (value=0)
//and empty the o_vmtas_id html content
$('#vmtas').html('<option value="0">All Classes</option>');
$('#o_vmtas').html('');
}
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:13:11.877",
"Id": "75202",
"Score": "2",
"body": "Your indentation is damn confusing"
}
] | [
{
"body": "<p>Curious,</p>\n\n<ul>\n<li><code>$(\"#delivers #servers\")</code> does not do what you think it does, <code>$(\"#delivers, #servers\")</code> might, UPDATE: unless you mean to look for <code>#servers</code> under <code>#delivers</code> in which case you should strive to only have one tag with the <code>#servers</code> <code>id</code> and then go for <code>$(\"#servers\")</code></li>\n<li>I don't understand why you at one point use <code>$(this).val()</code> and at another point <code>$(\"#delivers #servers\").val()</code> if you say that they both point to <code>servers_id</code></li>\n<li>Furthermore, you could simply use <code>var sid = this.value</code></li>\n<li>You are performing many jQuery calls, those could be cached.</li>\n<li>Your comments are too much, you don't have to explain every line ;)</li>\n<li>On the other hand, what I would really want to know ( the difference between <code>vmtas</code> and <code>o_vmtas</code> is not commented )</li>\n<li><code>vmtas</code> and <code>o_vmtas</code> are terrible names </li>\n<li>Your indenting is confusing</li>\n<li>Consider <code>$.empty()</code> over <code>$.html('')</code></li>\n</ul>\n\n<p>I took some guesses as to what you are trying to and incorporated my feedback into this:</p>\n\n<pre><code>var $dropdown = $('#vmtas')\nvar $deliverability = $('#o_vmtas')\n\n//Listen to changes in server id\n$(\"#delivers\").change(function () {\n\n //What server id are we dealing with ?\n var sid = this.value;\n //Is it something we can get deliverability info on?\n if ( sid != '0') {\n $.get(\"/deliverability/get_vmtas/\" + sid, function (data) {\n $deliverability.html(data);\n $dropdown.html('');\n });\n }\n else {\n $dropdown.html('<option value=\"0\">All Classes</option>');\n $deliverability.html('');\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:23:18.540",
"Id": "43508",
"ParentId": "43504",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T12:06:05.023",
"Id": "43504",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "Script for managing server IDs"
} | 43504 |
<p>I use the <a href="https://www.sencha.com/learn/how-to-use-src-sencha-io/" rel="nofollow">src.sencha.io service</a> to resize images on the fly according to device width, saving lots of bandwidth on mobiles etc.</p>
<p>Sometimes the service fails randomly with a 503 error, so a fallback is needed. I've written this JS to fallback to "non-sencha" urls, and emit an error event, if the first image requested through sencha fails.</p>
<p>This is my first open-sourced bit of code, so am keen to get feedback on my:</p>
<ul>
<li>code correctness</li>
<li>whether this prototype-based design pattern is appropriate</li>
<li>alternative better patterns</li>
<li>comment/code clarity</li>
</ul>
<p>Even just confirming whether it's good would be helpful, as I don't have any formal programming training to be confident.</p>
<p><a href="https://github.com/ultrapasty/sencha-src-image-fallback" rel="nofollow">Github repo here.</a></p>
<p><strong><a href="http://jsfiddle.net/t8aDW/" rel="nofollow">jsfiddle with test case prepared for you here.</a></strong></p>
<pre><code>/** SENCHA SRC IMAGE FALLBACK ***************************************
*
* Author: Josh Harrison (http://www.joshharrison.net/)
* URL: https://github.com/ultrapasty/sencha-src-image-fallback
* Version: 1.0.0
* Requires: jQuery
*
* Tests to see if the src.sencha.io service is down, and if so,
* falls back to local images, by removing the sencha domain
* from the src.
*
* Can be instantiated with `new SenchaSRCFallback().init();`
* Or `var instance = new SenchaSRCFallback().init();`
*
* Emits the event `senchafailure` if sencha fails.
* Listen with `instance.onsenchafailure = func;`
*
*/
;(function(window, $) {
var SenchaSRCFallback = function() {
this.sencha_path_identifier = '.sencha.io/';
this.sencha_path_regex = /http:\/\/src[1-4]?\.sencha\.io\//i;
this.$imgs = null;
};
SenchaSRCFallback.prototype = {
init : function() {
this.$imgs = $("img[src*='" + this.sencha_path_identifier + "']");
if(this.$imgs.length) {
this.test_sencha_availability();
}
return this;
},
test_sencha_availability : function() {
var t = this, img = new Image();
img.onerror = function() {
$(t).trigger("senchafailure");
t.fallback_to_local_srcs();
};
img.src = this.$imgs[0].getAttribute("src");
},
fallback_to_local_srcs : function() {
var t = this;
this.$imgs.each(function() {
this.setAttribute("src", this.getAttribute("src").replace(t.sencha_path_regex, ""));
});
}
};
window.SenchaSRCFallback = SenchaSRCFallback;
})(window, jQuery);
// Example usage:
// Instantiate the fallback
var senchafallback = new SenchaSRCFallback().init();
// Listen for failure like this:
senchafallback.onsenchafailure = function() {
console.log("It failed.");
// log failure event in google analytics, etc
};
</code></pre>
<p>Images would be initially routed through src.sencha.io to avoid downloading twice. With the above JS, should sencha fail, these image tags:</p>
<pre><code><img src="http://src.sencha.io/http://mysite.com/image1.png">
<img src="http://src1.sencha.io/http://mysite.com/image2.png">
<img src="http://src2.sencha.io/http://mysite.com/image3.png">
</code></pre>
<p>... would become the following:</p>
<pre><code><img src="http://mysite.com/image1.png">
<img src="http://mysite.com/image2.png">
<img src="http://mysite.com/image3.png">
</code></pre>
| [] | [
{
"body": "<p>I like the idea, from a once over:</p>\n\n<ul>\n<li>Since you use an IIFE I would declare <code>sencha_path_identifier</code> and <code>sencha_path_regex</code> outside of the constructor, then you can access them without specifying <code>this.</code></li>\n<li>I would do either <code>function SenchaSRCFallback() {</code> or <code>var SenchaSRCFallback = function SenchaSRCFallback() {</code>, anonymous functions are a pain to troubleshoot</li>\n<li>Why do you require the caller to call <code>init()</code>? In my mind this call should be done within the constructor.</li>\n</ul>\n\n<p>This is something I might borrow at some point.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:05:26.553",
"Id": "75385",
"Score": "0",
"body": "One thought on your first point – is it better to store this on the object, in order to avoid one extra look up the chain? Also on the third point, I may want to use `var instance = new SenchaImageFallback(); instance.onsenchafailure = func; instance.init()` to bind the fail fallback before it attempts to request the image. Is this a good reason to require the call to `init()` separately?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T11:59:24.817",
"Id": "75396",
"Score": "1",
"body": "1. I think it makes for cleaner code, performance penalty should be minimal if any. 2. I would actually make `func` an optional parameter of the constructor in that case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:36:47.217",
"Id": "43547",
"ParentId": "43507",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43547",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:21:07.060",
"Id": "43507",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"web-services",
"prototypal-class-design"
],
"Title": "Graceful JavaScript fallback for external web service failure"
} | 43507 |
<p>The <code>results</code> variable is coming from an API that have a arrays in arrays, etc.</p>
<p>I have made a <code>foreach</code> with <code>for</code> loops inside, which looks like this:</p>
<pre><code>foreach (var s in results)
{
var dataRowsCollection = s.ResultRows;
for (int g = 0; g <= dataRowsCollection.Count; g++)
{
for (int i = 0; i <= dataRowsCollection[g].ItemArray.Count(); i++)
{
var dataRows = dataRowsCollection[i].ItemArray;
var Title = dataRows[0].ToString();
var Url = dataRows[4].ToString();
var TemplateId = dataRows[6].ToString();
}
}
}
</code></pre>
<p>Can I do this in LINQ or should I keep it like this? I can't figure out how it would look like with LINQ since its the array objects I'm working with.</p>
<p>Note: I will later on map <code>Title</code>, <code>Url</code> and <code>TemplateId</code> to my model class properties.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:09:38.187",
"Id": "75229",
"Score": "4",
"body": "What are you trying to do with these values? This code doesn't do anything with the values it creates in the inner most for loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:10:20.210",
"Id": "75230",
"Score": "0",
"body": "I will map the data I take out to my model class I have not implemented it yet. edited the question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:31:15.633",
"Id": "75234",
"Score": "2",
"body": "Is there a reason for using LINQ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:35:32.203",
"Id": "75252",
"Score": "3",
"body": "@Obsivus Then you should include that code in the question, because: 1. It can change the answer. 2. Code Review is about reviewing real code."
}
] | [
{
"body": "<p>Before you ask yourself \"<em>can I do this with LINQ?</em>\", you need to look at the body of your loop:</p>\n\n<blockquote>\n<pre><code>var dataRows = dataRowsCollection[i].ItemArray;\nvar Title = dataRows[0].ToString();\nvar Url = dataRows[4].ToString();\nvar TemplateId = dataRows[6].ToString();\n</code></pre>\n</blockquote>\n\n<p>These variables are <em>scoped</em> to the loop's body, which means your loop is essentially useless, because each iteration will re-assign a new value to a new variable that will become candidate for garbage collection as soon as the iteration finishes.</p>\n\n<p>I suspect that you haven't posted the entire loop body... or that your code doesn't do what you think it does.</p>\n\n<blockquote>\n <p><em>Note: I will later on map Title, Url and TemplateId to my model class properties.</em></p>\n</blockquote>\n\n<p>This <em>has</em> to be done <em>inside</em> the loop's body.</p>\n\n<p>As it stands / as posted, there's nothing in this loop that makes it a good candidate for a more LINQ representation that would be more readable and/or easier to maintain. </p>\n\n<p>LINQ stands for <em>Language-INtegrated Query</em>, which means it's useful for <em>querying</em> objects. Your loop isn't doing that - it's <em>iterating</em> objects, and then performing assignations.</p>\n\n<p>To LINQify your loop, you would have to change your logic - <em>query</em> <code>dataRowsCollection</code> and <em>project</em> (<code>Select</code>) each <code>ItemArray</code> into an <code>IEnumerable<T></code> that contains each item's <code>dataRows</code>.</p>\n\n<p>And <em>then</em> you could iterate the result of that <em>query</em> to assign your model class properties.</p>\n\n<hr>\n\n<p><strong>Naming</strong></p>\n\n<p>Naming conventions make our lives easier. Respecting them makes your code easier to follow and to understand. <em>Local variables</em> should be <code>camelCase</code>, like <code>dataRows</code> is.</p>\n\n<p>The other local variables you're declaring are <code>PascalCase</code>, which makes your naming inconsistent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:05:52.707",
"Id": "43516",
"ParentId": "43512",
"Score": "7"
}
},
{
"body": "<p>As a general review of the existing code: This block does not make much sense to me:</p>\n\n<blockquote>\n<pre><code>for (int g = 0; g <= dataRowsCollection.Count; g++)\n{\n for (int i = 0; i <= dataRowsCollection[g].ItemArray.Count(); i++)\n {\n var dataRows = dataRowsCollection[i].ItemArray;\n var Title = dataRows[0].ToString();\n var Url = dataRows[4].ToString();\n var TemplateId = dataRows[6].ToString();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Your inner loop will only ever pull data out of the first <code>N</code> entries in <code>dataRowsCollection</code> depending what the longest <code>ItemArray</code> in any of the data rows is because you are doing this: <code>dataRowsCollection[i].ItemArray;</code>. </p>\n\n<p>If we assume that each data row has an <code>ItemArray</code> of length 10 then you will pull the first 10 entries out of the <code>dataRowsCollection</code> over and over again. This seems broken.</p>\n\n<p>So instead of worrying about \"should I use LINQ instead of a for loop\" you should worry about getting your code to work first properly. First make it work - then make it better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:46:29.377",
"Id": "43538",
"ParentId": "43512",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43538",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:00:19.423",
"Id": "43512",
"Score": "-2",
"Tags": [
"c#",
"linq"
],
"Title": "Is this correct way to use loops or should it be in LINQ?"
} | 43512 |
<p>I'm attempting to apply a long set of conditions and operations onto a pandas dataframe (see the dataframe below with VTI, upper, lower, etc). I attempted to use apply, but I was having a lot of trouble doing so. My current solution (which works perfectly) relies on a <code>for</code> loop iterating through the dataframe. But my sense is that this is an inefficient way to complete my simulation. I'd appreciate help on the design of my code.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>VTI uppelower sell buy AU BU BL date Tok order
44.58 NaN NaN False False False False False 2001-06-15 5 0
44.29 NaN NaN False False False False False 2001-06-18 5 1
44.42 NaN NaN False False False False False 2001-06-19 5 2
44.88 NaN NaN False False False False False 2001-06-20 5 3
45.24 NaN NaN False False False False False 2001-06-21 5 4
</code></pre>
</blockquote>
<p>If I wanted to run a bunch of conditions and <code>for</code> loops like the below and run the function below (the get row data function) only if the row meets the conditions provided, how would I do so?</p>
<p>My intuition says to use <code>.apply()</code> but I'm not clear how to do it within this scenario. With all the if's and <code>for</code>-loops combined, it's a lot of rows. The below actually outputs an entirely new dataframe. I'm wondering if there are more efficient/better ways to think about the design of this simulation/stock backtesting process.</p>
<p>Get row data simply obtains key data from the dataframe and computes certain information based on globals (like how much capital I have already, how many stocks I have already) and spits out a list. I append all these lists into a dataframe that I call the portfolio.</p>
<p>I've given a snippet of the code that I've already made using a <code>for</code>-loop.</p>
<pre class="lang-python prettyprint-override"><code> ##This is only for the sell portion of the algorithm
if val['sell'] == True and tokens == maxtokens:
print 'nothign to sell'
if val['sell'] == True and tokens < maxtokens:
print 'sellprice', price
#CHOOSE THE MOST EXPENSIVE POSITION AND SELL IT#
portfolio = sorted(portfolio, key = lambda x: x[0], reverse = True)
soldpositions = [position for position in portfolio if position[7] == 'sold']
soldpositions = sorted(portfolio, key=lambda x: x[1], reverse = True)
for position in portfolio:
#Position must exist
if position[9] == True:
print 'position b4 sold', position
#Position's price must be LOWER than current price
#AND the difference between the position's price and current price must be greater than sellbuybuffer
if abs(position[0] - price) <= sellbuybuffer:
print 'does not meet sellbuybuffer'
if position[0] < price and abs(position[0] - price) >= sellbuybuffer:
status = 'sold'
#This is if we have no sold positions yet
if len(soldpositions) == 0:
##this is the function that is applied only if the row meets a large number of conditions
get_row_data(price, date, position, totalstocks, capital, status, tokens)
</code></pre>
| [] | [
{
"body": "<p>Pandas allows you to filter dataframes efficiently using boolean formulas.</p>\n\n<p>Instead of using a <code>for</code> loop and conditional branching, use the following syntax:</p>\n\n<pre><code>df = portfolio[(portfolio['sell'] == True) & (portfolio['Tok'] < maxtokens)]\n</code></pre>\n\n<p>To sort a dataframe, you can also simply write:</p>\n\n<pre><code>portfolio = portfolio.sort('VTI', ascending=False)\nsold_positions = portfolio[portfolio['BL'] == True].sort('upperlower', ascending=True)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T03:24:57.423",
"Id": "44224",
"ParentId": "43517",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:07:40.277",
"Id": "43517",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Working with pandas dataframes for stock backtesting exercise"
} | 43517 |
<p>I wrote some compare-functions that I pass to other methods in javascript:</p>
<pre><code>function equal(a, b) {
if (a instanceof Date) return a.getTime() == b.getTime();
return a == b;
}
function lessThan(a, b) {
if (a instanceof Date) return a.getTime() < b.getTime();
return a < b;
}
function greaterThan(a, b) {
if (a instanceof Date) return a.getTime() > b.getTime();
return a > b;
}
function lessOrEqual(a, b) {
return equal(a, b) || lessThan(a, b);
}
function greaterOrEqual(a, b) {
return equal(a, b) || greaterThan(a, b);
}
</code></pre>
<p>Is there a way to get this a bit more compact? If I want to add another comparable type I always have to modify the first three functions.</p>
| [] | [
{
"body": "<p>No need to check if the variables are <code>instanceof Date</code>. <strong>A dates value is its time</strong> so when you make (less than/greater than) comparisons with a Date instance (<code>x</code>) you're essentially comparing it to <code>+x</code> or <code>x.valueOf()</code> which will be the same as <code>x.getTime()</code>. Therefore the below will always be equivalent:</p>\n\n<pre><code>function equal(a, b) {\n if (a instanceof Date && b instanceof Date) return +a == +b; //compare the 2 dates times as noted in the above statement +x == x.getTime() == x.valueOf()\n return a == b;\n}\n\nfunction lessThan(a, b) {\n return a < b;\n}\n\nfunction greaterThan(a, b) {\n return a > b;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:27:02.597",
"Id": "75243",
"Score": "0",
"body": "new Date(\"2014-03-05\") == new Date(\"2014-03-05\") and new Date(\"2014-03-05\").getTime() == new Date(\"2014-03-05\").getTime() are not the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:28:00.500",
"Id": "75244",
"Score": "0",
"body": "new Date(\"2014-03-05\") == new Date(\"2014-03-05\") returns false"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:28:02.583",
"Id": "75245",
"Score": "0",
"body": "@user2033412 ah you're right for that case"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:32:54.043",
"Id": "75247",
"Score": "0",
"body": "I like your new approach, now I can just write plus before every variable inside the functions and get rid of the typecheck."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:33:28.713",
"Id": "75248",
"Score": "0",
"body": "You'll still need it for `equal`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:34:01.647",
"Id": "75250",
"Score": "0",
"body": "no, because +new Date(\"2014-05-03\") == +new Date(\"2014-05-03\") returns true"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:34:34.623",
"Id": "75251",
"Score": "0",
"body": "I don't know the allowed inputs but consider `+window` or `+{test: 1}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:39:13.983",
"Id": "75254",
"Score": "0",
"body": "@user2033412 no need for `+a > +b` it will be handled internally. Also you may want to consider using `===` as `\"\" == 0`. Anyway I don't know what inputs you plan to give `equal` but you should be careful with `==`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:42:12.930",
"Id": "75256",
"Score": "0",
"body": "I don't use defensive programming, I assume the programmer will check for the types and the bounds of the application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:42:56.317",
"Id": "75257",
"Score": "0",
"body": "Is it good style to override valueof in my own objects for comparison? Example: var test = (function (val) {\n\n var val = val;\n var name = \"test\";\n\n return {\n name: name,\n valueOf: function () { return val; }\n }\n});"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:44:54.707",
"Id": "75258",
"Score": "0",
"body": "Thats not overriding `instanceOf` but setting `valueOf` is perfectly fine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:47:36.080",
"Id": "75259",
"Score": "1",
"body": "Perfect! I'll go for +a === +b and overriding valueOf"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:24:27.087",
"Id": "43519",
"ParentId": "43518",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43519",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:17:21.503",
"Id": "43518",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "remove redundance in compare-functions"
} | 43518 |
<p>This code currently works, but I'm new to Objective-C from a Python/PHP background. How can I improve it/make it more Objective-Cesque?</p>
<p><strong>Header File/Interface</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@interface Monster : NSObject
@property NSString* name;
@property NSNumber* health;
@property NSNumber* strength;
@property NSNumber* dexterity;
@property NSNumber* magic;
//
- (id) initWithName: (NSString*) nameToBeConstructedWithMethodConstructorInitWithName;
- (void) attack: (Monster*) sentMonster blocking:(BOOL)block isWithMagic:(BOOL)magicYes andMagicType:(NSString*)whatMagic andBurn:(NSInteger)burning;
- (bool) isDead;
- (void) printInfo;
@end
</code></pre>
<p><strong>Implementation File</strong></p>
<pre><code>#import "Monster.h"
@implementation Monster
- (id) initWithName: (NSString*) nameToBeConstructedWithMethodConstructorInitWithName{
self = [super init];
if (self){
_name = nameToBeConstructedWithMethodConstructorInitWithName;
_dexterity = @((arc4random() % 15) + 3);
_strength = @((arc4random() % 15) + 3);
_magic = @((arc4random() % 15) + 3);
_health = @((arc4random() % 40) + 60);
}
return self;
}
- (void) attack: (Monster*) sentMonster blocking:(BOOL)block isWithMagic:(BOOL)magicYes andMagicType:(NSString*)whatMagic andBurn:(NSInteger)burning{
NSInteger health = [sentMonster.health intValue];
NSInteger modifier = [self.strength intValue];
if (modifier > 5) modifier = 1;
if (modifier > 10) modifier = 2;
if (modifier > 15) modifier = 5;
NSInteger hit = 0;
if (magicYes){
if ([whatMagic characterAtIndex:0] == 'i'){
NSInteger baseHit = ((arc4random() % 15) + 5);
NSLog(@"%@'s health: %ld", sentMonster.name, health);
hit = baseHit + modifier;
health -= hit;
sentMonster.health = @(health);
NSLog(@"%@ was hit for %ld magical damage and has a new health of %ld", sentMonster.name, hit, health);
}
if ([whatMagic characterAtIndex:0] == 'f'){
NSInteger baseHit = ((arc4random() % 25) + 10);
NSLog(@"%@'s health: %ld", sentMonster.name, health);
hit = baseHit + modifier;
if (burning) health -= ((arc4random()% 7) + 3);
health -= hit;
sentMonster.health = @(health);
NSLog(@"%@ was hit for %ld magical damage and has a new health of %ld", sentMonster.name, hit, health);
}
}
else if (((arc4random() % 20) + [sentMonster.dexterity intValue]) >= 11){
NSInteger baseHit = ((arc4random() % 3)+2);
NSLog(@"%@'s health: %ld", sentMonster.name, health);
NSLog(@"Basehit: %ld",baseHit);
NSLog(@"Modifier: %ld:",modifier);
if (block) hit = baseHit;
else hit = baseHit + modifier;
NSLog(@"Hit: %ld", hit);
health -= hit;
sentMonster.health = @(health);
NSLog(@"%@ was hit for %ld physical damage and has a new health of %ld", sentMonster.name, hit, health);
}
else {
NSLog(@"%@ successfully dodged an attack", sentMonster.name);
}
}
- (bool) isDead{
if ([self.health intValue] <= 0)return YES;
return NO;
}
- (void) printInfo{
NSLog(@"\nName: %@\nHealth: %@\nStrength: %@\nDexterity: %@\nMagic: %@\n",self.name, self.health, self.strength, self.dexterity, self.magic);
}
@end
</code></pre>
<p><strong>Main</strong></p>
<pre><code>#import <Foundation/Foundation.h>
#import "Monster.h"
NSString* getNSString(NSString *prompt);
int main()
{
@autoreleasepool {
Monster* player = [[Monster alloc]initWithName:getNSString(@"What is the player's name:\n")];
Monster* monster = [[Monster alloc]initWithName:@"Brad"];
BOOL whichMonsterWon,skipMonsterAttack,isCast;
NSInteger chanceSkip, chanceBurn;
NSString* magicType = getNSString(@"Do you use (I)ce or (F)ire magic");
magicType = [magicType lowercaseString];
NSLog(@"\n\n\n");
[player printInfo];
[monster printInfo];
while (YES){
chanceSkip = 0;
skipMonsterAttack = NO;
if ([monster isDead]){
whichMonsterWon = YES;
break;
}
if ([player isDead]){
whichMonsterWon = NO;
break;
}
NSString* playerChoice = getNSString(@"\n(A)ttack\n(B)lock\n(M)agic\n");
playerChoice = [playerChoice lowercaseString];
if ((isCast) && ([playerChoice characterAtIndex:0] == 'm')) NSLog(@"You have already cast your magic!");
else if ([playerChoice characterAtIndex:0] == 'a') [player attack:monster blocking:NO isWithMagic:NO andMagicType:magicType andBurn:chanceBurn];
else if ([playerChoice characterAtIndex:0] == 'b'){
[monster attack:player blocking:YES isWithMagic:NO andMagicType:magicType andBurn:chanceBurn];
skipMonsterAttack = YES;
}
else if (([playerChoice characterAtIndex:0] == 'm') && !isCast){
if ([magicType characterAtIndex:0] == 'i'){
chanceSkip = arc4random() % 2;
if (chanceSkip) NSLog(@"%@ was stunned for one turn",monster.name);
}
if ([magicType characterAtIndex:0] == 'f'){
chanceBurn = arc4random() % 2;
if (chanceBurn) NSLog(@"%@ was burned for one turn",monster.name);
}
[player attack:monster blocking:NO isWithMagic:YES andMagicType:magicType andBurn:chanceBurn];
chanceBurn = 0;
isCast = YES;
}
else NSLog(@"You have entered an unknown command, %@ gets a free turn", monster.name);
if (!(skipMonsterAttack) && !chanceSkip) [monster attack:player blocking:NO isWithMagic:NO andMagicType:magicType andBurn:chanceBurn];
}
[player printInfo];
[monster printInfo];
if (whichMonsterWon == YES) NSLog(@"%@ beat the monster!",player.name);
if (whichMonsterWon == NO) NSLog(@"%@ beat the player!",monster.name);
}
return 0;
}
NSString* getNSString(NSString *prompt){
NSLog(@"%@", prompt);
char cString[100] = "";
scanf("%s", cString);
NSString* oString = [NSString stringWithUTF8String:cString];
return oString;
}
</code></pre>
| [] | [
{
"body": "<p>First and foremost, the best way to make this "more Objective-Cesque" would be to develop a UI for it. Whether OSX or iOS, the tools available for develop UI are really quite good... but let me look at the rest of your code... ;)</p>\n<hr />\n<p>I can't see any good reason for your <code>Monster</code> class properties (other than <code>name</code>) to be objects. Simple primitive data types would more than suffice here. It would make parts of your code simpler, more readable, and as far as I can tell, you don't actually need these values as <code>NSNumber</code> anywhere. Even if you do, it's extraordinarily simply to create the <code>NSNumber</code> when it's needed, if that ever comes around, so let's just use an <code>int</code> here?</p>\n<p>But moreover, should these properties necessarily be public? And even if they're public readable, should they by public writable?</p>\n<p>As far as I can tell, you don't need these variables publicly, so let's make these private. Keep the <code>name</code> property in the <code>.h</code>, but move the rest into a class category in the <code>.m</code> file:</p>\n<h1>Monster.m</h1>\n<pre><code>#import Monster.h\n\n@interface Monster()\n\n@property int health;\n@property int strength;\n@property int dexterity;\n@property int magic;\n\n@end\n\n@implementation Monster\n\n...\n</code></pre>\n<hr />\n<p>There are aspects to <code>- (void) attack: (Monster*) sentMonster blocking:(BOOL)block isWithMagic:(BOOL)magicYes andMagicType:(NSString*)whatMagic andBurn:(NSInteger)burning;</code> that I find troubling from an Objective-C stand point and from an OOP standpoint.</p>\n<p>First off all, I think the monster who stands to have properties changed is the one the method should be called on. Instead, the attacking monster is the monster on which the method is called and none of his stats are modified.</p>\n<p>The method should either be rewritten to be called on the defending monster or possibly be rewritten into a class method which is called on neither, but rather both are sent as arguments.</p>\n<p>But I also think we can probably have a class for our magic types. Or maybe our attack types. Right now, <code>isWithMagic:</code>, <code>andMagicType:</code>, and <code>andBurn:</code> are only relevant if you're using magic. What about an attack-type class? Objects would hold information on what type of magic (or non-magic) the attack was and whether or not it burned.</p>\n<p>And finally, we can add a <code>isBlocking</code> property to the <code>Monster</code> class which is just an on/off bool for whether the monster is currently blocking. So now, the header for the method will look more like this:</p>\n<pre><code>- (void)attackedBy:(AttackType*)incomingAttack;\n</code></pre>\n<p>And instead of <code>sentMonster.health</code>, we'll be referring to <code>self.health</code>. And the <code>incomingAttack</code> variable will have properties describing the magic type (or non magic), how much damage it might do, whether or not it burns and for how much, etc.</p>\n<hr />\n<pre><code>if ((isCast) && ([playerChoice characterAtIndex:0] == 'm')) NSLog(@"You have already cast your magic!");\n\n// stuff\n\nelse if (([playerChoice characterAtIndex:0] == 'm') && !isCast)\n</code></pre>\n<p>This section of code is bothersome to me. Particularly because there are two other <code>if</code> statements in the middle. Even if there weren't though, this is still bothersome.</p>\n<p>I'd simply take the <code>isCast</code> out of both of these and refactor as such:</p>\n<pre><code>if ([playerChoice characterAtIndex:0] == 'm') {\n if (isCast) {\n // stuff\n } else {\n // stuff\n }\n} else if ([playerChoice...\n</code></pre>\n<p>This is better for readability in a couple of ways. First of all, all the <code>if</code> statements in this tree correspond to different user selections, and within this <code>if</code> we handle what happens EVERY TIME the user makes that selection, and second, because on top of the statement I just made, Xcode will let me collapse this entire <code>if ... == 'm')</code> section all at once if I don't need to look at it any more.</p>\n<hr />\n<p>But with that said...</p>\n<pre><code>NSString* getNSString(NSString *prompt)\n</code></pre>\n<p>First of all, this is poorly named. It's not a getter (even though in English, its functionality could easily be described as getting something). And its description of what it is getting isn't helpful at all. We KNOW it returns a NSString regardless of what it's named.</p>\n<p>But why do we bother turning this into a string and then once we have that string, we use an NSString method to pull the first character out of that string for comparison? Can we change that method to this:</p>\n<pre><code>char fetchUserInput(NSString *prompt)\n</code></pre>\n<p>And within this function, include the logic for simply returning the first character the use entered?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T23:44:50.287",
"Id": "43564",
"ParentId": "43523",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:43:37.727",
"Id": "43523",
"Score": "5",
"Tags": [
"beginner",
"game",
"objective-c",
"console"
],
"Title": "Console monster battle game"
} | 43523 |
<p>I am relatively new to JavaScript/jQuery, and cobbled together a script. Essentially, the script sets individual timers on specific DOM elements, and then recursively applies timed functions to them. The functions actually apply a "flip" effect to a div, showing a front and back, and then do different things on each side. The references to "Vague" are from Vague.js, and external library I didn't write that provides a blur effect to elements. The script works, but writing working code and writing good code are two separate things. </p>
<pre><code>$(document).ready( function() {
$('.flipper').each(function(e) {
var flipper = new myFlipper($(this));
})
});
var myFlipper = function (flipper) {
//console.log(flipper);
this.flipper = flipper;
this.image = flipper.find('img');
this.blurStatus = true;
this.flipStatus = true;
this.Vague = this.image.Vague ({
intensity: 8,
forceSVGUrl: false
});
this.blurContext = $.proxy(this.myBlur, this);
this.flipContext = $.proxy(this.myFlip, this);
// $(this.image).on("click", this.blurContext);
var randomNumber = Math.floor(Math.random()*10);
var timer = randomNumber * 1000;
setTimeout(this.blurContext, timer);
}
myFlipper.prototype.myBlur = function(e) {
console.log(this.flipContext);
if(this.blurStatus) {
this.Vague.blur();
this.blurStatus = false;
this.flipper.find('.caption').animate({opacity: 1.0}, 3000);
setTimeout(this.flipContext,5000);
} else {
this.Vague.unblur();
this.blurStatus = true;
}
}
myFlipper.prototype.myFlip = function(e) {
console.log(this.flipper.attr("class"));
console.log(this.flipStatus);
if (this.flipStatus) {
this.flipper.addClass('hover');
this.flipper.find('.caption').animate({opacity: 0.0}, 1000);
this.blurContext();
this.flipStatus = false;
setTimeout(this.flipContext, 20000);
} else {
this.flipper.removeClass('hover');
this.flipStatus = true;
setTimeout(this.blurContext,5000);
}
}
</code></pre>
<p><a href="http://jsfiddle.net/K33t6/1/" rel="nofollow">Here is the JSFiddle</a> of the whole thing.</p>
| [] | [
{
"body": "<p>This might not be an improvement per se, but you can change this:</p>\n\n<pre><code>$(document).ready( function() {\n $('.flipper').each(function(e) {\n var flipper = new myFlipper($(this));\n })\n});\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>$(function() {\n $('.flipper').each(function(e) {\n var flipper = new myFlipper($(this));\n });\n});\n</code></pre>\n\n<p>The reason this works is <code>$()</code> is a shortcut for <code>$(document).ready()</code>.</p>\n\n<p>With JavaScript, it is usually recommended that you keep from cluttering the global namespace. You currently have everything contained in <code>var myFlipper</code>, which is good. But since you're using jQuery, you might as well use a <a href=\"http://learn.jquery.com/plugins/basic-plugin-creation/\">jQuery plugin</a>, which would allow you to do something like this:</p>\n\n<pre><code>$.fn.myFlipper = function () {\n //...\n};\n\n$(function() {\n $('.flipper').myFlipper();\n});\n</code></pre>\n\n<p>This way, you aren't introducing another variable into the global namespace. Plus, the jQuery plugin architecture affords you some additional benefits, like syntax, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:29:57.137",
"Id": "75278",
"Score": "0",
"body": "On the second example:with `$('.flipper').myFlipper();`, I would NOT need to pass $(this) like I do to my current function because it's passing it to the function automatically, correct? Would I even need the 'each' function at that point, or would the plugin interact on each .flipper element as separately?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:33:50.180",
"Id": "75282",
"Score": "0",
"body": "Additionally, using the plugin route, are my prototype calls still valid? Do I need to address myFlipper in the $.fn namespace when I refer to it, like: `$.fn.myFlipper.prototype...` or would the current syntax still be valid?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:06:42.887",
"Id": "75301",
"Score": "0",
"body": "To your first question: correct, you would not need to pass `$(this)` to the jQuery plugin. The `each` function would be in the plugin code. To your second question: I would assume you can use `prototype` inside a jQuery plugin, but I've never tried it. Read [this](http://learn.jquery.com/plugins/basic-plugin-creation/), post your revisions, and we can critique some more."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:39:21.727",
"Id": "43527",
"ParentId": "43526",
"Score": "8"
}
},
{
"body": "<p>From a once over,</p>\n\n<ul>\n<li>You are not doing anything with <code>flipper</code> in <code>var flipper = new myFlipper($(this));</code> you might as well just <code>new myFlipper($(this));</code></li>\n<li>Of course, that shows that <code>myFlipper</code> is not the best of names, perhaps simply <code>Flip</code>?</li>\n<li>If you are not going to use <code>e</code>, then you do not need to declare it as a variable</li>\n<li><p>As @DavidKennedy mentioned, you can simply use <br></p>\n\n<pre><code>$(function() {\n $('.flipper').each(function() {\n new myFlipper($(this)); //Or startFlipping( $(this) );\n });\n});\n</code></pre></li>\n<li>Please indent inside your functions for readability</li>\n<li>Production code does not use <code>console.log</code></li>\n<li>Production code does not have commented out code</li>\n<li><p>You can show the flipping of the boolean blurStatus better like this:</p>\n\n<pre><code>if(this.blurStatus) {\n this.Vague.blur();\n this.flipper.find('.caption').animate({opacity: 1.0}, 3000);\n setTimeout(this.flipContext,5000);\n} else {\n this.Vague.unblur();\n}\nthis.blurStatus = !this.blurStatus; //<- Flipping happens here\n</code></pre></li>\n<li><p>The following code seems too long to me:</p>\n\n<pre><code>var randomNumber = ;\nvar timer = ;\nsetTimeout(this.blurContext, timer);\n</code></pre>\n\n<p>I would write it likes this, you should find a middle ground.</p>\n\n<pre><code>setTimeout(this.blurContext, Math.floor(Math.random()*10000 );\n</code></pre>\n\n<p>Since there is not much difference between say 8 seconds or 8.345 seconds, I just used <code>Math.random()*10000</code></p></li>\n<li>Consider using <code>$.toggleClass('hover')</code> instead of setting or removing it each time in <code>if</code> blocks.</li>\n<li>You should use for strings either all single or all double quotes, the preference du jour is single quotes</li>\n<li>You have some constants like <code>5000</code> that you repeat, consider using named constants instead</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:02:02.300",
"Id": "75339",
"Score": "0",
"body": "Thanks for this, too. I'm going to work on incorporating these changes and repost my new code. As for the indentation, I think it's an artifact from pasting code here. It's indented in Sublime Text, but not when I paste it. I don't know how to add 4 spaces to every line I paste except manually, so I just indent the flush lines. until the snippet all lists as code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:43:53.890",
"Id": "43537",
"ParentId": "43526",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:06:21.603",
"Id": "43526",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "Applying timed functions recursively"
} | 43526 |
<p>I have a small little function in a VB6 codebase:</p>
<pre><code>Public Function GetEquivalentCode(Optional ByVal code As String) As String
If IsMissing(code) Or code = vbNullString Then code = m_GlobalCode
Dim result As String
If StringStartsWith("ABC", code) Then
result = "ABC2013"
Else
result = code
End If
GetEquivalentCode = result
End Function
</code></pre>
<p>The implications of this function are massive, so before I deployed it I wrote a small test to ensure it returns the correct/expected value in all cases:</p>
<pre><code>Public Sub GetEquivalentCodeTest()
Dim result As String
m_GlobalCode = "ABC2013"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"
m_GlobalCode = "ABC2014"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"
m_GlobalCode = "ABC2013A"
result = GetEquivalentCode
Debug.Assert result = "ABC2013"
m_GlobalCode = "XYZ2013"
result = GetEquivalentCode
Debug.Assert result = "XYZ2013"
m_GlobalCode = "SOMETHING ELSE"
result = GetEquivalentCode
Debug.Assert result = "SOMETHING ELSE"
m_GlobalCode = vbNullString
result = GetEquivalentCode
Debug.Assert result = vbNullString
Debug.Print "GetEquivalentCodeTest: Passed."
End Sub
</code></pre>
<p>Running this method from the immediate pane prints <code>GetEquivalentCodeTest: Passed.</code>, and if I tweak it to make it fail, it breaks at the assertion that evaluates to <code>False</code>.</p>
<p>Is this the best way to write automated tests in VB6?</p>
<hr>
<p>Colleagues call me a "purist" - I take it as a compliment. The thing is, without this test method, the mere fact that you give "ABC2014" to the function and it returns "ABC2013" can (will) be a major WTF for anyone maintaining this code in 2 years' time (including myself); the way I see it, these tests document what the [funky] business rules are.</p>
<p>Is there a way to write the test so as to make the business rules even more obvious?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:52:14.230",
"Id": "75291",
"Score": "1",
"body": "I would make a single test case for every comportement you have! In my opinion it show that there is different rules (or a complex one)."
}
] | [
{
"body": "<p>The only thing that I can see at first glance to show what the business rule is, is to do something like this</p>\n\n<pre><code>m_GlobalCode = \"ABC\"\nresult = GetEquivalentCode\nDebug.Assert result = \"ABC2013\"\n</code></pre>\n\n<p>probably at the beginning. </p>\n\n<p>I think this is exactly what the business rule is saying from my understanding of the information that you have given</p>\n\n<hr>\n\n<p>you probably want to add something like this to follow it, just to be clear what the rule is.</p>\n\n<pre><code>m_GlobalCode = \"AB\"\nresult = GetEquivalentCode\nDebug.Assert result = \"AB\"\n</code></pre>\n\n<p>These two pieces coupled together show the entire Business Rule.</p>\n\n<blockquote>\n <p>if the input string starts with \"ABC\" then return \"ABC2013\" otherwise return the input</p>\n</blockquote>\n\n<hr>\n\n<p><strong>6 tests should clearly define the Business Rule</strong></p>\n\n<ol>\n<li>Input: \"ABC\"</li>\n<li>Input: \"AB\"</li>\n<li>Input: <code>vbNullString</code></li>\n<li>Input: {Random String not Starting with \"ABC\"}</li>\n<li>Input: \"DABC\" Result: \"DABC\"</li>\n<li>Input: \"ABC5029DDD\"</li>\n</ol>\n\n<p>Number 5 shows that ABC must be at the beginning of the string</p>\n\n<p>Numbers 1 & 6 shows what the Function is doing.</p>\n\n<p>Numbers 2,3,4, & 5 show what happens when the ABC is not at the beginning</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:49:46.563",
"Id": "43532",
"ParentId": "43531",
"Score": "11"
}
},
{
"body": "<p>As of now I see one <strong>major</strong> problem with this...</p>\n\n<p>You are not even testing with the optional parameter.</p>\n\n<p>All else equal, you are reusing the same variable and make multiple OPERATE statements.</p>\n\n<blockquote>\n <p>\"Each of the tests is clearly split into three parts. The first part builds up the test data, the second part operates on that test data, and the third part checks the operation yielded the expected results.\" - Robert C. Martin, Clean Code, p.127</p>\n</blockquote>\n\n<p>Following this advice, you might want to split your test into neat compartments as mentioned by @Marc-Andre</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:31:52.460",
"Id": "75309",
"Score": "2",
"body": "I agree and will +1 when I have ammo; one thing that's driving me insane is the `m_GlobalCode` variable which is `Private` to the code module it's in - the rest of the code really isn't testable at all."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:59:20.817",
"Id": "43534",
"ParentId": "43531",
"Score": "6"
}
},
{
"body": "<p>In my opinion, tests should be like a class, they should have only one responsibility. For a test, that would mean every time you want to show a special case, you should have a test method. The name that would represent what will be return or what the method is currently testing. Is a corner case, a typical case or just some examples ? </p>\n\n<p>In your particular case every time you have something like : </p>\n\n<blockquote>\n<pre><code>m_GlobalCode = \"ABC2013\"\nresult = GetEquivalentCode\nDebug.Assert result = \"ABC2013\"\n</code></pre>\n</blockquote>\n\n<p>would be a new test method. </p>\n\n<p>I would add one more test method at least : </p>\n\n<pre><code>m_GlobalCode = \"XYZ2014\"\nresult = GetEquivalentCode\nDebug.Assert result = \"XYZ2014\"\n</code></pre>\n\n<p>Why ? Because it would make clear that the method will change when the string start with <code>ABC</code> and nothing else.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:57:50.063",
"Id": "75314",
"Score": "0",
"body": "he sort of already has that. the only difference is what I am assuming is the year. `2013` v `2014`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:05:15.640",
"Id": "75318",
"Score": "0",
"body": "Well just by looking at the tests (which is what I've done in the first place) I was thinking that 2014 was being changed to 2013. But in fact, it has nothing to do with the second part at all, the first part is what matters.By having two similar cases of the same format (three letters and 2013 || 2014) but with different result help me understand the rules."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:06:10.433",
"Id": "43535",
"ParentId": "43531",
"Score": "8"
}
},
{
"body": "<p>Ok so this is what I ended up doing.</p>\n\n<p>I created an interface, called it <code>ITestClass.cls</code>:</p>\n\n<pre><code>Option Explicit\n\nPublic Sub RunAllTests()\nEnd Sub\n</code></pre>\n\n<p>Then I created a new module, called <code>Tests.bas</code>:</p>\n\n<pre><code>Private AllTests As Collection\nOption Explicit\n\nPrivate Sub SetupTestClasses()\n\n Set AllTests = New Collection\n\n AllTests.Add New PricingModuleTests\n 'AllTests.Add New xxxxxxxxxTests\n\nEnd Sub\n\nPublic Sub Run()\n\n SetupTestClasses\n\n Dim testClass As ITestClass\n For Each testClass In AllTests\n testClass.RunAllTests\n Next\n\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>And then I added a new class to implement the <code>ITestClass</code> interface:</p>\n\n<pre><code>Implements ITestClass\nOption Explicit\n\nPrivate Sub ITestClass_RunAllTests()\n\n CodeShouldBeAsSpecified\n AnyABCCodeShouldBecomeABC2013\n\n Debug.Print TypeName(Me) & \" completed.\"\n\nEnd Sub\n\n\nPublic Sub CodeShouldBeAsSpecified()\n\n 'arrange\n Dim code As String\n code = \"XYZ123\"\n\n Dim expected As String\n expected = \"XYZ123\"\n\n Dim actual As String\n\n 'act\n actual = ModuleBeingTested.GetEquivalentCode(code)\n\n 'assert\n Debug.Assert expected = actual\n Debug.Print \"CodeShouldBeAsSpecified: PASS\"\n\nEnd Sub\n\nPublic Sub AnyABCCodeShouldBecomeABC2013()\n\n 'arrange \n Dim code As String\n code = \"ABC123\"\n\n Dim expected As String\n expected = \"ABC2013\"\n\n Dim actual As String\n\n 'act\n actual = ModuleBeingTested.GetEquivalentCode(code)\n\n 'assert\n Debug.Assert expected = actual\n Debug.Print \"AnyABCCodeShouldBecomeABC2013: PASS\"\n\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>Now this has the drawback that I <strong>had</strong> to make the <code>GetEquivalentCode</code> method <code>Public</code> when it could have really been <code>Private</code> to <code>ModuleBeingTested</code>, but now I have a little bit of a structure so that whenever I write a piece of testable code (the rest of the code has too many dependencies to be anywhere near testable), I can write a test for it and have all tests execute with a single call.</p>\n\n<p>As you can see, properly defining what the rules are makes much fewer tests required.</p>\n\n<p>Immediate pane:</p>\n\n<blockquote>\n<pre><code>Tests.Run\nCodeShouldBeAsSpecified: PASS\nAnyABCCodeShouldBecomeABC2013: PASS\nPricingModuleTests completed.\n</code></pre>\n</blockquote>\n\n<p>If any test fails, it won't output a \"FAIL\", rather the debugger will break at the assertion that failed; I'm fine with that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:33:40.070",
"Id": "75322",
"Score": "0",
"body": "and of course I can add more tests to make sure an unspecified optional parameter is handled the way it should be... but then I'll have to make more `Private` stuff `Public` in the `ModuleBeingTested` in order to control the dependencies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:40:55.540",
"Id": "75324",
"Score": "0",
"body": "Individual test methods could be Private, but that would rule out the possibility to run the tests individually."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:29:58.303",
"Id": "43542",
"ParentId": "43531",
"Score": "7"
}
},
{
"body": "<p>Your <code>GetEquivalentCode</code> procedure is flawed. \nThe <code>IsMissing()</code> function requires a variant; it will not behave as you may imagine when passed a string variable. \nOptional parameters if not variants will be assigned their default values: passed or not, they will be there.<br>\nYour initial test cases all had this.</p>\n\n<p>To understand the risk here try this:</p>\n\n<pre><code>Private Sub Form_Load()\n Call TestIt \nEnd Sub\n\nPrivate Sub TestIt(Optional bKeepIt As Boolean)\n If Not IsMissing(bKeepIt) Then\n If bKeepIt Then\n Debug.Print \"saving data\"\n Else\n Debug.Print \"ok lets delete everything\"\n End If\n End If\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-10T22:54:51.520",
"Id": "119806",
"Score": "2",
"body": "Excellent catch! Welcome to CR! The code isn't technically broken because OP is checking for `vbNullString`, but certainly `IsMissing()` does nothing here. ++"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-10T18:49:36.697",
"Id": "65300",
"ParentId": "43531",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43535",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:41:52.697",
"Id": "43531",
"Score": "10",
"Tags": [
"unit-testing",
"vb6",
"assertions"
],
"Title": "Testing code with Debug.Assert"
} | 43531 |
<p>Based on the true condition, I am making some operations. But I want to simplify the below HTML code in a better way.</p>
<pre class="lang-html prettyprint-override"><code>@{
bool savingHtml = (Request.QueryString["savehtml"] == "1");
string activeTab = Request.QueryString["from"];
}
@if (savingHtml)
{
if (activeTab.ToLower() == "index")
{
<div class="summaryTab">
<ul class="nav nav-tabs" data-tabs="tabs">
<li><a data-toggle="tab" href="#heat">Heat Map</a></li>
<li class="active"><a data-toggle="tab" href="#table">Table</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane active" id="table1">
@Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model)
</div>
<div class="tab-pane" id="heat1">
</div>
</div>
}
else{
<div class="summaryTab">
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#heat">Heat Map</a></li>
<li><a data-toggle="tab" href="#table">Table</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane" id="table2">
</div>
<div class="tab-pane active" id="heat2">
@Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model)
</div>
</div>
}
}
else
{
<div class="summaryTab">
<ul class="nav nav-tabs" data-tabs="tabs">
<li><a data-toggle="tab" href="#heat">Heat Map</a></li>
<li class="active"><a data-toggle="tab" href="#table">Table</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane active" id="table">
@Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model)
</div>
<div class="tab-pane" id="heat">
</div>
</div>
}
</code></pre>
| [] | [
{
"body": "<p>Most of your code is duplicated, what I did is extract the logic to the first code block, and left only the placeholders in the HTML.</p>\n\n<pre><code>@{\n bool savingHtml = (Request.QueryString[\"savehtml\"] == \"1\");\n string activeTab = Request.QueryString[\"from\"];\n string tabContent = Html.Partial(\"~/Views/Shared.MultiQuery/_resultset.cshtml\", Model);\n string heatClass, tableClass;\n string tableId = \"table\";\n string heatId = \"heat\";\n string heatTabContent, tableTabConten;\n\n if (savingHtml && activeTab.ToLower() != \"index\") {\n heatClass = \"active\";\n heatTabContent = tabContent;\n tableId += \"2\";\n heatId += \"2\";\n } else {\n tableClass = \"active\";\n tableTabContent = tabContent;\n if (savingHtml) {\n tableId += \"1\";\n heatId += \"1\";\n }\n }\n}\n\n<div class=\"summaryTab\">\n <ul class=\"nav nav-tabs\" data-tabs=\"tabs\">\n <li class=\"@heatClass\"><a data-toggle=\"tab\" href=\"#heat\">Heat Map</a></li>\n <li class=\"@tableClass\"><a data-toggle=\"tab\" href=\"#table\">Table</a></li>\n </ul>\n</div>\n<div class=\"tab-content\">\n <div class=\"tab-pane active\" id=\"@tableId\">\n @tableTabContent\n </div>\n <div class=\"tab-pane\" id=\"@heatId\">\n @heatTabContent\n </div>\n\n</div>\n</code></pre>\n\n<ul>\n<li><strong>Note</strong>: I have no experience with ASP.Net, so I apologize if the code is not as clean as possible, or has any syntax errors... The gist of the matter is still that if you extract the logic, you get shorter and cleaner code, with much less copy+paste...</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:44:10.537",
"Id": "43543",
"ParentId": "43536",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:07:11.867",
"Id": "43536",
"Score": "3",
"Tags": [
"html",
"mvc",
"asp.net-mvc-4"
],
"Title": "Avoiding redundant code in MVC view page"
} | 43536 |
<p>I recently posted a question about modeling a system that contains elements that can perform actions (<a href="https://codereview.stackexchange.com/questions/42332/model-simulation-using-java-annotations">here</a>). The model runs in cycles and parts perform their action every cycle. The model should have some kind of visual representation displaying changes in model state. In my test code the model updated on timer events and the user sees the changes through observed state changes. The user can start or stop the model through the controller.</p>
<p>I wonder if the MVC pattern is suitable for this setup and if I got the basics of the MVC pattern right.</p>
<pre><code>import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
Model model = new Model();
final View view = new View();
Controller controller = new Controller(model, view);
view.addController(controller);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
view.createAndShowGUI();
}
});
}
}
class Controller implements ActionListener {
Model model;
View view;
public Controller(Model m, View v) {
model = m;
view = v;
model.addObserver(v);
}
@Override
public void actionPerformed(ActionEvent e) {
if (model.isRunning()) {
model.stop();
view.changeCommandText("Start");
} else {
model.start();
view.changeCommandText("Stop");
}
}
public void addModel(Model m) {
model = m;
}
public void addView(View v) {
view = v;
}
}
class Model extends Observable {
private Integer modelState;
private boolean running;
private final Timer timer;
ActionListener taskPerformer;
public Model() {
this.running = false;
modelState = 0;
taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
changeState();
}
};
timer = new Timer(1000, taskPerformer);
}
public boolean isRunning() {
return running;
}
public void changeState() {
modelState++;
setChanged();
notifyObservers(modelState);
}
public String getState() {
return modelState.toString();
}
public void start() {
timer.start();
running = true;
}
public void stop() {
timer.stop();
running = false;
}
}
class View implements Observer {
private final JLabel output = new JLabel();
private final JButton button = new JButton("Start");
public void createAndShowGUI() {
JFrame frame = new JFrame("MVC test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setPreferredSize(new Dimension(240, 50));
frame.setContentPane(panel);
output.setSize(100, 30);
output.setLocation(10, 10);
panel.add(output);
button.setSize(100, 30);
button.setLocation(120, 10);
panel.add(button);
frame.pack();
frame.setVisible(true);
}
@Override
public void update(Observable obs, Object obj) {
output.setText(((Model) obs).getState());
}
public void addController(ActionListener controller) {
button.addActionListener(controller);
}
public void changeCommandText(String command) {
button.setText(command);
}
}
</code></pre>
| [] | [
{
"body": "<p>It looks quite good, some, mostly minor notes:</p>\n\n<ol>\n<li><blockquote>\n<pre><code>class Controller implements ActionListener {\n</code></pre>\n</blockquote>\n\n<p>Having an <code>actionPerformed</code> method in the controller <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smells</a> a little bit for me. I'm not sure about that but I'd rename the controller's method to <code>changeModelState()</code> (without any parameter) and use an inner class to call it:</p>\n\n<pre><code>public void addController(final Controller controller) {\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n controller.changeModelState();\n }\n });\n}\n</code></pre>\n\n<p>It would eliminate the following imports from the <code>Controller.java</code>, therefore the controller would not depend on Swing and it could be used with other view implementations without importing Swing classes:</p>\n\n<blockquote>\n<pre><code>import java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n</code></pre>\n</blockquote></li>\n<li><p>The code contains a <code>Start</code> string in the view:</p>\n\n<blockquote>\n<pre><code>private final JButton button = new JButton(\"Start\");\n</code></pre>\n</blockquote>\n\n<p>and in the controller as well:</p>\n\n<blockquote>\n<pre><code>view.changeCommandText(\"Start\");\n</code></pre>\n</blockquote>\n\n<p>I guess the controller should not know about that how the view presents this information. There could be another view which shows pictures/icons instead of a button with a string. It would be loosely coupled if the controller just set a state, for example, with an enum or separate methods for separate states.</p></li>\n<li><p>On bigger projects I'd consider using something else than <code>Observers</code> and <code>Observables</code>. <a href=\"https://stackoverflow.com/a/2380694/843804\"><em>Péter Török</em>'s answer on SO</a> has a good explanation about its disadvantages:</p>\n\n<blockquote>\n <p>They are not used, because their design is flawed: \n they are not type safe. You can attach any object \n that implements <code>Observer</code> to any <code>Observable</code>, which \n can result in subtle bugs down the line.</p>\n \n <p>[...]</p>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/q/10218895/843804\">Alternative to Java's Observable class?</a></p></li>\n<li><blockquote>\n<pre><code> Model model;\n View view;\n</code></pre>\n</blockquote>\n\n<p>These fields could be <code>private</code>. (<a href=\"https://stackoverflow.com/questions/5484845/should-i-always-use-the-private-access-modifier-for-class-fields\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><blockquote>\n<pre><code>public void addModel(Model m) {\n model = m;\n}\n\npublic void addView(View v) {\n view = v;\n}\n</code></pre>\n</blockquote>\n\n<p><code>setModule</code> and <code>setView</code> would be more descriptive. <code>add</code> is usually used with collections and implies that the method adds the parameter to a list/set/etc. and it still stores the former value too.</p></li>\n<li><p>This field is only accessed in the constructor:</p>\n\n<blockquote>\n<pre><code>ActionListener taskPerformer;\n</code></pre>\n</blockquote>\n\n<p>It could be a local variable. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Using <code>this.</code> is unnecessary here:</p>\n\n<blockquote>\n<pre><code>this.running = false;\nmodelState = 0;\n</code></pre>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:58:07.383",
"Id": "75755",
"Score": "1",
"body": "Thanks for the answer. That question recommends Guava EventBus, I'll have to check that out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:00:37.830",
"Id": "43732",
"ParentId": "43540",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43732",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:19:17.950",
"Id": "43540",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"mvc"
],
"Title": "Java MVC pattern"
} | 43540 |
<p>I'm creating a game that implements a finite automaton and I don't know if I'm doing it right. Any advice?</p>
<p><strong>Game class</strong></p>
<pre><code>import java.awt.Canvas;
import java.awt.event.KeyListener;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener
{
public final String TITLE = "Game";
public final int WIDTH = 640;
public final int HEIGHT = 680;
public int LEVEL = 1;
public int FPS = 0;
public int SCORE = 0;
public int LIFE = 5;
private boolean running = false;
private Thread thread;
private BufferedImage textBackground = null;
private BufferedImage spriteSheet = null;
private BufferedImage background = null;
private int enemyCount = 3;
private int enemyKilled = 0;
private int enemyNotKilled = 0;
private boolean target = false;
private String targetText = "";
private Controller c;
private LinkedList<Enemy> e = new LinkedList<Enemy>();
private Enemy enemy;
public void init()
{
requestFocus();
try
{
spriteSheet = ImageIO.read(getClass().getResource("/spritesheet.png"));
background = ImageIO.read(getClass().getResource("/background.png"));
}
catch(IOException e)
{
e.printStackTrace();
}
textBackground = getSprite(1, 1, 96, 32);
c = new Controller(textBackground, this);
addKeyListener(this);
c.createEnemy(enemyCount);
e = c.getEnemy();
}
private void start()
{
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private void stop()
{
if(!running)
return;
running = false;
try
{
thread.join();
}
catch(Exception e)
{
e.printStackTrace();
}
System.exit(1);
}
public void run()
{
init();
long lastTime = System.nanoTime();
final int framesPerSecond = 30;
double ns = 1000000000 / framesPerSecond;
double delta = 0;
int framesCount = 0;
long timer = System.currentTimeMillis();
int update = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
//if(LIFE == 0)
// break; game over
if(delta >= 1)
{
update();
delta--;
update++;
}
render();
framesCount++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
System.out.println("Update : " + update + " --- FPS : " + framesCount);
FPS = framesCount;
framesCount = 0;
update = 0;
}
}
stop();
}
private void update()
{
c.update();
if(enemyKilled + enemyNotKilled >= enemyCount)
{
targetText = "";
LEVEL++;
enemyKilled = 0;
enemyNotKilled = 0;
enemyCount += 2;
c.createEnemy(enemyCount);
}
}
private void render()
{
BufferStrategy bs = getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(background, 0, 0, null);
c.render(g);
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent ek)
{
int key = ek.getKeyCode();
char character = Character.toLowerCase(ek.getKeyChar());
boolean result = isValid(key);
if(result && !target)
{
for(int i = 0; i < e.size(); i++)
if(e.get(i).getFirstLetter() == character && e.get(i).getOnScreen())
{
enemy = e.get(i);
targetText = enemy.getText();
enemy.addIndex(1);
target = true;
break;
}
}
else if(result && targetText.charAt(enemy.getIndex()) == character)
enemy.addIndex(1);
}
public void keyReleased(KeyEvent ek) { }
public void keyTyped(KeyEvent ek) { }
public static void main(String[] args)
{
Game game = new Game();
game.setPreferredSize(new Dimension(game.WIDTH, game.HEIGHT));
game.setMaximumSize(new Dimension(game.WIDTH, game.HEIGHT));
game.setMinimumSize(new Dimension(game.WIDTH, game.HEIGHT));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
public boolean isValid(int key)
{
return key >= 65 && key <= 90 ? true : false;
}
public BufferedImage getSprite(int col, int row, int width, int height)
{
return spriteSheet.getSubimage((col * 32) - 32, (row * 32) - 32, width, height);
}
public int getEnemyCount()
{
return enemyCount;
}
public void setEnemyCount(int b)
{
enemyCount = b;
}
public int getEnemyKilled()
{
return enemyKilled;
}
public void setEnemyKilled(int b)
{
enemyKilled = b;
}
public int getEnemyNotkilled()
{
return enemyNotKilled;
}
public void setEnemyNotkilled(int enemyNotKilled)
{
this.enemyNotKilled = enemyNotKilled;
}
public int getScore()
{
return SCORE;
}
public void setScore(int b)
{
SCORE = b;
}
public int getLife()
{
return LIFE;
}
public void setLife(int b)
{
LIFE = b;
}
public boolean getTarget()
{
return target;
}
public void setTarget(boolean b)
{
target = b;
}
public String getTargetText()
{
return targetText;
}
public void setTargetText(String b)
{
targetText = b;
}
}
</code></pre>
<p><strong>Enemy Class</strong></p>
<pre><code>import java.awt.Font;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.text.AttributedString;
public class Enemy
{
private double x ,y;
private String text;
private char firstLetter;
private AttributedString as;
private Controller c;
private BufferedImage background;
private Game game;
private int index = 0;
private int textLength = 0;
private double speed = 0.0;
private int stringWidth = 0;
private boolean onScreen = false;
public Enemy(double x, double y, double speed, BufferedImage background, Controller c, Game game, String text, int stringWidth)
{
this.x = x;
this.y = y;
this.background = background;
this.text = text;
this.game = game;
this.c = c;
this.speed = speed;
firstLetter = this.text.charAt(0);
textLength = this.text.length();
this.stringWidth = stringWidth;
}
public void update()
{
y += speed;
if(y >= 0)
onScreen = true;
if(index >= textLength)
{
game.setScore(game.getScore() + 5);
game.setTargetText("");
c.removeEnemy(this);
game.setEnemyKilled(game.getEnemyKilled() + 1);
game.setTarget(false);
}
if(y >= game.HEIGHT - 50)
{
if(game.getLife() != 0)
game.setLife(game.getLife() - 1);
c.removeEnemy(this);
game.setEnemyNotkilled(game.getEnemyNotkilled() + 1);
if(game.getTargetText().equals(text))
{
game.setTarget(false);
game.setTargetText("");
}
}
}
public void render(Graphics g)
{
g.drawImage(background, (int)x, (int)y, null);
as = new AttributedString(text);
if(index >= 1)
as.addAttribute(TextAttribute.FOREGROUND, Color.WHITE, 0, index);
as.addAttribute(TextAttribute.FONT, new Font("Consolas", Font.BOLD, 12), 0, text.length());
g.drawString(as.getIterator(), (int)x + getAdd(stringWidth), (int)y + 13);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public String getText()
{
return text;
}
public char getFirstLetter()
{
return firstLetter;
}
public void addIndex(int b)
{
index += b;
}
public int getIndex()
{
return index;
}
public int getTextLength()
{
return textLength;
}
public int getAdd(int width)
{
return (96 / 2) - (width / 2);
}
public boolean getOnScreen()
{
return onScreen;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T11:11:52.707",
"Id": "75393",
"Score": "0",
"body": "In the future, it would help if you make life easier for reviewers and explain a bit about [what your code does](http://meta.codereview.stackexchange.com/questions/1226/code-should-include-a-description-of-what-the-code-does). Simple examples of images of input/output or similar is *extremely* helpful, and is likely to give your question more attention."
}
] | [
{
"body": "<p>There are a number of things to comment on here.</p>\n<h2>Code-Style</h2>\n<p>Java coding style puts <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#15395\" rel=\"noreferrer\">the <code>{</code> opening brace at the end of the line</a> containing the condition/construct that starts the block. Code like:</p>\n<blockquote>\n<pre><code>public char getFirstLetter()\n{\n return firstLetter;\n}\n</code></pre>\n</blockquote>\n<p>should be:</p>\n<pre><code>public char getFirstLetter() {\n return firstLetter;\n}\n</code></pre>\n<p>Additionally, there <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html#487\" rel=\"noreferrer\">should be an empty line after the closing <code>}</code> and the start of the next method declaration</a>.</p>\n<h2>Threads</h2>\n<p>You are using swing, yet I cannot see any places where you are accommodating work that is done on the <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html\" rel=\"noreferrer\">Event Dispatch Thread (EDT)</a> vs. your game thread.</p>\n<p>This is likely to lead to inconsistent gameplay, irregular timing, and other problems.... especially during the manipulation of the Graphics objects.</p>\n<h2>Terminology</h2>\n<p>I am not seeing a <em>Finite</em> Automata here... this looks pretty open-ended, not finite.</p>\n<h2>Magic Numbers</h2>\n<p>These are everywhere. There must be a better way to centralize them.</p>\n<h2>Integer Arithmetic</h2>\n<p>This line:</p>\n<blockquote>\n<pre><code>double ns = 1000000000 / framesPerSecond;\n</code></pre>\n</blockquote>\n<p>is doing integer arithmetic, in your case, you would expect <code>ns</code> to be <code>33333333.33.....</code> but it will be plain <code>33333333.0</code> because the integer division is done before the value is converted to a double. Consider using:</p>\n<pre><code>double ns = 1000000000.0 / framesPerSecond;\n</code></pre>\n<p>which converts the one value to a double, and thus the entire expresion is evaluated in the double-precision space.</p>\n<p>in this case, the loss of accuracy will likely not significantly affect the game, but you should be aware.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T01:23:36.777",
"Id": "75363",
"Score": "0",
"body": "Thanks! :) Do you have any advice on how can I implement a Finite Automaton here?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T23:48:48.560",
"Id": "43565",
"ParentId": "43544",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:55:45.220",
"Id": "43544",
"Score": "6",
"Tags": [
"java",
"game",
"homework"
],
"Title": "Finite Automaton for a Typing Game"
} | 43544 |
<p>I am populating a drop down list from my SQL database. List should be able to be displayed with active only, inactive only or both at the same time.</p>
<p>OfficeRepository.cs:</p>
<pre><code> public static List<OfficeRollups> ListOfficeRollups(bool active, bool inactive)
{
List<DataRow> listDataRow = null;
string whereClause = string.Empty;
if (active && !inactive)
whereClause += @" And Active = 1";
else if (!active && inactive)
whereClause += @" And Active = 0";
string srtQry = @"
Select OfficeRollupID, OfficeRollupName, Active
From OfficeRollups
Where 1 = 1 " + whereClause + @"
Order By OfficeRollupName
";
using (SqlConnection conn = new SqlConnection(Settings.ConnectionString))
{
using (SqlCommand objCommand = new SqlCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
listDataRow = dt.AsEnumerable().ToList();
}
}
}
var listOfficeRollups = (from o in listDataRow
select new OfficeRollups
{
OfficeRollupID = o.Field<int>("OfficeRollupID"),
OfficeRollupName = o.Field<string>("OfficeRollupName"),
Active = o.Field<bool>("Active")
}).ToList();
return listOfficeRollups;
}
public static IEnumerable<SelectListItem> ListOfficeRollupsForDD(bool active, bool inactive)
{
var listOfficeRollups = OfficeRepository.ListOfficeRollups(active, inactive);
return from o in listOfficeRollups.ToList()
where o.OfficeRollupName.Length != 0
orderby o.OfficeRollupName
select new SelectListItem
{
Text = o.OfficeRollupName,
Value = o.OfficeRollupID.ToString()
};
}
</code></pre>
<p>HomeController.cs:</p>
<pre><code> public ActionResult Create()
{
Office currentOffice = new Office();
var listOfficeRollups = OfficeRepository.ListOfficeRollupsForDD(true, false);
currentOffice.OfficeRollups = listOfficeRollups;
return View(currentOffice);
}
</code></pre>
<p>Create.cshtml:</p>
<pre><code>@model Office
@using (Html.BeginForm())
{
@(Html.DropDownList("OfficeRollupID", Model.OfficeRollups))
}
</code></pre>
<p>Office.cs:</p>
<pre><code>public class Office
{
[Required]
[Display(Name = "Office Rollup")]
public IEnumerable<SelectListItem> OfficeRollups { get; set; }
public Int32 OfficeRollupID { get; set; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:29:35.003",
"Id": "75344",
"Score": "3",
"body": "There's a typo in your Hungarian notation for `strQry`... ;)"
}
] | [
{
"body": "<p>Here's a simplification of the <code>OfficeRepository</code> methods. Note the other <code>IDisposable</code> types in <code>using</code> blocks:</p>\n\n<pre><code> public static IEnumerable<OfficeRollups> ListOfficeRollups(bool active, bool inactive)\n {\n var whereClause = active && !inactive\n ? @\"Where Active = 1\"\n : (!active && inactive ? @\"Where Active = 0\" : string.Empty);\n var srtQry = @\"\nSelect OfficeRollupID, OfficeRollupName, Active\nFrom OfficeRollups\n\" + whereClause + @\"\nOrder By OfficeRollupName\n\";\n\n using (var conn = new SqlConnection(Settings.ConnectionString))\n using (var objCommand = new SqlCommand(srtQry, conn) { CommandType = CommandType.Text })\n using (var dt = new DataTable())\n using (var adp = new SqlDataAdapter(objCommand))\n {\n conn.Open();\n adp.Fill(dt);\n return dt.AsEnumerable().Select(o => new OfficeRollups\n {\n OfficeRollupID = o.Field<int>(\"OfficeRollupID\"),\n OfficeRollupName = o.Field<string>(\"OfficeRollupName\"),\n Active = o.Field<bool>(\"Active\")\n }).ToList();\n }\n }\n\n public static IEnumerable<SelectListItem> ListOfficeRollupsForDD(bool active, bool inactive)\n {\n var listOfficeRollups = OfficeRepository.ListOfficeRollups(active, inactive);\n\n return listOfficeRollups\n .Where(o => !string.IsNullOrEmpty(o.OfficeRollupName))\n .OrderBy(o => o.OfficeRollupName)\n .Select(o => new SelectListItem\n {\n Text = o.OfficeRollupName,\n Value = o.OfficeRollupID.ToString()\n })\n .ToList();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:12:32.917",
"Id": "43551",
"ParentId": "43545",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43551",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:07:24.680",
"Id": "43545",
"Score": "3",
"Tags": [
"c#",
"sql-server",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Populate Drop Down List from SQL Database"
} | 43545 |
<p>I'm adding additional functionality to an existing MVC .net application, and to help prevent or at least reduce repeated reads to the dB I'm dumping a few custom entities in session. I'm limiting what can be stored in session to say a max of 5 objects for now. </p>
<p>Given below is the code and it seems generic enough and works fine locally on my box; any suggestions to improve this and session is In-Proc but if it does get stored in a persistent medium say SQL server then I would need to customize this further - decorate custom object properties w/XML element attributes</p>
<pre><code>public class QuestionModelSessionStateProvider : IQuestionModelSessionStateProvider
{
const int MaxSize = 5;
public T GetValue<T>(string key)
{
HttpSessionState session = GetSessionState();
T returnValue = default(T);
if (session == null) return returnValue;
if (session["QuestionModelStore"] != null)
{
var questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
foreach (var t in questionModelStore.Where(t => t.Key.Equals(key)))
{
returnValue = t.Value;
}
}
return returnValue;
}
public void SetValue<T>(string key, T value)
{
HttpSessionState session = GetSessionState();
if (session == null) return;
List<KeyValuePair<string, T>> questionModelStore;
if (session["QuestionModelStore"] == null)
{
questionModelStore = new List<KeyValuePair<string, T>> { new KeyValuePair<string, T>(key, value) };
session["QuestionModelStore"] = questionModelStore;
}
else
{
questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
questionModelStore.Add(new KeyValuePair<string, T>(key, value));
}
if (questionModelStore.Count > MaxSize)
{
questionModelStore.RemoveAt(0);
}
}
public void RemoveValue<T>(string key)
{
HttpSessionState session = GetSessionState();
int indexToRemoveAt = 0;
var found = false;
if (session != null && session["QuestionModelStore"] != null)
{
var questionModelStore = (List<KeyValuePair<string, T>>) session["QuestionModelStore"];
for (var i = 0; i < questionModelStore.Count; i++)
{
if (questionModelStore[i].Key.Equals(key))
{
indexToRemoveAt = i;
found = true;
break;
}
}
if (found)
questionModelStore.RemoveAt(indexToRemoveAt);
}
}
public void Clear()
{
HttpSessionState session = GetSessionState();
if (session != null)
{
session["QuestionModelStore"] = null;
}
}
public int Count<T>()
{
HttpSessionState session = GetSessionState();
if (session != null)
{
//return session.Count;
if (session["QuestionModelStore"] != null)
{
var questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
return questionModelStore.Count;
}
}
return 0;
}
private static HttpSessionState GetSessionState()
{
if (HttpContext.Current != null)
return HttpContext.Current.Session;
return null;
}
}
</code></pre>
| [] | [
{
"body": "<p>There are 4 places where you have code like,</p>\n\n<pre><code>if (session != null)\n{\n List<KeyValuePair<string, T>> questionModelStore;\n\n if (session[\"QuestionModelStore\"] == null)\n {\n questionModelStore = (List<KeyValuePair<string, T>>)session[\"QuestionModelStore\"];\n</code></pre>\n\n<p>It would be neater if these were a common subroutine:</p>\n\n<pre><code>List<KeyValuePair<string, T>> GetQuestionModelStore<T>()\n{\n var session = HttpContext.Current.Session;\n if (!session)\n return null;\n return (List<KeyValuePair<string, T>>)session[\"QuestionModelStore\"];\n}\n</code></pre>\n\n<p>That would simplify code such as:</p>\n\n<pre><code>public T GetValue<T>(string key)\n{\n var cached = GetQuestionModelStore();\n if (cached == null)\n return default(T);\n return cached.FirstOrDefault(t => t.Key.Equals(key));\n}\n</code></pre>\n\n<p>It might be slightly faster to use a Queue than a List, because a Queue is designed to let you enqueue at one end and dequeue at the other.</p>\n\n<p>You're not quite implementing a LRU algorithm: if you want to do that, when you find an item in the cache you should move the item to the most-recently-used end of the list.</p>\n\n<p>There's one bug I see, which is that your methods are generic: the first time you call SetValue it creates a <code>List<KeyValuePair<string, T>></code>; unless all your SetValue and GetValue methods use the same type of T this will cause a run-time error (casting between different types of T). If all your SetValue and GetValue methods do use the same type of T then you might as well specify what T is instead of making it generic.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:32:19.497",
"Id": "43570",
"ParentId": "43546",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43570",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:18:16.643",
"Id": "43546",
"Score": "3",
"Tags": [
"c#",
".net",
"mvc",
"generics",
"session"
],
"Title": "Session state wrapper, extending an existing application"
} | 43546 |
<p>I implemented a fixed-size matrix class which supports basic matrix operations (cannot use C++11). What do you think, and how could it be improved?</p>
<pre><code>#ifndef FIXED_SIZE_MATRIX_H__
#define FIXED_SIZE_MATRIX_H__
#include <iostream>
#include <cstdlib>
template <typename Ty, int N, int M = N>
struct FixedSizeMatrix {
typedef Ty value_type;
union {
struct {
Ty element[N][M];
};
struct {
Ty flatten[N * M];
};
};
// Access with bounds checking
Ty& operator()(int r, int c) {
assert(r >= 0 && r < N);
assert(c >= 0 && c < M);
return element[r][c];
}
// Return matrix transpose
FixedSizeMatrix<Ty, M, N> T() const {
FixedSizeMatrix<Ty, M, N> result;
for (int r = 0; r < N; ++r) {
for (int c = 0; c < M; ++c) {
result.element[c][r] = element[r][c];
}
}
return result;
}
// Return matrix inverse
FixedSizeMatrix<Ty, N, M> I();
};
///
// Matrix Inverse
///
// A design choice was made to keep FixedSizeMatrix an aggregate class to enable
// FixedSizeMatrix<float, 2, 2> = {1.0f, 1.0f, 0.5f, 0.2f} initialization.
// With c++11 it would be possible to create a FixedSizeMatrix base class
// and derive all variations from it, while retaining the brace
// initialization.
//
// Matrix inverse helpers
namespace detail {
// General version not implemented
template <typename Ty, int N, int M>
struct inverse;
// Matrix inversion for 2x2 matrix
template <typename Ty>
struct inverse<Ty, 2, 2> {
FixedSizeMatrix<Ty, 2, 2> operator()(FixedSizeMatrix<Ty, 2, 2> a) {
FixedSizeMatrix<Ty, 2, 2> result;
Ty det =
a.element[0][0] * a.element[1][1] - a.element[0][1] * a.element[1][0];
assert(det != 0);
result.element[0][0] = a.element[1][1] / det;
result.element[1][1] = a.element[0][0] / det;
result.element[0][1] = -a.element[0][1] / det;
result.element[1][0] = -a.element[1][0] / det;
return result;
}
};
} // detail
// Define matrix inverse
template <typename Ty, int N, int M>
FixedSizeMatrix<Ty, N, M> FixedSizeMatrix<Ty, N, M>::I() {
return detail::inverse<Ty, N, M>()(*this);
}
///
// Matrix operations
///
// Matrix product
template <typename Ty, int N, int M, int P>
FixedSizeMatrix<Ty, N, P> operator*(FixedSizeMatrix<Ty, N, M> a,
FixedSizeMatrix<Ty, M, P> b) {
FixedSizeMatrix<Ty, N, P> result;
for (int r = 0; r < N; ++r) {
for (int c = 0; c < P; ++c) {
Ty accum = Ty(0);
for (int i = 0; i < M; ++i) {
accum += a.element[r][i] * b.element[i][c];
}
result.element[r][c] = accum;
}
}
return result;
}
// Unary negation
template <typename Ty, int N, int M>
FixedSizeMatrix<Ty, N, M> operator-(FixedSizeMatrix<Ty, N, M> a) {
FixedSizeMatrix<Ty, N, M> result;
for (int e = 0; e < N * M; ++e) result.flatten[e] = -a.flatten[e];
return result;
}
#define MATRIX_WITH_MATRIX_OPERATOR(op_symbol, op) \
template <typename Ty, int N, int M> \
FixedSizeMatrix<Ty, N, M> operator op_symbol(FixedSizeMatrix<Ty, N, M> a, \
FixedSizeMatrix<Ty, N, M> b) { \
FixedSizeMatrix<Ty, N, M> result; \
for (int e = 0; e < N * M; ++e) \
result.flatten[e] = a.flatten[e] op b.flatten[e]; \
return result; \
}
MATRIX_WITH_MATRIX_OPERATOR(+, +);
MATRIX_WITH_MATRIX_OPERATOR(-, -);
#undef MATRIX_WITH_MATRIX_OPERATOR
#define MATRIX_WITH_SCALAR_OPERATOR(op_symbol, op) \
template <typename Ty, int N, int M> \
FixedSizeMatrix<Ty, N, M> operator op_symbol(FixedSizeMatrix<Ty, N, M> a, \
Ty scalar) { \
FixedSizeMatrix<Ty, N, M> result; \
for (int e = 0; e < N * M; ++e) \
result.flatten[e] = a.flatten[e] op scalar; \
return result; \
}
MATRIX_WITH_SCALAR_OPERATOR(+, +);
MATRIX_WITH_SCALAR_OPERATOR(-, -);
MATRIX_WITH_SCALAR_OPERATOR(*, *);
MATRIX_WITH_SCALAR_OPERATOR(/, / );
#undef MATRIX_WITH_SCALAR_OPERATOR
template <typename Ty, int N, int M>
FixedSizeMatrix<Ty, N, M> operator+(Ty scalar, FixedSizeMatrix<Ty, N, M> a) {
return a + scalar;
}
template <typename Ty, int N, int M>
FixedSizeMatrix<Ty, N, M> operator*(Ty scalar, FixedSizeMatrix<Ty, N, M> a) {
return a * scalar;
}
template <typename Ty, int N, int M>
FixedSizeMatrix<Ty, N, M> operator-(Ty scalar, FixedSizeMatrix<Ty, N, M> a) {
return -a + scalar;
}
template <typename Ty, int N>
FixedSizeMatrix<Ty, N, N> identity_matrix() {
FixedSizeMatrix<Ty, N, N> result = FixedSizeMatrix<Ty, N, N>();
for (int i = 0; i < N; ++i) result.element[i][i] = Ty(1);
return result;
}
template <typename Ty, int N, int M>
std::ostream& operator<<(std::ostream& out, FixedSizeMatrix<Ty, N, M> a) {
for (int r = 0; r < N; ++r) {
for (int c = 0; c < M; ++c) {
out << a.element[r][c] << " ";
}
out << std::endl;
}
return out;
}
#endif
</code></pre>
| [] | [
{
"body": "<p>Looks good over all, but I have a few thoughts. A few are stylistic, some are technical, and some are just trade offs I want to make sure you're aware of.</p>\n\n<hr>\n\n<p>I would use the <code>value_type</code> typedef for method return types, temporary types, etc. It should make for a bit prettier signature in IDEs and any kind of auto generated documentation.</p>\n\n<hr>\n\n<p>I would try to be consistent with variable names with regards to N/M/r/c. I either use N/M/n/m or R/C/r/c. Some people like to avoid using different capitalizations though, so that might be a valid concern.</p>\n\n<hr>\n\n<p>Template type parameters default to the current ones inside of a templated class, so all of the <code>FixedSizeMatrix<Ty, M, N></code> types can be simplified to <code>FixedSizeMatrix</code>.</p>\n\n<hr>\n\n<p>It's good that you're consistent, but 2 spaces is rather unusual for C++. I would use either 4 spaces or tabs.</p>\n\n<hr>\n\n<p>You should also have a const version of <code>operator()</code>.</p>\n\n<hr>\n\n<p>If you ever decide to make the class more sophisticated, you might regret exposing <code>element</code>. Perhaps hide the struct as a private member, have <code>operator()</code> be unchecked, and have a checked version called <code>at</code>. You could even have a 1 parameter version of each one that would provide the <code>flattened</code> functionality.</p>\n\n<p>This unfortunately would break aggregate initialization though, which I suspect is why you've made the decision to have it public.</p>\n\n<p>Still though, even if you make keep it public, you can get in a habit of using <code>operator()</code> and <code>at()</code> and then if you ever use C++11, you can properly encapsulate it with minimal code breakage.</p>\n\n<hr>\n\n<p>I would throw a <code>std::out_of_range</code> instead of using asserts in <code>operator()</code>. Note that this and having the checked version named <code>at</code> while using the operator as a pass through is consistent with the behavior of <code>std::vector</code>.</p>\n\n<hr>\n\n<p>Same thing for your other asserts. Exceptions can be caught and handled if desired. Asserts not so much. if you're using asserts for performance reasons, please consider if the tiny difference really matters. Modern C++ compilers have a zero cost exception model where exceptions are only costly if they're actually thrown.</p>\n\n<hr>\n\n<p>Don't use double underscores. You technically can in certain situations, but <a href=\"https://stackoverflow.com/q/228783/567864\">the rules are very difficult to remember</a>. Your FIXED_SIZE_MATRIX_H__ is technically invalid.</p>\n\n<hr>\n\n<p>Is <code>I</code> common notation for a matrix inverse (makes me think identity matrices)? Even if it is, I would name the method <code>invert</code>. </p>\n\n<hr>\n\n<p>Same thing with the transpose.</p>\n\n<hr>\n\n<p>Any time you're passing the matrix as an argument to a function and you're not modifying it, pass it by constant reference. There's no need to make a potentially very expensive copy just to read from it. There's also the option of having the argument copy but then using the copy to store the result (though that requires that you can operate on the matrix without a dependency cycle between elements). This would allow move semantics in C++11 on temporaries passed as the argument.</p>\n\n<hr>\n\n<p>Everywhere you do <code>Ty(0)</code>, you force an interface constraint on <code>Ty</code> in that it must have a constructor that is compatible with a single integer parameter. If you default construct the <code>Ty</code>, you avoid this interface constraint, though you of course add a new one. Consider the two cases this can affect: is a type used more likely to have a default constructor that represents 0 or a single integer constructor? I would lean towards the first one, oddly enough. For example, a <code>Complex</code> might not have an integer constructor.</p>\n\n<hr>\n\n<p>It might be nice to put this in a namespace if you plan on the usage of this to grow to more than just 1 or 2 simple programs. That helps mentally organize your library as one coherent part, and it provides a few technical advantages. Namely, your <code>detail</code> namespace could conflict with someone else's <code>::detail</code> namespace, and it would be nice to give your macros, though short lived, a prefix of some kind. It's relatively unlikely that anything in this would actually conflict, but if someone were using this with another matrix library, you never know. Namespaces don't cost anything to you as the developer (or to consumers of the class), but they offer a few advantages.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:30:22.663",
"Id": "43553",
"ParentId": "43548",
"Score": "5"
}
},
{
"body": "<p>There are better ways of defining operators than using macros that are only (slightly) more verbose:</p>\n\n<pre><code>#define MATRIX_WITH_MATRIX_OPERATOR(op_symbol, op) \\\ntemplate <typename Ty, int N, int M> \\\nFixedSizeMatrix<Ty, N, M> operator op_symbol(FixedSizeMatrix<Ty, N, M> a, \\\n FixedSizeMatrix<Ty, N, M> b) { \\\n FixedSizeMatrix<Ty, N, M> result; \\\n for (int e = 0; e < N * M; ++e) \\\n result.flatten[e] = a.flatten[e] op b.flatten[e]; \\\n return result; \\\n}\n</code></pre>\n\n<p>Firstly, these parameters should be passed by <code>const &</code> (you're creating full copies of them currently). Secondly, you can easily do this with templates:</p>\n\n<pre><code>template <typename Ty, int N, int M, typename BinaryOp>\nFixedSizeMatrix<Ty, N, M> base_op(const FixedSizeMatrix<Ty, N, M>& a,\n const FixedSizeMatrix<Ty, N, M>& b,\n BinaryOp f)\n{\n FixedSizeMatrix<Ty, N, M> result;\n for(int e = 0; e < N * M; ++e) {\n result.flatten[e] = f(a.flatten[e], b.flatten[e]);\n }\n return result;\n}\n</code></pre>\n\n<p>Your operators can then be one liners for the implementation:</p>\n\n<pre><code>#include <functional>\n\ntemplate <typename Ty, int N, int M>\nFixedSizeMatrix<Ty, N, M> operator+(const FixedSizeMatrix<Ty, N, M>& a,\n const FixedSizeMatrix<Ty, N, M>& b)\n{\n return base_op(a, b, std::plus<Ty>());\n}\n\ntemplate <typename Ty, int N, int M>\nFixedSizeMatrix<Ty, N, M> operator-(const FixedSizeMatrix<Ty, N, M>& a,\n const FixedSizeMatrix<Ty, N, M>& b)\n{\n return base_op(a, b, std::minus<Ty>());\n}\n</code></pre>\n\n<p>And so on. This is slightly more verbose, but avoids macro ugliness (and will be just as efficient, once the compiler is done inlining everything).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T03:14:07.920",
"Id": "75367",
"Score": "0",
"body": "Great point on the operators. Wish that had occurred to me :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T08:03:47.713",
"Id": "75372",
"Score": "0",
"body": "I did this modification and changed scalar operators the same. However, looking at the code with all the modifications it seems like I added large sections of boilerplate code. Are there any advantages of doing things this way, besides avoiding macros?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T08:12:56.373",
"Id": "75373",
"Score": "0",
"body": "@BlazBratanic It's mainly for avoiding macros. You might decide it's a worthwhile tradeoff to stick with macros here, but most of the boilerplate code is just function signatures. I think it's worthwhile to get rid of macros, personally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:56:19.307",
"Id": "75558",
"Score": "0",
"body": "@Yuushi Thanks for your helpful suggestion. I would accept both answers if I could."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T03:12:13.197",
"Id": "43575",
"ParentId": "43548",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:47:36.543",
"Id": "43548",
"Score": "5",
"Tags": [
"c++",
"matrix",
"c++03"
],
"Title": "Fixed size matrix implementation"
} | 43548 |
<p>How could I make this code more effective? I'm just experimenting and learning the different ways of how Python runs.</p>
<pre><code>list=[]
original=mkPoint3D(x,y)
z1=mkPoint3D(x-d,y)
z2=mkPoint3D(x+d,y)
z3=mkPoint3D(x,y-d)
z4=mkPoint3D(x,y+d)
list.append(original)
list.append(z1)
list.append(z2)
list.append(z3)
list.append(z4)
if(maxPoint(list).z==original.z):
print("The local maximum is at " + "( " + str(original.x) + " , " + str(original.y) + " )" + " = " + str(original.z))
elif maxPoint(list).z==z1.z:
hillClimb(z1.x,z1.y,d)
elif maxPoint(list).z==z2.z:
hillClimb(z2.x,z2.y,d)
elif maxPoint(list).z==z3.z:
hillClimb(z3.x,z3.y,d)
elif maxPoint(list).z==z4.z:
hillClimb(z4.x,z4.y,d)
</code></pre>
| [] | [
{
"body": "<p>Don't use \"list\" as a variable name, since it is a python function.\nDon't initialize it a list and append to it, if you can\njust create it and populate it with one line.\nDon't call a function more than once, if you don't need to.\nUse a loop with a break statement, instead of all the elif statements</p>\n\n<pre><code>original=mkPoint3D(x,y)\nz1=mkPoint3D(x-d,y)\nz2=mkPoint3D(x+d,y)\nz3=mkPoint3D(x,y-d)\nz4=mkPoint3D(x,y+d)\n\npoint_list = [original, z1, z2, z3, z4]\n\nmaxz = maxPoint(point_list).z\n\nif maxz == original.z:\n print (\" The local ...\")\n\nelse:\n for next_point in point_list[1:]:\n if maxz == next_point.z:\n matching_point = next_point\n break\n\n hillClimb(matching_point.x, matching_point.y, d)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:58:28.167",
"Id": "43556",
"ParentId": "43554",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43556",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:38:26.133",
"Id": "43554",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Determine local maximum from given points"
} | 43554 |
<p>Is this orthogonal?</p>
<pre><code>#ifndef TOKENIZER_H
#define TOKENIZER_H
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
class StringTokenizer
{
private:
std::vector<std::string> tokens;
unsigned int index;
public:
StringTokenizer(std::string const & str, const char delim)
{
index = 0;
// Populate the token vector...
std::istringstream stream(str);
std::string token;
while (std::getline(stream, token, delim))
{
tokens.push_back(token);
}
}
~StringTokenizer(void) { };
bool HasMoreTokens() { return index < tokens.size(); };
std::string NextToken() { return TokenAtIndex(index++); };
std::string PreviousToken() { return TokenAtIndex(index--); };
std::string TokenAtIndex(int x)
{
std::string token = "";
try
{
token = tokens.at(x);
}
catch (const std::out_of_range& range_error)
{
std::cerr << "[!!] Out of Range: " << range_error.what() << std::endl;
}
return token;
}
void Clear() { index = 0; };
};
#endif
</code></pre>
| [] | [
{
"body": "<p>Your constructor is nigh-identical to <a href=\"https://stackoverflow.com/a/236803/49942\">this up-voted answer</a> for splitting a string.</p>\n\n<p>The rest of the class doesn't add much value: IMO the vector provides the same API as your class and more besides; so a user might prefer to have the vector than to have your StringTokenizer instance which wraps/encapsulates/hides the vector.</p>\n\n<p><code>vector.at</code> returns a const reference, instead of returning by value: perhaps your methods should too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:37:53.500",
"Id": "75360",
"Score": "0",
"body": "Thanks! I tend to obsess over details, and overlook more obvious design issues, like \"IS THIS THING ACTUALLY USEFUL?!\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T02:03:46.553",
"Id": "75364",
"Score": "1",
"body": "You can actually go a step further, and use something like `std::istringstream i(input); std::vector<std::string>{std::istream_iterator<std::string>(i), std::istream_iterator<std::string>()};` to create the vector\\from the tokens. Also see [Boost Tokenizer](http://www.boost.org/doc/libs/release/libs/tokenizer/)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T23:57:42.897",
"Id": "43566",
"ParentId": "43561",
"Score": "4"
}
},
{
"body": "<p>Seems like overkill.<br>\nThe reason I would use the class is this:</p>\n\n<pre><code>std::string data(getData());\nStringTokenizer token(data, ' ');\n\nwhile(token.HasMoreTokens())\n{\n std::string value = token.NextToken();\n // STUFF\n}\n</code></pre>\n\n<p>Which seems OK. But when I compare this with the way I would normally do it.</p>\n\n<pre><code>std::string data(getData());\nstd::stringstream token(data);\n\nstd::string value;\nwhile(std::getline(token, value, ';'))\n{\n // STUFF\n}\n</code></pre>\n\n<p>I don't see any real advantage. Why would I use a non tested class in place where I can easily use standard functions? </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:54:16.327",
"Id": "43629",
"ParentId": "43561",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T23:00:59.447",
"Id": "43561",
"Score": "7",
"Tags": [
"c++",
"design-patterns",
"strings"
],
"Title": "Simple string tokenizer wrapper"
} | 43561 |
<p>We have a geocoding samples <a href="https://github.com/agrc/GeocodingSample">github repository</a>. The snippet below came through in an email and I am not very familiar with PHP. I'd like to add this as the PHP example in the samples repository but would like someone to review it first. The idea is that some other php dev can use this as a starting point and it will be considered good code. </p>
<p>Basically what it does, along with the other samples in the <a href="https://github.com/agrc/GeocodingSample">repository</a>, is to geocodes an address against a web service.</p>
<p>Right off the bat, I am not sure I like that the <code>referer</code> header is being set and not added by the browser. What would you change about this? If you want, pull request against the samples repo or post answers here or both!</p>
<pre><code>/**
* Access API from http://api.mapserv.utah.gov
* uses curl library
*/
class geocoder {
private $apiKey = '';
private $apiUrl = 'http://api.mapserv.utah.gov/api/v1/geocode/%s/%s';
private $options = array(
CURLOPT_RETURNTRANSFER => true, //return the transfer as string instead of writing directly
CURLOPT_HTTPHEADER => array('Content-type: application/json'), //specify content type (json)
CURLOPT_REFERER => 'http://www.example.com/' //status 400 "Referrer http header is missing" without this line, but it needs to be the originating website
);
/**
* Class constructor /
*/
public function __construct($userApiKey) {
$this->apiKey = $userApiKey;
}
/**
* curl processes the request as a function so that it can be reused with multiple mapserv api requests
* @param object $options
* @return
*/
private function curl ($options){
$cUrl = curl_init();
curl_setopt_array( $cUrl, $options );
$response = curl_exec( $cUrl );
curl_close( $cUrl );
return $response;
}
/**
* locate returns x/y coordinate based on address and zone (and possibly other parameters)
* @param object $address
* @param object $zone
* @param object $parameters [optional]
* @return
*/
public function locate ($address, $zone, $parameters = array()){
$parameters['apiKey'] = $this->apiKey;
$paramArray = array();
foreach($parameters as $k => $v){
$paramArray[] = $k.'='.$v;
}
$parameterStr = '?'.implode('&', $paramArray);
$url = sprintf($this->apiUrl, rawurlencode($address), rawurlencode($zone) ).$parameterStr;
$this->options[CURLOPT_URL] = $url;
$response = $this->curl($this->options);
$decoded = json_decode( $response );
if($decoded->status != 200){
$decoded->result = 'Error status = '.$decoded->status;
}
return $decoded->result;
}
}
//Usage
//generate private apiKey at https://developer.mapserv.utah.gov/secure/KeyManagement
$geocoder = new geocoder(‘insert your api key here');
$result = $geocoder->locate('123 South Main Street', 'SLC', array('acceptScore' => 90, 'spatialReference' => 4326));
echo '<pre>'.print_r($result,1).'</pre>;
</code></pre>
| [] | [
{
"body": "<p>There are a number of concerns - from code styling to error handling (echoing out an error is not good. Use Exceptions or a custom Error handler). </p>\n\n<pre><code><?\n\n/**\n * Access API from http://api.mapserv.utah.gov\n * \n * @require cURL\n * @internal Create your api key at https://developer.mapserv.utah.gov/secure/KeyManagement\n */\nclass Geocoder {\n private $api_key;\n private $api_url;\n private $options;\n\n public function __construct($user_api_key, $curl_ref = '') {\n if(empty($user_api_key)){\n throw new InvalidArgumentException(\"Expecting API key, none received in Geocoder::__construct\");\n }\n\n $this->api_key = $user_api_key; \n $this->api_url = 'http://api.mapserv.utah.gov/api/v1/geocode/%s/%s';\n $this->options = array(\n # Return the transfer as string\n CURLOPT_RETURNTRANSFER => true,\n\n # Specify content type (json)\n CURLOPT_HTTPHEADER => array('Content-type: application/json'),\n\n # Status 400 \"Referrer http header is missing\" without this line, but it needs to be the originating website \n CURLOPT_REFERER => (empty($curl_ref) ? $curl_ref : $_SERVER['HTTP_REFERER'])\n );\n }\n\n /**\n * Wrap our cURL call in a function.\n *\n * @param array $options\n * @return \n */\n private function curl ($options){\n $cUrl = curl_init();\n curl_setopt_array( $cUrl, $options );\n $response = curl_exec( $cUrl );\n curl_close( $cUrl );\n return $response;\n }\n\n /**\n * Locate returns {X, Y} coordinates based on address, zone and any other parameters\n *\n * @param string $address\n * @param string $zone\n * @param array $parameters [optional]\n * @return \n */\n public function locate ($address, $zone, $parameters = array()){\n $paramArray = array();\n $parameters['api_key'] = $this->api_key;\n\n foreach($parameters as $k => $v){\n $paramArray[] = $k . '=' . $v;\n }\n\n $this->options[CURLOPT_URL] = sprintf($this->api_url, rawurlencode($address), rawurlencode($zone) ) . \n '?' . implode('&', $paramArray);\n\n $response = $this->curl($this->options);\n $decoded = json_decode( $response );\n\n if($decoded->status != 200){\n throw new RuntimeException(\"Error status: \" . $decoded->status, $decoded->status);\n }\n\n return $decoded->result; \n }\n}\n</code></pre>\n\n<p>Then to initialize and use it, as follows:</p>\n\n<pre><code>try{\n $Geocoder = new Geocoder('insert-api-key-here');\n $result = $Geocoder->locate('123 South Main Street', 'SLC', array('acceptScore' => 90, 'spatialReference' => 4326));\n\n echo '<pre>' . print_r($result, 1) . '</pre>';\n} catch(Exception $e){\n if ($e instanceof InvalidArgumentException OR $e instanceof RuntimeException){\n die($e->getMessage());\n } else {\n die(\"Caught unrecognized exception: \" . $e->getMessage());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:52:01.250",
"Id": "75441",
"Score": "0",
"body": "The sample is supposed to print out the result for the person running the sample to see. It looks like you took that out?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:54:45.537",
"Id": "75442",
"Score": "0",
"body": "You mean the print_r() call? I did take that out (I'd imagine a developer would want to access the $result data rather than print_r it out, but can be put in right after `$result` is set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:02:14.960",
"Id": "75445",
"Score": "0",
"body": "well the idea is https://github.com/agrc/GeocodingSample/blob/master/README.md"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:06:39.720",
"Id": "75446",
"Score": "1",
"body": "I put in the print_r again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:07:50.350",
"Id": "75447",
"Score": "0",
"body": "what are your thoughts on using curl to make the request and setting the http referrer header? Is that legit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:12:00.470",
"Id": "75450",
"Score": "0",
"body": "you're also missing a ' after </pre>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:12:47.763",
"Id": "75451",
"Score": "0",
"body": "It's legit. The python version in your repo is using Request (http://docs.python-requests.org/en/latest/) which handles headers. PHP is a different monster and getting the user referer from $_SERVER is not a reliable method, so in this case, just hard code or pass in the requesting referer via the construct. EDIT:: I added the ability to pass in the referer, otherwise it defaults to _SERVER[HTTP_REFERER] if its empty. I would suggest you enforce passing it in via documentation."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:26:47.723",
"Id": "43623",
"ParentId": "43567",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:08:07.430",
"Id": "43567",
"Score": "6",
"Tags": [
"php",
"http"
],
"Title": "Geocode an address"
} | 43567 |
<p>I'm writing an algorithm to take in a sample list of sequences of events, calculate 1-step transitional probabilities from the sequences, forward or in reverse, then calculate the joint probability of n events occurring from those conditional probabilities.</p>
<p>Eg. if the sample list of sequences is:</p>
<blockquote>
<p>['TTAGCAGTCAGT', 'TCAGCGTTCGACTGA']</p>
</blockquote>
<p><code>cond_probs()</code> produces a dictionary <code>{'AT': n1, 'AG': n2, 'AA': n3, 'AC': n4, ... , 'TC': n16}</code>, where, for one, <code>n1 + n2 + n3 + n4 = 1</code>, from those sequences. In reverse, the transitional probabilities are calculated with the sequences in reverse.</p>
<p>With that dictionary, <code>exp_joint_probs()</code> produces another dictionary which, when n = 3, looks like <code>{'TTA': m1, 'TTC': m2, ..., 'GAC': m64}</code>, where <code>'TTA'</code> is calculated by <code>P('T') * P('TT') * P('TA')</code>. In reverse, it is <code>P('A') * P('AT') * P('TT')</code>, but the dictionary entry should still be <code>'TTA'</code>.</p>
<p>I'm wondering if my algorithm could be cleaner. I feel that perhaps using Numpy would make it much nicer, so a word from a Numpy expert would be great. I'm also looking for help double-checking the math.</p>
<pre><code>from collections import Counter
from itertools import product
def exp_joint_probs(seqList, n, reverse = 0):
probs = {}
counts = Counter(''.join(seqList))
states = counts.keys()
sumv = sum(counts.values())
initProbs = {c: counts[c] / float(sumv) for c in counts}
condProbs = cond_probs(seqList, reverse)
paths = product(counts.keys(), repeat = n)
for p in paths:
p = ''.join(p)
if reverse == 0:
probs[p] = initProbs[p[0]]
for i in range(n - 1):
probs[p] = probs[p] * condProbs.get((p[i], p[i + 1]), 0)
else:
probs[p] = initProbs[p[2]]
for i in range(n)[::-1][:-1]:
probs[p] = probs[p] * condProbs.get((p[i], p[i - 1]), 0)
return probs
def cond_probs(seqList, reverse = 0):
counts = {}
probs = {}
for seq in seqList:
if reverse:
for i in range(len(seq))[::-1][:-1]:
counts[seq[i],seq[i - 1]] = counts.get((seq[i], seq[i - 1]), 0) + 1
else:
for i in range(len(seq) - 1):
counts[seq[i],seq[i + 1]] = counts.get((seq[i], seq[i + 1]), 0) + 1
states = list(set(k[0] for k in counts.keys()))
for s in states:
if reverse:
sCounts = dict((k,v) for (k,v) in counts.items() if k[1] == s)
else:
sCounts = dict((k,v) for (k,v) in counts.items() if k[0] == s)
sumv = sum(sCounts.values())
probs.update({(k,float(v)/sumv) for (k, v) in sCounts.items()})
return probs
</code></pre>
| [] | [
{
"body": "<p>Counting in Python is best done using <a href=\"http://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a>.</p>\n\n<p>The problem you have described sounds like a Markov chain, and the probabilities would best be represented as a <a href=\"http://en.wikipedia.org/wiki/Markov_chain#Example\" rel=\"nofollow\">Markov chain transition matrix</a>. You could then obtain the joint probabilities using matrix multiplication.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:18:48.463",
"Id": "75430",
"Score": "0",
"body": "Yes - I'm aware it is a Markov chain! Would be pretty impressive I knew the phrase '1-step transition' without knowing that. But what you say isn't true. Matrix multiplication of transition matrices would result in n-step transition matrices, which give probabilities of going from one state to another in n steps, considering every possible state it can go through in between. Here I want specific states in between."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T04:55:10.823",
"Id": "43576",
"ParentId": "43568",
"Score": "2"
}
},
{
"body": "<p>I'm just going to look at <code>cond_probs</code> here. You'll see that there's plenty in this function for one answer.</p>\n\n<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>The line <code>return probs</code> has the wrong indentation. Copy/paste error?</p></li>\n<li><p>There are no docstrings. What do these functions do and how do I call them? (The text from your question would be a good starting-point for docstrings.)</p></li>\n<li><p>There are no test cases. This is the kind of code that would benefit from some <a href=\"http://docs.python.org/3/library/unittest.html\">unit tests</a> and/or <a href=\"http://docs.python.org/3/library/doctest.html\">doctests</a>.</p></li>\n<li><p>You write, \"<code>cond_probs()</code> produces a dictionary <code>{'AT': n1, 'AG': n2, 'AA': n3, 'AC': n4, ... , 'TC': n16}</code>\" but when I run it the dictionary has tuples for keys, not strings:</p>\n\n<pre><code>>>> cond_probs(['AAC'])\n{('A', 'C'): 0.5, ('A', 'A'): 0.5}\n</code></pre></li>\n<li><p>I don't understand the behaviour when <code>reverse=True</code>. You write, \"In reverse, the transitional probabilities are calculated with the sequences in reverse\" but this doesn't seem to be the case:</p>\n\n<pre><code>>>> cond_probs(['CAA'], reverse=True)\n{('A', 'A'): 1.0}\n</code></pre>\n\n<p>What has happened to <code>C</code>? This looks wrong to me.</p>\n\n<p>If I were writing this, I'd implement <code>cond_probs</code> to run only in the forward direction; to do the reverse direction I would pass in reversed sequences.</p></li>\n<li><p>Prefer using <code>True</code> and <code>False</code> for Booleans, not <code>1</code> and <code>0</code>. So the second parameter to <code>cond_probs</code> should be <code>reverse=False</code>.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>counts = {}\n# ...\ncounts[X] = counts.get(X, 0) + 1\n</code></pre>\n\n<p>use <a href=\"http://docs.python.org/3/library/collections.html#collections.Counter\"><code>collections.Counter</code></a> and write:</p>\n\n<pre><code>counts = Counter()\n# ...\ncounts[X] += 1\n</code></pre>\n\n<p>(But see below for how to use <a href=\"http://docs.python.org/3/library/collections.html#collections.Counter.update\"><code>collections.Counter.update</code></a>.)</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>range(len(seq))[::-1][:-1]\n</code></pre>\n\n<p>write:</p>\n\n<pre><code>range(len(seq) - 1, 0, -1)\n</code></pre>\n\n<p>(But see below for how to avoid this.)</p></li>\n<li><p>Prefer iteration over elements of sequences instead of iteration over their indexes. So instead of:</p>\n\n<pre><code>for i in range(len(seq) - 1):\n counts[seq[i],seq[i + 1]] = counts.get((seq[i], seq[i + 1]), 0) + 1\n</code></pre>\n\n<p>use <a href=\"http://docs.python.org/3/library/functions.html#zip\"><code>zip</code></a>:</p>\n\n<pre><code>for t in zip(seq, seq[1:]):\n counts[t] += 1\n</code></pre>\n\n<p>or, even more simply, using <a href=\"http://docs.python.org/3/library/collections.html#collections.Counter.update\"><code>collections.Counter.update</code></a>:</p>\n\n<pre><code>counts.update(zip(seq, seq[1:]))\n</code></pre>\n\n<p>(If you are concerned about memory use, then you could use <a href=\"http://docs.python.org/3/library/itertools.html#itertools.islice\"><code>itertools.islice</code></a> and write <code>islice(seq, 1, None)</code> instead of <code>seq[1:]</code> to avoid the copy.)</p></li>\n<li><p>In this code:</p>\n\n<pre><code>for s in states:\n sCounts = dict((k,v) for (k,v) in counts.items() if k[0] == s)\n</code></pre>\n\n<p>you iterate over the whole of <code>counts</code> for every state, collecting the ones you want. It would be more efficient to iterate only over the transitions from <code>s</code>. See below for how this would look.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>def cond_probs_2(sequences):\n \"\"\"Calculate 1-step transitional probabilities from sequences.\n Return dictionary mapping transitions to probabilities.\n\n >>> sequences = ['ACABC', 'ABCAB']\n >>> sorted(cond_probs_2(sequences).items())\n ... # doctest: +NORMALIZE_WHITESPACE\n [(('A', 'B'), 0.75),\n (('A', 'C'), 0.25),\n (('B', 'C'), 1.0),\n (('C', 'A'), 1.0)]\n\n \"\"\"\n counts = Counter()\n entries = set()\n for seq in sequences:\n entries.update(seq)\n for a, b in zip(seq, islice(seq, 1, None)):\n counts[a, b] += 1\n probs = {}\n for a in entries:\n suma = float(sum(counts[a, b] for b in entries))\n if suma != 0:\n probs.update(((a, b), counts[a, b] / suma) for b in entries\n if counts[a, b])\n return probs\n</code></pre>\n\n<p>This is about 30% faster than your code:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> from random import choice\n>>> data = ''.join(choice('ACGT') for _ in range(1000000))\n>>> cond_probs([data]) == cond_probs_2([data])\nTrue\n>>> timeit(lambda:cond_probs([data]), number=1) # yours\n1.4706195190083236\n>>> timeit(lambda:cond_probs_2([data]), number=1) # mine\n0.9721288200234994\n</code></pre>\n\n<h3>3. Rewriting in NumPy</h3>\n\n<p>Here's how I'd go about this kind of task in NumPy. NumPy works best with fixed-size numeric data, so I'd encode the input as small integers:</p>\n\n<pre><code>>>> import numpy as np\n>>> data = 'TTAGCAGTCAGTTCAGCGTTCGACTGA'\n>>> distinct = set(data)\n>>> coding = {j:i for i, j in enumerate(distinct)}\n>>> coding\n{'A': 0, 'C': 1, 'T': 2, 'G': 3}\n>>> coded_data = np.fromiter((coding[i] for i in data), dtype=np.uint8)\n>>> coded_data\narray([2, 2, 0, 3, 1, 0, 3, 2, 1, 0, 3, 2, 2, 1, 0, 3, 1, 3, 2, 2, 1, 3, 0,\n 1, 2, 3, 0], dtype=uint8)\n</code></pre>\n\n<p>(I've chosen the type <code>np.uint8</code> here because there are only four different characters in the input strings. You might need to choose a different type.)</p>\n\n<p>Then you can encode adjacent pairs of numbers from 0–3 as a single number from 0–15, count the number of occurrences of each pair using <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html\"><code>numpy.bincount</code></a>, and decode the result using <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html\"><code>numpy.reshape</code></a>:</p>\n\n<pre><code>>>> n = len(distinct)\n>>> pairs = coded_data[:-1] + n * coded_data[1:]\n>>> counts = np.bincount(pairs, minlength=n*n).reshape(n, n)\n>>> counts\narray([[0, 3, 1, 2],\n [1, 0, 3, 2],\n [0, 1, 3, 3],\n [4, 2, 1, 0]])\n</code></pre>\n\n<p>This array represents the transition table:</p>\n\n<pre><code> source \n │ A C T G\n ──┼───────────\n A │ 0, 3, 1, 2\ndest C │ 1, 0, 3, 2\n T │ 0, 1, 3, 3\n G │ 4, 2, 1, 0\n</code></pre>\n\n<p>You can then compute the transition probabilities by dividing each element by the sum of its column:</p>\n\n<pre><code>>>> counts / counts.sum(axis=0)\narray([[ 0. , 0.5 , 0.125 , 0.28571429],\n [ 0.2 , 0. , 0.375 , 0.28571429],\n [ 0. , 0.16666667, 0.375 , 0.42857143],\n [ 0.8 , 0.33333333, 0.125 , 0. ]])\n</code></pre>\n\n<p>Here's the above as a function:</p>\n\n<pre><code>from itertools import chain\nimport numpy as np\n\ndef cond_probs_np(sequences):\n \"\"\"Calculate 1-step transitional probabilities from sequences.\n Return dictionary mapping transitions to probabilities.\n\n >>> sequences = ['ACABC', 'ABCAB']\n >>> sorted(cond_probs_np(sequences).items())\n ... # doctest: +NORMALIZE_WHITESPACE\n [(('A', 'B'), 0.75),\n (('A', 'C'), 0.25),\n (('B', 'C'), 1.0),\n (('C', 'A'), 1.0)]\n\n \"\"\"\n distinct = set(chain.from_iterable(sequences))\n n = len(distinct)\n assert(n < 256) # so that they will fit in an np.uint8\n coding = {j:i for i, j in enumerate(distinct)}\n counts = np.zeros((n, n))\n for seq in sequences:\n coded_seq = np.fromiter((coding[i] for i in seq), dtype=np.uint8)\n pairs = coded_seq[:-1] + n * coded_seq[1:]\n counts += np.bincount(pairs, minlength=n*n).reshape(n, n)\n totals = counts.sum(axis=0)\n totals[totals == 0] = 1 # avoid division by zero\n probs = counts / totals\n return {(a, b): p for a, b in product(distinct, repeat=2) \n for p in (probs[coding[b], coding[a]],) if p}\n</code></pre>\n\n<p>And this is about seven times faster than your original code:</p>\n\n<pre><code>>>> cond_probs([data]) == cond_probs_np([data])\nTrue\n>>> timeit(lambda:cond_probs_np([data]), number=1)\n0.2206433709943667\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-12T02:11:48.957",
"Id": "304111",
"Score": "0",
"body": "Checking this question three years on, I had missed this answer entirely somehow!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T00:34:48.143",
"Id": "45049",
"ParentId": "43568",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "45049",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:27:49.587",
"Id": "43568",
"Score": "11",
"Tags": [
"python",
"algorithm",
"numpy",
"bioinformatics"
],
"Title": "Calculating the joint probability of n events from a sample sequence of occurrences"
} | 43568 |
<p>For this problem, I came up with this ugly solution of appending the characters to the output and in case there is adjacent duplicate deleting from the output. Considering <code>StringBuilder.deleteCharAt(i)</code> is O(N), performance is O(N) + O(N) = O(N).</p>
<p>Please critique this, if this is a right way.</p>
<pre><code>public static String removeDuplicate(String s) {
StringBuilder builder = new StringBuilder();
char lastchar = '\0';
for (int i = 0; i < s.length(); i++) {
String str = builder.toString();
if (!str.equals("")
&& (str.charAt(str.length() - 1) == s.charAt(i))) {
builder.deleteCharAt(str.length() - 1);
} else if (s.charAt(i) != lastchar)
builder.append(s.charAt(i));
lastchar = s.charAt(i);
}
return builder.toString();
}
</code></pre>
<p>Sample input outputs: </p>
<blockquote>
<p>Input: azxxzy <br>
Output: ay</p>
<p>Input: caaabbbaacdddd <br>
Output: Empty String</p>
<p>Input: acaaabbbacdddd <br>
Output: acac</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:31:46.990",
"Id": "75358",
"Score": "6",
"body": "Why does it have to be recursive? ... and if it has to be recursive, why is your code ***not*** recursive?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:34:25.827",
"Id": "75359",
"Score": "1",
"body": "Additionally, what does it mean to remove duplicates? If I give your code the word `messy` it returns `mey`... I was expecting `mesy`... which one is right? Why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T05:58:18.003",
"Id": "75368",
"Score": "0",
"body": "@rolfl The examples added in [Rev 2](http://codereview.stackexchange.com/revisions/43569/2) clarify both issues. `\"messy\"` → `\"mey\"`. \"Recursively remove\" refers to the problem statement, not the implementation."
}
] | [
{
"body": "<h2>General</h2>\n<p>Your code formatting is all over the place. You should use consistent and structured indentation. See the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\" rel=\"nofollow noreferrer\">Java Code-Style guide for, well, guidance</a>.</p>\n<p>if I take your code, and re-format it (Eclipse, <kbd>Ctrl</kbd><kbd>A</kbd> and <kbd>Ctrl</kbd><kbd>shift</kbd><kbd>F</kbd>), it looks like:</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code>public static String removeDuplicate(String s) {\n StringBuilder builder = new StringBuilder();\n char lastchar = '\\0';\n for (int i = 0; i < s.length(); i++) {\n String str = builder.toString();\n if (!str.equals("") && (str.charAt(str.length() - 1) == s.charAt(i))) {\n builder.deleteCharAt(str.length() - 1);\n } else if (s.charAt(i) != lastchar)\n builder.append(s.charAt(i));\n lastchar = s.charAt(i);\n }\n return builder.toString();\n}\n</code></pre>\n</blockquote>\n<p>At least this allows us to see what you are doing.</p>\n<h2>Algorithm</h2>\n<p>A nice algorithm will take data from the input string, and add it to the output if it should be added. A system where you do multiple conversions, add things, and remove things, is complicated, and hard to follow.</p>\n<p>Additionally, the null character <code>\\0</code> is actually a valid character in Java, so you may have (an extremely rare) bug.</p>\n<p>I do not like that your code is removing all the duplicate values, it seems more practical to remove all but one of the duplicates, but you do not explain why it is supposed to be this way.</p>\n<h2>More Information required</h2>\n<p>The above, in itself, is a review, but, if you update your question with the requested details:</p>\n<ul>\n<li>recursion yes/no/why?</li>\n<li>dedup all, or all-but-one?</li>\n</ul>\n<p>then I can add suggestions as to how to solve this in a more efficient way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T01:10:28.340",
"Id": "75361",
"Score": "0",
"body": "Actually I had issue while posting the code here, thats why formatting is all over the place. Anyways I follow Google style sheet in my eclipse, so it will be all right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T01:11:55.677",
"Id": "75362",
"Score": "0",
"body": "The question was : to remove adjacent duplicates from the code. I will post the valid inputs outputs in the question"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T01:00:56.170",
"Id": "43572",
"ParentId": "43569",
"Score": "4"
}
},
{
"body": "<p>The problem is not that <code>StringBuilder.deleteCharAt()</code>is O(<em>n</em>) — you only ever use it to strip the last character. Rather, it's your <code>builder.toString()</code> that is problematic. It's an O(<em>n</em>) operation that is invoked in a loop up to <em>n</em> times.</p>\n\n<p>Rather than using a <code>StringBuilder</code>, I recommend manipulating a <code>char[]</code> array directly. <del>The problem, as you pointed out, is that <code>StringBuilder.deleteCharAt(i)</code> is O(<em>n</em>) because it shifts the rest of the string over.</del> By doing your own accounting, you can just build the string correctly the first time.</p>\n\n<pre><code>public static String removeDuplicates(String s) {\n if (s.isEmpty()) {\n return s;\n }\n char[] buf = s.toCharArray();\n char lastchar = buf[0];\n\n // i: index of input char\n // o: index of output char\n int o = 1;\n for (int i = 1; i < buf.length; i++) {\n if (o > 0 && buf[i] == buf[o - 1]) {\n lastchar = buf[o - 1];\n while (o > 0 && buf[o - 1] == lastchar) {\n o--;\n }\n } else if (buf[i] == lastchar) {\n // Don't copy to output\n } else {\n buf[o++] = buf[i];\n }\n }\n return new String(buf, 0, o);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T05:55:00.427",
"Id": "43578",
"ParentId": "43569",
"Score": "3"
}
},
{
"body": "<p>Ultimately you have to remove the duplicates from the String without using HashSet. One technique is to sort the char array first. The complete code is:</p>\n\n<pre><code>public class Test3 {\n public static void main(String[] args) {\n String str = \"ABBCDAABBBBBBBBOR\";\n char[] ca = str.toCharArray();\n\n Arrays.sort(ca);\n\n String a = new String(ca);\n System.out.println(\"original => \" + a);\n int i = 0 ;\n StringBuffer sbr = new StringBuffer();\n while(i < a.length()) {\n if(sbr.length() == 0 ) {sbr.append(a.charAt(i));}\n if(a.charAt(i) == sbr.charAt(sbr.length() -1)) {i++ ;}\n else {sbr.append(a.charAt(i));}\n }//while\n\n System.out.println(\"After removing the duplicates => \" + sbr);\n }//main\n}// end1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-20T19:45:56.763",
"Id": "192595",
"ParentId": "43569",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "43578",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:28:58.540",
"Id": "43569",
"Score": "2",
"Tags": [
"java",
"algorithm",
"performance"
],
"Title": "Remove all adjacent duplicates"
} | 43569 |
<p>Here is the question: find the largest palindrome from a string.</p>
<p>Ex:</p>
<pre><code>ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD
</code></pre>
<p>Result:</p>
<pre><code>ILOVEUEVOLI
</code></pre>
<p>I am not sure of the efficiency of the algorithm.</p>
<pre><code>static void Main(string[] args)
{
var str = "ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD";
var longestPalindrome = GetLongestPalindrome(str);
Console.WriteLine(longestPalindrome);
Console.Read();
}
private static string GetLongestPalindrome(string input)
{
int rightIndex = 0, leftIndex = 0;
List<string> paliList = new List<string>();
string currentPalindrome = string.Empty;
string longestPalindrome = string.Empty;
for (int currentIndex = 1; currentIndex < input.Length - 1; currentIndex++)
{
leftIndex = currentIndex - 1;
rightIndex = currentIndex + 1;
while (leftIndex >= 0 && rightIndex < input.Length)
{
if (input[leftIndex] != input[rightIndex])
{
break;
}
currentPalindrome = input.Substring(leftIndex, rightIndex - leftIndex + 1);
paliList.Add(currentPalindrome);
leftIndex--;
rightIndex++;
}
}
var x = (from c in paliList
select c).OrderByDescending(w => w.Length).First();
return x;
}
</code></pre>
| [] | [
{
"body": "<p>Your basic algorithm seems pretty efficient, but building a list then sorting it just to find the longest one isn't very efficient. It would be much more efficient to just keep track of the longest palindrome:</p>\n\n<pre><code> private static string GetLongestPalindrome(string input)\n {\n int rightIndex = 0, leftIndex = 0;\n var x = \"\";\n string currentPalindrome = string.Empty;\n string longestPalindrome = string.Empty;\n for(int currentIndex = 1; currentIndex < input.Length - 1; currentIndex++)\n {\n leftIndex = currentIndex - 1;\n rightIndex = currentIndex + 1;\n while(leftIndex >= 0 && rightIndex < input.Length)\n {\n if(input[leftIndex] != input[rightIndex])\n {\n break;\n }\n currentPalindrome = input.Substring(leftIndex, rightIndex - leftIndex + 1);\n if(currentPalindrome.Length > x.Length)\n x = currentPalindrome;\n leftIndex--;\n rightIndex++;\n }\n }\n return x;\n }\n</code></pre>\n\n<p>In my tests this is 3 times faster.</p>\n\n<p>I hate to break this to you, but there is a bug in your code, which will probably mean rewriting your algorithm. You algorithm assumes that the palindrome will be an odd number of characters. However, a palindrome can be an even number of characters and your code won't find it if it is.</p>\n\n<p>Here's some code that will find the longest palindrome regardless:</p>\n\n<pre><code>static string LargestPalindrome(string input)\n{\n string output = \"\";\n int minimum = 2;\n for(int i = 0; i < input.Length - minimum; i++)\n {\n for(int j = i + minimum; j < input.Length - minimum; j++)\n {\n string forstr = input.Substring(i, j - i);\n string revstr = new string(forstr.Reverse().ToArray());\n if(forstr == revstr && forstr.Length > minimum)\n {\n output = forstr;\n minimum = forstr.Length;\n }\n }\n }\n return output;\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>The above code has a bug. Here it is reworked:</p>\n\n<pre><code>static string LargestPalindrome(string input)\n{\n int longest = 0;\n int limit = input.Length;\n for (int i = 0; i < limit; i++)\n {\n for (int j = limit-1; j > i; j--)\n {\n string forStr = input.Substring(i, j - i);\n string revStr = new string(forStr.Reverse().ToArray());\n if (forStr == revStr && forStr.Length > longest)\n {\n return forStr;\n }\n }\n }\n return \"\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:27:38.650",
"Id": "75379",
"Score": "0",
"body": "A tiny optimisation : `forstr.Length` is `j-i`. Thus, the test `forstr.Length > minimum` can be rewritten `j-i > minimum` which is `j > i + minimum`. This condition is false on first iteration so either this is wrong or you can skip first iteration. Also, I think your indices `i` and `j` should go in opposite direction so that you can stop the inner loop when you find a palindrom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-29T19:59:34.703",
"Id": "237584",
"Score": "0",
"body": "This code (the final code block in the answer) is broken on the input of \"addcdxddf\" in my testing, returns empty string when it should return \"dcd\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-01T05:10:08.197",
"Id": "237782",
"Score": "0",
"body": "@Haney - The challenge I made it for wouldn't accept a palindrome length of less than 4. I've edited it to accept palindromes of 3 characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T18:02:01.460",
"Id": "386432",
"Score": "0",
"body": "Although I marked it as an answer. But after many years, I test it again. It failed for the string `cbbd`. The expected answer is `bb`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T07:34:59.050",
"Id": "386527",
"Score": "0",
"body": "@Love - As per my comment to Haney, this code isn't designed to find palindromes of less than 3 characters"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T14:43:42.483",
"Id": "386597",
"Score": "0",
"body": "@Love - I looked at the code again and reworked it to find the longest palindrome of any length;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T12:37:45.207",
"Id": "428369",
"Score": "0",
"body": "is this program bug free ? I am expecting longest palindrome in `mzmqnnrkurfmmfrukrnnqsm` as `nnrkurfmmfrukrnn` where code above returns `mzm`"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-06T02:04:28.983",
"Id": "43574",
"ParentId": "43571",
"Score": "11"
}
},
{
"body": "<p>For what its worth, here is another algorithm. It tries to find the largest palindrome by searching for the largest possible palindrome first, and if not found, gradually for smaller ones. Not tested for speed but should be significantly faster.</p>\n\n<pre><code>static string FindLargestPalindrome(string data, int minLength) {\n int length = data.Length;\n\n // test from max length to min length\n for (int size = length; size >= minLength; --size)\n // establish attempt bounds and test for the first palindrome substring of given size\n for (int attemptIdx = 0, attemptIdxEnd = length - size + 1; attemptIdx < attemptIdxEnd; ++attemptIdx)\n if (IsPalindrome(data, attemptIdx, size))\n return data.Substring(attemptIdx, size);\n\n return null;\n}\n\nstatic bool IsPalindrome(string data, int idxStart, int count) {\n int idxEnd = idxStart+count-1;\n\n while (idxStart < idxEnd && data[idxStart] == data[idxEnd]) {\n ++idxStart;\n --idxEnd;\n }\n\n return idxStart >= idxEnd;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:33:17.573",
"Id": "75608",
"Score": "0",
"body": "It is a good idea. Can you reformat the code to make it readable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:48:24.547",
"Id": "75638",
"Score": "0",
"body": "Thanks for recognizing the algorithm idea. Feel free to reformat the code at you end, based on your personal preferences and readability criteria."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T18:28:08.000",
"Id": "159516",
"Score": "0",
"body": "Not a review, It's a code dump"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:01:18.720",
"Id": "43675",
"ParentId": "43571",
"Score": "5"
}
},
{
"body": "<p>With all due respect to solutions offered, the solutions offered here are naive (naive in the sense of something that someone unfamiliar with computer science algorithms would think of). The most optimal solution will most probably be implemented using a dynamic programming approach (at the risk of stating the obvious I must emphasize that dynamic programming is not a language but an algorithmic concept that can be implemented in any language) where the program recursively finds smaller palindromes and combines them into larger ones when possible. The main problem with solutions offered here is that many sub-problems (which are essentially the same) are computed over and over and over and over again (you get the idea).</p>\n\n<p>Actually, I just did a search for this and an elegant solution using dynamic programming is offered <a href=\"http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/\" rel=\"nofollow\">here</a>. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-28T10:32:58.923",
"Id": "159638",
"Score": "0",
"body": "Links can rot, please incorporate the main points from your link into the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-28T10:52:10.913",
"Id": "159645",
"Score": "0",
"body": "The gist of my comment is that this problem has an elegant solution using dynamic programming approach. I would not be able to do justice to dynamic programming or the solution to this problem using that approach in this context. In case of a rotted link, I suggest that interested reader do a search on \"dynamic programming\" + \"finding the largest palindrome\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T18:49:23.287",
"Id": "88156",
"ParentId": "43571",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43574",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:49:39.007",
"Id": "43571",
"Score": "17",
"Tags": [
"c#",
"algorithm",
"palindrome"
],
"Title": "Return the largest palindrome from the string"
} | 43571 |
<p>I'm comparing two distinct instances and if they are not the same I save to the dB, so I've given snippet of code below of the way I am comparing these instances, I realize I could use reflection and generalize but short of using reflections is there any other way I could optimize the code or make it neater? </p>
<pre><code> public class QuestionModel
{
private string _selectedId = string.Empty;
public string SelectedId
{
get { return _selectedId; } set { _selectedId = value; }
}
private List<UserResponseModel> _userResponse;
public List<UserResponseModel> UserResponses
{
get { return _userResponse ?? (_userResponse = new List<UserResponseModel>()); }
set { _userResponse = value; }
}
}
public class UserResponseModel
{
public string QuestionId { get; set; }
public string QuestionText { get; set; }
public bool IsChecked { get; set; }
public int? Value { get; set; }
public string TextValue { get; set; }
public Byte[] Content { get; set; }
public string FilePath { get; set; }
public int? Points { get; set; }
public int? InputType { get; set; }
public bool? IsCheckedRadioButton1 { get; set; }
public bool? IsCheckedRadioButton2 { get; set; }
public bool? IsCheckedRadioButton3 { get; set; }
public bool? IsCheckedRadioButton4 { get; set; }
public bool? IsCheckedRadioButton5 { get; set; }
public bool IsCheckedCheckbox1 { get; set; }
public bool IsCheckedCheckbox2 { get; set; }
private string _selectedId = string.Empty;
public string SelectedId
{
get { return _selectedId; }
set { _selectedId = value; }
}
}
//snippet of code that compares instances of QuestionModel
QuestionModel questionModelInDb = null;
if (existingResponsesInDb.Any())
questionModelInDb = UtilityFunctions.MapResponsestoUserResponses(existingResponsesInDb);
if (questionModelInDb == null) return false;
var isSame = questionModelInDb.SelectedId == questionModel.SelectedId;
if (!isSame) return false;
var index = 0;
foreach (var response in questionModel.UserResponses)
{
if (isSame)
{
isSame = response.IsChecked == questionModelInDb.UserResponses[index].IsChecked;
isSame = response.IsCheckedCheckbox1 ==
questionModelInDb.UserResponses[index].IsCheckedCheckbox1 && isSame;
isSame = response.IsCheckedCheckbox2 ==
questionModelInDb.UserResponses[index].IsCheckedCheckbox2 &&
isSame;
isSame = response.IsCheckedRadioButton1 ==
questionModelInDb.UserResponses[index].IsCheckedRadioButton1 &&
isSame;
isSame = response.IsCheckedRadioButton2 ==
questionModelInDb.UserResponses[index].IsCheckedRadioButton2 &&
isSame;
isSame = response.IsCheckedRadioButton3 ==
questionModelInDb.UserResponses[index].IsCheckedRadioButton3 &&
isSame;
isSame = response.IsCheckedRadioButton4 ==
questionModelInDb.UserResponses[index].IsCheckedRadioButton4 &&
isSame;
isSame = response.IsCheckedRadioButton5 ==
questionModelInDb.UserResponses[index].IsCheckedRadioButton5 &&
isSame;
isSame = response.SelectedId ==
questionModelInDb.UserResponses[index].SelectedId &&
isSame;
isSame = (response.TextValue ?? String.Empty) ==
(questionModelInDb.UserResponses[index].TextValue ?? String.Empty) &&
isSame;
isSame = (response.Value ?? 0) ==
(questionModelInDb.UserResponses[index].Value ?? 0) &&
isSame;
index++;
}
else
break;
}
return isSame;
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Property names like <code>IsCheckedRadioButton1</code> are completely useless as they in no way indicate the purpose of it's intended usage or what it represents. Given that it's probably bound to a radio button it means it's very likely some sort of option to chose from. My guess you could replace all those <code>IsCheckedRadioButtonX</code> properties with a single enum property which states the option which has been chosen. At the very least all those properties should be renamed to something meaningful.</p></li>\n<li><p>You should move the comparison into a method on the<code>UserResponseModel</code> like <code>IsSameAs(UserReponseModel other)</code>. Then your main loop becomes:</p>\n\n<pre><code>foreach (var response in questionModel.UserResponses)\n{\n isSame = isSame && response.IsSameAs(questionModelInDb.UserResponses[index]);\n\n if (!isSame) break; \n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:52:08.440",
"Id": "75422",
"Score": "0",
"body": "I thought about having descriptive property names - but here the same model is used across multiple views, this is a survey application with close to 100 questions - each question having options, text boxes - numeric &/or alphanumeric - quick followup question would reflection be a better solution here? - in terms of elegance/performance? - or is it more of personal choice for elegance"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T08:24:35.053",
"Id": "43582",
"ParentId": "43577",
"Score": "3"
}
},
{
"body": "<p>If you want to compare two <code>List</code>s, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.sequenceequal%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Enumerable.SequenceEqual</code></a></p>\n\n<pre><code>public class UserResponseModelComparer : IEqualityComparer<UserResponseModel> {\n\n public bool Equals(UserResponseModel userResponse1, UserResponseModel userResponse2) {\n //... compare the two responses\n }\n\n public int GetHashCode(UserResponseModel userResponse) {\n // .. calculate hash code... \n // see guidelines here: \n // http://stackoverflow.com/questions/462451/gethashcode-guidelines-in-c-sharp\n }\n}\n\nreturn Enumerable.SequenceEqual(questionModel.UserResponses, \n questionModelInDb.UserResponses, \n new UserResponseModelComparer());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:19:10.100",
"Id": "75476",
"Score": "0",
"body": "Ups sorry, haven't had my coffee yet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:57:55.010",
"Id": "75800",
"Score": "1",
"body": "+1. Very Object Oriented; hits OO buttons: \"single responsibility\", \"push details down\", \"encapsulation\". And I expect lots of that busy code in the question will simply melt away."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:02:43.890",
"Id": "43596",
"ParentId": "43577",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T05:18:00.810",
"Id": "43577",
"Score": "4",
"Tags": [
"c#",
"algorithm",
".net",
"reflection"
],
"Title": "comparing objects; optimize code short of using reflection"
} | 43577 |
<blockquote>
<p>Regex parser which follows the following rule</p>
<ol>
<li><code>.</code> (dot) means a any single character match</li>
<li><code>*</code> (star) means 0 or more character match</li>
<li><code>?</code> (question) means previous char is an option i.e <code>colou?r</code> matches <code>color</code> and <code>colour</code>.</li>
</ol>
</blockquote>
<p>A large feedback has been taken from <a href="https://codereview.stackexchange.com/questions/35552/regex-parser-request-for-review-and-optimization">here</a>.</p>
<p>I'm looking for code review, optimizations, best practices. I also still get confused with complexity. Let's say regex string has length of <code>m</code> and string has length of <code>n</code>. Then it appears the complexity would be <code>O(n! * (n-1)! * ... (n-m)!)</code></p>
<p></p>
<pre><code>public final class Regex {
private Regex() {};
private static enum Wildcards {
STAR('*'), DOT('.'), QUESTION('?');
private final char wildCard;
Wildcards (char wildCard) {
this.wildCard = wildCard;
}
public char getWildCard() {
return this.wildCard;
}
}
/**
* The index of first non-star character following first occurence of star
* eg: if regex is a**b, then index is startIndex is 1 and return value is 3 (index of b)
*
* @param regex : the regex string.
* @param firstStarIndex : index of the first occurene of * after a non *, eg: a**b, then starIndex would be 1
* @return : the index of first non-star character following first occurence of star
*/
private static final int getNonWildCardIndex(String regex, int firstQuestionIndex, Wildcards foo) {
for (int k = firstQuestionIndex; k < regex.length(); k++) {
if (regex.charAt(k) != foo.getWildCard()) {
return k;
}
}
return regex.length();
}
/**
* A valid wildcard tail is a tail of ?' s and *'s.
* Its a tail which matches 0 characters
*
* @param regex The input regex
* @param index The index from which the wild card check must be initiated.
* @return true is the resulting wildcard matches empty string.
*/
private static final boolean validWildCardTail(String regex, int index) {
assert regex != null;
for (int i = index; i < regex.length(); i++) {
if (regex.charAt(i) != Wildcards.QUESTION.getWildCard() &&
regex.charAt(i) != Wildcards.STAR.getWildCard()) {
return false;
}
}
return true;
}
/**
* Checks if we have scanned the entire string for regex match.
* If not, it means some characters from strPos in the input string do not match regex.
*
* @param str The input string.
* @param strPos The current string index
* @return true if entire string has been scanned for regex match.
*/
private static final boolean endOfStringCheck(String str, int strPos) {
return str.length() == strPos;
}
/**
* Checks if the regex matches matches the empty string. At this point input string has been traversed.
* Only the regex needs to be travelled to.
*
* @param regex The input regex
* @param regexPos The current regex index.
* @return true if regex matches the input string
*/
private static final boolean endOfRegexCheck (String regex, int regexPos) {
if (regexPos == regex.length()) return true;
// example: regex: "colou?", string: "colou"
if (regex.charAt(regexPos) == Wildcards.QUESTION.getWildCard() ||
// example: regex: "colou?", string: "colo"
(regexPos < (regex.length() - 1)) && regex.charAt(regexPos + 1) == Wildcards.QUESTION.getWildCard() ||
// example: regex: "colo*", string: "colour"
regex.charAt(regexPos) == Wildcards.STAR.getWildCard()) {
// regex : colou?**.***, string : colou
// check the `regexPos + 1 argument`, its very sensible. regixPos is already checked. thus we start check from the next position.
return validWildCardTail(regex, regexPos + 1);
} else {
return false;
}
}
private static final boolean matcher(String regex, int regexPos, String str, int strPos) {
assert regexPos >= 0 && regexPos <= regex.length();
assert strPos >= 0 && strPos <= str.length(); // it should break when its == strPos, > strpos is an impossible condition.
while ((regexPos < regex.length() && strPos < str.length())) {
if (regex.charAt(regexPos) == str.charAt(strPos) || regex.charAt(regexPos) == Wildcards.DOT.getWildCard()) {
regexPos++;
strPos++;
}
/*
* nested if else is better than non-nested.
* http://www.macs.hw.ac.uk/~pjbk/pathways/cpp1/node99.html
*/
else if (regex.charAt(regexPos) == Wildcards.STAR.getWildCard()) {
int nextNonStarIndex = getNonWildCardIndex(regex, regexPos, Wildcards.STAR);
/*
* For a case where regex and string, both have not yet reached the last char but regex is all *'s till end.
* Eg: Regext abc*** && String is abcxyz
*/
if (nextNonStarIndex == regex.length()) return true;
while (strPos < str.length()) {
if (matcher(regex, nextNonStarIndex, str, strPos)) return true;
strPos = strPos + 1;
}
return false;
} else {
// regex : colou?r
// string : colour
if (regex.charAt(regexPos) == Wildcards.QUESTION.getWildCard()) {
return matcher(regex, getNonWildCardIndex(regex, regexPos, Wildcards.QUESTION), str, strPos);
}
// regex: colou?r
// regex: color
if (regexPos < (regex.length() - 1) && regex.charAt(regexPos + 1) == Wildcards.QUESTION.getWildCard()) {
return matcher(regex, getNonWildCardIndex(regex, regexPos + 1, Wildcards.QUESTION), str, strPos);
}
return false;
}
}
return endOfStringCheck(str, strPos) && endOfRegexCheck(regex, regexPos);
}
/**
* Matches the regex with the string with the following rules.
* * means 0 or more number of any char matches
* . means just a single any char match.
* ? means the immediate preceding character can exist or not. eg: colour? matches color and colour
*
* @param regex : The regex to match the string again
* @param str : The string to be matched.
* @return : true / false
*/
public static final boolean matches(String regex, String str) {
return matcher(regex, 0, str, 0);
}
public static void main(String[] args) {
Assert.assertTrue(Regex.matches("colou?**rs", "colours"));
Assert.assertTrue(Regex.matches("colou?**rs", "colors"));
Assert.assertTrue(Regex.matches("colou**?rs", "colours"));
// Assert.assertTrue(RegexToy.matches("colou**?rs", "colors")); <---- exlusive case.
Assert.assertTrue(Regex.matches("colou?**r", "colour"));
Assert.assertTrue(Regex.matches("colou?**r", "color"));
Assert.assertTrue(Regex.matches("colou?*", "colou"));
Assert.assertTrue(Regex.matches("colou?*", "colo"));
Assert.assertTrue(Regex.matches("colou?r", "colour"));
Assert.assertTrue(Regex.matches("colou?r", "color"));
Assert.assertTrue(Regex.matches("colou?*?r", "colour"));
Assert.assertTrue(Regex.matches("colou?*?r", "color"));
// Success cases
Assert.assertTrue(Regex.matches("", ""));
Assert.assertTrue((Regex.matches("***", "")));
String[] regexList = { "abc****", "abc", "a*b*c", "****abc", "**a**b**c****", "abc*" };
String str1 = "abc";
for (String regex : regexList) {
Assert.assertTrue(Regex.matches(regex, str1));
}
String regex = "abc****";
String[] strList1 = { "abcxyz", "abcx", "abc" };
for (String str : strList1) {
Assert.assertTrue(Regex.matches(regex, str));
}
regex = "***abc";
String[] strList2 = { "xyzabc", "xabc", "abc" };
for (String str : strList2) {
Assert.assertTrue(Regex.matches(regex, str));
}
Assert.assertTrue(Regex.matches("a.c", "abc"));
Assert.assertTrue(Regex.matches("a*.*c", "abc"));
Assert.assertTrue(Regex.matches("a*.b.*c", "axxbxxbxxc"));
// Fail cases.
Assert.assertFalse(Regex.matches("abc", "abcd"));
Assert.assertFalse(Regex.matches("*a", "abcd"));
Assert.assertFalse(Regex.matches("a", ""));
Assert.assertFalse(Regex.matches(".a*c", "abc"));
Assert.assertFalse(Regex.matches("a.*b", "abc"));
Assert.assertFalse(Regex.matches("..", "abc"));
Assert.assertFalse(Regex.matches("", "abc"));
// exceptions
try {
Regex.matches(null, "abc");
Assert.fail();
} catch (NullPointerException e) {
}
try {
Regex.matches("abc", null);
Assert.fail();
} catch (NullPointerException e) {
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Your code is rather nice, but the algorithm is fundamentally flawed. Consider these test cases, which you currently fail:</p>\n\n<pre><code>// The empty string is a substring of any string\nAssert.assertTrue(Regex.matches(\"\", \"abc\"));\n\n// Because you check for direct character equivalence before metacharacters,\n// a string containing regex metacharacters will falsely pass\nAssert.assertFalse(Regex.matches(\"a*b\", \"a*b\"));\n\n// We should reject malformed regexes\ntry {\n Regex.matches(\"***\", \"\");\n Assert.fail();\n} catch (PatternSyntaxException e) {\n}\n</code></pre>\n\n<p>Furthermore, your regex dialect is unable to match all regular languages: It is possible that a <em>group</em> of characters (and not just a single character) is repeated:</p>\n\n<pre><code>S := A\nA := \"ab\" A\nA := \"\"\n</code></pre>\n\n<p>This grammar can produce the strings <code>\"\"</code>, <code>\"ab\"</code>, <code>\"abab\"</code> etc. It is matched by the regular expression <code>(ab)*</code>. However, you do not offer such groupings. Other features that are lacking and are generally expected of regexes:</p>\n\n<ul>\n<li>A <code>+</code> quantifier</li>\n<li>alternatives <code>|</code> (this is strictly required)</li>\n<li>character classes <code>[a-z]</code> (only needed in real-life applications, not in theoretical settings)</li>\n<li>Escape sequences like <code>\\*</code> to match a literal <code>*</code>, instead of <code>*</code> being a metacharacter.</li>\n</ul>\n\n<p>Don't <em>interpret</em> the regex character by character. This is buggy, and – as shown above – prone to all kinds of failures<sup>(1)</sup>. Instead, write a proper <em>parser</em> and compile the regex to some intermediate representation. For example, the regex <code>(ab|c)*</code> might be equivalent to this data structure:</p>\n\n<pre><code>new Regex.Star(new Regex.Alternative(new Regex.Constant(\"ab\"),\n new Regex.Constant(\"c\")))\n</code></pre>\n\n<p>Given such a data structure, writing a backtracking regex engine is very easy. Of course, regular expressions can also be translated to a state machine, which is a bit more complicated – but the first step is to make it work correctly, before you try any clever optimizations.</p>\n\n<hr>\n\n<ol>\n<li>Especially, regular expressions themselves do not follow a regular grammar.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:54:22.473",
"Id": "75462",
"Score": "0",
"body": "Seems to me that: `matches(\"a*b\", \"a*b\")` should yield true. The pattern says: `\"a\" optionally followed by arbitrary characters, followed by \"b\"`. The target of `a*b` seems to fit the perfectly well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:34:23.673",
"Id": "75465",
"Score": "0",
"body": "@JerryCoffin in a [*shell glob pattern*](https://en.wikipedia.org/wiki/Glob_(programming)), yes. In a [regular expression](https://en.wikipedia.org/wiki/Regular_expression), `*` (the [Kleene Star](https://en.wikipedia.org/wiki/Kleene_star)) is a *repetition operator* that repeats the previous atom (character or group) zero or more times. So `a*b` means any number of `a`s followed by a single `b`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:36:58.420",
"Id": "75466",
"Score": "0",
"body": "He's pretty clearly described the goal at the beginning of the question, and it says: \"* (star) means 0 or more character match\". Seems to me you've concentrated a lot on the \"regex\" part, and nearly ignored the more specific description of the code's intent."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:15:06.613",
"Id": "43585",
"ParentId": "43579",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T06:25:53.770",
"Id": "43579",
"Score": "5",
"Tags": [
"java",
"regex",
"reinventing-the-wheel"
],
"Title": "Regex parser implementing dot, star and question mark"
} | 43579 |
<p>I'm trying to tidy the following fragment of code:</p>
<pre><code> if (this.Details.Recipients.Count > 0)
this.Recipient = this.Details.Recipients[0];
else
{
this.Recipient = new Contact();
this.Details.Recipients.Add(this.Recipient);
}
if (this.Details.CCs.Count > 0)
this.CC = this.Details.CCs[0];
else
{
this.CC = new Contact();
this.Details.CCs.Add(this.CC);
}
if (this.Details.BCCs.Count > 0)
this.BCC = this.Details.BCCs[0];
else
{
this.BCC = new Contact();
this.Details.BCCs.Add(this.BCC);
}
</code></pre>
<p>But when I simplify it in the following way, I run into problems because I have to pass the objects by ref. And if I do that, then I get an error (A property, indexer or dynamic member access may not be passed as an out or ref):</p>
<pre><code> InitialiseContacts(this.Details.Recipients, this.Recipient);
InitialiseContacts(this.Details.CCs, this.CC);
InitialiseContacts(this.Details.BCCs, this.BCC);
}
static void InitialiseContacts(ObservableCollection<Contact> contacts, Contact contact)
{
if (contacts.Count > 0)
contact = contacts[0];
else
{
contact = new Contact();
contacts.Add(contact);
}
}
</code></pre>
<p>Any ideas?</p>
| [] | [
{
"body": "<p>So I think the error you is getting is hopefully obvious. You can't pass a property by ref. There is quite a few answers if you google this. Here's a quick one I found on <a href=\"https://stackoverflow.com/questions/1402803/passing-properties-by-reference-in-c-sharp\">stack overflow</a></p>\n\n<p>So instead don't pass in the object, but rather have a new instance returned from the method. Something along the lines of </p>\n\n<pre><code>this.BCC = FirstOrCreateIfEmpty(this.Details.BCCs);\nthis.CC = FirstOrCreateIfEmpty(this.Details.CCs);\n\npublic Contact FirstOrCreateIfEmpty(List<Contact> contacts)\n{\n if(contacts.Any())\n {\n return contacts.First();\n } \n\n var contact = new Contact();\n contacts.Add(contact);\n\n return contact; \n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:52:45.240",
"Id": "75467",
"Score": "1",
"body": "There are ways to pass a property by reference if you really need to of course, but in an overly accurate sense. You can pass delegates that assign or get from the property. Still, you're probably right in not suggesting that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:04:46.233",
"Id": "75471",
"Score": "0",
"body": "@Magnus Yes, those examples are shown in the Stack overflow link. However, that is still not passing a property by reference as such I believe. Just a work around to effect the same result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:11:01.127",
"Id": "75474",
"Score": "0",
"body": "Technically, a property is a hidden pair of methods, so delegates are somewhat closer. You can pass the getter and setter directly with reflection, but that's even more horrific. But again, you've suggested a solution which has no need for either, which is definitely preferable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:12:46.080",
"Id": "75559",
"Score": "0",
"body": "Thanks. Yes, i see now how I could use a delegate if i **had** to. But I don't and your solution is nice and easy to understand/read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T01:02:34.900",
"Id": "75861",
"Score": "0",
"body": "Thanks, I ended up creating an extension method to help me:\npublic static T FirstOrCreateIfEmpty<T>(this IList<T> list) where T : new()\n {\n if (list.Any())\n return list.First();\n var item = new T();\n list.Add(item);\n return item;\n }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T07:51:19.877",
"Id": "75870",
"Score": "0",
"body": "@MattFitzmaurice excellant. Even better."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T08:11:25.150",
"Id": "43581",
"ParentId": "43580",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T07:39:01.087",
"Id": "43580",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Managing contacts"
} | 43580 |
<p>I had three multi-select boxes from <a href="http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/#basic" rel="nofollow">this page</a>. I want to customize each box so I simply repeat the code three times with different options: <strong><a href="http://jsfiddle.net/akhyp/1004/" rel="nofollow">Check the fiddle</a></strong></p>
<pre><code>$(".choose").multiselect({
header: "Choose only One item!",
multiple: false,
noneSelectedText: "Select an Option",
selectedList: 1
});
$(".pick").multiselect({
header: "Pick Any",
selectedList: 5
});
$(".filter").multiselect({
header: "Filter Three",
selectedList: 3
});
</code></pre>
<p>It's working fine but I'm curious if there's any better way to do that. </p>
| [] | [
{
"body": "<p>Because you have different options for each one, there isn't really an efficient way to combine them into a common selector. And, with only three items, other options aren't really that likely to be more compact. Here's a pure table driven mode that would be more advantageous if you had many more of these:</p>\n\n<pre><code>var multiData = [{ \n sel: \".choose\", \n options: { header: \"Choose only One item!\", multiple: false,\n noneSelectedText: \"Select an Option\", selectedList: 1 }\n }, { \n sel: \".pick\",\n options: { header: \"Pick Any\", selectedList: 5 }\n }, { \n sel: \".filter\",\n options: { header: \"Filter Three\", selectedList: 3 }\n }];\n\n$.each(multiData, function(index, item) {\n $(item.sel).multiselect(item.options);\n});\n</code></pre>\n\n<p>FYI, your jsFiddle doesn't work on Chrome because Chrome won't run scripts linked directly from github (because scripts from gitjub are reported as text/plain).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:33:33.653",
"Id": "43590",
"ParentId": "43584",
"Score": "3"
}
},
{
"body": "<p>With only three different items I don't think there's much benefit from iterating through a list and instantiating the multi-selects automatically. Your version IMO is much more legible than a version iterating through an embedded data structure. Although with lots of selects this could change fast.</p>\n\n<p>You could take the approach of specifying the attributes of the selects (<code>header</code>, <code>noneSelectedText</code> etc.) as data attributes on the HTML. Then you could wire up your jQuery multiselect code to read the information from the selects themselves. So your jQuery would only have to specify the type of select to trigger the <code>multiselect</code> call on and you could add as many as you like without having to update your scripts.</p>\n\n<p>So something like this:</p>\n\n<pre><code><select class=\"dynamic-multiselect\" data-header=\"Choose only One item!\" data-none-selected-text=\"Select an Option\" ...>\n <option ...>\n ...\n</select>\n\n<select class=\"dynamic-multiselect\" data-header=\"Pick Any\" ...>\n <option ...>\n ...\n</select>\n...\n</code></pre>\n\n<p>And the Javascript would simply be:</p>\n\n<pre><code>$('.dynamic-multiselect').multiselect();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:25:32.313",
"Id": "43593",
"ParentId": "43584",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:10:12.430",
"Id": "43584",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "Do I need to trim this jQuery code?"
} | 43584 |
<p>I appreciate any feedback on where I might alter or improve my code for this project. This is an old attempt at implementing a Hierarchical State Machine in F#. I'm from a C#/OO background mostly.</p>
<pre><code>module FSharp.HSM
open Option
open System.Collections.Generic
exception NoTransition
exception NotInitialized
exception AlreadyStarted
type IStateMachine<'state,'event> =
abstract member StateChanged: IEvent<'state>
abstract member Init: 'state -> unit
abstract member State: 'state with get
abstract member IsIn: 'state -> bool
abstract member Fire: 'event -> unit
abstract member Fire: 'event * obj -> unit
type Transition<'state,'event> =
{ Event: 'event
NextState: 'event -> obj -> 'state option
Guard: unit -> bool }
type StateConfig<'state,'event> =
{ State: 'state
Entry: unit -> unit
Exit: unit -> unit
SuperState: 'state option
Parents: 'state list
AutoTransition: 'state option
Transitions: Transition<'state,'event> list }
type internal StateMachine<'state,'event when 'state : equality and 'event :equality>(stateList:StateConfig<'state,'event> list) =
let stateEvent = new Event<'state>()
let mutable current = stateList.Head.State
let mutable started = false
let states = stateList |> List.map (fun x -> x.State) |> List.toArray
let configs = new Dictionary<'state,StateConfig<'state,'event>>()
let find state : StateConfig<'state,'event> = configs.[state]
let rec getParents results state =
let currentConfig = stateList |> List.find (fun x -> x.State = state)
if isSome currentConfig.SuperState then
let super = get currentConfig.SuperState
getParents (super::results) super
else results |> List.rev
do
for stateConfig in stateList do
configs.[stateConfig.State] <- { stateConfig with Parents = getParents [] stateConfig.State }
let rec findTransition event state =
match state.Transitions |> List.tryFind (fun x -> x.Event = event), state.SuperState with
| None, None -> raise NoTransition
| None, Some x -> findTransition event (find x)
| Some x, _ -> x
let rec exitToCommonParent state limit =
match state.SuperState, limit with
| None, _ -> ()
| Some super, Some lim when super = lim -> ()
| Some super, _ ->
let superConfig = find super
superConfig.Exit()
exitToCommonParent superConfig limit
let rec findCommon (list1:'state list) list2 =
if list1.IsEmpty then None else
let restOfList1 = list1.Tail
match list2 |> List.tryFind (fun x -> x = list1.Head), restOfList1 with
| None, [] -> None
| None, _ -> findCommon restOfList1 list2
| Some x, _ -> Some(x)
let rec transition currentState newState =
let currentStateConfig = find currentState
let newStateConfig = find newState
let isSelf = currentStateConfig.State = newStateConfig.State
let moveToSub = not isSelf || newStateConfig.Parents |> List.exists (fun x -> x = currentState)
let commonParent = if isSelf then None else findCommon currentStateConfig.Parents newStateConfig.Parents
if not moveToSub || isSelf then
currentStateConfig.Exit()
exitToCommonParent currentStateConfig commonParent
//enter parents below common Parents before newState,
//but not if we just autoed from there..
match commonParent with
| None -> ()
| Some x -> //todo: optimize this
let revParents = newStateConfig.Parents |> List.rev
let index = revParents |> List.findIndex (fun y -> y = x)
for parent in revParents |> Seq.skip (index + 1) do
if parent <> currentState then (find parent).Entry()
current <- newState
newStateConfig.Entry()
stateEvent.Trigger newState
match newStateConfig.AutoTransition with
| None -> ()
| Some x -> transition newState x
interface IStateMachine<'state, 'event> with
///Initializes the state machine with its initial state
member this.Init state =
if started then raise AlreadyStarted else started <- true
let stateConfig = find state
current <- state
stateConfig.Entry()
stateEvent.Trigger current
match stateConfig.AutoTransition with
| None -> ()
| Some x -> transition state x
///Gets the current state
member this.State with get() = if not started then raise NotInitialized else current
///Raise on a state change
member this.StateChanged = stateEvent.Publish
///Check whether in state or parent state
member this.IsIn (state:'state) =
if not started then raise NotInitialized
if current = state then true else
(find current).Parents |> List.exists (fun x -> x = state)
///Fire an event without data
member this.Fire(event) =
if not started then raise NotInitialized
let cur = find current
let trans = findTransition event cur
if trans.Guard() then
let nextState = trans.NextState event null
if isSome nextState then
transition current (get nextState)
///Fire an event with data
member this.Fire(event, data) =
let cur = find current
let trans = findTransition event cur
if trans.Guard() then
let nextState = trans.NextState event data
if isSome nextState then
transition current (get nextState)
let create(stateList:StateConfig<'state,'event> list) = (new StateMachine<'state,'event>(stateList)) :> IStateMachine<'state,'event>
///Sets up a new state config
let configure state =
{ State = state; Entry = (fun () -> ()); Exit = (fun () -> ());
SuperState = None; Parents = []; AutoTransition = None; Transitions = [] }
///Sets an action on the entry of the state
let onEntry f state = {state with Entry = f }
///Sets an action on the exit of the state
let onExit f state = {state with Exit = f }
///Sets this state as a substate of the given state
let substateOf superState state = { state with SuperState = Some(superState) }
///Sets an auto transition to a new state
let transitionTo substate state = { state with AutoTransition = Some(substate) }
///Sets a transition to a new state on an event (same state allows re-entry)
let on event endState state =
{ state with Transitions =
{ Event = event; NextState = (fun _ _ -> Some(endState)); Guard = (fun () -> true) }::state.Transitions }
///Sets a guarded transition to a new state on an event (same state allows re-entry)
let onIf event guard endState state =
{ state with Transitions =
{ Event = event; NextState = (fun _ _ -> Some(endState)); Guard = guard }::state.Transitions }
///Sets an event handler (with or without data) which returns the new state to transition to
let handle event f state =
{ state with Transitions =
{ Event = event; NextState = f; Guard = (fun () -> true) }::state.Transitions }
///Sets a guarded event handler (with or without data) which returns the new state
let handleIf event guard f state =
{ state with Transitions =
{ Event = event; NextState = f; Guard = guard }::state.Transitions }
</code></pre>
<p>Here's a simple example from some test code:</p>
<pre><code>type State =
| OffHook
| Ringing
| Connected //composite
| InCall
| OnHold
type Trigger =
| CallDialed
| HungUp
| CallConnected
| PlacedOnHold
| TakenOffHold
let mutable timerOn = false
let startTimer() =
printfn "%A connected" DateTime.Now
timerOn <- true
let stopTimer() =
printfn "%A ended" DateTime.Now
timerOn <- false
let newPhoneCall() =
[ configure OffHook
|> on CallDialed Ringing
configure Ringing
|> on CallConnected Connected
configure Connected
|> onEntry startTimer
|> onExit stopTimer
|> transitionTo InCall
|> on HungUp OffHook
configure InCall
|> substateOf Connected
|> on PlacedOnHold OnHold
configure OnHold
|> substateOf Connected
|> on TakenOffHold InCall ]
|> create
</code></pre>
<p>and a much more complicated example from an article about HSM's I used as a ref:</p>
<pre><code>type State =
| S0
| S1
| S11
| S2
| S21
| S211
type Sig =
| A
| B
| C
| D
| E
| F
| G
| H
type ComplexHSM() =
let mutable foo = false
let hsm = [ configure S0
|> onEntry (fun () -> printfn "Enter S0")
|> onExit (fun () -> printfn "Exit S0")
|> transitionTo S1
|> on E S211
configure S1
|> onEntry (fun () -> printfn "Enter S1")
|> onExit (fun () -> printfn "Exit S1")
|> substateOf S0
|> transitionTo S11
|> on A S1
|> on B S11
|> on C S211
|> on D S0
|> on F S211
configure S11
|> onEntry (fun () -> printfn "Enter S11")
|> onExit (fun () -> printfn "Exit S11")
|> substateOf S1
|> on G S211
|> handleIf H (fun () -> foo) (fun event arg -> printfn "fooFal"; foo <- false; None)
configure S2
|> onEntry (fun () -> printfn "Enter S2")
|> onExit (fun () -> printfn "Exit S2")
|> substateOf S0
|> on C S1
|> on F S11
configure S21
|> onEntry (fun () -> printfn "Enter S21")
|> onExit (fun () -> printfn "Exit S21")
|> substateOf S2
|> transitionTo S211
|> on B S211
|> handleIf H (fun () -> not foo) (fun event arg -> printfn "fooTru"; foo <- true; Some(S21) )
configure S211
|> onEntry (fun () -> printfn "Enter S211")
|> onExit (fun () -> printfn "Exit S211")
|> substateOf S21
|> on D S21
|> on G S0 ]
|> create
member this.Hsm with get() = hsm
</code></pre>
| [] | [
{
"body": "<pre><code>let rec getParents results state =\n let currentConfig = stateList |> List.find (fun x -> x.State = state)\n if isSome currentConfig.SuperState then \n let super = get currentConfig.SuperState\n getParents (super::results) super\n else results |> List.rev\n</code></pre>\n\n<p>I think it's cleaner to use pattern matching here, it would avoid having to repeat <code>currentConfig.SuperState</code>.</p>\n\n<p>Also, using accumulator like this makes sense if the results from the deepest level of recursion should be first, not last. But that's not what you want, so you can just drop the accumulator and then do something like <code>super::(getParents super)</code>.</p>\n\n<p>The rewritten function would look like this:</p>\n\n<pre><code>let rec getParents state =\n let currentConfig = stateList |> List.find (fun x -> x.State = state)\n match currentConfig.SuperState with\n | None -> []\n | Some super -> super::(getParents super)\n</code></pre>\n\n<p>It's possible you intentionally wrote it the way you did, because it's tail recursive, so it won't blow up your stack no matter how deep the recursion is. If that's the case, then I think you should make sure stack overflow is a real risk with the non-tail-recursive version. And then you should add a comment that explains that's the reason why you wrote it that way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:05:43.763",
"Id": "81522",
"Score": "0",
"body": "Thanks! I integrated your suggestion into the code. Not sure if that's the way the site is intended to work, but seems appropriate given my code's length..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T17:00:28.193",
"Id": "81564",
"Score": "1",
"body": "@user38198 [The consensus is not to do that](http://meta.codereview.stackexchange.com/a/1037/2041), so I rolled back your edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T11:58:50.767",
"Id": "46542",
"ParentId": "43587",
"Score": "4"
}
},
{
"body": "<h2>Review</h2>\n\n<p>Implementing a Hierarchical State Machine can get really tricky. You have a done a decent job, using both Mealy and Moore concepts. There are a couple of aspects that still require to be addressed further to make this a reusable API:</p>\n\n<ul>\n<li>pseudo states (fork, join infrastructure)</li>\n<li>(deep) history states (when entering a state with composite states, the default entry might be to enter its last activated state)</li>\n<li>exception handling (should you fallback to an error state or recover a history state?)</li>\n<li>local vs external vs internal transition (self-transitions can be internal or external, transitioning to substates can be local or external)</li>\n<li>there is entry and exit behavior, but no do behavior</li>\n<li>triggers should also have specific event data attached</li>\n<li>event deferral options (priority and deferral of events)</li>\n<li>event conflict resolution if both a state and substate allow to handle the event</li>\n<li>dynamic transition flow resolution (based on extended state, transition tables and guards, make a transition plan at runtime)</li>\n</ul>\n\n<h3>Extended state</h3>\n\n<p>What I'm really missing is <em>extended state</em>. This is data available to all states in the state machine. Each state should be able to access and change the extended state and consult it in the behavior, transition and auto-transition guards.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T04:53:52.673",
"Id": "227702",
"ParentId": "43587",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:25:06.500",
"Id": "43587",
"Score": "9",
"Tags": [
"f#",
"state-machine"
],
"Title": "Hierarchical State Machine in F#"
} | 43587 |
<p><a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a> is a Python data analysis library.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:30:16.107",
"Id": "43588",
"Score": "0",
"Tags": null,
"Title": null
} | 43588 |
Pandas is a Python data analysis library. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:30:16.107",
"Id": "43589",
"Score": "0",
"Tags": null,
"Title": null
} | 43589 |
<p>I am trying to solve <a href="http://www.spoj.com/problems/PRIMEZUK/" rel="nofollow">this SPOJ question</a>.</p>
<pre><code> #include<iostream>
#include<cstdio>
#include<math.h>
#define l long long
using namespace std;
l chk(l a)
{
for(int i=2;i<=sqrt(a);++i)
{
if(a%i==0)
{
return a/i;
}
}
return 0;
}
main()
{
// freopen("in.txt","r",stdin);
int t,n,a;
l prod=1,flag;
//t=inp();
cin>>t;
for(int j=1;j<=t;++j)
{
cin>>n;
//n=inp();
if(n==0)
prod=-1;
else
prod=1;
while(n--)
{
cin>>a;
//a=inp();
prod*=a;
}
++prod;
flag=chk(prod);
if(!flag)
printf("Case #%d: %lld\n",j,prod);
else
printf("Case #%d: %lld\n",j,flag);
}
}
</code></pre>
<p>I am getting the right answer for the sample test case, but when I submit, I am getting the wrong answer. Any hints?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:09:59.970",
"Id": "75386",
"Score": "5",
"body": "Welcome to Code Review! Unfortunately, this question appears to be off-topic because it is about solving a problem rather than asking for a Code Review. We improve code cleaniness on this site, we don't help in fixing incorrect results of code."
}
] | [
{
"body": "<p>I cannot help you with your issue before commenting and fixing on the formating of your code :</p>\n\n<ol>\n<li>Remove whatever you want to remove before going through code reviews.</li>\n<li>Give your function relevant names and add some documentation and unit tests.</li>\n<li>Indent your code properly</li>\n<li>Define your local variables in the smallest possible scope and as late as possible to make things easier to track.</li>\n<li>Don't use macros to define types. C/C++ provides you different ways to do this (<code>typedef</code>) and this is not even required here as it just obfuscates the code.</li>\n<li>Use <code>for</code> loops over <code>while</code> whenever you can to make things clearer.</li>\n<li>Don't compute <code>sqrt</code> many times as it is an expensive operation.</li>\n<li>Use <a href=\"https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main\">the correct return type</a> for <code>main</code>.</li>\n<li>Using <code>using namespace std;</code> is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">usually frowned upon</a>.</li>\n</ol>\n\n<p>Here's what I have for the time being. We cannot really help you </p>\n\n<pre><code>#include<iostream>\n#include<cstdio>\n#include<math.h>\n\nusing namespace std;\n\nlong long chk(long long a)\n{\n long long root = sqrt(a);\n for(int i=2; i <= root; i++)\n {\n if(a%i==0)\n {\n return a/i;\n }\n }\n return 0;\n}\nint main()\n{\n int t;\n cin>>t;\n for(int i=1; i<=t; i++)\n {\n int n;\n cin>>n;\n long long prod = (n==0) ? -1 : 1;\n while(n--)\n {\n int a;\n cin>>a;\n prod*=a;\n }\n ++prod;\n long long flag = chk(prod);\n printf(\"Case #%d: %lld\\n\",i,flag ? flag : prod);\n }\n return 0;\n}\n</code></pre>\n\n<p>Now, if you want to have actual helpful answers, you should give more information about what you are trying to do and how.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:23:22.623",
"Id": "75388",
"Score": "0",
"body": "thanx for your help but i found mistake in my code while commenting :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:06:21.130",
"Id": "43592",
"ParentId": "43591",
"Score": "2"
}
},
{
"body": "<p>Your problem is with function <code>chk</code>, which is supposed to return the largest prime factor of a given integer. Unfortunately, it returns the largest <strong>not-necessarily-prime</strong> factor (smaller than the given input).</p>\n\n<p>For example, <code>chk(75)</code> will return <code>75/3</code>, which is <code>25</code> - obviously <strong>not a prime</strong>.</p>\n\n<p>Here is one way to fix this problem (recursive implementation):</p>\n\n<pre><code>typedef unsigned long long t_ull;\n\nt_ull chk(t_ull a)\n{\n t_ull root = (t_ull)sqrt(a);\n for(t_ull i=2; i<=root; i++)\n {\n if(a%i==0)\n {\n return chk(a/i);\n }\n }\n return a;\n}\n</code></pre>\n\n<p>Please note that if no prime factor is found, then the function returns the input itself (which is prime).</p>\n\n<p>This allows you to revoke the use of <code>flag</code>, and simply print the output of <code>chk</code>:</p>\n\n<pre><code>cout<<\"Case #\"<<j<<\": \"<<chk(prod)<<endl;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T11:02:34.490",
"Id": "43594",
"ParentId": "43591",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:41:43.470",
"Id": "43591",
"Score": "0",
"Tags": [
"c++",
"primes"
],
"Title": "Prime conjecture"
} | 43591 |
<p>I have been working on a linked list for some while now and started out with <a href="https://stackoverflow.com/questions/22141477/simple-linked-list-c">this</a>.</p>
<p>Is my code clean? Or is there some way to make it better and more readable? </p>
<p>The reason for this question is for me to be a better programmer. I would love to get one step further for making more clean code. </p>
<p>my class:</p>
<pre><code>using namespace std;
class Node
{
public:
int nX;
Node *next;
//constructor
Node(){ head = NULL; } //Initialising head to NULL
void addValueLeft(int nVal);
void addValueRight(int nVal);
void deleteValueLeft();
void deleteValueRight();
void printList();
private:
Node *head; //a pointer to the first Node
};
</code></pre>
<p>my main:</p>
<pre><code>int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
//creating a new object
Node list;
list.addValueLeft(5);
list.addValueLeft(6);
list.addVaueRight(8);
list.deleteValueRight();
list.printList();
return 0;
}
</code></pre>
<p>my functions:</p>
<pre><code> void Node::addValueLeft(int nVal)
{
Node *newNode = new Node;
if(!head)
{
newNode->nX = nVal;
newNode->next = NULL;
head = newNode;
}
else
{
newNode->nX = nVal;
newNode->next = head;
head = newNode;
}
}
void Node::printList()
{
if(!head) //list is empty - nothing to print
{
//cout << "nothing to print - list empty " << endl;
}
else
{
Node *tempNode = new Node;
tempNode = head;
while(tempNode)
{
cout << tempNode-> nX << endl;
tempNode = tempNode->next;
}
}
}
void Node::addValueRight(int nVal)
{
Node *tempNode1 = new Node;
if(!head) //List is empty
{
tempNode1 -> nX = nVal;
tempNode1 -> next = head;
head = tempNode1;
}
else
{
tempNode1 = head;
while(tempNode1 -> next != NULL) //Go to last Node
{
tempNode1 = tempNode1->next;
}
Node *tempNode2 = new Node; //create temp node
tempNode2 -> nX = nVal;
tempNode2 -> next = NULL;
tempNode1 -> next = tempNode2; //tempNode1 will be last Node
}
}
void Node::deleteValueLeft()
{
if(!head) //list is empty - Nothing to Delete
{
//cout << " deleteValueLeft: Nothing to delete" << endl;
}
else
{
head = head->next;
}
}
void Node::deleteValueRight()
{
if(head == NULL) //Nothing to delete
{
//cout << "Nothing to delete " << endl;
}
else
{
Node *tempNode1 = new Node;
Node *oldNode = new Node;
tempNode1 = head;
if(tempNode1->next == NULL) //only one element
{
head = NULL;
}
else
{
while(tempNode1->next!=NULL) //Go to last Node
{
oldNode = tempNode1;
tempNode1 = tempNode1->next;
}
oldNode->next = NULL;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:57:43.107",
"Id": "75444",
"Score": "0",
"body": "If you use a `Sentinal` it makes the creation of a linked list a lot easier to write and the code a lot cleaner. http://codereview.stackexchange.com/a/9399/507"
}
] | [
{
"body": "<p>Here's some feedback (not an exhaustive list).</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Please stop doing this. when you add <code>using namespace</code> directives in header files, any file including that header will have potential namespace clashes (which is the problem namespaces are trying to prevent).</p>\n\n<pre><code>class Node\n{\npublic:\n int nX; // (1)\n Node *next; // (2)\n Node(){ head = NULL; } // (3)\n</code></pre>\n\n<p>Notes:</p>\n\n<p>The only ways lines (1) and (2) are acceptable, are:</p>\n\n<ul>\n<li>if instances of your class are valid regardless what you place in nX and next.</li>\n</ul>\n\n<p>Client code example:</p>\n\n<pre><code>Node n;\nn.nX = 1001; // is this valid?\nn.next = n; // is this valid?\n</code></pre>\n\n<ul>\n<li>if Node class is moved from the global namespace to the private section of another class. That way, the outer class will protect the node's data.</li>\n</ul>\n\n<p>Otherwise, nX and next should be private data, with getters to read the values and setters to validate and set the values.</p>\n\n<p>Line (3) is a bad implementation for a constructor, because it leaves a new instance in a partially-initialized state (it should initialize nX, next and head, explicitly and in this specific order).</p>\n\n<p>Better implementation:</p>\n\n<pre><code>explicit Node(int value = 0): nX(value), next(nullptr), head(nullptr) {}\n</code></pre>\n\n<p>Note regarding class API design:</p>\n\n<p>You are implementing both a node (for an element of the list) and a list of nodes. You should have two classes instead of one, and the <code>head</code> pointer should be a member of the list, not a node:</p>\n\n<pre><code>class Node {\n int nX; Node* next;\npublic:\n // ... rest of node interface here\n};\n\nclass List {\n Node *head;\npublic:\n List() {}\n const std::size_t size() const;\n void add_value_end(int value);\n // ... rest of interface here\n};\n</code></pre>\n\n<p>Eventually, you should consider using node as an internal structure of the list:</p>\n\n<pre><code>class List {\n class Node { /* same as above */ };\n Node *head;\npublic:\n // same as above\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:38:17.960",
"Id": "75415",
"Score": "0",
"body": "Implementing a linked list without a dummy head node should be very, very high on the list of \"do nots\" in my opinion. Just means the code needs tons of special cases for no good reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:50:11.803",
"Id": "75421",
"Score": "0",
"body": "@Voo, can you please be more specific? My proposed implementation doesn't require (or impose) a dummy head, nor special cases in processing (as far as I can tell). Maybe I am missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:52:54.990",
"Id": "75423",
"Score": "0",
"body": "Implement the usual functions (add, remove, search,..) on a double linked list twice. Once assume that an empty list has `head = nullptr` and the second time that `head` is always a valid dummy node (which if the list is empty points to itself). You'll see that the later results in much nicer code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:59:07.643",
"Id": "75426",
"Score": "1",
"body": "I just tried writing an append method for the list and saw what you mean: an implementation with a dummy head, will ensure that in the situations where you implement iteration (`Node *p = head; while(p->next) ...`) you don't need to check the validity of the iterator before accessing 'next'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:15:49.870",
"Id": "75429",
"Score": "0",
"body": "Exactly. It's one of those tricks when working with data structures that makes reasoning about them (and implementing) easier. Very useful trick to have in your toolbox."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:11:07.760",
"Id": "75449",
"Score": "1",
"body": "If you're going to do `Node(int value=0)`... you really _must_ make it an explicit constructor - `explicit Node(int value=0)` - or you will create an implicit casting between your list node and its payload and you do not want that. In fact, in general, you should get in the habit of _always_ putting `explicit` in front of single parameter constructors unless you really, really want casting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:48:16.547",
"Id": "75610",
"Score": "0",
"body": "so instead of _using_ _namespace_ _std_ , I should use _std::cout_ etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:07:41.690",
"Id": "75613",
"Score": "0",
"body": "Either use `std::cout`, or place `using std::cout;` in the functions where you use std::cout. Same for other std:: symbols. Worst case, you can place `using namespace std;` in the body of various functions. The point is to not put it globally (not in cpp and especially not in header files)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:13:20.177",
"Id": "43597",
"ParentId": "43595",
"Score": "8"
}
},
{
"body": "<p>I agree with @utnapistim answer, that you should have two classes: a <code>List</code> class with a <code>head</code> element, and a <code>Node</code> class with a <code>next</code> element.</p>\n\n<p>As well:</p>\n\n<ul>\n<li>The <code>if</code> in your <code>addValueLeft</code> is unecessary: you do the same thing (i.e. you assign the same value to <code>nX</code>, <code>next</code>, and <code>head</code>) no matter what the <code>if</code> value is.</li>\n<li>In <code>addValueRight</code> you should not have two <code>new Node;</code> statements: you are leaking the first new node.</li>\n<li>You should have a <code>List</code> destructor which deletes all the nodes on the list</li>\n<li><p>Your <code>deleteValue</code> methods should delete the node before forgetting about it; for example:</p>\n\n<pre><code>void Node::deleteValueLeft()\n{\n if(!head)\n return; //list is empty - Nothing to Delete\n Node* firstNode = head;\n head = head->next;\n // you weren't doing the following;\n // note that I get/dereference head->next before I delete this old head\n delete firstNode; \n}\n</code></pre></li>\n<li><p>Perhaps your Node should have a non-default constructor; because a Node is only created when there's a value to store in it:</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:23:14.513",
"Id": "43599",
"ParentId": "43595",
"Score": "4"
}
},
{
"body": "<p>Well, there are many problems in the code. Does this compile and run correctly? Some things I have noticed:</p>\n\n<ul>\n<li><p>Make the member variables in <code>Node</code> private as they are not needed outside. And if they were, you should probably provide getter and setter methods.</p></li>\n<li><p>The member variable <code>Node::head</code> should be <code>static</code> because the head is ALWAYS the same. The way you are doing it now each instance of Node (so each Node) has its own <code>head</code>. This is not only waste of memory but also wrong. With <code>static</code> there is only <em>one</em> instance of <code>Node *head</code> in the memory. (Of course in that case you must not set <code>head</code> to <code>NULL</code>). Notice that this solution has the disadvantage that you can only have one list at a time. But to solve this there are only two possibilities:</p>\n\n<ol>\n<li>Leave it non static. But then you have to adjust the member variable in each node once the head changes (very costly). Moreover (as mentioned above) you waste memory.</li>\n<li>As suggested by the other answers: make two classes. A class for the <code>List</code> and a (nested) class for the node. The <code>head</code> pointer is then a member of the <code>List</code> (not the <code>Node</code> anymore). This way you can instantiate many <code>List</code>s with different <code>head</code>s.</li>\n</ol></li>\n</ul>\n\n<p>The latter is obviously the better solution an is the common way to solve that problem.</p>\n\n<p>So <code>Node</code> should/could be changed to be like that:(here <code>head</code> is static)</p>\n\n<pre><code>class Node\n{\npublic:\n Node(); //Do NOT initialize to NULL\nprivate:\n int nX; \n Node *next;\n static Node *head = NULL;// initialize to NULL\n};\n</code></pre>\n\n<p>Another thing that is seen as better practice is to use initialization lists (read about it). In short:\nAn initialization list initializes (as the name suggests) variables on construction.</p>\n\n<p>And many other things. Including but not limited to the following:</p>\n\n<pre><code> void Node::addValueLeft(int nVal)\n{\n Node *newNode = new Node;\n\n newNode->nX = nVal;\n newNode->next = head; // set to old head. If head is NULL, it is OK, too.\n if(!head) // if list is empty, make head pointing at the new node\n head = newNode;\n}\n\nvoid Node::printList()\n{\n // if is unnecessary here. If list is empty the while loop\n // is skipped anyway.\n\n Node *tempNode = head; // no new Node here\n while(tempNode)\n {\n cout << tempNode-> nX << endl;\n tempNode = tempNode->next;\n }\n}\n\nvoid Node::addValueRight(int nVal)\n{\n Node *tempNode1; // no good naming and no need for new Node\n\n Node *tempNode2 = new Node; //create temp node\n tempNode2 -> nX = nVal;\n tempNode2 -> next = NULL;\n\n if(head == NULL){ // if list is empty, the new Node is the first Node\n head = tempNode2;\n }else{ // if there are Nodes in the list ...\n tempNode1 = head;\n while(tempNode1 -> next != NULL) // ... Go to last Node\n {\n tempNode1 = tempNode1->next;\n }\n tempNode1 -> next = tempNode2; //tempNode2 will be last Node\n }\n}\n</code></pre>\n\n<p>I would really like to help more but I think you have to read more about the basics. Most important: read much much much about pointers. Moreover read about <code>new</code> and <code>delete</code>.\nIf you have more (specific) questions feel free to ask.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:27:20.420",
"Id": "75411",
"Score": "1",
"body": "+1; but `head` cannot be static if there is more than one List in the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:05:43.060",
"Id": "75413",
"Score": "2",
"body": "A static `head` member in the Node class is so wrong that you should edit it out of your answer entirely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:28:42.757",
"Id": "75414",
"Score": "0",
"body": "@Peter on the one hand you are right. But on the other hand it is much better than the solution from the OP. But I will think about it and edit my answer to something more secure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:41:35.627",
"Id": "75419",
"Score": "0",
"body": "@exilit The OPs code may not be great but at least correct (ok, there's at least a *chance* it may be correct at least). Making the head node static on the other hand is a bug in any way you think about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:47:12.523",
"Id": "75420",
"Score": "0",
"body": "@Voo I disagree. It is not a bug at all. The way this linked list is designed it is very obvious that there couldn't be multiple instances of that list. So is it a limitation? definitely! Is it poor design? It is! But is it a bug? no, it is not, because it works the way it is expected to. (statically it works just fine)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:57:14.550",
"Id": "75424",
"Score": "0",
"body": "Well it's either a horrible bug in the implementation or a horrible bug in the specification (a datastructure where you can only ever have a single instance of is nigh useless) - however you look at it, there's a bug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:08:47.687",
"Id": "75448",
"Score": "0",
"body": "@Voo I agree with you that there is a flaw somewhere, I wouldn't usually call a flaw in the specification a \"bug\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:13:05.980",
"Id": "75452",
"Score": "1",
"body": "Putting a pointer to the head in a node is just plain bad design (since it prevents many of the operations that make lists worthwhile speedily). Doing it statically is even worse (since it limits you to one list in your whole program!)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:28:58.857",
"Id": "75464",
"Score": "0",
"body": "This is codereview. When there's a major architectural issue, recommend fixing the architecture, not a band-aid that will NEVER lead to a good design or clean code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:24:08.443",
"Id": "75550",
"Score": "0",
"body": "@Peter You are totally right. But my aim was to modify HIS code so that he can identify what he has done himself and notice the differences (mistakes) more easy. Of course it is important to show him also the \"right\" way (as I have tried in the [initial](http://stackoverflow.com/questions/22141477/simple-linked-list-c/22141970#22141970) discussion). This is the reason why utnapistim's answer is rated so high. Because this is the \"best\" practice but it's more difficult for the OP to understand because he lacks the basics. (But nonetheless +1 for utnapistim's nice answer)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:20:17.863",
"Id": "43608",
"ParentId": "43595",
"Score": "4"
}
},
{
"body": "<p>Aside from the problems with the code itself as pointed out in the other answers, I would like to comment on your interface naming. There are a few common names for linked list operations that any experienced programmer will expect:</p>\n\n<ul>\n<li><code>push</code> / <code>pop</code> for stacks (first in, last out): Add an element to the end of the list, or remove the last added element from the end of the list</li>\n<li><code>queue</code>/ <code>dequeue</code> for queues (first in, first out lists): Add an element to the start of the list and remove one from the end of the list.</li>\n<li><code>shift</code> / <code>unshift</code> - I am not sure how common these terms are, but for example PHP uses this as the analog to <code>push</code> and <code>pop</code> for operations on the start of the list.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:41:42.707",
"Id": "43626",
"ParentId": "43595",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43597",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T12:44:27.877",
"Id": "43595",
"Score": "4",
"Tags": [
"c++",
"linked-list"
],
"Title": "Make LinkedList in C++ more clean"
} | 43595 |
<p>I'd like to get some input on whether or not to DRY up this code. And if so how to implement it correctly. How do I know when it's worth refactoring?</p>
<pre><code>public class Win32OperatingSystem
{
public Win32OperatingSystem() { }
/// <summary>
/// Number, in megabytes, of physical memory currently unused and available.
/// </summary>
public ulong FreePhysicalMemory()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUlong("FreePhysicalMemory", "Win32_OperatingSystem");
}
}
/// <summary>
/// Number, in megabytes, of virtual memory.
/// </summary>
public ulong TotalVirtualMemorySize()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUlong("TotalVirtualMemorySize", "Win32_OperatingSystem");
}
}
/// <summary>
/// Number, in megabytes, of virtual memory currently unused and available.
/// </summary>
public ulong FreeVirtualMemory()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUlong("FreeVirtualMemory", "Win32_OperatingSystem");
}
}
}
/// <summary>
/// The Win32_ComputerSystem WMI class represents a computer system running Windows.
/// </summary>
public class Win32ComputerSystem
{
public Win32ComputerSystem() { }
/// <summary>
/// Key of a CIM_System instance in an enterprise environment.
/// This property is inherited from CIM_ManagedSystemElement.
/// </summary>
public string Name()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Name", "Win32_ComputerSystem");
}
}
/// <summary>
/// Name of a computer manufacturer.
/// </summary>
public string Manufacturer()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Manufacturer", "Win32_ComputerSystem");
}
}
/// <summary>
/// Product name that a manufacturer gives to a computer. This property must have a value.
/// </summary>
public string Model()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Model", "Win32_ComputerSystem");
}
}
}
/// <summary>
/// The Win32_Processor WMI class represents a device that can interpret a sequence of instructions on a computer
/// running on a Windows operating system. On a multiprocessor computer, one instance of the Win32_Processor class
/// exists for each processor.
/// </summary>
public class Win32Processor
{
public Win32Processor() { }
/// <summary>
/// Processor architecture used by the platform.
/// </summary>
public ushort Architecture()
{
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUshort("Architecture", "Win32_Processor");
}
}
}
/// <summary>
/// Description of the object. This property is inherited from CIM_ManagedSystemElement.
/// </summary>
public string Description()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Description", "Win32_Processor");
}
}
}
/// <summary>
/// The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS)
/// that are installed on a computer.
/// </summary>
public class Win32BIOS
{
public Win32BIOS() { }
/// <summary>
/// Version of the BIOS. This string is created by the BIOS manufacturer.
/// This property is inherited from CIM_SoftwareElement.
/// </summary>
public string Version()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Version", "Win32_BIOS");
}
}
/// <summary>
/// Assigned serial number of the software element. This property is inherited from CIM_SoftwareElement.
/// </summary>
public string SerialNumber()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("SerialNumber", "Win32_BIOS");
}
}
/// <summary>
/// Internal identifier for this compilation of this software element.
/// This property is inherited from CIM_SoftwareElement.
/// </summary>
public string BuildNumber()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("BuildNumber", "Win32_BIOS");
}
}
/// <summary>
/// Name of the current BIOS language.
/// </summary>
public string CurrentLanguage()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("CurrentLanguage", "Win32_BIOS");
}
}
/// <summary>
/// Manufacturer of this software element.
/// </summary>
public string Manufacturer()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Manufacturer", "Win32_BIOS");
}
}
/// <summary>
/// BIOS version as reported by SMBIOS.
/// </summary>
public string SMBIOSBIOSVersion()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("SMBIOSBIOSVersion", "Win32_BIOS");
}
}
/// <summary>
/// Current status of the object. Various operational and nonoperational statuses can be defined.
/// Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled
/// hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational
/// statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during
/// mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such
/// work is online, yet the managed element is neither "OK" nor in one of the other states.
/// This property is inherited from CIM_ManagedSystemElement.
/// </summary>
/// <returns></returns>
public string Status()
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetString("Status", "Win32_BIOS");
}
}
/// <summary>
/// Number of languages available for installation on this system. Language may determine properties such as
/// the need for Unicode and bidirectional text.
/// </summary>
public ushort InstallableLanguages()
{
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUshort("InstallableLanguages", "Win32_BIOS");
}
}
}
/// <summary>
/// Major SMBIOS version number. This property is NULL if SMBIOS is not found.
/// </summary>
/// <returns></returns>
public ushort SMBIOSMajorVersion()
{
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUshort("SMBIOSMajorVersion", "Win32_BIOS");
}
}
}
/// <summary>
/// Minor SMBIOS version number. This property is NULL if SMBIOS is not found.
/// </summary>
public ushort SMBIOSMinorVersion()
{
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetUshort("SMBIOSMinorVersion", "Win32_BIOS");
}
}
}
/// <summary>
/// If true, the SMBIOS is available on this computer system.
/// </summary>
public bool SMBIOSPresent()
{
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetBool("SMBIOSPresent", "Win32_BIOS");
}
}
}
/// <summary>
/// Release date of the Windows BIOS converted from UTC format to DateTime.
/// </summary>
public DateTime ReleaseDate()
{
{
using (PropertyGetter getProperty = new PropertyGetter())
{
return getProperty.GetDateTimeFromDmtf("ReleaseDate", "Win32_BIOS");
}
}
}
}
#endregion
/// <summary>
/// Handles the actual WMI queries for the other classes in this file
/// </summary>
public class PropertyGetter : IDisposable
{
public PropertyGetter() { }
/// <summary>
/// Converts kilobyte values to megabytes for readability.
/// </summary>
/// <param name="kiloBytes">Value to be converted</param>
/// <returns>Kilobytes converted to megabytes as ulong</returns>
private ulong KiloBytesToMegaBytes(ulong kiloBytes)
{
return kiloBytes / (ulong)1024;
}
/// <summary>
/// Performs WMI queries on objects which return Int64 bit values
/// </summary>
/// <param name="propertyName">Property value to be returned</param>
/// <param name="Win32Class">WMI class which contains desired property</param>
/// <returns>The property value of the Int64 bit object queried for</returns>
public ulong GetUlong(string propertyName, string Win32Class)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + Win32Class);
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext())
{
return 0;
}
return KiloBytesToMegaBytes((ulong)enu.Current[propertyName]);
}
}
public string GetString(string propertyName, string Win32Class)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + Win32Class);
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext() || enu.Current[propertyName].ToString() == null)
{
return String.Empty;
}
return enu.Current[propertyName].ToString();
}
}
public ushort GetUshort(string propertyName, string Win32Class)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + Win32Class);
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext())
{
return (ushort)0;
}
return (ushort)enu.Current[propertyName];
}
}
public bool GetBool(string propertyName, string Win32Class)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + Win32Class);
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext())
{
return false;
}
return true;
}
}
public DateTime GetDateTimeFromDmtf(string propertyName, string Win32Class)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + Win32Class);
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext())
{
return DateTime.Today;
}
return ManagementDateTimeConverter.ToDateTime(enu.Current[propertyName].ToString());
}
}
public void Dispose(){ }
}
</code></pre>
<h3>Questions in this series</h3>
<p><a href="https://codereview.stackexchange.com/questions/43432/class-seperation-vs-polymorphism">Class Seperation vs Polymorphism.</a></p>
<p>You're currently viewing the second question in the series.</p>
<p><a href="https://codereview.stackexchange.com/questions/43719/next-instance-of-dry-refactoring/43735?noredirect=1#43735">Second iteration of DRY refactoring.</a></p>
<p><a href="https://codereview.stackexchange.com/questions/43777/adding-generics-and-or-enums">Genericizing PropertyValues</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:33:00.523",
"Id": "75399",
"Score": "0",
"body": "Hi! I have removed the extra closing brace at the end; you could add a bit more context to the question, describing what the code is doing - comments are part of your code and can be subject to review, so don't remove them unless it makes your post too long to be posted ;) - IIRC this is a follow-up to another question, you can consider adding a link to the previous one too. Thanks for posting! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:39:55.080",
"Id": "75400",
"Score": "0",
"body": "I was thinking of adding the link. I'll do that now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:41:53.703",
"Id": "75401",
"Score": "0",
"body": "Could you explain why PropertyGetter needs to be IDisposable? It doesn't seem to persist anything outside of its methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:43:15.453",
"Id": "75402",
"Score": "0",
"body": "That's something I was playing around with because VS was barking at me for all my using statements. How should this be handled instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:44:23.343",
"Id": "75403",
"Score": "0",
"body": "Don't use using statements. Instead just have a single PropertyGetter instance as a class-level field or property"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:23:50.273",
"Id": "75409",
"Score": "0",
"body": "I have a more full answer partially written up but it'll be quite a few hours before I can finish it. For now, removing the IDisposable and using are definitely your best bet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:14:58.510",
"Id": "75453",
"Score": "0",
"body": "I'll start there and look forward to your other answer if you get time to finish it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:42:49.760",
"Id": "75535",
"Score": "0",
"body": "@Mat'sMug I've refactored and would like another iteration of review. Is it best practice to start a new question? Or add it here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:02:02.883",
"Id": "75571",
"Score": "0",
"body": "http://meta.codereview.stackexchange.com/search?q=edit+question+code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:35:43.970",
"Id": "75587",
"Score": "0",
"body": "[Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/a/1483/34757)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:37:16.350",
"Id": "75588",
"Score": "0",
"body": "It's best to start a new question, if you want to ensure that the new version is reviewed. See [How to post a follow-up question?](http://meta.codereview.stackexchange.com/a/1066/34757)"
}
] | [
{
"body": "<p>Your PropertyGetter.Dispose method does nothing and has nothing to do, so there's no point in PropertyGetter being disposable.</p>\n\n<p>Instead its methods could be static, for example:</p>\n\n<pre><code>public static ulong GetUlong(string propertyName, string Win32Class) { ... }\n</code></pre>\n\n<p>You can call static methods without <code>using</code> a <code>new PropertyGetter</code> for example:</p>\n\n<pre><code>public ulong FreePhysicalMemory()\n{\n return PropertyGetter.GetUlong(\"FreePhysicalMemory\", \"Win32_OperatingSystem\");\n}\n</code></pre>\n\n<hr>\n\n<p>By the way, you should theoretically call Dispose on the result of Get() as well as on the result of GetEnumerator():\nbecause the result of Get() is a <code>ManagementObjectCollection</code> instance which is IDisposable, and the result of GetEnumerator() is <code>ManagementObjectEnumerator</code> which is also IDisposable (as well as IEnumerable).</p>\n\n<p>So instead of this ...</p>\n\n<pre><code>using (var enu = moSearcher.Get().GetEnumerator())\n{\n ... etc ...\n}\n</code></pre>\n\n<p>... this instead ...</p>\n\n<pre><code>using (var collection = moSearcher.Get())\n{\n using (var enu = collection.GetEnumerator())\n {\n ... etc ...\n }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>However there are members of my group that have an aversion to static classes as they fear they lead to things staying in memory longer that a manually instantiated and disposed class. Can you help shed some light on the subject?</p>\n</blockquote>\n\n<p>(The following example pseudo-code won't compile, because it uses a too-simplistic version of the SqlConnection API; but I hope it illustrates the point, i.e. object lifetimes.)</p>\n\n<p>Static data exists forever (which may be bad):</p>\n\n<pre><code>static class Foo\n{\n // this SqlConnection exists forever!\n static SqlConnection connection = new SqlConnection(\"sql connection string\");\n\n public static string selectUserName(int userId)\n {\n return connection(\"select username from users where userid=\" + userid.ToString());\n }\n}\n</code></pre>\n\n<p>Local (non-static) data in a static method is eligible for garbage collection as soon as the static method returns (which may be harmless):</p>\n\n<pre><code>static class Foo\n{ \n // No static data here!\n\n public static string selectUserName(int userId)\n {\n // this SqlConnection is temporary\n using (SqlConnection connection = new SqlConnection(\"sql connection string\"))\n {\n return connection(\"select username from users where userid=\" + userid.ToString());\n }\n }\n}\n</code></pre>\n\n<p>The above class has no instance data so there's no reason to construct it: it can be a static class.</p>\n\n<p>Alternatively it could be coded with instance data:</p>\n\n<pre><code>// implements IDisposable because it contains a data member which needs to be disposed\nclass Foo : IDisposable\n{\n // this non-static SqlConnection exists for the same lifetime as\n // the Foo instance[s] which contain[s] it\n SqlConnection connection;\n\n public Foo()\n {\n SqlConnection connection = new SqlConnection(\"sql connection string\");\n }\n\n // can't be static because it uses non-static 'connection' member\n public string selectUserName(int userId)\n {\n return connection(\"select username from users where userid=\" + userid.ToString());\n }\n\n public void Dispose()\n {\n connection.Dispose();\n }\n}\n</code></pre>\n\n<p>The disadvantage of this last one is:</p>\n\n<ul>\n<li>You must instantiate a Foo because you call a non-static method</li>\n<li>You should remember to dispose the Foo perhaps with a <code>using</code> statement</li>\n</ul>\n\n<p>The advantage of this last one is:</p>\n\n<ul>\n<li>You can construct a Foo and then call selectUserName several times, using the same Foo instance (therefore the same SqlConnection instance) each time (which may be good if SqlConnection is expensive to construct)</li>\n<li>You can Dispose Foo (and therefore Dispose the SqlConnection instance) when you have finished with it (which may be better than a static SqlConnection instance which exists forever)</li>\n</ul>\n\n<p>In summary the members of your group are semi-correct:</p>\n\n<ul>\n<li>Static data exists forever (e.g. instance member data of a static object exist forever)</li>\n<li>Local variables in a static method don't exist forever</li>\n</ul>\n\n<p>The code you posted in the OP only uses local data (not instance data, and not static data); therefore it would be better as static methods in a static class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:21:49.580",
"Id": "75457",
"Score": "0",
"body": "Thanks Chris. Quick follow up. If I change the methods in PropertyGetter to static what is the impact on the program memory wise? Are they still disposed of after being called? To sum up how do I differentiate between managed and unmanaged resources?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:38:54.747",
"Id": "75459",
"Score": "0",
"body": "Usually your classes needn't be disposable. But when you use a framework class then you should check whether it is disposable: if (only if) it is then it should be explicitly disposed. Your class should be disposable if it contains, as an instance data member, an instance of a class which needs to be disposed: e.g. Google for \"implement IDisposable\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:39:23.793",
"Id": "75460",
"Score": "0",
"body": "As for `static`, you can use it when a class contains no instance data at all: therefore you never need to create an instance of the PropertyGetter class, never mind dispose it: see for example [Static Classes and Static Class Members](http://msdn.microsoft.com/en-us/library/79b3xss3.aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T02:20:30.600",
"Id": "75524",
"Score": "1",
"body": "After reading that article and one on [Instance Constuctors](http://msdn.microsoft.com/en-us/library/k6sa6h87.aspx) I don't see any reason not to use static classes for these queries. However there are members of my group that have an aversion to static classes as they fear they lead to things staying in memory longer that a manually instantiated and disposed class. Can you help shed some light on the subject?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T06:07:00.557",
"Id": "75545",
"Score": "0",
"body": "@GabrielW I updated my answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:09:28.960",
"Id": "43602",
"ParentId": "43598",
"Score": "6"
}
},
{
"body": "<p>There is no reason for your <code>PropertyGetter</code> to be <code>IDisposable</code>, or to be disposed of after every usage - simply put it as a member of your classes.</p>\n\n<p>As an added bonus for this, you can declare the table name on the <code>PropertyGetter</code> instance, so you don't have to repeat it:</p>\n\n<pre><code>public class PropertyGetter\n{\n private string win32Class;\n\n public PropertyGetter(string win32Class) { \n this.win32Class = win32Class;\n }\n\n public ulong GetUlong(string propertyName)\n {\n ManagementObjectSearcher moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM \" + win32Class);\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext())\n {\n return 0;\n }\n return KiloBytesToMegaBytes((ulong)enu.Current[propertyName]);\n }\n }\n\n // ... etc.\n\n}\n\npublic class Win32OperatingSystem\n{\n private PropertyGetter propertyGetter = new PropertyGetter(\"Win32_OperatingSystem\");\n\n public Win32OperatingSystem() { }\n\n /// <summary>\n /// Number, in megabytes, of physical memory currently unused and available.\n /// </summary>\n public ulong FreePhysicalMemory()\n {\n return propertyGetter.GetUlong(\"FreePhysicalMemory\");\n }\n // ...\n}\n</code></pre>\n\n<p>Also, some of the properties which don't change (like processor architecture), you might want to cache your answers:</p>\n\n<pre><code>public class Win32Processor\n{\n private PropertyGetter propertyGetter = new PropertyGetter(\"Win32_Processor\");\n\n public Win32Processor() { }\n\n private ushort? _architecture;\n /// <summary>\n /// Processor architecture used by the platform.\n /// </summary>\n public ushort Architecture()\n {\n if (_architecture == null) {\n _architecture = propertyGetter.GetUshort(\"Architecture\");\n }\n return _architecture;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:14:58.970",
"Id": "43604",
"ParentId": "43598",
"Score": "2"
}
},
{
"body": "<p>I assume you are using Visual Studio <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>F</kbd> to format your code, thus I will spare you from formatting... But here's my 5 cents after reading your code twice:</p>\n<hr/> \n<h1>Naming</h1>\n<blockquote>\n<pre><code>using(PropertyGetter getProperty = new PropertyGetter())\n</code></pre>\n</blockquote>\n<p>could really use a rename... getProperty looks so much like a standard getter method.<br />\nAs you are always using the <code>PropertyGetter</code> only for one line, you might as well just name him: <code>pg</code>.</p>\n<blockquote>\n<pre><code>public String getString(string propertyName, string Win32Class)\n</code></pre>\n</blockquote>\n<p>and others on the other hand are in dire need for a refactor.</p>\n<p>You nicely use <code>camelCase</code> until there, but suddenly you switch to <code>PascalCasing</code>. Be consistent. Also you already can see it's a String from the type it returns. writing that in the name is not helpful or clear in any way...</p>\n<h1>Drying this out:</h1>\n<blockquote>\n<pre><code>public someType getType(string propertyName, string Win32Class) \n</code></pre>\n</blockquote>\n<p>is often repeated and almost completely the same in each one. You might instead want to go for:</p>\n<pre><code>public T? getProperty<T>(string propertyName, Win32Class parentClass){\n ManagementObjectSearcher moSearcher = \n new ManagementObjectSearcher("SELECT " + propertyName + " FROM " + class);\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext() || enu.Current[propertyName] == null)\n {\n return null;\n }\n return (T?)enu.Current[propertyName];\n }\n}\n</code></pre>\n<p>This method returns a nullable generic type of the inferred type you give. You could also return the inferred type itself, but then you are not allowed to return null. That is your choice to make.</p>\n<p>This assumes you have already extracted possible Win32Class values into an enum:</p>\n<pre><code>public enum Win32Class{\n Win32OperatingSystem, Win32ComputerSystem, [...]\n}\n</code></pre>\n<p>You'd then have to introduce nullchecks in your calling methods, similar to this one:</p>\n<pre><code>public ulong FreeVirtualMemory()\n{\n using (PropertyGetter pg= new PropertyGetter())\n {\n ulong? val = pg.getProperty<ulong>("FreeVirtualMemory", Win32Class.Win32_OperatingSystem);\n return val != null ? (ulong)val : (ulong)0;\n }\n}\n</code></pre>\n<p>Alternatively you just return T and nullcheck in <code>getProperty</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:20:03.380",
"Id": "75406",
"Score": "0",
"body": "Having 'string' in the name might be necessary, because you can't have overloaded method names which are overloaded only on the return type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:21:03.167",
"Id": "75407",
"Score": "0",
"body": "On unexpected null it would IMO be better to throw an exception than to return a bogus value such as `0`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:21:59.653",
"Id": "75408",
"Score": "0",
"body": "@ChrisW null is not unexpected... but i didn't want to switch the expected type to return the \"correct\" bogus value..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:30:11.540",
"Id": "75534",
"Score": "0",
"body": "I really like your 'getProperty' method and I can see where that would cut down that class greatly. But isn't it better to go with strongly typed things rather than objects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:32:25.713",
"Id": "75542",
"Score": "0",
"body": "@GabrielW `getProperty` should probably be private e.g. as shown in [my previous answer](http://codereview.stackexchange.com/a/43445/34757)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:07:14.640",
"Id": "75583",
"Score": "0",
"body": "`enu.Current[propertyName]` is of type `object`; so your `getProperty<T>` won't compile. It will compile if you make it return `T` instead of `T?` and if you include a cast i.e. `return (T)enu.Current[propertyName];`. IMO it should also be private, an implementation helper wrapped by public methods such as `FreeVirtualMemory()`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:15:49.037",
"Id": "43606",
"ParentId": "43598",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43602",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:22:39.240",
"Id": "43598",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Should I refactor for DRY?"
} | 43598 |
<p>I'm writing a simple table-oriented storage for objects. The schema of a table is stored in the <code>columns</code>-array and the data in the <code>rows</code>-array.</p>
<pre><code>// example: table "employees"
var columns = ["id", "name"]
var rows = [[1, "Alice"], [2, "Bob"]];
</code></pre>
<p>I wrote a function to convert a row-array into an object:</p>
<pre><code>function convertRowToObject(row) {
var result = {};
for (var i = 0; i < columns.length; i++) result[columns[i]] = row[i];
return result;
}
</code></pre>
<p>Now I can get an employee-object where I can access the fields by name, not by index.</p>
<pre><code>// [1, "Alice"] -> { id: 1, name: "Alice" }
</code></pre>
<p>Is there any way to get the <code>convertRowToObject</code> function any smaller? I think there should be a way to get rid of the loop and make this with a single line of code.</p>
| [] | [
{
"body": "<p>You could make it smaller by turning your function into a constructor:</p>\n\n<pre><code>function RowObject(row) {\n for (var i = 0; i < columns.length; i++) \n this[columns[i]] = row[i];\n}\n</code></pre>\n\n<p>You would have to call this function with <code>new</code> then. I would avoid putting the assignment on the same line as the <code>for</code>, it is too Golfic to maintain.</p>\n\n<p>The only way to avoid a loop is to fake it:</p>\n\n<pre><code>function convertRowToObject2(row) {\n //o -> object, v -> value, i -> index\n return row.reduce( function(o, v, i){ o[columns[i]] = v; return o; } , {} );\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:06:28.287",
"Id": "75427",
"Score": "1",
"body": "I like the one-liner, but the compiler will not know that he can handle the elements of the array independently, hence I will not be executed in parallel, as it can be done with map for example."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:02:30.933",
"Id": "43613",
"ParentId": "43603",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:12:40.873",
"Id": "43603",
"Score": "2",
"Tags": [
"javascript",
"array",
"properties"
],
"Title": "Create object-properties from an array"
} | 43603 |
<p>I've been suggested to put the following snippet of code up for review, hence I will do so, review of everything is appreciated, also posting as much relevant code as possible:</p>
<pre><code>abstract public class Primitive {
protected List<VertexData> vertexData;
public List<VertexData> getVertexData() {
return vertexData;
}
public static void calculateNormals(final List<Primitive> primitives) {
primitives.stream()
.flatMap(primitive -> primitive.getVertexData().stream())
.collect(Collectors.groupingBy(VertexData::getVertex)) //Map<Vector3f, List<VertexData>>
.entrySet().stream()
.map(Map.Entry::getValue) //List<VertexData>
.forEach(Primitive::calculateNormalsOfVertexData);
}
private static void calculateNormalsOfVertexData(final List<VertexData> vertexData) {
Vector3f averageNormal = vertexData.stream()
.map(VertexData::getNormal)
.reduce(new Vector3f().zero(), (n1, n2) -> n1.add(n2))
.scale(1f / vertexData.size());
vertexData.forEach(vd -> vd.setNormal(averageNormal));
}
}
</code></pre>
<hr>
<pre><code>public class VertexData {
private Vector3f vertex;
private Vector3f normal;
public VertexData(final Vector3f vertex, final Vector3f normal) {
this.vertex = vertex;
this.normal = normal;
}
public Vector3f getVertex() {
return vertex;
}
public void setVertex(final Vector3f vertex) {
this.vertex = vertex;
}
public Vector3f getNormal() {
return normal;
}
public void setNormal(final Vector3f normal) {
this.normal = normal;
}
@Override
public String toString() {
return "VertexData(" + vertex + ", " + normal + ")";
}
@Override
public int hashCode() {
int hash = 7;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final VertexData other = (VertexData) obj;
if (!Objects.equals(this.vertex, other.vertex)) {
return false;
}
if (!Objects.equals(this.normal, other.normal)) {
return false;
}
return true;
}
}
</code></pre>
<hr>
<pre><code>public class CustomCollectors {
/**
* Returns a mapping of an index to elements of the stream following the natural order at which the elements are to be encountered.
*
* @param <T> The type of th elements in the stream
* @return A Map<Long, T> that is indexed
*/
public static <T> Collector<T, ?, Map<Long, T>> indexing() {
return Collector.of(
HashMap::new,
(map, t) -> map.put(Long.valueOf(map.size() + 1), t),
(left, right) -> {
final long size = left.size();
right.forEach((k, v) -> left.put(k + size, v));
return left;
},
Collector.Characteristics.CONCURRENT
);
}
}
</code></pre>
<p>Now onto the real code snippet that I would like to be reviewed, first of all what the code does is the following:</p>
<p>Given a <code>List<Primitive></code>, I want to obtain an indexed <code>Map<Long, VertexData></code> of the distinct <code>VertexData</code> of the <code>Primitive</code>s.</p>
<p>My latest piece of code:</p>
<pre><code>Map<Long, VertexData> vdMapping = primitives.stream()
.flatMap(primitive -> primitive.getVertexData().stream())
.distinct()
.collect(CustomCollectors.indexing());
vdMapping.forEach((k, v) -> System.out.println("k = " + k + " / v = " + v));
</code></pre>
<p>Before the last refactoring:</p>
<pre><code>AtomicLong index = new AtomicLong();
Map<Long, VertexData> vdMapping = primitives.stream()
.flatMap(primitive -> primitive.getVertexData().stream())
.distinct()
.collect(Collectors.toMap(k -> index.getAndIncrement(), v -> v));
vdMapping.forEach((k, v) -> System.out.println("k = " + k + " / v = " + v));
</code></pre>
<p>And in comparison, how a Java 7 piece of code would look like:</p>
<pre><code>Map<Long, VertexData> vdMapping = new HashMap<>();
Set<VertexData> vdSet = new HashSet<>();
long index = 0;
for (Primitive primitive : primitives) {
for (VertexData vd : primitive.getVertexData()) {
vdSet.add(vd);
}
}
for (VertexData vd : vdSet) {
vdMapping.put(index++, vd);
}
for (Map.Entry<Long, VertexData> entry : vdMapping.entrySet()) {
System.out.println("k = " + entry.getKey() + " / v = " + entry.getValue());
}
</code></pre>
<p>A better name for <code>CustomCollector.indexing()</code> is also allowed.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-01T13:23:06.537",
"Id": "149067",
"Score": "2",
"body": "Instead of looping and doing `vdSet.add(vd);` you can in Java 7 do `vdSet.addAll(primitive.getVertexData());`"
}
] | [
{
"body": "<h2>long vs. int</h2>\n\n<p>In your map you are keyed off the long value of the index. The long is simply related to the size of the map as you accumulate things.</p>\n\n<p>A Map can never have more than Integer.MAX_INT members, thus you can never accumulate more than that number of key values.... thus, why are you using a Long when an Integer will suffice?</p>\n\n<h2>Simplification</h2>\n\n<p>Consider this simplification, where the distinct phase is done in the intermediate Collector:</p>\n\n<pre><code>Map<Long, VertexData> vdata = primitives\n .stream()\n .collect(Collector.of(\n LinkedHashSet<VertexData>::new,\n (acc, t) -> acc.add(t),\n (left, right) -> {left.addAll(right); return left;}))\n .stream().collect(CustomCollectors.indexing());\nvdMapping.forEach((k, v) -> System.out.println(\"k = \" + k + \" / v = \" + v));\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>In this particular case, I am not certain that the streaming API from Java8 is the right solution. You are creating much more uncertainty than needs to happen.</p>\n\n<p>The right solution to this is a LinkedHashSet data structure. Your Java7 equivalent is a better solution, but change the HashSet to a LinkedHashSet, and then your results are going to be deterministic. The code is simpler, more maintainable, and the parallel benefits of your stream are not possible anyway, so the added overheads of creating intermediate maps, running complicated <code>distinct()</code> filters, and other processes are just painful....</p>\n\n<p>Just because it <em>can</em> be done with a stream <em>does not</em> mean that is the better solution.</p>\n\n<hr>\n\n<p><strike></p>\n\n<h2>Collector associativeness</h2>\n\n<p>One of the properties of a Collector is that it <a href=\"http://download.java.net/jdk8/docs/api/java/util/stream/Collector.html\" rel=\"nofollow\">is supposed to be associative</a>.</p>\n\n<blockquote>\n <p>The associativity constraint says that splitting the computation must produce an equivalent result.</p>\n</blockquote>\n\n<p>Your collector is not associative. Consider your implementation:</p>\n\n<blockquote>\n<pre><code> return Collector.of(\n HashMap::new,\n (map, t) -> map.put(Long.valueOf(map.size() + 1), t),\n (left, right) -> {\n final long size = left.size();\n right.forEach((k, v) -> left.put(k + size, v));\n return left;\n },\n Collector.Characteristics.CONCURRENT\n );\n</code></pre>\n</blockquote>\n\n<p>If your collector is used on a concurrent stream, there is no way for you to determine the order of the combination function calls:</p>\n\n<blockquote>\n<pre><code> (left, right) -> {\n final long size = left.size();\n right.forEach((k, v) -> left.put(k + size, v));\n return left;\n },\n</code></pre>\n</blockquote>\n\n<p>For example, suppose your stream is split in two, and the two parts are accumulated in two maps <code>mapA</code> and <code>mapB</code>. Your collector should produce the same results regardless of whether <code>left == mapA && right == mapB</code> or whether <code>left == mapB && right == mapA</code>.</p>\n\n<p>Your streams will produce non-deterministic values for your inputs because your Collector is non-deterministic.</p>\n\n<p>I am not certain how I would solve this problem.... there has to be a way to 'tag' the data at the beginning of the stream such that it is labelled with a 'key' sooner.... instead of arbitrarily, and non-deterministically assigning one later. </p>\n\n<h2>Conclusion</h2>\n\n<p>I believe the code produces results that are 'correct' for the context of the way you use it, but the results are non-deterministic, and thus are going to be a problem in the future when things go wrong.</p>\n\n<p>You need to do something to fix the non-determinisim earlier in the stream:</p>\n\n<blockquote>\n<pre><code>Map<Long, VertexData> vdMapping = primitives.stream()\n .flatMap(primitive -> primitive.getVertexData().stream())\n .distinct()\n .collect(CustomCollectors.indexing());\nvdMapping.forEach((k, v) -> System.out.println(\"k = \" + k + \" / v = \" + v));\n</code></pre>\n</blockquote>\n\n<p>I believe the only decent solution would be to do something like guarantee sequential processing until the data leaves the <code>distinct()</code> phase, and then add a map phase at that point which numbers the <code>VertexData</code> that exits at that point.</p>\n\n<p></strike></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T13:49:37.130",
"Id": "44444",
"ParentId": "43607",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "44444",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:20:16.980",
"Id": "43607",
"Score": "7",
"Tags": [
"java",
"stream"
],
"Title": "Java 8 stream collector for numbering vertices"
} | 43607 |
<p>I want to factor out the <code>AsyncTask</code> to a <code>Manager</code>. I thought to make it a singleton, but then I cannot use generics as the object to serialize to JSON and send (e.g. <code>PostManager<T></code>).</p>
<p>How can this be refactored?</p>
<pre><code>public class RestPostActivity extends BaseActivity implements OnClickListener {
...
public static String POST(String url, Person person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin
// Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnPost:
if (!validate())
Toast.makeText(getBaseContext(), "Enter some data!",
Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask()
.execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG)
.show();
}
}
private boolean validate() {
if (etName.getText().toString().trim().equals(""))
return false;
else if (etCountry.getText().toString().trim().equals(""))
return false;
else if (etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
</code></pre>
| [] | [
{
"body": "<p>First thing I would do is separate the two concerns you have in the POST method.</p>\n\n<p>The POST method should have a different name (since <code>POST</code> does not match Java conventions), and the signature should be something like:</p>\n\n<pre><code>public static String httpPost(String url, JSONObject data) {\n ....\n}\n</code></pre>\n\n<p>And that method should handle the server communication.</p>\n\n<p>You should have a second method, perhaps Person.toJSON() that converts the Person to a JSONObject.</p>\n\n<p>I know I have used a different capitalization for <code>httpPost()</code> vs. <code>toJSON()</code>. For some reason, it makes sense to me since JSONObject is capitalized that way. Strict conformance to code-style guidelines suggests the method should be called <code>toJson()</code></p>\n\n<p>Once you have separated the concerns, the <code>httpPost(...)</code> method should be completely reusable.</p>\n\n<p>If you want to be smart, create an interface <code>JSONConvertible</code> like:</p>\n\n<pre><code>public interface JSONConvertible {\n public JSONObject toJSON();\n}\n</code></pre>\n\n<p>Then, you can have the stand-alone class (with the embedded httpPost method):</p>\n\n<pre><code>public class HttpPostAsyncTask extends AsyncTask<String, Void, String> {\n\n private static final String httpPost(String url, JSONObject value) {\n .....\n }\n\n private final JSONObject toPost;\n\n public HttpAsyncTask (JSONConvertible convertible) {\n this(convertible.toJSON());\n }\n\n public HttpPostAsyncTask(JSONObject json) {\n this.toPost = json;\n }\n\n @Override\n protected String doInBackground(String... urls) {\n return POST(urls[0], topost);\n }\n\n // onPostExecute displays the results of the AsyncTask.\n @Override\n protected void onPostExecute(String result) {\n Toast.makeText(getBaseContext(), \"Data Sent!\", Toast.LENGTH_LONG)\n .show();\n }\n}\n</code></pre>\n\n<p>Then, make <code>Person</code> implement <code>JSONConvertible</code> ....</p>\n\n<p>and you can simply do:</p>\n\n<pre><code>HttpPostAsyncTask atask = new HttpPostAsync(person);\n\natask.execute(url)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:27:34.317",
"Id": "75648",
"Score": "0",
"body": "thanks. How would you generalize \"GET\" in the same manner? you would create `FromJsonParseable fromJson (Objext obj)` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:31:35.313",
"Id": "75650",
"Score": "0",
"body": "I would probably do something similar, yes. As the data comes back, jave a custom method that interprets the JSON data back in to the right Java Object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:53:48.817",
"Id": "43632",
"ParentId": "43611",
"Score": "1"
}
},
{
"body": "<p>There are three types to do that.</p>\n\n<ol>\n<li>Use AsyncTask with Listener. <a href=\"https://stackoverflow.com/questions/22234924/having-trouble-with-async-task-and-flow-of-program/22235712#22235712\">Check the example here</a></li>\n<li>Use AsyncHttpHandler <a href=\"http://loopj.com/android-async-http/\" rel=\"nofollow noreferrer\">Here</a>.</li>\n<li>Combination of type 1 & 2</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:24:07.410",
"Id": "43686",
"ParentId": "43611",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "43632",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:55:19.567",
"Id": "43611",
"Score": "2",
"Tags": [
"java",
"android",
"database"
],
"Title": "Factoring out REST-POST activity to a manager"
} | 43611 |
<p>I have a lot of functions in this class to implement a login client. How do I modularize it ?</p>
<pre><code>from PyQt4 import QtGui, QtCore
from xml.dom.minidom import parseString
from datetime import datetime
import urllib2, urllib
import sys
import time
import base64
import fcntl
class Cyberoam(QtGui.QWidget):
def __init__(self):
super(Cyberoam, self).__init__()
self.initializeSettings()
self.createwindow()
self.placeContents()
self.attachSignals()
self.initializeSystemTray()
self.autologin()
def initializeSettings(self):
self.loggedIn = 0
self.actionMessages = ['&Login', '&Logout']
self.userSettings = {'url': 'http://172.50.1.1:8090', 'askonexit': '1',
'autologin': '0', 'lastuser': 'null', 'lastpassword': 'null',
'rememberme': '1'}
self.savedSettings = QtCore.QSettings("cyberoam-client", "cyberoam")
for key in self.userSettings.iterkeys():
if(self.savedSettings.contains(key)):
self.userSettings[key] = str(self.savedSettings.value(key).toString())
else:
self.savedSettings.setValue(key, self.userSettings[key])
if self.userSettings['lastuser'] != "null":
self.user = self.userSettings['lastuser']
else:
self.user = ""
if self.userSettings['lastpassword'] != "null":
self.password = base64.b64decode(self.userSettings['lastpassword'])
else:
self.password = ""
def createwindow(self):
self.setFixedSize(320, 300)
self.setWindowTitle("Cyberoam Client")
self.setWindowIcon(QtGui.QIcon("./cyberoam.png"))
#center window
qr = self.frameGeometry()
center = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(center)
self.move(qr.topLeft())
def placeContents(self):
self.userLabel = QtGui.QLabel("Username")
self.passwordLabel = QtGui.QLabel("Password")
self.userField = QtGui.QLineEdit()
self.passwordField = QtGui.QLineEdit()
self.passwordField.setEchoMode(QtGui.QLineEdit.Password)
self.rememberField = QtGui.QCheckBox("Remember Me")
self.actionButton = QtGui.QPushButton(self.actionMessages[self.loggedIn])
self.exitButton = QtGui.QPushButton("&Exit")
self.settingsButton = QtGui.QPushButton("&Settings")
self.statusLabel = QtGui.QTextEdit()
self.statusLabel.setReadOnly(True)
layout = QtGui.QGridLayout()
layout.setSpacing(10)
layout.addWidget(self.userLabel, 1, 0)
layout.addWidget(self.passwordLabel, 2, 0)
layout.addWidget(self.userField, 1, 1)
layout.addWidget(self.passwordField, 2, 1)
layout.addWidget(self.rememberField, 3, 0)
layout.addWidget(self.actionButton, 4, 0)
layout.addWidget(self.settingsButton, 4, 1)
layout.addWidget(self.exitButton, 5, 1)
layout.addWidget(self.statusLabel, 6, 0, 1, 2)
self.setLayout(layout)
self.userField.setText(self.user)
self.passwordField.setText(self.password)
if self.userSettings['rememberme'] == '1':
self.rememberField.setChecked(True)
self.show()
def attachSignals(self):
self.actionButton.clicked.connect(self.handleActionButton)
self.settingsButton.clicked.connect(self.showSettingsWindow)
self.exitButton.clicked.connect(self.exitApp)
self.trytimer = QtCore.QTimer(self)
self.trytimer.timeout.connect(self.login)
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.relogin)
self.passwordField.returnPressed.connect(self.handleActionButton)
def initializeSystemTray(self):
self.tray = QtGui.QSystemTrayIcon(QtGui.QIcon("./cyberoam.png"), self)
menu = QtGui.QMenu(self)
windowAction = menu.addAction("Hide/Restore")
windowAction.triggered.connect(self.changeWindowStatus)
exitAction = menu.addAction("Exit")
exitAction.triggered.connect(self.exitApp)
self.tray.setContextMenu(menu)
self.tray.activated.connect(self.handleTrayAction)
self.tray.show()
def changeWindowStatus(self):
if self.isHidden():
self.show()
else:
self.hide()
def autologin(self):
if self.userSettings['autologin'] == '1':
if self.userSettings['lastuser'] != "null" and self.userSettings['lastpassword'] != "null":
self.login()
if self.loggedIn == 1:
self.hide()
else:
self.updateStatus("Could not auto login. Username or password missing!")
else:
self.statusLabel.setText("Not Logged In")
def handleTrayAction(self):
if self.isHidden():
self.show()
else:
self.hide()
def handleActionButton(self):
if self.loggedIn == 0:
if self.userField.text() == "" or self.passwordField.text() == "":
self.updateStatus("Username or Password Missing!")
return
self.user = str(self.userField.text())
self.password = str(self.passwordField.text())
val = {}
if self.rememberField.isChecked():
val['lastuser'] = self.user
val['rememberme'] = '1'
val['lastpassword'] = base64.b64encode(self.password)
else:
val['lastuser'] = self.user
val['rememberme'] = '0'
val['lastpassword'] = "null"
self.saveSettings(val)
self.login()
elif self.loggedIn == 1:
self.logout()
def showSettingsWindow(self):
self.settingsWindow = QtGui.QDialog(self)
self.settingsWindow.setFixedSize(300, 150)
self.settingsWindow.setWindowTitle("Settings")
urlLabel = QtGui.QLabel("Url")
askOnExitLabel = QtGui.QLabel("Ask On Exit")
autoLoginLabel = QtGui.QLabel("Auto Login")
self.urlField = QtGui.QLineEdit()
self.askOnExitField = QtGui.QCheckBox()
self.autoLoginField = QtGui.QCheckBox()
okButton = QtGui.QPushButton("&OK")
okButton.clicked.connect(self.handleSaveSettings)
cancelButton = QtGui.QPushButton("&Cancel")
cancelButton.clicked.connect(self.settingsWindow.close)
layout = QtGui.QGridLayout()
layout.addWidget(urlLabel, 1, 0)
layout.addWidget(self.urlField, 1, 1)
layout.addWidget(askOnExitLabel, 2, 0)
layout.addWidget(self.askOnExitField, 2, 1)
layout.addWidget(autoLoginLabel, 3, 0)
layout.addWidget(self.autoLoginField, 3, 1)
layout.addWidget(okButton, 4, 0)
layout.addWidget(cancelButton, 4, 1)
self.settingsWindow.setLayout(layout)
self.settingsWindow.show()
self.urlField.setText(self.userSettings['url'])
if self.userSettings['askonexit'] == '1':
self.askOnExitField.setChecked(True)
if self.userSettings['autologin'] == '1':
self.autoLoginField.setChecked(True)
def saveSettings(self, val):
for key in val.iterkeys():
self.userSettings[key] = str(val[key])
self.savedSettings.setValue(key, str(val[key]))
self.savedSettings.sync()
def handleSaveSettings(self):
val = {}
val['url'] = str(self.urlField.text()).strip(" /")
if self.askOnExitField.isChecked():
val['askonexit'] = '1'
else:
val['askonexit'] = '0'
if self.autoLoginField.isChecked():
val['autologin'] = '1'
else:
val['autologin'] = '0'
self.saveSettings(val)
self.settingsWindow.close()
def updateStatus(self, message):
timestamp = str(datetime.now().strftime("[ %I:%M:%S %p ] ")).lower()
self.statusLabel.append(timestamp + message)
def login(self):
self.trytimer.stop()
self.timer.stop()
cyberoamAddress = self.userSettings['url']
data = {"mode":"191","username":self.user,"password":self.password,"a":(str)((int)(time.time() * 1000))}
try:
self.updateStatus("Sending Log In request...")
myfile = urllib2.urlopen(cyberoamAddress + "/login.xml", urllib.urlencode(data) , timeout=3)
except IOError:
self.updateStatus("Error: Could not connect to server")
self.trytimer.start(1000)
return
data = myfile.read()
myfile.close()
dom = parseString(data)
xmlTag = dom.getElementsByTagName('message')[0].toxml()
message = xmlTag.replace('<message>', '').replace('</message>', '').replace('<message/>', '')
message = message.replace('<![CDATA[','').replace('logged in]]>','logged in.')
xmlTag = dom.getElementsByTagName('status')[0].toxml()
status = xmlTag.replace('<status>', '').replace('</status>', '')
if status.lower() != 'live':
self.updateStatus("Error: " + message)
return
self.updateStatus(message)
self.loggedIn = 1
self.userField.setEnabled(False)
self.passwordField.setEnabled(False)
self.rememberField.setEnabled(False)
self.actionButton.setText(self.actionMessages[self.loggedIn])
self.tray.setIcon(QtGui.QIcon("./cyberoam-loggedin.png"))
self.setWindowIcon(QtGui.QIcon("./cyberoam-loggedin.png"))
self.passwordField.setText("abcdefghijklmnopqrstuvwxyz")
self.timer.start(180000)
def relogin(self):
cyberoamAddress = self.userSettings['url']
data = {"mode":"192","username":self.user,"a":(str)((int)(time.time() * 1000))}
try:
self.updateStatus("Sending Logged In acknowledgement request...")
myfile = urllib2.urlopen(cyberoamAddress + "/live?"+urllib.urlencode(data), timeout=3)
except IOError:
self.updateStatus("Error: Could not connect to server")
self.logout()
self.trytimer.start(1000)
return
data = myfile.read()
myfile.close()
dom = parseString(data)
xmlTag = dom.getElementsByTagName('ack')[0].toxml()
message = xmlTag.replace('<ack>', '').replace('</ack>', '')
if message == 'ack':
self.updateStatus("You are logged in")
else:
self.updateStatus("Error: Server response not recognized: " + message)
self.login()
return
def logout(self):
self.trytimer.stop()
self.timer.stop()
if self.userSettings['lastpassword'] != 'null':
self.passwordField.setText(self.password)
else:
self.passwordField.setText("")
self.userField.setEnabled(True)
self.passwordField.setEnabled(True)
self.rememberField.setEnabled(True)
self.tray.setIcon(QtGui.QIcon("./cyberoam.png"))
self.setWindowIcon(QtGui.QIcon("./cyberoam.png"))
if self.loggedIn == 1:
self.loggedIn = 0
self.actionButton.setText(self.actionMessages[self.loggedIn])
self.timer.stop()
cyberoamAddress = self.userSettings['url']
data = {"mode":"193","username":self.user,"a":(str)((int)(time.time() * 1000))}
try:
self.updateStatus("Sending Log Out request...")
myfile = urllib2.urlopen(cyberoamAddress + "/logout.xml", urllib.urlencode(data), timeout=3)
except IOError:
self.updateStatus("Error: Could not connect to server")
return
data = myfile.read()
myfile.close()
dom = parseString(data)
xmlTag = dom.getElementsByTagName('message')[0].toxml()
message = xmlTag.replace('<message>', '').replace('</message>', '')
self.updateStatus(message)
def closeEvent(self, event):
self.hide()
event.ignore()
def exitApp(self):
if self.userSettings['askonexit'] == '1':
reply = QtGui.QMessageBox.question(self, "Exit Cyberoam", "Are you sure you want to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply != QtGui.QMessageBox.Yes:
return
self.logout()
QtCore.QCoreApplication.instance().quit()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:56:06.937",
"Id": "43612",
"Score": "1",
"Tags": [
"python",
"authentication",
"pyqt"
],
"Title": "Implementing a login client"
} | 43612 |
<p>I have a program that processes Microsoft Office documents (and other kinds, but primarily Office). I am replacing one purchased product that performs this processing with a new one. This new product consists of a library which is linked in to my code and a Windows service, which performs the actual work. For the most part this new product works better than the old one, but it has a flaw in how it handles some Office documents. Documents that are password-protected can't be processed, and furthermore the third-party product never returns from processing them. For my code this is not a problem; I run the call to the processing on a separate thread with a timeout. After a while I give up. Unfortunately the third-party Windows service does not, and it turns out that it has only a limited number of processing slots. If I send too many documents that don't finish processing, the service stops processing new requests.</p>
<p>I have developed a "hack" to work around this flaw. All requests for processing are sent as lambdas to the class I show below. The requests are multi-threaded at a higher level, so there may be more than one request processing at any time. If a request fails (either by returning false or by throwing an exception), the class stops processing new requests by having threads wait on a manual reset event and waits for threads that are currently processing to finish. Once there are no more running requests for processing, the class calls the code that restarts the service. Once the reset finishes, the class releases any threads waiting on the manual reset event.</p>
<p>There are a number of points on which I am looking for review. First, I have concerns about the correctness of the multi-threaded code. There is one "flaw" that I know about. If any of the passed-in lambdas go into an infinite loop, the reset won't work. This is mitigated in the rest of the code where the lambdas have a "timed executor" wrapper around themselves. But I could have made the timed executor part of the reset class, and I wonder if I should have.</p>
<p>Second, see if it follows SOLID principles. For instance, I wonder if the class is "too big." I can't think of any way I could split it, but it looks a bit big to me.</p>
<p>Third I am unhappy about how the reset action and reset fail action lambdas are set, because they can be accessed by any code at any time. In my code these are set only once, but there's nothing preventing them from being reset by other code. Because this is a singleton, the constructor is private and called in the class, so the obvious solution of passing in these lambdas on the constructor won't work. I don't have any good ideas on how to solve this, if in fact it needs solving.</p>
<p>Bonus: I wish the class had a better name.</p>
<p>Note, his was written for .NET version 2.0. Because of that, I have defined two delegates that are part of later versions of .NET, Action() and Func(). </p>
<pre><code>public class CoordinatedActionWithReset {
private static CoordinatedActionWithReset() {
_coordinatedActionWithReset = new CoordinatedActionWithReset();
}
private readonly object _coordinatedActionWithResetLock = new object();
private int _countCurrentlyExecuting;
private bool _resetRequested;
private readonly ManualResetEvent _waitForReset = new ManualResetEvent(true);
private static CoordinatedActionWithReset _coordinatedActionWithReset;
private CoordinatedActionWithReset() {
ResetAction = () => { };
ResetFailAction = (ex) => { };
}
public static CoordinatedActionWithReset Instance {
get { return _coordinatedActionWithReset; }
}
public delegate void Action();
public delegate T Func<T>();
public Action ResetAction { get; set; }
public Action<Exception> ResetFailAction { get; set; }
private void RequestReset() {
lock (_coordinatedActionWithResetLock) {
_resetRequested = true;
_waitForReset.Reset();
CheckForReset();
}
}
public bool ExecuteAction(Func<bool> action) {
DelayIfResetPending();
bool goodResult;
try {
goodResult = action();
if (!goodResult) {
RequestReset();
}
}
catch {
goodResult = false;
RequestReset();
}
finally {
EndAction();
}
return goodResult;
}
private void DelayIfResetPending() {
var succeeded = false;
while (!succeeded) {
_waitForReset.WaitOne();
lock (_coordinatedActionWithResetLock) {
if (!_resetRequested) {
_countCurrentlyExecuting++;
succeeded = true;
}
}
}
}
private void EndAction() {
lock (_coordinatedActionWithResetLock) {
_countCurrentlyExecuting--;
CheckForReset();
}
}
private void CheckForReset() {
if (_resetRequested && _countCurrentlyExecuting == 0) {
Reset();
}
}
private void Reset() {
try {
ResetAction();
}
catch (Exception ex) {
try {
ResetFailAction(ex);
}
catch { }
}
finally {
_resetRequested = false;
_waitForReset.Set();
}
}
}
</code></pre>
| [] | [
{
"body": "<p>There's one thing that annoys me about your class and it's the order of the code. You should follow this order: </p>\n\n<ol>\n<li>Private members </li>\n<li>Constructors</li>\n<li>Properties</li>\n<li>Methods</li>\n</ol>\n\n<p>Your code looks fine, but you could pull the delegates out of your class, since they have their own reason to \"live\" and are not linked to your class and you should remove the <code>private</code> modifier to your <code>static</code> constructor, this doesn't compile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-06T15:13:35.380",
"Id": "126136",
"Score": "0",
"body": "Actually (see http://www.stylecop.com/docs/SA1201.html), it's recommended to do: Fields, Constructors, Properties, Methods. Also, private static constructors are valid in c# (and recommended, see: http://msdn.microsoft.com/en-us/library/ms182320.aspx), what is the reason for it not compiling?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-06T15:32:30.430",
"Id": "126140",
"Score": "0",
"body": "I'm confused, if I try to add any accessibility modifier to a static constructor in my Visual Studio (2013, C# 5) I get a compiler error. And thank you for the recommended order, I'll update my answer :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-06T15:45:47.367",
"Id": "126145",
"Score": "0",
"body": "My mistake, looks like that rule is language agnostic, and you're correct, c# static constructors are private by default and should not have access modifiers."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-07T13:11:53.473",
"Id": "64980",
"ParentId": "43615",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:27:43.420",
"Id": "43615",
"Score": "6",
"Tags": [
"c#",
"multithreading"
],
"Title": "Safely resetting an outside service that handles requests from multiple threads"
} | 43615 |
<p>A lookup (table) is an array that replaces run time computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than undergoing an 'expensive' computation or input/output operation.</p>
<p>Over time the definition has become less strict, any kind of searching with a key value can be considered a lookup.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:30:18.883",
"Id": "43616",
"Score": "0",
"Tags": null,
"Title": null
} | 43616 |
A lookup (table) is an array that replaces run-time computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than undergoing an 'expensive' computation or input/output operation.
Over time the definition has become less strict, any kind of searching with a key value can be considered a lookup. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:30:18.883",
"Id": "43617",
"Score": "0",
"Tags": null,
"Title": null
} | 43617 |
<p>I just want to checking if this kind of routing is good or bad?</p>
<p>I implement the routing of my web appl to something like this.</p>
<p>All page will be pointing to the index.php</p>
<p>in index.php I have this code</p>
<pre><code>$url = array_values(array_filter( explode( '/', strtolower($_SERVER["REQUEST_URI"]) ) ) );
switch( $url[0] ) {
case "admin" : {
if( !$this->us->isAdmin ) {
$this->GoToLoginPage();
}
array_shift( $uri );
$department = new Admin( $uri );
} break;
case "article" : {
if( count( $uri ) == 2 ) {
displayArticle( $uri[1] );
}
else {
displayError();
}
} break;
default : {
displayIndex();
} break;
}
</code></pre>
<p>I just want to know is there any pro and con of doing something like this.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:38:44.887",
"Id": "75416",
"Score": "0",
"body": "I would separate the logic and the site specific functionality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:13:15.020",
"Id": "75463",
"Score": "0",
"body": "What your mean by separate logic and site specific functionality?"
}
] | [
{
"body": "<p>Separate your logic and site specific functionality like this:</p>\n\n<pre><code>function Router{\n $url = array_values(array_filter(explode('/', strtolower($_SERVER[\"REQUEST_URI\"]))));\n switch($url[0]){\n case \"admin\": $this->Admin($url);\n break;\n case \"article\": $this->Article($url);\n break;\n default: displayIndex();\n }\n}\n\nfunction Admin($uri){\n if( !$this->us->isAdmin ) {\n $this->GoToLoginPage();\n }\n array_shift( $uri );\n $department = new Admin( $uri );\n}\n\nfunction Article($uri){\n if( count( $uri ) == 2 ) {\n displayArticle( $uri[1] );\n } else {\n displayError();\n }\n}\n</code></pre>\n\n<p>It's much cleaner, and easier to update.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:03:20.997",
"Id": "43710",
"ParentId": "43618",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43710",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:36:12.207",
"Id": "43618",
"Score": "1",
"Tags": [
"php"
],
"Title": "Is my routing good or bad? in PHP"
} | 43618 |
<p>This question specifically relates to the use of the class constants ABOVE and BELOW in the sample code below.</p>
<p>I have a few different classes that look like this:</p>
<pre><code>class MyClass(object):
ABOVE = 1
BELOW = 0
def __init__(self):
self.my_numbers = [1,2,3,4,5]
def find_thing_in_direction(self, direction, cutoff):
if direction == self.ABOVE:
return [n for n in self.my_numbers if n > cutoff]
else:
return [n for n in self.my_numbers if n < cutoff]
my_class = MyClass()
my_var = my_class.find_thing_in_direction(MyClass.ABOVE, 3)
</code></pre>
<p>If I have a handful of classes scattered across different .py files that each have their own <code>ABOVE</code> and <code>BELOW</code>, should I extract these constants to somewhere, or is it better to keep the constants within their own classes?</p>
<p>Is there a more Pythonic way to do this instead of using these class constants?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:25:45.517",
"Id": "75458",
"Score": "0",
"body": "Updated the code to be working python in response to off-topic flags"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:54:42.853",
"Id": "75468",
"Score": "0",
"body": "Your two return statement both seem to return the same thing: surely that's not correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:32:36.090",
"Id": "75478",
"Score": "0",
"body": "I fixed the suspected bug"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:16:36.790",
"Id": "75494",
"Score": "2",
"body": "Looking for [an enum type](https://pypi.python.org/pypi/enum34)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:44:13.967",
"Id": "75498",
"Score": "0",
"body": "@JanneKarila Wow, I did not know about that package. I'm really going to go and rewrite a bunch of code now. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T21:18:32.960",
"Id": "75501",
"Score": "0",
"body": "This was cross-posted on SO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T21:20:02.283",
"Id": "75502",
"Score": "0",
"body": "@Marc-Andre Yes, originally the question was put on hold and I wasn't sure it would be reopened. I asked on the Programming chat and they suggested it would be better at SO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T21:21:44.277",
"Id": "75503",
"Score": "0",
"body": "@user939259 I got no problem with that! I find it more suitable for SO myself. I was just informing people here that it has been posted somewhere else."
}
] | [
{
"body": "<p>I think the answer depends on the scope of your constants. </p>\n\n<p>If you're trying to keep the constants the same across your handful of classes, i.e., you have many class definitions and they all use ABOVE and BELOW, and ABOVE and BELOW always have the same value, then you should pull them out. You could put them into a base class and create subclasses from that base class:</p>\n\n<pre><code>class myBaseClass(object):\n ABOVE = 1\n BELOW = 0\n\n\nclass mySubclass(myBaseClass):\n \"\"\" ABOVE and BELOW will be available here \"\"\"\n pass\n</code></pre>\n\n<p>If the scope is greater than that, say module-level then put the definitions in the module <code>__init__.py</code></p>\n\n<p>Greater still? Then maybe move them to a settings file.</p>\n\n<p>Otherwise if the scope is where you currently have it then it's ok as-is.</p>\n\n<p>The line:</p>\n\n<pre><code>my_var = my_class.find_thing_in_direction(MyClass.ABOVE, 3)\n</code></pre>\n\n<p>puzzles me because you're referring to the constant of the Class when the instance already has it itself. It's not wrong, just differs from my reaction to use the object's own attributes:</p>\n\n<pre><code> my_var = my_class.find_thing_in_direction(my_class.ABOVE, 3)\n</code></pre>\n\n<p>If you go the way of a base class, have a look at <a href=\"http://docs.python.org/2/library/abc.html\" rel=\"noreferrer\">ABCs</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T08:34:14.213",
"Id": "481436",
"Score": "0",
"body": "Surely ABOVE and BELOW are class, not instance constants, similar to static variables in a Java class. Therefore they should be referenced as such, and `MyClass.ABOVE` is correct."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:16:57.840",
"Id": "43648",
"ParentId": "43619",
"Score": "9"
}
},
{
"body": "<p>You get strong kudos for not making this a boolean parameter <code>above</code> where passing <code>True</code> gets you the above search and <code>False</code> gets the below search. Yet it's worth taking a step back here to ask a different question first: should you even expose constants? In order to answer this, you must determine how your direction parameter will be used in practice.</p>\n\n<p>As <a href=\"https://mail.python.org/pipermail/python-dev/2009-April/088860.html\" rel=\"noreferrer\">reported by Nick</a>, Guido gave some advice for functions or methods that expose a boolean parameter. Namely, if callers \"almost always [pass] a literal <code>True</code> or <code>False</code>, [it] is a good sign that there are two functions involved rather than just\none.\" Prefer to provide these two functions—one for each case—and make the boolean parameter part of the function's name.</p>\n\n<p>Your function takes an enumeration with two values, instead of a boolean, but I believe the advice holds. It takes <code>x.ABOVE</code> and <code>x.BELOW</code>, and you're trying to determine what <code>x</code> should be. Instead you need to figure out what the callers of your function will look like. Will they hardcode the direction, or will they be wrappers that determine the direction variably?</p>\n\n<pre><code># Scenario 1: hardcoded \"literals\"\nabove = my_class.find_thing_in_direction(x.ABOVE, 3)\nbelow = my_class.find_thing_in_direction(x.BELOW, 3)\n\n# Scenario 2: passed value\nresult = my_class.find_thing_in_direction(direction, value)\n</code></pre>\n\n<p>If your callers are almost always going to be in scenario 1, that is if they almost always know the direction they are asking for, it would be better to rewrite the interface to avoid this extra parameter. It does make the second scenario a little harder, though:</p>\n\n<pre><code># Modified for scenario 1:\nabove = my_class.find_thing_above(3)\nbelow = my_class.find_thing_below(3)\n\n# Repercussions on scenario 2:\nif direction == x.ABOVE:\n result = my_class.find_thing_above(3)\nelse:\n result = my_class.find_thing_below(3)\n</code></pre>\n\n<p>As Nick said, this is not universal advice; there are exceptions. For instance, if you have more than just <code>ABOVE</code> and <code>BELOW</code>, it may be painful to expose all the various options as their own function. Consider as well the impact on the implementation. With your example code, it's trivial this way, and is arguably cleaner than the original:</p>\n\n<pre><code>def find_thing_above(self, cutoff):\n return [n for n in self.my_numbers if n > cutoff]\n\ndef find_thing_below(self, cutoff):\n return [n for n in self.my_numbers if n < cutoff]\n</code></pre>\n\n<p>However if the search itself was more complex, its repetition would dominate, and you will likely want to factor all search options into a single main function internally. Internally used values don't have to be quite as easily understood as values that client code might pass. In the example given by your code, perhaps you could pass a predicate:</p>\n\n<pre><code># assume real search pattern is more complex than a single list comprehension\ndef _find_thing(self, predicate):\n return [n for n in self.my_numbers if predicate(n)]\n\ndef find_thing_above(self, cutoff):\n return self._find_thing(lambda n: n > cutoff)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T15:04:06.587",
"Id": "43860",
"ParentId": "43619",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43648",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:38:15.263",
"Id": "43619",
"Score": "19",
"Tags": [
"python",
"classes",
"constants"
],
"Title": "Proper use of class constants"
} | 43619 |
<p>I am building a PHP framework and would like to get some feedback on a few different sections of the project so far. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing these different tasks in an efficient and or correct way. </p>
<p>I am currently working on a session management class. What I have done is create methods that deal with a specific action when dealing with sessions. Pinoniq has suggested to me:</p>
<blockquote>
<p>Always think this: everything you code must solve some kind of
problem. If it doesn't solve a problem. Remove it.</p>
</blockquote>
<p>So I kept that in mind when creating this class. </p>
<p>What I am trying to do in this class is create methods that do most of the work for you when creating and working with sessions.</p>
<p>Methods like <code>namePattern()</code> and <code>ParamBreak()</code> are operations for use inside the class class method.</p>
<pre><code>class Sessions {
/**
* Start a session
*
* @param $id string - Set sestion id
* @return boolean or trigger_error
*/
public function StartSession($id = null){
if(!session_start()){
trigger_error('Unble to create session',E_USER_WARNING);
}
if($id != null && is_string($id)){
//Check pattern to make sure it's supported
if($this->namePattern($id)){
return session_id($id);
}
}
return true;
}
/**
* Create a session value in the $_SESSION array
* if key is not supplied then one will be
* created and incremented
* automaticly
*
* @param $key string - Index key for array
* @param $value mixed - value to be stored
*/
public function CreateSession($key = null,$value = null){
if(!$key && !$value){
trigger_error('Missing argument for Sessions::CreateSession()');
}
if(empty($value)){
$value = $key;
$key = null;
}
$_SESSION[$this->FindSessionKey($key)] = $value;
return true;
}
/**
* Return or set the session_id
*
* @param $id string - string to set the id to
* @return current session_id
*/
public function SessionId($id = null){
if(isset($id)){
return session_id($id);
}
return session_id();
}
/**
* Check if the key supplied exists in the $_SESSION array
* if not increment to the next value
*
*
* @param $key mixed -
*/
private function FindSessionKey($key){
if(!empty($_SESSION)){
$index = count($_SESSION)-1;
if(!isset($key)){
return $index+1;
}else{
if(array_key_exists($key,$_SESSION)){
return $index+1;
}else{
return $key;
}
}
}
if(isset($key)){
return $key;
}
return 0;
}
public function SearchSessions($key = null,$value = null){
}
/**
* Remove a session using a key as the needle
*
* @param $key mixed - key to find the value
* @return void
*/
public function RemoveSessionByKey($key){
if(is_array($key) || ($key = $this->ParamBreak($key))){
for ($i=0; $i < count($key); $i++) {
unset($_SESSION[$this->KeyCycle($key[$i])]);
}
}else{
unset($_SESSION[$this->KeyCycle(func_get_arg(0))]);
}
}
/**
* Find a return a key value
*
* @param $key mixed - key to compare to
* @return $key found
*
* To be honest looking at this again I
* have no idea whats going on. It works
* but "WHAT WAS I DOING?" I don't know.
*/
public function KeyCycle($key){
if(is_string($key)){
$key = trim($key);
}
while(current($_SESSION) !== false){
if($key == ($index = key($_SESSION))){
//Prevent the removing of index 0
//if $key index are not found
if($key == 0 && $index == $key){
return $index;
}
return $index;
}
next($_SESSION);
}
}
/**
* Remove a unset a session value using its
* value as the needle
*
* @param $value string -
*/
public function RemoveSessionByValue($value){
if(is_array($value) || ($value = $this->ParamBreak($value))){
for ($i=0; $i < count($value); $i++){
for($j=0; $j < count($_SESSION); $j++){
unset($_SESSION[$this->ValueCycle($value[$i])]);
}
}
}else{
for($j=0; $j < count($_SESSION); $j++){
unset($_SESSION[$this->ValueCycle(func_get_arg(0))]);
}
}
}
protected function ValueCycle($value){
if(is_string($value)){
$value = trim($value);
}
while(current($_SESSION) !== false){
if($value === current($_SESSION)){
return key($_SESSION);
}
next($_SESSION);
}
}
public function RemoveSessionByValuei($pattern){
for ($i=0; $i < count($_SESSION) ; $i++) {
if(is_array($_SESSION[$i])){
for ($j=0; $j < count($_SESSION[$i]); $j++) {
if(preg_match($pattern,$_SESSION[$i][$j],$match) > 0){
unset($_SESSION[$i][$j]);
$this->RemoveSessionByValue($match[0]);
}
}
}else{
if(preg_match($pattern,$_SESSION[$i],$match) > 0){
unset($_SESSION[$i]);
}
}
}
}
public function ReturnSession($key){
if(array_key_exists($key, $_SESSION)){
return $_SESSION[$key];
}
return false;
}
public function ReturnAllSessions(){
if(!empty($_SESSION)){
return $_SESSION;
}
return false;
}
public function ShowSessions(){
return var_dump($_SESSION);
}
public function DestroySessions(){
return session_destroy();
}
protected function ParamBreak($string){
if(strpos($string,',') !== false){
return explode(',', $string);
}
return false;
}
private function namePattern($string){
if(preg_match('/^([a-zA-Z0-9\,\-])+$/',$string) > 0){
return $string;
}
return false;
}
}
</code></pre>
| [] | [
{
"body": "<p>First off the code is hard to make sense of, because I only see part of it. Most importantly I don't have the source for SessionsStruction class, which you are extending, and the name \"Struction\" doesn't make any sense to me (is it even in dictionary?).</p>\n\n<p>It would also help to have a code sample of using this class.</p>\n\n<p>The class also has no documentation describing its purpose - and after reading it all, I'm still wondering what's this all about.</p>\n\n<p>Some immediate problems I see with this class:</p>\n\n<ul>\n<li><p>It has too many responsibilities - parsing config file and debugging the sessions data (in ShowSessions method) should be handled outside of this class.</p></li>\n<li><p>It has too wide API - an entire 13 public methods. Do you really need to provide such fine-grained interface?</p></li>\n<li><p>It depends on global state: APP_PATH, CURRENT_FILE are defined somewhere else. Consider passing them in as parameters instead. Also the $_SESSION var.</p></li>\n<li><p>why the empty __destroy() and SearchSessions() methods?</p></li>\n<li><p>why the RemoveSession() which just delegates to RemoveSessionByKey()?</p></li>\n<li><p>why the unused $active and $maltivalue class variables?</p></li>\n<li><p>you really should check your spelling.</p></li>\n- \n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T06:11:50.087",
"Id": "81269",
"Score": "0",
"body": "Thank you for your feedback. I have added more to the post in hope that it will help. I have removed the portions of the class that are not needed to explain and run the class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:41:01.430",
"Id": "81419",
"Score": "0",
"body": "Now that I've seen some examples of using this class, it makes me wonder, why should one use this whole complicated thing instead of directly using the $_SESSION variable? All the features it adds, look kinda weird and not very useful. Like when I ask it to create a field with already existing name, it assigns a numeric field instead, but I have no way of knowing, which field did it assign to. Why would I ever want that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T03:29:46.697",
"Id": "81445",
"Score": "0",
"body": "I understand, thank you for your comment. I am building a PHP framework to learn and experiment with PHP. I am currently working on the Session handling portion of it. I am posting my code to get feedback on its structure and code layout in hope to get any suggestions or advice on how it might be better."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T19:22:35.053",
"Id": "46488",
"ParentId": "43620",
"Score": "5"
}
},
{
"body": "<p>Here is some examples in how this class can be used</p>\n\n<pre><code>$session = new Session();\n//Start new session\n$session->StartSession();\n\n//Print sessions ID\necho \"SESSION ID: \".$session->SessionID();\n\n$array = array(1=>'One',2=>'two',3=>'three', 4=>4);\n\n //Add value to session array\n$session->CreateSession('Array',$array);\n$session->CreateSession(1,'Zim');\n$session->CreateSession('Tak');\n$session->CreateSession('Gaz');\n\n//.Uset session with ID 1\n$session->RemoveSessionByKey(1);\n\n//return value $array\n$value = $session->ReturnSession('Array'); \n\n//Destroy session\n$session->DestroySessions();\n\n\necho '<pre>';\necho $session->ShowSessions(); \necho '</pre>';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:31:26.850",
"Id": "46569",
"ParentId": "43620",
"Score": "1"
}
},
{
"body": "<p>First of I think you have written the start of some good functionality, but there are some aspects of the session that I think you have interpreted a little wrong.</p>\n\n<p>The session is a mechanism is designed be very generic while storing data specific to an id. This id could then be linked to a login or something similar. But the values of an session could be anything or be stored in any order and this are therefore never known. So you cannot rely of the value if you do a look up, in fact that would ruin the purpose of sessions in the first place. If you already know the value, then why use sessions? Consider from the mentioned example about a login where a username and a user id (an integer) is stored. The user id is not always the first element in the sessions array, so a call to <code>$_SESSION[0]</code> could possibly return the username (a string) and make trouble in for code because of the wrong type and wrong values. Because of such inconsistencies session elements are always stored with an unique key, which can be used for retrieval. When I say session can store anything keep in mind that best practice is to keep only what is required in the session. Remember the session can be hijacked by attackers and a session with a bunch of information takes longer to load, this is especially true when using file- or database-based storing mechanism. </p>\n\n<p>Now to the code itself. Thinking about the things I have outlined above, some of your methods should be restructured or lose their purpose entirely. First the <code>FindSessionKey()</code> method. Because all values should be associated with a KNOWN unique key, auto-incrementing (while making the key that started as a string an integer) an array key at an unknown index almost spells trouble for you down the road. How would you retrieve that again? With the key (string) that does not work or an unknown integer that could change from time to time? This leads me the to <code>CreateSession()</code> method. Here the <code>key</code> and <code>value</code> arguments are optional (why both?). Such should not happen. If you do not have a value then why store it? And if you do not have an unique key then how would you retrieve the value again? The value could be <code>nice car</code> as well as <code>bumble bee</code> or any other thing you can imagine. This would be quite hard to code. For the same reasons <code>KeyCycle()</code> (as you said yourself, what is it doing?), <code>RemoveSessionByValue()</code>, <code>ValueCycle</code> and <code>RemoveSessionByValuei()</code> should be removed as we do not rely on the value.</p>\n\n<p>Now when all these methods that could spell trouble are removed, you have a good foundation, but there is more (there always is :D). The <code>SearchSessions()</code> method could be extracted into its own class along with other utility methods. I have utility class named <code>SessionUtilities</code> which declares the methods <code>increment($key, $interval = 1)</code> and <code>decrement($key, $interval = 1)</code> (<code>increment()</code> and <code>decrement()</code> checks if the value is an integer) and a <code>compare($key, $value, $strict = false)</code> etc. These are used for easier <strong>manipulation</strong> of the session array.</p>\n\n<p>Now to the code structure. The <code>FindSessionKey</code> method could use <em>early returns</em> to make the code more readable. I feel like the <code>RemoveSessionByKey()</code> method should only take one key. This will make your calling code a little more verbose, but help readability as another developer (or yourself) shouldn't keep track of which values are stored in the array defining the keys to be removed. When we have removed this feature the <code>ReturnSession()</code> method does the same, but with less code. If you want the functionality to remove from an array, then make it clear in the method name and arguments list. Example: <code>RemoveSessionByArray(array $keys)</code>?</p>\n\n<p>The <code>StartSession()</code> method could be extracted to another class which would give you more flexibility. PHP provides a way to overwrite the standard behavior when working with sessions. Take a look at the <a href=\"http://php.net/manual/en/class.sessionhandler.php\" rel=\"nofollow\"><code>SessionHandler</code></a> class or the <a href=\"http://php.net/manual/en/class.sessionhandlerinterface.php\" rel=\"nofollow\"><code>SessionHandlerInterface</code></a> interface. By creating a class extending the <code>SessionHandler</code> or implementing the <code>SessionHandlerInterface</code> you wouldn't have to write methods operations such as opening, closing and destroying the session as the native PHP functions would use your implementation. Now <code>session_start()</code>, <code>session_write_close()</code> and <code>session_destroy()</code> all responds to the behavior you have provided. This will also make it easier for other developers not aware of your class, as they can stick with the native functions.</p>\n\n<p>Then you should add some error handling. Consider using a <code>constructor</code> that can check if sessions are enabled at all before using the class.</p>\n\n<pre><code>public function __construct() {\n\n $status = session_status();\n\n // Check if sessions are enabled.\n if($status == PHP_SESSION_DISABLED) {\n throw new \\LogicException('Sessions are disabled.');\n }\n\n // Check if sessions are started.\n if($status == PHP_SESSION_NONE) {\n session_start();\n }\n\n}\n</code></pre>\n\n<p>Now you have checked if sessions are enabled on the server and made sure that a session is active before working with them. See the <a href=\"http://php.net/manual/en/function.session-status.php\" rel=\"nofollow\"><code>session_status()</code></a> documentation for more information.</p>\n\n<p>Now to some less important things. Experience have learned me that methods which can both <code>set</code> and <code>get</code> are very prone to errors. Consider your method <code>SessionId()</code>. If you provide an <code>$id</code> it will <code>get</code>, otherwise it will <code>set</code> the id. Consider making that two different methods <code>setSessionId($id)</code> and <code>getSessionId()</code>. That will make your code more readable as well.\nEven though we have removed the <code>KeyCycle()</code> and <code>ValueCycle()</code> methods I am going to write a little about their <code>visibility</code>. Methods only used by the class should be declared <code>private</code>. That is also true of properties. A good rule is to keep as many methods <code>private</code> and only declare internal methods <code>protected</code> if they are known to be used by child classes. If the situation arises where a private method could be used by a child class, then change the visibility of that method to <code>protected</code>. The reason is that child classes can now declare their own methods of the same name (helps if the name is used often) and child classes is now unable to overwrite the behavior (change the return type etc.) of methods the parent class relies on.\nAt last before I will give you my version of a session class I must write a little about naming.</p>\n\n<p>As said in one of the other posts, method/function names usually starts with lowercase letters. Then it is up to you if you want to use the <a href=\"http://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow\">CamelCase</a> or <a href=\"http://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow\">Snake_case</a> naming convention. Usually in PHP only clasess, abstract classes, interfaces and traits starts with an uppercase letter. And a for the purists, abstract classes, interfaces and traits also have appended their type to the name such as <code>ClassnameAbstract</code>, <code>SomeTrait</code> or <code>AwesomeInterface</code>.\nTaking all that in consideration I think you can rename some of your methods. You often write methods where the word <code>session</code> takes place. Consider removing this entirely as we already know what class we are working with, the <code>Sessions</code> class. A good rule is to find the shortest, BUT most describing name. So <code>FindSessionKey</code> could be renamed to <code>find</code> or <code>get</code>? And the <code>CreateSession</code> could be renamed to <code>set($key, $value)</code>? Even though the shortest name is preferred don't make it an excuse for naming your methods or variables <code>$i</code>, <code>i()</code> or <code>getFOrDName</code> (get file or directory name) as that has no indication of what is doing/storing what so ever. The same goes for the <code>RemoveSessionByKey</code>. As we only work on keys in the session the <code>ByKey</code> part should be self evident and the method could be renamed to <code>remove($key)</code>?</p>\n\n<p>That was quite a lot, so I have written a simple class as an example of all that I have mentioned.</p>\n\n<pre><code>class Session {\n\n public function __construct() {\n\n $status = session_status();\n\n if($status == PHP_SESSION_DISABLED) {\n throw new \\LogicException('Sessions are disabled.');\n }\n\n if($status == PHP_SESSION_NONE) {\n session_start();\n }\n\n }\n\n /**\n * Gets a session value associated with the specified key.\n *\n * @param string $key\n *\n * @return mixed|null Returns the value on success. NULL if the key doesn't exist.\n */\n public function get($key) {\n if(array_key_exists($key, $_SESSION)) {\n return $_SESSION[$key];\n }\n return null;\n }\n\n /**\n * Set a new session elements or update an existing one.\n *\n * @param string $key\n * @param mixed $value\n */\n public function set($key, $value) {\n $_SESSION[$key] = $value;\n }\n\n /**\n * Deletes a session element.\n *\n * @param string $key\n *\n * @return bool\n */\n public function delete($key) {\n if(array_key_exists($key, $_SESSION)) {\n unset($_SESSION[$key]);\n return true;\n }\n return false;\n }\n\n /**\n * Determines if a session key exists.\n *\n * @param string $key\n *\n * @return bool\n */\n public function exists($key) {\n return array_key_exists($key, $_SESSION);\n }\n\n}\n</code></pre>\n\n<p>And a minor thing. In the <code>KeyCycle()</code> method you have written a comment. This is good, but remember to use the correct comment type. Single line comments are indicated by</p>\n\n<pre><code>// This is a single line comment.\n</code></pre>\n\n<p>and multi-line comments are indicated by:</p>\n\n<pre><code>/*\n * This is a multi-line\n * comment.\n */\n</code></pre>\n\n<p>But be aware the <a href=\"http://www.phpdoc.org/docs/latest/index.html\" rel=\"nofollow\">PHP documentation</a> body looks like the multi-line comment, but starts with two star symbols <code>/**</code> and uses a clearly defined syntax.</p>\n\n<p>I hope this can guide you, happy coding!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-11T10:08:39.997",
"Id": "150736",
"Score": "0",
"body": "Thanks @anotherguy for the feedback. Once again very helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T18:58:43.457",
"Id": "212367",
"Score": "0",
"body": "This is what I call \"some free time\" :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-04T11:49:59.007",
"Id": "79559",
"ParentId": "43620",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:45:25.130",
"Id": "43620",
"Score": "6",
"Tags": [
"php",
"design-patterns"
],
"Title": "PHP framework building: Sessions Managment Class"
} | 43620 |
<p>I am writing a Sudoku solver in C, but am having problems with how long it takes to run. It can solve easier puzzles but once I put in one a little more difficult it runs and runs and never stops.</p>
<pre><code>int solver (int x, int y)
{
int a;
int b;
int i;
int j;
printf("Depth: %d\n", counter);
for (a=1; a<10; a++)
{
if (checkEverything(x, y, a))
{
board[x][y] = a;
counter++;
if (counter == 81)
{
return true;
}
if (counter > 200 || counter < -10) {
return false;
}
for (i=0; i<9; i++)
{
for (j=0; j<9; j++)
{
if (board[i][j] == 0)
{
if (solver(i, j))
{
return true;
}
}
}
}
counter--;
//printf("%d", a);
}
}
//printf("No Solution1");
board[x][y] = 0;
return false;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:03:43.380",
"Id": "75431",
"Score": "0",
"body": "maybe threads help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:04:35.250",
"Id": "75432",
"Score": "1",
"body": "What is `checkEverything()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:04:37.247",
"Id": "75433",
"Score": "3",
"body": "@parsaporahmad Why should threads make anything faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:04:43.340",
"Id": "75434",
"Score": "6",
"body": "Please format your code correctly, even if it takes you 3 minutes more !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:05:42.017",
"Id": "75435",
"Score": "6",
"body": "`if ( board[x][y] = a; xxx;`? (The code requires a bit more than just formatting)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:06:18.127",
"Id": "75436",
"Score": "0",
"body": "@Till do you prefer to pick up 10 things with 1 hand while you have got two? so why should not threads make anything faster? do you believe in GPU?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:08:10.703",
"Id": "75437",
"Score": "3",
"body": "Put a counter in and check how many guesses you are making. Mathemathics suggests this runs in the *billions*. Try to make a \"hard\" Sudoku into a \"simple\" one by first testing for easy solutions on rows, columns, and blocks, before going Brute Force."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:17:08.217",
"Id": "75438",
"Score": "2",
"body": "I don't see any of the important parts here so I don't know why it's slow. If it takes more than a few seconds to solve a 9x9 sudoku, the algorithm is flawed. I did a sudoku solver (in java) that solves (one solution) all \"hard\" examples on wiki in one or two seconds, and human solvable (or at least by me) in a few milliseconds. It's based on a naive depth first search with backtracking, but the trick to get that to work is to calculate all \"fixed\" positions before going bananas with generating solution candidates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:51:19.557",
"Id": "209514",
"Score": "1",
"body": "[This is your algorithm](http://www.youtube.com/watch?v=TYM4QKMg12o). Now do you see why it takes so long? There are lots of web sites on writing a fast Sudoku solver. My articles on how to do so in C# are [here](http://blogs.msdn.com/b/ericlippert/archive/tags/graph+colouring/). You can adopt the algorithm described here to the language of your choice."
}
] | [
{
"body": "<p>There are a number of things that could be improved in this code.</p>\n\n<h2>Post complete code</h2>\n\n<p>I understand that this code was migrated from Stack Overflow where the rules are a little different, but here on Code Review, we want to see not just one small piece but the whole code. I can guess what <code>checkEveryting()</code> and <code>solver()</code> might do, but you'll get better reviews here by not making reviewers guess.</p>\n\n<h2>Use a better algorithm</h2>\n\n<p>The fundamental problem with this code is that the algorithm is very inefficient. Look at the <strong>Related</strong> panel to the right and you'll see more than a half dozen other similar programs. Look over those to get ideas about how this might more efficiently be done.</p>\n\n<h2>Make the formatting consistent</h2>\n\n<p>The code currently include this:</p>\n\n<pre><code> if (counter == 81)\n {\n return true;\n }\n\n if (counter > 200 || counter < -10) {\n return false;\n }\n</code></pre>\n\n<p>In one case, the opening <code>{</code> is on the same line, and in the other it's on the next line. It's a small thing, but it's useful to choose a convention and stick with it.</p>\n\n<h2>Avoid the use of global variables</h2>\n\n<p>I see that <code>counter</code> and <code>board</code> are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. </p>\n\n<h2>Use meaningful variable names</h2>\n\n<p>The variable names <code>a</code>, and <code>b</code> are not at all descriptive. Better naming makes your code easier to read, understand and maintain.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>Unused variables are a sign of poor code quality, so eliminating them should be a priority. In this code, <code>b</code> is declared but never actually used. My compiler also tells me that. Your compiler is probably also smart enough to tell you that, if you ask it to do so. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-27T14:36:02.253",
"Id": "115184",
"ParentId": "43624",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T20:01:05.103",
"Id": "43624",
"Score": "3",
"Tags": [
"c",
"performance",
"sudoku"
],
"Title": "Faster Sudoku solver in C"
} | 43624 |
<p>I want a thread safe list with a max item count, will the following implementation correctly provide this?</p>
<pre><code>public class ConcurrentThrottledList<T>
{
private readonly List<T> items = new List<T>();
private readonly int maxItems;
private object _lock = new object();
public ConcurrentThrottledList(int maxItems)
{
this.maxItems = maxItems;
}
public bool TryAdd(T item)
{
lock (_lock)
{
if (items.Count < maxItems)
{
items.Add(item);
return true;
}
return false;
}
}
public bool TryRemove(T item)
{
lock (_lock)
{
return items.Remove(item);
}
}
public bool IsFull { get { lock (_lock) { return items.Count >= maxItems; } } }
public T[] Items { get { lock(_lock) { return items.ToArray(); } } }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:54:52.853",
"Id": "75443",
"Score": "0",
"body": "I really can't see anything to improve."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:22:31.570",
"Id": "75566",
"Score": "0",
"body": "Thanks everyone, all your comments are well received. The input is much appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:41:50.683",
"Id": "75569",
"Score": "0",
"body": "You might want to expose `Count` similarly if is `IsFull` is useful. For example in a client/server application to show the clients the (most up-to-date available) number elements in some lists and not just if they are full or not. Currently `.Items.Length` would cause memory waste."
}
] | [
{
"body": "<blockquote>\n <p>will the following implementation correctly provide this?</p>\n</blockquote>\n\n<p>Yes, it would appear so.</p>\n\n<p>Minor comments:</p>\n\n<ul>\n<li>TryRemove could be called Remove (because List.Remove is called Remove).</li>\n<li>IsFull may not be useful (because it may be obsoleted by a subsequent Remove by another thread, before this thread is able to act on the IsFull return value)</li>\n<li>Do you want to be able to remove any element? If not, if you only want to remove the first or last element, then ConcurrentQueue or ConcurrentStack might be better than List (in which case only your TryAdd method would need your own explicit lock). </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:19:50.713",
"Id": "43630",
"ParentId": "43627",
"Score": "4"
}
},
{
"body": "<p>@ChrisW made valuable comments, I'll add mine:</p>\n<h3>Well done:</h3>\n<ul>\n<li>I like that private fields are all<sup>1</sup> <code>readonly</code>, this makes intent explicit, which works towards greater maintainability.</li>\n<li>I like that the class is highly cohesive and focused, this works towards greater readability, maintainability and extensibility.</li>\n</ul>\n<h3>Nitpicks:</h3>\n<ul>\n<li><p>I don't see why <code>_lock</code> gets an underscore and <code>items</code> and <code>maxItems</code> don't; being consistent with the underscore prefix for private fields would mootinate the <code>this</code> qualifier in the constructor.</p>\n</li>\n<li><p><code>Items</code> could be called <code>ToArray</code>, making it more consistent with the framework's lingo, and more representative of its semantics.</p>\n</li>\n<li><p><code>TryAdd</code> and <code>TryRemove</code> both look like they were named after <a href=\"https://stackoverflow.com/questions/5505391/is-there-a-name-for-this-pattern\">the <code>TryParse</code> pattern</a>; a developper looking at the API would then also be expecting an <code>Add</code> and a <code>Remove</code> method:</p>\n<ul>\n<li><code>Add</code> would add the specified item, throw an exception if it can't, and return <code>void</code>.</li>\n<li><code>TryAdd</code> would add the specified item, return <code>true</code> if successful and <code>false</code> otherwise.</li>\n<li><code>Remove</code> would remove the specified item, throw an exception if it can't, and return <code>void</code>.</li>\n<li><code>TryRemove</code> would remove the specified item, return <code>true</code> if successful and <code>false</code> otherwise.</li>\n</ul>\n</li>\n</ul>\n<p><strong>However</strong>, <a href=\"http://msdn.microsoft.com/en-us/library/cd666k3e(v=vs.110).aspx\" rel=\"nofollow noreferrer\"><code>List<T>.Remove()</code></a> is already taking care of returning <code>false</code> if the specified item cannot be removed - throwing an exception in that case would be utter nonsense. Therefore, I'll second @ChrisW in saying that <code>TryRemove</code> should be simply called <code>Remove</code>.</p>\n<p>I agree with <code>TryAdd</code> being called as such, because I would seriously expect an <code>Add</code> method to return <code>void</code>, so I'd <em>consider</em> also having an <code>Add</code> method that throws some <code>CapacityExceededException</code> (or whatever is more appropriate) when it can't add the specified item.</p>\n<hr />\n<p><sub><sup>1</sup> I would be led to believe <code>_lock</code> could also be made <code>readonly</code>, but I don't work with enough multithreaded code to know whether that would/could impact anything.</sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:53:56.203",
"Id": "43636",
"ParentId": "43627",
"Score": "5"
}
},
{
"body": "<p>In addition to the existing answers:</p>\n\n<ol>\n<li><p>I concur that <code>IsFull</code> is probably not all that useful.</p></li>\n<li><p><code>_lock</code> should be <code>readonly</code></p></li>\n<li><p>Your class is called <code>ConcurrentThrottledList</code> but you don't implement any of the collection interfaces. If you want to make it more useful consider implementing <code>IEnumerable<T></code>, <code>ICollection<T></code> and possibly <code>IList<T></code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:43:36.913",
"Id": "43645",
"ParentId": "43627",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T16:44:47.190",
"Id": "43627",
"Score": "8",
"Tags": [
"c#",
"thread-safety"
],
"Title": "ConcurrentThrottledList - Will this implementation be thread safe?"
} | 43627 |
<p>I need to take data from a MySQL database and message it into a format expected by the front end of an application - I can not change the front end as other services provide it data in this same format.</p>
<p>The database is structured as follows:</p>
<pre><code>id type value label optgroup
1 car ix5 Ford Taurus Ford
2 car ix6 Ford Focus Ford
3 car ix9 Cobalt Chevy
4 planet ix8 Earth Default
</code></pre>
<p>The output from this code must do the following: for types with optgroups, records must be categorized by optgroup; if there is only one optgroup, then it should be ignored. The real data has hundreds to thousands of rows per type. The finally array output from this data would be:</p>
<pre><code>$data = [
'car' => [
'chevy' => [ 'ix9' => 'Cobalt' ],
'ford' => [ 'ix5' => 'Ford Taurus', 'ix6' => 'Ford Focus' ]
],
'planet' => [ 'ix8' => 'earth' ]
];
</code></pre>
<p>The code I have doing this currently works, but is a bit slow, and I am looking for a possible improvement. Here's the functioning code, where <code>$STH->result()</code> is the database result as an array of rows:</p>
<pre><code>protected function _format($STH)
{
$data = [];
foreach ($STH->result() as $row)
{
if ( ! $row->optgroup)
$data[ $row->type ][ $row->value ] = $row->label;
else
$data[ $row->type ][ $row->optgroup ][ $row->value ] = $row->label;
}
// selects with a single optgroup can have that optgroup removed
foreach ($data as $menutype => $optorkey)
{
if (is_array($optorkey) && count($optorkey) == 1)
$data[$menutype] = current($optorkey);
}
return $data;
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>The original query generating the data is very simple, as follows:</p>
<pre><code>SELECT type, value, label, optgroup FROM ####.options ORDER BY type, optgroup, label ASC
</code></pre>
<p>The data in this table is updated frequently by automated processes.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:17:54.917",
"Id": "75495",
"Score": "1",
"body": "slow just means it could be faster; for the current dataset it runs for about .75 seconds but it runs on EVERY page load. Currently I'm caching the results for 30 seconds but honestly web pages shouldn't take .75 in total to generate, much less for a few dozen menus -- maybe there's no a faster way to do it, but I thought here would be the place to ask."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:33:11.440",
"Id": "75574",
"Score": "0",
"body": "I'd be interested to know how big your table is/is supposed to be. Also are your times there *just* for the formatting of the data or does it include the query? It'd be good to know if the operation is spending time streaming data off disk or processing it in php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:08:29.527",
"Id": "75615",
"Score": "0",
"body": "Can you post the SQL query you are using? That would better allow us to determine if PHP is at fault or if an intricate SQL query is at fault."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:42:44.817",
"Id": "75680",
"Score": "0",
"body": "@jsanc623 The times are just for formatting data, the query itself is very simple and fast. See above edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:59:05.350",
"Id": "75692",
"Score": "0",
"body": "@Erik - thanks! Just wanted to make sure that wasn't a cause. Are you able to do a `top` on the machine running the script while the script is running and see if PHP bubbles in memory or CPU usage? If not, use http://us2.php.net/memory_get_usage to get the memory usage of the script."
}
] | [
{
"body": "<p><strong>Non-optimizing suggestions</strong></p>\n\n<p>Your SQL is not very clear. What kind of object is acceptable for the <code>type</code> column, and how do you manage to put items into that column? How specific or general should the terms be in that column? What is the <code>value</code> column? <code>label</code>, and even <code>optgroup</code>? To me, these are extremely confusing. Is <code>optgroup</code> a group of options, or a group of outputs? <a href=\"http://leshazlewood.com/software-engineering/sql-style-guide/\" rel=\"nofollow\">This isn't official</a>, but it's a good read and it might help you.</p>\n\n<p>If each value of <code>value</code> (naming confusion right there!) starts with \"ix\", then why is it there? I can't even tell what that column means because the Earth comes between two cars! Anyways, if each entry starts with that prefix, consider adding it in your PHP.</p>\n\n<p><strong>Optimizing...</strong></p>\n\n<p>I don't see to much you can do. Your query is already quite minimal, but I'm not an expert there. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T01:25:18.680",
"Id": "43761",
"ParentId": "43635",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:41:22.217",
"Id": "43635",
"Score": "5",
"Tags": [
"php",
"optimization"
],
"Title": "How can I optimize this database to array structure code?"
} | 43635 |
<p>After reading @JavaDeveloper's <a href="https://codereview.stackexchange.com/q/43579/489">recent question</a>, I was inspired<sup>1</sup> to try my hand at writing code to accomplish the same task.</p>
<p>The "rules" for this code (i.e., its intent) is to match a subset of regular expressions, defined as follows:</p>
<blockquote>
<ol>
<li><code>.</code> (dot) means a any single character match</li>
<li><code>*</code> (star) means 0 or more character match</li>
<li><code>?</code> (question) means previous char is an option i.e <code>colou?r</code> matches <code>color</code> and <code>colour</code>.</li>
</ol>
</blockquote>
<p>Just to be clear: I'm well aware that this is <em>not</em> how regular expressions are normally defined, and that the fundamental capability of this subset is exactly that--a subset of what full regexes can recognize/match.</p>
<p>As an aside: although tagging a question with both C and C++ is normally a mistake, I believe in this case it's justified. In particular, the <code>match</code> function is at least intended to be work as either C or C++. The test rig (enabled by defining <code>TEST</code> when compiling) uses features to specific to C++, but <code>match</code> itself should not.</p>
<p>Without further ado, my attempt at implementing this functionality:</p>
<pre><code>#include <string.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
bool match(char const *needle, char const *haystack) {
for (; *needle!='\0'; ++needle) {
switch (*needle) {
case '.': ++haystack;
case '?': break;
case '*': {
size_t max = strlen(needle);
for (size_t i = 0; i < max; i++)
if (match(needle + 1, haystack + i))
return true;
return false;
}
default:
if (*haystack == *needle)
++haystack;
else if (needle[1] != '?')
return false;
}
}
return *haystack == '\0';
}
#ifdef TEST
#include <iostream>
#include <vector>
#include <string>
template<class F>
void assertTrue(F f, char const *needle, char const *hay_stack) {
static const std::string names [] = { "Failure", "Success" };
std::cout << names[f(needle, hay_stack)];
std::cout << " for: " << needle << "->" << hay_stack << "\n";
}
template<class F>
void assertFalse(F f, char const *needle, char const *hay_stack) {
static const std::string names [] = { "Success", "Failure" };
std::cout << names[f(needle, hay_stack)];
std::cout << " for: " << needle << "->" << hay_stack << "\n";
}
int main(){
assertTrue(match,"colou?**rs", "colours");
assertTrue(match,"colou?**rs", "colors");
assertTrue(match,"colou**?rs", "colours");
// assertTrue(RegexToy.match,"colou**?rs", "colors"); <---- exlusive case.
assertTrue(match,"colou?**r", "colour");
assertTrue(match,"colou?**r", "color");
assertTrue(match,"colou?*", "colou");
assertTrue(match,"colou?*", "colo");
assertTrue(match,"colou?r", "colour");
assertTrue(match,"colou?r", "color");
assertTrue(match,"colou?*?r", "colour");
assertTrue(match,"colou?*?r", "color");
// Success cases
assertTrue(match,"", "");
assertTrue(match, "***", "");
std::vector<char const *> regexList { "abc****", "abc", "a*b*c", "****abc", "**a**b**c****", "abc*" };
char const *str1 = "abc";
for (auto regex : regexList)
assertTrue(match,regex, str1);
char const *regex = "abc****";
std::vector<char const *> strList1 { "abcxyz", "abcx", "abc" };
for (auto str : strList1)
assertTrue(match,regex, str);
regex = "***abc";
std::vector<char const *> strList2 { "xyzabc", "xabc", "abc" };
for (auto str : strList2)
assertTrue(match, regex, str);
assertTrue(match, "a.c", "abc");
assertTrue(match, "a*.*c", "abc");
assertTrue(match,"a*.b.*c", "axxbxxbxxc");
// Fail cases.
assertFalse(match,"abc", "abcd");
assertFalse(match,"*a", "abcd");
assertFalse(match,"a", "");
assertFalse(match,".a*c", "abc");
assertFalse(match,"a.*b", "abc");
assertFalse(match,"..", "abc");
assertFalse(match,"", "abc");
}
#endif
</code></pre>
<hr>
<ol>
<li>Along with stealing the idea from @JavaDeveloper, I also stole his test rig, with only minor editing. I hope that's not a problem (I think my making attribution to him clear mans it falls within SE's licensing).</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T00:47:44.697",
"Id": "75520",
"Score": "0",
"body": "This is actually a complete wildcards grammar, I think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T00:55:40.197",
"Id": "75521",
"Score": "0",
"body": "@AJMansfield: It is much closer to globbing than normal regexes, but I decided to keep the same rules as the previous question."
}
] | [
{
"body": "<p>The regex flavour is non-standard, as you noted. Just to be clear, <code>?</code> acts as a zero-or-one-of-the-previous-character modifier, while <code>*</code> acts more like a shell glob.</p>\n\n<p>You have an access-past-the-end-of-string error when testing for glob matches in a test such as this:</p>\n\n<pre><code>assertFalse(match, \"**a\", \"b\");\n</code></pre>\n\n<p>The for-loop speculatively matches <code>max</code> substrings of the <code>haystack</code>, where <code>max</code> is based on the length of the <code>needle</code>. If the matches don't succeed, you could easily walk past the end of the haystack.</p>\n\n<p>Your <code>switch</code> block is fragile: the <code>'.'</code> case relies on the <code>break</code> of the following <code>'?'</code> case. That's a bit too clever and dangerous for my taste, and a warning comment would be useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:10:35.817",
"Id": "75490",
"Score": "0",
"body": "Good point--I'd intended `strlen(haystack)`, but that's not quite right either. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:03:18.440",
"Id": "43647",
"ParentId": "43637",
"Score": "2"
}
},
{
"body": "<p>The output of your unit tests is unintuitive. For example,</p>\n\n<blockquote>\n<pre><code>Success for: ..->abc\n</code></pre>\n</blockquote>\n\n<p>Huh? That should not match. Oh, it turns out that it was an <code>assertFalse()</code>. It would have been clearer to print</p>\n\n<pre><code>[PASS] Match ..->abc returns false\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:35:24.357",
"Id": "43650",
"ParentId": "43637",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43647",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:54:01.197",
"Id": "43637",
"Score": "6",
"Tags": [
"c++",
"c",
"regex"
],
"Title": "Another regex subset matcher"
} | 43637 |
<p>This is my first attempt to create an STL-compliant container. I'd like to know whether it meets STL concepts & requirements, so feel free to critique.</p>
<p><a href="https://www.mediafire.com/?0c5zb05izkinjnu" rel="nofollow"><strong>list.h</strong></a></p>
<pre><code>#include <cstdint>
#include <limits>
#include <memory>
#include <iterator>
#include <type_traits>
#include <initializer_list>
#include <algorithm>
#include <utility>
#include <functional>
template <typename T, typename Allocator = std::allocator<T>>
class clist
{
private:
struct node
{
public:
node() : m_pT(nullptr), m_pNext(nullptr), m_pPrev(nullptr) {}
void loop() {this->m_pNext = this; this->m_pPrev = this;}
static void link(node *lhs, node *rhs) {lhs->m_pNext = rhs; rhs->m_pPrev = lhs;}
void unlink()
{
if (this->m_pPrev != nullptr) {this->m_pPrev->m_pNext = this->m_pNext;}
if (this->m_pNext != nullptr) {this->m_pNext->m_pPrev = this->m_pPrev;}
}
void reverse() {std::swap(this->m_pPrev, this->m_pNext);}
private:
T *m_pT;
node *m_pNext;
node *m_pPrev;
friend class clist<T, Allocator>;
};
template <bool is_const_iter>
class iterator_cnc : public std::iterator<std::bidirectional_iterator_tag, typename std::conditional<is_const_iter, const T, T>::type>
{
using node_ptr_type = typename std::conditional<is_const_iter, const node*, node*>::type;
using const_reference = const T&;
public:
iterator_cnc() : m_pT(nullptr) {}
iterator_cnc(node_ptr_type p) : m_pT(p) {}
iterator_cnc(const iterator_cnc<false> &it) : m_pT(it.m_pT) {}
bool operator == (const iterator_cnc &rhs) {return (this->m_pT == rhs.m_pT);}
bool operator != (const iterator_cnc &rhs) {return !((*this) == rhs);}
reference operator * () {return *(this->m_pT->m_pT);}
const_reference operator * () const {return *(this->m_pT->m_pT);}
iterator_cnc& operator ++ () {this->m_pT = this->m_pT->m_pNext; return (*this);}
iterator_cnc& operator -- () {this->m_pT = this->m_pT->m_pPrev; return (*this);}
iterator_cnc operator ++ (int) {iterator_cnc rv(*this); this->m_pT = this->m_pT->m_pNext; return rv;}
iterator_cnc operator -- (int) {iterator_cnc rv(*this); this->m_pT = this->m_pT->m_pPrev; return rv;}
pointer operator -> () {return &(*(*this));}
private:
node_ptr_type m_pT;
friend class clist<T, Allocator>;
};
using value_type = T;
using reference = T&;
using const_reference = const T&;
using allocator_type = Allocator;
using allocator_traits = typename std::allocator_traits<allocator_type>;
using pointer = typename allocator_traits::pointer;
using const_pointer = typename allocator_traits::const_pointer;
using iterator = iterator_cnc<false>;
using const_iterator = iterator_cnc<true>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using difference_type = typename iterator::difference_type;
using size_type = std::size_t;
using node_allocator_type = typename allocator_traits::template rebind_alloc<node>::other;
using node_allocator_traits = typename std::allocator_traits<node_allocator_type>;
// [decl--virt] [st] [type] [cc] [name]
node_allocator_type& _alc() {return this->m_alloc_node;}
allocator_type _alcv() {return allocator_type(this->m_alloc_node);}
typename node_allocator_traits::pointer _mknode(pointer pv = nullptr);
void _delnode(typename node_allocator_traits::pointer p, bool destrv = false);
template <typename... Args> pointer _mkval(Args &&... args);
void _delval(pointer p);
void _mkinit() {node::link(this->m_head = this->_mknode(), this->m_tail = this->_mknode());}
void _delinit() {if (this->m_head) {this->_delnode(this->m_head);} if (this->m_tail) {this->_delnode(this->m_tail);}};
public:
explicit clist(const Allocator &alloc = Allocator())
: m_alloc_node(node_allocator_type(alloc))
{this->_mkinit();}
explicit clist(size_type count, const T &v, const Allocator &alloc = Allocator())
: clist(alloc)
{this->resize(count, v);}
explicit clist(size_type count, const Allocator &alloc = Allocator())
: clist(alloc)
{this->resize(count);}
template <typename InputIt>
clist(InputIt first, InputIt last, const Allocator &alloc = Allocator())
: clist(alloc)
{this->insert(this->end(), first, last);}
clist(const clist<T, Allocator> &l, const Allocator &alloc)
: clist(alloc)
{for (auto &v : l) {this->emplace_back(v);}}
clist(const clist<T, Allocator> &l)
: clist(l, node_allocator_traits::select_on_container_copy_construction(l._alc()))
{}
clist(clist<T, Allocator> &&l, const Allocator &alloc);
clist(clist<T, Allocator> &&l)
: clist(std::move(l), l._alcv())
{}
clist(std::initializer_list<T> l, const Allocator &alloc = Allocator())
: clist(alloc)
{this->insert(this->cbegin(), l);}
~clist()
{this->clear(); this->_delinit();}
clist<T, Allocator>& operator = (const clist<T, Allocator> &l);
clist<T, Allocator>& operator = (clist<T, Allocator> &&l);
clist<T, Allocator>& operator = (std::initializer_list<T> l);
allocator_type get_allocator() const {return this->_alcv();}
iterator begin() {return iterator(this->m_head->m_pNext);}
iterator end() {return iterator(this->m_tail);}
const_iterator begin() const {return const_iterator(this->m_head->m_pNext);}
const_iterator end() const {return const_iterator(this->m_tail);}
iterator rbegin() {return reverse_iterator(this->begin());}
iterator rend() {return reverse_iterator(this->end());}
const_iterator rbegin() const {return const_reverse_iterator(this->begin());}
const_iterator rend() const {return const_reverse_iterator(this->end());}
const_iterator cbegin() const {return const_cast<const clist<T, Allocator> *>(this)->begin();}
const_iterator cend() const {return const_cast<const clist<T, Allocator> *>(this)->end();}
const_iterator crbegin() const {return const_cast<const clist<T, Allocator> *>(this)->rend();}
const_iterator crend() const {return const_cast<const clist<T, Allocator> *>(this)->rend();}
void swap(clist<T, Allocator> &l);
size_type size() const {return std::distance(this->cbegin(), this->cend());}
size_type max_size() const {return (std::numeric_limits<std::size_t>::max() / sizeof(node));}
void resize(size_type count) {this->resize(count, value_type());}
void resize(size_type count, const value_type &v);
bool empty() const {return (this->cbegin() == this->cend());}
reference front() {return *(this->begin());}
/*constexpr*/ const_reference front() const {return *(this->cbegin());}
reference back() {return *(--(this->end()));}
/*constexpr*/ const_reference back() const {return *(--(this->cend()));}
iterator insert(const_iterator pos, const T &v);
iterator insert(const_iterator pos, T &&v);
iterator insert(const_iterator pos, size_type count, const T &v);
template <typename InputIt> iterator insert(const_iterator pos, InputIt first, InputIt last);
iterator insert(const_iterator pos, std::initializer_list<T> l);
iterator erase(const_iterator pos) {auto posold = pos++; return this->erase(posold, pos);}
iterator erase(const_iterator first, const_iterator last);
void clear() {this->erase(this->begin(), this->end());}
void push_back(const T &v) {this->insert(this->cend(), v);}
void push_back(T &&v) {this->insert(this->cend(), std::move(v));}
void pop_back() {this->erase(--(this->end()));}
void push_front(const T &v) {this->insert(this->cbegin(), v);}
void push_front(T &&v) {this->insert(this->cbegin(), std::move(v));}
void pop_front() {this->erase(this->begin());}
template <typename... Args> iterator emplace(const_iterator pos, Args &&... args);
template <typename... Args> void emplace_front(Args &&... args) {this->emplace(this->cbegin(), std::forward<Args>(args)...);}
template <typename... Args> void emplace_back(Args &&... args) {this->emplace(--(this->cend()), std::forward<Args>(args)...);}
void assign(size_type count, const T &v) {this->clear(); this->insert(this->end(), count, v);}
template <typename InputIt> void assign(InputIt first, InputIt last) {this->clear(); this->insert(this->end(), first, last);}
void assign(std::initializer_list<T> l) {this->clear(); this->insert(this->end(), l);}
void splice(const_iterator pos, clist<T, Allocator> &l);
void splice(const_iterator pos, clist<T, Allocator> &&l) {this->splice(pos, l);}
void splice(const_iterator pos, clist<T, Allocator> &l, const_iterator i);
void splice(const_iterator pos, clist<T, Allocator> &&l, const_iterator i) {this->splice(pos, l, i);}
void splice(const_iterator pos, clist<T, Allocator> &l, const_iterator first, const_iterator last);
void splice(const_iterator pos, clist<T, Allocator> &&l, const_iterator first, const_iterator last) {this->splice(pos, l, first, last);}
void remove(const T &v);
template <typename Pred> void remove_if(Pred pred);
void unique() {this->unique(std::equal_to<>());}
template <typename BinPred> void unique(BinPred binpred);
void merge(clist<T, Allocator> &l) {this->merge(l, std::less<>());}
void merge(clist<T, Allocator> &&l) {this->merge(l);}
template <typename Compare> void merge(clist<T, Allocator> &l, Compare comp);
template <typename Compare> void merge(clist<T, Allocator> &&l, Compare comp) {this->merge(l, comp);}
void sort() {this->sort(std::less<>());}
template <typename Compare> void sort(Compare comp);
void reverse();
private:
node *m_head;
node *m_tail;
node_allocator_type m_alloc_node;
};
template <typename T, typename Allocator>
typename clist<T, Allocator>::node_allocator_traits::pointer clist<T, Allocator>::_mknode(pointer pv)
{
node_allocator_traits::pointer p = node_allocator_traits::allocate(this->_alc(), 1);
node_allocator_traits::construct(this->_alc(), p);
if (pv != nullptr) {p->m_pT = pv;}
return p;
}
template <typename T, typename Allocator>
void clist<T, Allocator>::_delnode(typename node_allocator_traits::pointer p, bool destrv)
{
if (destrv)
{
allocator_traits::destroy(this->_alcv(), p->m_pT);
allocator_traits::deallocate(this->_alcv(), p->m_pT, 1);
}
node_allocator_traits::destroy(this->_alc(), p);
node_allocator_traits::deallocate(this->_alc(), p, 1);
}
template <typename T, typename Allocator>
template <typename... Args>
typename clist<T, Allocator>::pointer clist<T, Allocator>::_mkval(Args &&... args)
{
pointer p = allocator_traits::allocate(this->_alcv(), 1);
allocator_traits::construct(this->_alcv(), p, std::forward<Args>(args)...);
return p;
}
template <typename T, typename Allocator>
void clist<T, Allocator>::_delval(pointer p)
{
allocator_traits::destroy(this->_alcv(), p);
allocator_traits::deallocate(this->_alcv(), p, 1);
}
template <typename T, typename Allocator>
clist<T, Allocator>::clist(clist<T, Allocator> &&l, const Allocator &alloc)
{
if (alloc == l._alcv())
{
this->_alc() = std::move(l._alc());
this->m_head = l.m_head;
this->m_tail = l.m_tail;
l.m_head = nullptr;
l.m_tail = nullptr;
}
else
{
this->_alc() = node_allocator_type(alloc);
this->_mkinit();
for (auto &v : l) {this->emplace_back(std::move(v));}
}
}
template <typename T, typename Allocator>
clist<T, Allocator>& clist<T, Allocator>::operator = (const clist<T, Allocator> &l)
{
if (this != &l)
{
this->clear();
if (node_allocator_traits::propagate_on_container_copy_assignment::value)
{this->_alc() = node_allocator_traits::select_on_container_copy_construction(l._alc());}
for (auto &v : l) {this->emplace_back(v);}
}
return (*this);
}
template <typename T, typename Allocator>
clist<T, Allocator>& clist<T, Allocator>::operator = (clist<T, Allocator> &&l)
{
if (this != &l)
{
if (this->_alc() != l._alc())
{
if (node_allocator_traits::propagate_on_container_move_assignment::value) {std::swap(this->_alc(), l._alc());}
else {this->clear(); for (auto &v : l) {this->emplace_back(std::move(v));} return (*this);}
}
std::swap(this->m_head, l.m_head);
std::swap(this->m_tail, l.m_tail);
}
return (*this);
}
template <typename T, typename Allocator>
clist<T, Allocator>& clist<T, Allocator>::operator = (std::initializer_list<T> l)
{
this->clear();
for (auto &v : l) {this->push_back(v);}
return (*this);
}
template <typename T, typename Allocator>
void clist<T, Allocator>::swap(clist<T, Allocator> &l)
{
if (this->_alc() != l._alc())
{
if (node_allocator_traits::propagate_on_container_swap::value) {using std::swap; swap(this->_alc(), l._alc());}
else {return;}
}
std::swap(this->m_head, l.m_head);
std::swap(this->m_tail, l.m_tail);
}
namespace std
{
template <typename T, typename Allocator>
void swap(clist<T, Allocator> &lhs, clist<T, Allocator> &rhs) {lhs.swap(rhs);}
}
template <typename T, typename Allocator>
void clist<T, Allocator>::resize(size_type count, const value_type &v)
{
difference_type diff = this->size() - count;
if (diff >= 0) {this->insert(this->cend(), n, v);}
else {this->erase(std::next(this->cend(), diff), this->cend());}
}
template <typename T, typename Allocator>
typename clist<T, Allocator>::iterator clist<T, Allocator>::insert(const_iterator pos, const T &v)
{
node *pCur(const_cast<node *>(pos.m_pT)), *pNew(this->_mknode(this->_mkval(v)));
node::link(pCur->m_pPrev, pNew);
node::link(pNew, pCur);
return iterator(pNew);
}
template <typename T, typename Allocator>
typename clist<T, Allocator>::iterator clist<T, Allocator>::insert(const_iterator pos, T &&v)
{
node *pCur(const_cast<node *>(pos.m_pT)), *pNew(this->_mknode(this->_mkval(std::move(v))));
node::link(pCur->m_pPrev, pNew);
node::link(pNew, pCur);
return iterator(pNew);
}
template <typename T, typename Allocator>
typename clist<T, Allocator>::iterator clist<T, Allocator>::insert(const_iterator pos, size_type count, const T &v)
{
iterator rv(pos.m_pT->m_pPrev);
for (size_type i = 0; i < count; ++i) {this->insert(pos, v);}
return ++rv;
}
template <typename T, typename Allocator>
template <typename InputIt>
typename clist<T, Allocator>::iterator clist<T, Allocator>::insert(const_iterator pos, InputIt first, InputIt last)
{
iterator rv(pos.m_pT->m_pPrev);
while (first != last) {this->insert(pos, *(first++));}
return ++rv;
}
template <typename T, typename Allocator>
typename clist<T, Allocator>::iterator clist<T, Allocator>::insert(const_iterator pos, std::initializer_list<T> l)
{
iterator rv(pos.m_pT->m_pPrev);
this->insert(pos, l.begin(), l.end());
return ++rv;
}
template <typename T, typename Allocator>
typename clist<T, Allocator>::iterator clist<T, Allocator>::erase(const_iterator first, const_iterator last)
{
while (first != last)
{
node *pCur = const_cast<node *>(first.m_pT);
++first;
pCur->unlink();
this->_delnode(pCur, true);
}
return iterator(const_cast<node *>(last.m_pT));
}
template <typename T, typename Allocator>
template <typename... Args>
typename clist<T, Allocator>::iterator clist<T, Allocator>::emplace(const_iterator pos, Args &&... args)
{
node *pCur(const_cast<node *>(pos.m_pT)), *pNew(this->_mknode(this->_mkval(std::forward<Args>(args)...)));
node::link(pCur->m_pPrev, pNew);
node::link(pNew, pCur);
return iterator(pNew);
}
template <typename T, typename Allocator>
void clist<T, Allocator>::splice(const_iterator pos, clist<T, Allocator> &l)
{
if ((this != &l) && (this->_alc() == l._alc()))
{
if (!l.empty())
{
node *pCur(const_cast<node*>(pos.m_pT));
node::link(pCur->m_pPrev, l.begin().m_pT);
node::link((--l.end()).m_pT, pCur);
node::link((--l.begin()).m_pT, l.end().m_pT);
}
}
}
template <typename T, typename Allocator>
void clist<T, Allocator>::splice(const_iterator pos, clist<T, Allocator> &l, const_iterator i)
{
if (this->_alc() == l._alc())
{
if ((i != pos) && (std::next(i) != pos))
{
node *pCur(const_cast<node*>(pos.m_pT)), *pNew(const_cast<node*>(i.m_pT));
node::link(pNew->m_pPrev, pNew->m_pNext);
node::link(pCur->m_pPrev, pNew);
node::link(pNew, pCur);
}
}
}
template <typename T, typename Allocator>
void clist<T, Allocator>::splice(const_iterator pos, clist<T, Allocator> &l, const_iterator first, const_iterator last)
{
if (this->_alc() == l._alc())
{
if (first != last)
{
node *pCur(const_cast<node*>(pos.m_pT)), *pNewL(const_cast<node*>(first.m_pT)), *pNewR(const_cast<node*>((--last).m_pT));
node::link(pNewL->m_pPrev, pNewR->m_pNext);
node::link(pCur->m_pPrev, pNewL);
node::link(pNewR, pCur);
}
}
}
template <typename T, typename Allocator>
void clist<T, Allocator>::remove(const T &v)
{
if (!this->empty())
{
auto it(this->begin()), e(this->end());
while (it != e)
{
if ((*it) == v) {this->erase(it++);}
else {++it;}
}
}
}
template <typename T, typename Allocator>
template <typename Pred>
void clist<T, Allocator>::remove_if(Pred pred)
{
if (!this->empty())
{
auto it(this->begin()), e(this->end());
while (it != e)
{
if (pred(*it) != false) {this->erase(it++);}
else {++it;}
}
}
}
template <typename T, typename Allocator>
template <typename BinPred>
void clist<T, Allocator>::unique(BinPred binpred)
{
if (!this->empty())
{
auto it(++(this->begin())), e(this->end());
while (it != e)
{
if (binpred(*it, *std::prev(it))) {this->erase(it++);}
else {++it;}
}
}
}
template <typename T, typename Allocator>
template <typename Compare>
void clist<T, Allocator>::merge(clist<T, Allocator> &l, Compare comp)
{
if ((this != &l) && (this->_alc() == l._alc()))
{
auto it1(this->begin()), e1(this->end()), it2(l.begin()), e2(l.end());
while ((it1 != e1) && (it2 != e2))
{
if (comp(*it2, *it1)) {this->splice(it1, l, it2++);}
else {++it1;}
}
if (it2 != e2) {this->splice(it1, l, it2, e2);}
}
}
template <typename T, typename Allocator>
template <typename Compare>
void clist<T, Allocator>::sort(Compare comp) // merge sort (at least it was intended to be)
{
std::function<void(clist<T, Allocator>&, size_type)> fn_sort = [&comp, &fn_sort] (clist<T, Allocator> &l, size_type lsz) -> void
{
if (lsz > 1)
{
if (lsz == 2)
{
node *pL(l.begin().m_pT), *pR(pL->m_pNext);
if (comp(*(pR->m_pT), *(pL->m_pT))) {std::swap(pL->m_pT, pR->m_pT);}
}
else
{
clist<T, Allocator> rhs(l._alcv());
size_type sz2(lsz / 2);
rhs.splice(rhs.begin(), l, l.begin(), std::next(l.begin(), sz2));
fn_sort(rhs, sz2);
fn_sort(l, sz2 + (lsz % 2));
l.merge(rhs, comp);
}
}
};
fn_sort(*this, this->size());
}
template <typename T, typename Allocator>
void clist<T, Allocator>::reverse()
{
this->m_head->reverse();
this->m_tail->reverse();
std::swap(this->m_head, this->m_tail);
for (auto it = this->begin(), e = this->end(); it != e; ++it) {it.m_pT->reverse();}
}
template <typename T, typename Allocator>
bool operator == (const clist<T, Allocator> &lhs, const clist<T, Allocator> &rhs)
{return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());}
template <typename T, typename Allocator>
bool operator != (const clist<T, Allocator> &lhs, const clist<T, Allocator> &rhs) {return !(lhs == rhs);}
template <typename T, typename Allocator>
bool operator < (const clist<T, Allocator> &lhs, const clist<T, Allocator> &rhs)
{return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());}
template <typename T, typename Allocator>
bool operator <= (const clist<T, Allocator> &lhs, const clist<T, Allocator> &rhs) {return !(lhs > rhs);}
template <typename T, typename Allocator>
bool operator > (const clist<T, Allocator> &lhs, const clist<T, Allocator> &rhs) {return (rhs < lhs);}
template <typename T, typename Allocator>
bool operator >= (const clist<T, Allocator> &lhs, const clist<T, Allocator> &rhs) {return !(lhs < rhs);}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:28:04.867",
"Id": "75477",
"Score": "5",
"body": "Point #1: at least as it shows up here, the formatting renders the code excessively difficult to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:33:42.340",
"Id": "75479",
"Score": "0",
"body": "Yup, sorry, added mediafire link for .h file itself (you can view the file online fullscreen with the original formatting)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:39:16.210",
"Id": "75480",
"Score": "1",
"body": "Wherever did you get the idea to format it like this? How wide is your screen?? Could you use a more standard format [for example like this](http://en.cppreference.com/w/cpp/header/list) which uses less horizontal space? IMO \"excessively difficult to read\" in the comment above means \"nearly unreadable\" and \"difficult to review\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:54:31.543",
"Id": "75484",
"Score": "0",
"body": "Done. Online version also updated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:44:59.990",
"Id": "75499",
"Score": "0",
"body": "what do you mean there are no requirements for list operations such as `splice()`, `merge()` and `sort()` etc? Did you look at [the draft Standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf) (section 23.3.5.5)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T22:45:22.660",
"Id": "75511",
"Score": "1",
"body": "One tip: use alias templates instrad of `typedef`s: while keeping a consistent indentation, your subtype declarations will be even easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:05:35.753",
"Id": "75538",
"Score": "0",
"body": "@Morwenn I actually missed that language feature completely, thanks for the tip."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:05:52.180",
"Id": "75539",
"Score": "0",
"body": "@TemplateRex Sorry for the bad phrasing, what I meant is there isn't much to care about except for complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:24:33.903",
"Id": "75551",
"Score": "0",
"body": "The basic requirements for a container are defined here: http://www.sgi.com/tech/stl/Container.html A list is a normally considered to be a reversible container which has a few additional features see http://www.sgi.com/tech/stl/ReversibleContainer.html and http://www.sgi.com/tech/stl/ForwardContainer.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:22:45.293",
"Id": "75634",
"Score": "0",
"body": "I've updated the post with complete implementation, including several fixes & type aliases instead of typedefs. @LokiAstari Yup, that's the way I did it (at least tried to)."
}
] | [
{
"body": "<p>Why return a value:</p>\n\n<pre><code>value_type operator * () const {return *(this->m_pT->m_pT);}\n</code></pre>\n\n<p>I would return a const reference</p>\n\n<pre><code> const_reference operator * () const {return *(this->m_pT->m_pT);}\n</code></pre>\n\n<p>Iterator does not seem to support <code>operator-></code> which is a requirement of the iterator concept.</p>\n\n<p>Personally I don't like the leading '_' you put on your private members. If this is short hand to indicate they are private it just means you are not using descriptive enough names to describe your methods. The whole point in writing complex code is that the functions should be self descriptive.</p>\n\n<pre><code> allocator_type _alcv() {return allocator_type(this->m_alloc_node);}\n\n // why note use a descriptive name.\n // It will make the code easier to read and maintain.\n\nallocator_type allocate_node() {return allocator_type(this->m_alloc_node);}\n\n// Or I prefer camel case\n\nallocator_type allocateNode() {return allocator_type(this->m_alloc_node);}\n</code></pre>\n\n<p>Also (another personal preference) I like type names to begin with an uppercase letter. That way you can easily spot types in comparison to objects (ie runtime Vs compile time things). Its a shame the standard libraries does not use this convention but we are now stuck for backwards compatibility (But user defined types tend to be defined with an upper case letter (but thats not universal and a style thing so follow your local guidelines)).</p>\n\n<p>Personally I think <code>size()</code> should be <code>O(1)</code> not <code>O(n)</code>. I know this means things like splice go from <code>O(1)</code> to <code>O(n)</code> so there is a trade off and you probably chose the correct one (as thats how the standard version deals with it). But you could cache the size value so you calculate it on first it can be just returned on subsequent calls; then on <code>splice()</code> you can mark it as dirty and recalculate the next time <code>size()</code> is called.</p>\n\n<pre><code> size_type size() const {return std::distance(this->cbegin(), this->cend());}\n</code></pre>\n\n<p>Seems like <code>empty()</code> should be a bit more effecient.</p>\n\n<pre><code> bool empty() const {return (this->cbegin() == this->cend());}\n</code></pre>\n\n<p>Creating two objects and checking for equivalence seems to be overkill. There seems like there could be a much simpler test for empty.</p>\n\n<pre><code> bool empty() const {return m_head != NULL;} /* Does that work or is there a sentanal */\n</code></pre>\n\n<p>You seem to do a lot of functions this way when there seem to be easier alternatives:</p>\n\n<pre><code> reference front() {return *(this->begin());}\n /*constexpr*/ const_reference front() const {return *(this->cbegin());}\n reference back() {return *(--(this->end()));}\n /*constexpr*/ const_reference back() const {return *(--(this->cend()));}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:28:26.897",
"Id": "75670",
"Score": "0",
"body": "Thanks for pointing out the missing operator->. I've also followed your suggestion regarding returning const_reference. First post updated (also with fixes to .sort). I'd really love to know if there's anything else wrong or worth mentioning ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T01:40:29.993",
"Id": "75709",
"Score": "0",
"body": "@Desu_Never_Lies: Only have time for a cursory glance. I am away from home currently. But I will add more if I spot it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:13:23.277",
"Id": "75728",
"Score": "0",
"body": "I thought about caching size, but just didn't want to complicate things. empty(), front(), etc are implemented as operational semantics suggest (on a side note - compiled release version of the code optimizes these functions to a mere inline pointer comparison; I shouldn't just rely on compiler optimizations though)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:12:41.217",
"Id": "43730",
"ParentId": "43639",
"Score": "4"
}
},
{
"body": "<p>I think it should include the headers (e.g. <code><memory></code>, <code><type_traits></code>) on which this type depends.</p>\n\n<p>Is the <code>loop</code> method called from anywhere?</p>\n\n<p>Should the <code>iterator_cnc(const iterator_cnc<false> &it)</code> constructor be <code>iterator_cnc(const iterator_cnc<is_const_iter> &it)</code> instead?</p>\n\n<p>It's too new for Gimpel's Lint.</p>\n\n<p>What have you done to satisfy yourself that it's correct: is there a standard list of test cases?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:27:03.383",
"Id": "75685",
"Score": "0",
"body": "Loop isn't called from anywhere, guess I had some idea for it, but it didn't make it to the final version of the code. Constructor takes iterator_cnc<false> to allow implicit conversion from iterator to const_iterator. As for the tests all I did was check if I meet the standard & do a simple hand-written test, so there aren't any framework-driven ones (and I've never worked with them to be honest)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:36:11.143",
"Id": "75688",
"Score": "1",
"body": "If I were implementing a standard (e.g. writing a new HTML rendering engine) I would hope to find a pre-existing semi-standard list or lists of test cases, which I could use to test my implementation. Perhaps you could find an open-source test suite that is used to test std::list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:38:03.523",
"Id": "43741",
"ParentId": "43639",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43730",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:18:57.247",
"Id": "43639",
"Score": "6",
"Tags": [
"c++",
"c++11",
"linked-list",
"stl"
],
"Title": "STL-compliant list class"
} | 43639 |
<p>Today, I tried to create a really simple <code>sparse_array</code> container adapter. I did not provide all the STL-like functions, only the elementary ones as a proof of concept. I also trimmed the class from its copy constructor and all the unecessary things for this review actually. Here is the code:</p>
<pre><code>#include <cstddef>
#include <map>
template<typename T, template <typename...> class Container=std::map>
struct sparse_array
{
class proxy
{
sparse_array& sp;
std::size_t index;
proxy(sparse_array& sp, std::size_t index):
sp(sp),
index(index)
{}
public:
proxy(const proxy& other) = default;
auto operator=(const proxy& other)
-> proxy&
{
sp.data[index] = T(other);
return *this;
}
auto operator=(const T& val)
-> proxy&
{
if (val != sp.default_value)
{
sp.data[index] = val;
}
else
{
sp.data.erase(index);
}
return *this;
}
operator T() const
{
auto res = sp.data.find(index);
if (res != sp.data.end())
{
return res->second;
}
return sp.default_value;
}
friend class sparse_array;
};
auto operator[](std::size_t index)
-> proxy
{
return { *this, index };
}
auto operator[](std::size_t index) const
-> const proxy
{
return { *this, index };
}
auto size() const
-> std::size_t
{
return data.size();
}
private:
T default_value = {};
Container<std::size_t, T> data;
};
</code></pre>
<p>What I tried to do is to have a sparse array whose number of elements is strictly equal to the number of elements that are different from <code>default_value</code>, hence the elements that are deleted when <code>default_value</code> is assigned to them. Here comes a small example:</p>
<pre><code>#include <iostream>
int main()
{
sparse_array<int> sp;
std::cout << sp[15] << " / " << sp.size() << std::endl;
sp[8] = sp[13] = 9;
std::cout << sp[8] << " " << sp[13] << " / " << sp.size() << std::endl;
sp[11] = 0;
std::cout << sp[11] << " / " << sp.size() << std::endl;
sp[8] = 0;
std::cout << sp[8] << " / " << sp.size() << std::endl;
}
</code></pre>
<p>Do you think there are obvious design flaws in this code? I bet there are some in the <code>proxy</code> mechanism, and it would be great if you could hilight some of them.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-11T19:42:42.597",
"Id": "457297",
"Score": "0",
"body": "A possible API is to see your data structure more as a map, i.e. iteration returns key,value pairs, where key is the index and value is a non default value"
}
] | [
{
"body": "<p>The primary question I have is one of usage. By the name <code>sparse_array</code>, it sounds like you want to expose an interface that is similar to an array. Perhaps it needs dynamic sizing, or perhaps not, but in particular I expect to be able to iterate over its elements with code like this:</p>\n\n<pre><code>sparse_array<int> sp;\n// ::: fill array here :::\n\nfor (int elt: sp)\n std::cout << elt << \", \";\n\n// or better\nstd::ostream_iterator<int> out_it(std::cout, \", \");\nstd::copy(std::begin(sp), std::end(sp), out_it);\n</code></pre>\n\n<p>It needs to be clear what the output from that would be. Would it include the default values in most indices? Or is this usage prohibited (perhaps due to that unclarity), as currently there are no iterator related methods? Maybe this is just part of what you intentionally excluded from the review, but it leaves so much unanswered, including things that probably come back to your proxy class, such as how <code>*std::begin(sp) = 3</code> will work.</p>\n\n<p>The one definite gap I see has to do with <code>operator&</code>. Will you support code that looks like normal array-style addressing? Right now the following code will certainly not work correctly; should it fail to compile, or should it modify <code>sp[5]</code>?</p>\n\n<pre><code>auto spot = &sp[4];\n*(spot + 1) = 5;\n</code></pre>\n\n<p>Other comments:</p>\n\n<ul>\n<li>I think your proxy approach here is justified for the usage you want to offer.</li>\n<li>It's unclear what values are permissible as alternatives to <code>std::map</code> for your <code>Container</code>. Perhaps this is because there are no comments anywhere.</li>\n<li>You aren't completely consistent about use of parentheses vs. braces for initialization. For example, <code>proxy</code>'s constructor uses parentheses where I believe it should use braces: <code>proxy(sparse_array& sp, std::size_t index) : sp{sp}, index{index}</code></li>\n<li>It's plausible that <code>default_value</code> should be exposed in the template as well, rather than relying on its type's default.</li>\n<li>I'm not yet sold on <code>auto method_name(params) -> result_type</code> when <code>result_type</code> is a simple known type. It's too different from the <code>result_type method_name(params)</code> that I've been using for so many years.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:10:08.620",
"Id": "75909",
"Score": "0",
"body": "Haha, you're already the third to say you don't like the new return type syntax. As I said somewhere else, I find it clearer (but have to admit that it took me a while to adopt it) and allows me to always use the same function syntax. Also, it reminds me of types theory. Well, that's only stylistic whatsoever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T18:14:36.107",
"Id": "75910",
"Score": "0",
"body": "Concerning the `Container`, I should have called it `AssociativeContainer`, that's true. Concerning the iteration, the `operator&` the truth is that I still have choices to make and the exposition of `default_value`, which is why I did not include them. Actually, I was seeking review for the `proxy` mechanism. But your comments are insightful and underline the real problems :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:23:05.730",
"Id": "43865",
"ParentId": "43643",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43865",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:29:50.507",
"Id": "43643",
"Score": "8",
"Tags": [
"c++",
"array",
"c++11",
"container"
],
"Title": "Simple sparse array"
} | 43643 |
<p>In an example game engine server, the game world could be represented by a World object. The game might have multiple game worlds and a player who is in a world only needs to receive position data of units in that world.</p>
<pre><code>class World
{
public List<Unit> Units { get; set; }
}
</code></pre>
<p>However a piece of code also needs to be able to look up what world a unit is in easily, so the unit object itself keeps track of a world reference.</p>
<pre><code>class Unit
{
public World World { get; set; }
}
</code></pre>
<p>This works for lookup, but quickly becomes problematic when changing data when the programmer isn't aware of the relationship between objects going on, so I changed <code>Units</code> in <code>World</code> to be readonly and have the following code in <code>Unit</code>.</p>
<pre><code>public virtual World World
{
get { return _world; }
set
{
// If already this, don't do anything
if (value == _world) return;
var oldWorld = _world;
_world = value;
if(oldWorld != null) oldWorld.UpdateUnitEntry(this);
_world.UpdateUnitEntry(this);
}
}
</code></pre>
<p>This works, but it feels like there's a better way to do this. Especially as I add more stuff that needs to be linked the same way (a <code>World</code> also has <code>Structure</code>s and <code>Player</code>s, and <code>Structure</code>s maintain a list of <code>Unit</code>s as well), a lot of repeated functionality comes in. As well when I remove a unit from the game, it continues to be kept alive by this, so I have to remember to set the unit's structure to null every time (which I already forgot multiple times, resulting in weird bugs). Is there a better way to achieve this one-to-many relationship without manually updating both sides?</p>
| [] | [
{
"body": "<p>The best way to accomplish this is to have each <code>World</code>, <code>Structure</code>, and anywhere else a unit can move to inherit an interface <code>IEnterable</code>, which looks like</p>\n\n<pre><code>public interface IEnterable\n{\n void Enter(Unit unit);\n void Leave(Unit unit);\n}\n</code></pre>\n\n<p>Your unit would then have this as a property, and a <code>MoveTo(IEnterable location)</code> method</p>\n\n<pre><code>public class Unit\n{\n // ...\n\n public IEnterable CurrentLocation { get; set; }\n\n // ...\n\n public void MoveTo(IEnterable location)\n {\n if (CurrentLocation != null)\n {\n CurrentLocation.Leave(this);\n }\n\n location.Enter(this);\n }\n}\n</code></pre>\n\n<p>The <code>Enter</code> and <code>Leave</code> would handle all the logic for the <code>Unit</code> movement.</p>\n\n<p>If you wanted to get more fancy, you could have a <code>Movement</code> class that could describe the movement a little more accurately.</p>\n\n<pre><code>public class Movement\n{\n private readonly IEnterable _destination;\n\n public Movement(IEnterable destination)\n {\n if (destination== null) throw new ArgumentNullException(\"destination\"); \n\n _destination = destination;\n }\n\n public MoveResult MoveUnit(Unit unit)\n {\n if (unit == null) throw new ArgumentNullException(\"unit\");\n\n var currentLocation = unit.CurrentLocation;\n if (currentLocation == _destination) return MoveResult.SameLocation;\n\n if (!IsValidMove(currentLocation, _destination) return MoveResult.InvalidMovment;\n\n currentLocation.Leave(unit);\n\n _destination.Enter(unit);\n }\n}\n</code></pre>\n\n<p>This will get the movement logic out of the <code>Unit</code> class because a unit should not care about how it has to move, just that it has.</p>\n\n<p>I might be missing something, but my main point is to use an interface for each object that a <code>Unit</code> can enter, and the ease of moving a <code>Unit</code> becomes much better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:38:17.700",
"Id": "75496",
"Score": "0",
"body": "This would leave the problem that when a `Unit` gets removed, the `Structure` or `World` is still keeping it alive. How would I go about making sure `Unit`s are removed from all `IEnterable`s when they're removed from the main ID lookup table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T21:43:32.007",
"Id": "75504",
"Score": "0",
"body": "@LaylConway easiest way would be to add a Method `RemoveUnit` which stores the current location in a temp variable, sets it to Null in the unit, then updates the location with the new value. The location update would see the null and remove it from its internal list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:17:59.807",
"Id": "43649",
"ParentId": "43644",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:38:54.027",
"Id": "43644",
"Score": "7",
"Tags": [
"c#",
"game"
],
"Title": "Automatically update one-to-many bi-directional relationship"
} | 43644 |
<p><strong>Task:</strong> </p>
<blockquote>
<p>Draw a grid with a given number of rows and columns. Each cell can be
any color. The same grid should also be updated at a predetermined
time interval. The grid should cover the entire visible portion of the page in the
browser. Add a context menu with which you can change the parameters of the lattice.</p>
</blockquote>
<p>I would really like to hear feedback on the code: syntax, logic and general any comments and tips.</p>
<p>I'm a young programmer so I want to hear real reviews for further development.</p>
<pre><code><!DOCTYPE HTML>
<html style="height:100%">
<head>
<meta charset="utf-8">
<title></title>
<link href="css/common.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/grid.js"></script>
<script type="text/javascript">
window.onload = function () {
var grid = new Grid ("20", // rows
"6", // columns
"2000"); // update grid interval
}
</script>
</head>
<body style="margin:0; height:100%">
</body>
</html>
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>var interval = 0;
var stopUpdateGrid = false;
function Grid(numRows, numColumns, updateInterval) {
this.numRows = numRows;
this.numColumns = numColumns;
this.updateInterval = updateInterval;
var clientWidth = document.body.clientWidth;
var clientHeight = document.body.clientHeight;
(function createGrid(rows, columns) {
var container = document.createElement("div");
document.body.appendChild(container);
container.style.width = clientWidth + "px";
container.style.height = clientHeight + "px";
container.setAttribute("id", "container");
for (var i = 1; i <= rows * columns; i++) {
var div = document.createElement("div");
container.appendChild(div);
div.style.width = (clientWidth - rows - 1) / rows + "px";
div.style.height = (clientHeight - columns - 1) / columns + "px";
div.style.cssFloat = "left";
div.style.margin = "-1px 0 0 -1px";
div.style.border = "1px solid #000";
var n = randomColors();
div.style.backgroundColor = "#" + n;
}
})(this.numRows, this.numColumns);
function randomColors() {
var min = 0;
var max = 15;
var colors = '';
for (var i = 1; i <= 6; i++) {
var rand = min - 0.5 + Math.random() * (max - min + 1);
rand = Math.round(rand);
rand = parseInt(rand, 10).toString(16);
colors = colors + rand;
}
return colors;
}
(function updateColorsGrid(updInterval, rows, columns) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(function() {
if (stopUpdateGrid === false) {
var container = document.getElementById("container");
document.body.removeChild(container);
var grid = new Grid(rows, columns, updInterval);
}
}, updInterval);
})(this.updateInterval, this.numRows, this.numColumns);
document.onkeyup = function(e) {
e = e || window.event;
if (e.keyCode === 13) {
stopUpdateGrid = true;
changeGridOptions();
}
return false;
};
(function createNotification() {
var container = document.getElementById("container");
var notificationContainer = document.createElement("div");
container.appendChild(notificationContainer);
notificationContainer.style.width = "500px";
notificationContainer.style.height = "50px";
notificationContainer.innerHTML = "Press Enter to show menu change!!!";
notificationContainer.style.color = "#fff";
notificationContainer.style.fontSize = "30px";
notificationContainer.style.position = "absolute";
})();
function changeGridOptions() {
var container = document.getElementById("container");
var changeOptionsForm = document.createElement("form");
container.appendChild(changeOptionsForm);
changeOptionsForm.style.width = "200px";
changeOptionsForm.style.height = "200px";
changeOptionsForm.setAttribute("id", "changeOptionsForm");
changeOptionsForm.style.border = "2px solid #fff";
changeOptionsForm.style.backgroundColor = "#808080";
changeOptionsForm.style.position = "absolute";
changeOptionsForm.style.left = clientWidth - 220 + "px";
changeOptionsForm.style.top = "15px";
var changeRowsText = document.createElement("div");
changeOptionsForm.appendChild(changeRowsText);
changeRowsText.style.width = "50px";
changeRowsText.style.height = "20px";
changeRowsText.style.margin = "10px";
changeRowsText.innerHTML = "Rows:";
changeRowsText.style.cssFloat = "left";
var changeRows = document.createElement("input");
changeOptionsForm.appendChild(changeRows);
changeRows.type = "text";
changeRows.style.width = "100px";
changeRows.style.height = "20px";
changeRows.style.border = "2px solid #000";
changeRows.style.margin = "10px";
changeRows.style.cssFloat = "left";
var changeColumnsText = document.createElement("div");
changeOptionsForm.appendChild(changeColumnsText);
changeColumnsText.style.width = "50px";
changeColumnsText.style.height = "20px";
changeColumnsText.style.margin = "10px";
changeColumnsText.innerHTML = "Columns:";
changeColumnsText.style.cssFloat = "left";
var changeColumns = document.createElement("input");
changeOptionsForm.appendChild(changeColumns);
changeColumns.type = "text";
changeColumns.style.width = "100px";
changeColumns.style.height = "20px";
changeColumns.style.border = "2px solid #000";
changeColumns.style.margin = "10px";
changeColumnsText.style.cssFloat = "left";
var changeDelayUpdateGridText = document.createElement("div");
changeOptionsForm.appendChild(changeDelayUpdateGridText);
changeDelayUpdateGridText.style.width = "50px";
changeDelayUpdateGridText.style.height = "20px";
changeDelayUpdateGridText.style.margin = "10px";
changeDelayUpdateGridText.innerHTML = "Delay Update:";
changeDelayUpdateGridText.style.cssFloat = "left";
var changeDelayUpdateGrid = document.createElement("input");
changeOptionsForm.appendChild(changeDelayUpdateGrid);
changeDelayUpdateGrid.type = "text";
changeDelayUpdateGrid.style.width = "100px";
changeDelayUpdateGrid.style.height = "20px";
changeDelayUpdateGrid.style.border = "2px solid #000";
changeDelayUpdateGrid.style.margin = "10px";
changeDelayUpdateGrid.style.cssFloat = "left";
var changeButton = document.createElement("input");
changeOptionsForm.appendChild(changeButton);
changeButton.type = "button";
changeButton.value = "change";
changeButton.style.width = "100px";
changeButton.style.height = "25px";
changeButton.style.margin = "20px 50px";
changeButton.style.cssFloat = "left";
changeButton.onclick = function() {
numRows = changeRows.value || numRows;
numColumns = changeColumns.value || numColumns;
updateInterval = changeDelayUpdateGrid.value || updateInterval;
changeOptionsForm.style.display = "none";
stopUpdateGrid = false;
document.body.removeChild(container);
var grid = new Grid(numRows, numColumns, updateInterval);
};
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:11:18.857",
"Id": "75512",
"Score": "3",
"body": "Please leave the formatting alone. We are trying to make the question more readable for people who want to answer can understand the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:19:10.007",
"Id": "75515",
"Score": "0",
"body": "What are you going to do if the user resizes their browser"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:29:31.287",
"Id": "75517",
"Score": "0",
"body": "I do not know why, but I never thought of that! then probably block \"container\" need to make 100%!"
}
] | [
{
"body": "<p>Just a couple of things that I really feel strongly about (didn't work line for line through your code though).</p>\n\n<h1>Seperation of logic and presentation</h1>\n\n<p>Yes, there is a <code>.style</code> object, however this does <em>not</em> mean you should use it as the primary way to style your objects. Instead just apply the corresponding class (either through the <code>classList</code> object or the backwards compatible <code>class</code> property), and only the really dynamic things (random background colour for example) should indeed be done through Javascript.</p>\n\n<h1>Always use <code>addEventListener</code></h1>\n\n<p>In a simple stand alone case it doesn't matter, but at some point later you often end up regretting using things like <code>.onclick</code>, so instead use <code>.addEventListener('click',function(){...})</code>. </p>\n\n<h1>Generating HTML</h1>\n\n<p>You're doing a great job at using the proper DOM methods to build up your html, however sometimes code becomes more readable by building up a html <em>string</em> which you apply with <code>.innterHTML</code>. Or alternatively using a templating library might be an even better idea, though you would have to find one which fits your taste (just look around on google, I used to use pure.js for example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:19:38.243",
"Id": "75516",
"Score": "0",
"body": "I did not use CSS to show their knowledge of javascript! probably it was wrong)\n\nabout advice, thank you very much, you made a contribution to the development of my future;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T00:09:59.050",
"Id": "75518",
"Score": "0",
"body": "@sparcmen If you want to thank the reviewer, up-vote his question :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T01:00:29.897",
"Id": "75523",
"Score": "0",
"body": "You seem like a re-activated user, you should come join us in the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:11:03.610",
"Id": "43656",
"ParentId": "43655",
"Score": "5"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>This has the parameters split over multiple lines, that is to be avoided, you could do this:</p>\n\n<pre><code>window.onload = function () {\n\n var rowCount = 20,\n columnCount = 6,\n refreshRate = 2000,\n grid = new Grid( rowCount, columnCount, refreshRate );\n}\n</code></pre></li>\n<li>As David Mulder mentioned, your code could be a lot shorter if you moved more into CSS. In fact once you fixed that, I would re-submit this code. It would be interesting.</li>\n<li><code>stopUpdateGrid</code> should be part of <code>grid</code>, unless you meant all instances of <code>Grid</code> to stop in <code>document.onkeyup</code> which should be commented in that case.</li>\n<li>Same goes for <code>interval</code></li>\n<li>You are never using <code>grid</code> in <code>var grid = new Grid(rows, columns, updInterval);</code> so you might as well just do <code>new Grid(rows, columns, updInterval);</code></li>\n<li>Other than that your code is very clean, JsHint.com could find close to nothing, it is readable, follows lowerCamelCasing, variables are well named, fun to review.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:39:34.790",
"Id": "75543",
"Score": "0",
"body": "I will repurpose the code using CSS and acknowledge all the advice and comments)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T01:56:00.243",
"Id": "43665",
"ParentId": "43655",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T22:42:24.430",
"Id": "43655",
"Score": "5",
"Tags": [
"javascript",
"object-oriented",
"html",
"dom"
],
"Title": "Updating Grid on Webpage"
} | 43655 |
<p>I am trying to upload an image (screenshot from desktop) to an SQL database as fast as possible. I would like to optimize my current procedure in terms of speed:</p>
<pre><code>bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
byte[] imageBytes = convertImageToByteArray(bmpScreenshot);
MemoryStream mem = new MemoryStream(imageBytes);
using (Bitmap bmp1 = (Bitmap)Image.FromStream(mem))
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
ImageCodecInfo jgpEncoder = codecs[1];
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
}
using (MemoryStream m = new MemoryStream())
{
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 23L);
myEncoderParameters.Param[0] = myEncoderParameter;
bmp1.Save(m, jgpEncoder, myEncoderParameters);
using (Bitmap bmpLast = (Bitmap)Image.FromStream(m))
{
string query = "UPDATE ScreenCapture SET ScreenCapture=@Image,BroadcastTime=@BroadcastTime WHERE ID = 1";
SqlCommand sqlCommand = new SqlCommand(query, SQLconn);
ImageConverter converter = new ImageConverter();
byte[] beforeUpload = (byte[])converter.ConvertTo(bmpLast, typeof(byte[]));
sqlCommand.Parameters.AddWithValue("@Image", beforeUpload);
sqlCommand.Parameters.AddWithValue("@BroadcastTime", DateTime.Now);
SQLconn.Open();
sqlCommand.ExecuteNonQuery();
SQLconn.Close();
}
}
}
</code></pre>
<p><strong>Profiling - Performance and Diagnostics in Visual Studio 2013</strong></p>
<p>The method I posted has following usage:</p>
<ul>
<li>40,8% - <code>byte[] imageBytes = convertImageToByteArray(bmpScreenshot);</code></li>
<li>10,4% - <code>MemoryStream mem = new MemoryStream(imageBytes);</code></li>
<li>37,8% - <code>mp1.Save(m, jgpEncoder, myEncoderParameters);</code></li>
</ul>
<p>From <code>captureUpload</code> which takes 93.6% in System.Windows.Forms.ni.dll:</p>
<ul>
<li>69.9% - System.Drawing.ni.dll</li>
<li>26.8% - <code>convertImageToByteArray</code></li>
<li>8.8 - <code>PresentationFramework.ni.dll</code></li>
</ul>
<p><code>convertImageToByteArray</code> takes 26.8% on return <code>ms.ToArray()</code>.</p>
<p>It now takes me about 1 second to upload and download on client side, which is not so efficient in my case. If anyone have idea how this procedure is possible to make faster I would be glad to know. The image has around 60 KB, which is quite a lot.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:58:43.150",
"Id": "75642",
"Score": "0",
"body": "Have you profiled your code? Which part takes the most time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:38:50.647",
"Id": "75678",
"Score": "1",
"body": "Do you need to be able to see every pixel on the screen? If not, reduce the size of the image to half the height and width. Your image size will drop by about 75%. You can also lower the image quality of the JPEG by setting that attribute in the codec parameters (are you doing that with the 23 parameter?)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:39:54.450",
"Id": "75679",
"Score": "0",
"body": "Which database are you using? Some are more efficient about BLOB storage than others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:55:39.337",
"Id": "75681",
"Score": "0",
"body": "@AdamZuckerman I'm using SQL Database to upload. I thought that it would be efficient to change the image quality then the image size but I will definetly try out! Thanks for recomendation!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:44:41.270",
"Id": "76427",
"Score": "1",
"body": "Are there absolute values on the profiling results apart from percents. What amount of that 1 sec is spent on establishing a connection from client to app server and from app server to DB server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T01:04:44.653",
"Id": "77194",
"Score": "0",
"body": "@abuzittingillifirca Hello, thank you for your interest but I think I'm not able to extract this type of information from my VS2013, how can I achieve that?"
}
] | [
{
"body": "<p>For graphic part :</p>\n\n<p>I think Gdi++ of .NET framework is very slow.\nMainly the Bitmap() construtor and Save() method.</p>\n\n<p>If it's possible for screenshot, I recommend to use :\nEither directly gdi32.dll or (maybe, im not sure that is good idea) direct2d (benefits on hardware acceleration).</p>\n\n<p>For transfert :</p>\n\n<p>For your upload, run the transfert in other thread. (async or Delegate with BeginInvoke).\nAfter it depends on your internet connection speed.</p>\n\n<p>However, i don't understand why you recreate your Bitmap object twice :</p>\n\n<pre><code>using (Bitmap bmp1 = (Bitmap)Image.FromStream(mem))\nusing (Bitmap bmpLast = (Bitmap)Image.FromStream(m))\n</code></pre>\n\n<p>Don't reload with Bitmap,\ncreate only one Bitmap for your screenshot, save it with encoding in memory stream and send memory stream to your database. With your memory stream you can get directly byte array with no conversion.</p>\n\n<pre><code>MemoryStream.Read(byte[] buffer, int offset, int count)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T10:26:11.260",
"Id": "44498",
"ParentId": "43658",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:55:34.723",
"Id": "43658",
"Score": "8",
"Tags": [
"c#",
"sql",
"sql-server",
"winforms",
"image"
],
"Title": "Fastest image upload into SQL database"
} | 43658 |
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known implementations such as JavaScript, JScript and ActionScript. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T00:29:33.727",
"Id": "43661",
"Score": "0",
"Tags": null,
"Title": null
} | 43661 |
<p>Please give me some feedback to my <code>malloc</code> implementation. I implemented this design to understand the basic concept.</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define HEAP_MEM_SIZE 150
#define MEMORY_AVAILABLE 1
#define MEMORY_USED 0
struct chunk_header {
struct chunk_header *next; // next pointer on free list
size_t size; // the size of this chunk
bool is_available; // indicates if this chunk is MEMORY_AVAILABLE or MEMORY_USED
};
typedef struct chunk_header chunk_header;
chunk_header *chunk_header_begin;
static char buffer[HEAP_MEM_SIZE];
unsigned int heap_size;
void init() {
heap_size = HEAP_MEM_SIZE;
chunk_header_begin = (chunk_header*)&buffer;
chunk_header_begin->next = NULL;
chunk_header_begin->size = heap_size;
chunk_header_begin->is_available = MEMORY_AVAILABLE;
}
void init_next_chunk(chunk_header *curr, unsigned int bytes) {
heap_size -= bytes;
curr->next = NULL;
curr->size = heap_size;
curr->is_available = MEMORY_AVAILABLE;
}
void *my_malloc(unsigned int nbytes) {
static bool init_flag = false;
if(!init_flag) {
init();
init_flag = true;
}
int alloc_size = nbytes + sizeof(chunk_header);
chunk_header *curr = chunk_header_begin;
while(curr) {
if(curr->is_available && curr->size >= alloc_size) {
curr->is_available = MEMORY_USED;
curr->size = alloc_size;
curr->next = curr + alloc_size;
init_next_chunk(curr->next, alloc_size);
// return memory region
curr = curr + sizeof(chunk_header);
return curr;
}
curr = curr->next;
}
return NULL;
}
void my_free(void *firstbyte) {
chunk_header *mem = (chunk_header*)firstbyte - sizeof(chunk_header);
chunk_header *curr = chunk_header_begin;
while (curr) {
if (curr == mem) {
heap_size += curr->size;
// Mark the block as being available
curr->is_available = MEMORY_AVAILABLE;
break;
}
curr = curr->next;
}
firstbyte = NULL;
}
void print_heap_allocations() {
chunk_header *curr = chunk_header_begin;
printf("\n\tSize\tAvailable\tMemory-Ptr");
while (curr) {
void *mem_ptr = curr + sizeof(chunk_header);
printf("\n\t%d\t%d\t\t%x", curr->size, curr->is_available, mem_ptr);
curr = curr->next;
}
printf("\n");
}
int main() {
char *mem1 = (char*)my_malloc(20);
if(mem1 == NULL) {
goto err;
}
memset (mem1,'x',19);
mem1[19] = '\0';
print_heap_allocations();
char *mem2 = (char*)my_malloc(20);
if(mem2 == NULL) {
goto err;
}
memset (mem2,'y',19);
mem2[19] = '\0';
print_heap_allocations();
char *mem3 = (char*)my_malloc(20);
if(mem3 == NULL) {
goto err;
}
memset (mem3,'z',19);
mem3[19] = '\0';
print_heap_allocations();
my_free(mem2);
print_heap_allocations();
char *mem4 = (char*)my_malloc(20);
if(mem4 == NULL) {
goto err;
}
memset (mem4,'a',20);
mem4[19] = '\0';
print_heap_allocations();
printf("should be 19 x sein: %s\n", mem1);
printf("should be 19 a sein: %s\n", mem4);
printf("should be 19 z sein: %s\n", mem3);
return 0;
err:
printf("could not allocate mem\n");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T17:10:13.843",
"Id": "75906",
"Score": "1",
"body": "When you find an answer that is satisfactory to you, you should upvote and [accept it](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). :)"
}
] | [
{
"body": "<h1>Things you did well:</h1>\n\n<ul>\n<li><p>Some use of comments.</p></li>\n<li><p>Use of <code>typedef</code>.</p></li>\n</ul>\n\n<h1>Things you could improve:</h1>\n\n<h3>Syntax/Styling:</h3>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/q/46586/1937270\"><strong>Never</strong> use <code>goto</code>.</a> </p>\n\n<p><img src=\"https://i.stack.imgur.com/kMDAj.png\" alt=\"Neal Stephenson thinks it's cute to name his labels 'dengo'\"></p>\n\n<p>Yes, there are some rare situations where you may find it necessary to use it. This is not one of them.</p>\n\n<blockquote>\n<pre><code>err:\n printf(\"could not allocate mem\\n\");\n return 0;\n</code></pre>\n</blockquote>\n\n<p>As you can see, all you do in your little block of code here is print out an unspecific error message, and then exit (using <code>0</code>, which means the program was successful and is contradictory here).</p>\n\n<p>You should instead abolish the <code>goto</code>'s completely. Print out specific, <em>useful</em> error messages instead, and then return with a <em>unique</em> exit code.</p>\n\n<pre><code>if(mem2 == NULL) \n{\n fprintf(stderr, \"Error allocating memory to mem2.\\n\");\n return -2;\n}\n</code></pre></li>\n<li><p>Your format specifies type <code>int</code> when you are trying to print a string, but the argument has type <code>size_t</code> (basically, <code>unsigned long</code>). Your format also specifies type <code>unsigned int</code> but the argument has type <code>void *</code>.</p>\n\n<blockquote>\n<pre><code>printf(\"\\n\\t%d\\t%d\\t\\t%x\", curr->size, curr->is_available, mem_ptr);\n</code></pre>\n</blockquote>\n\n<p>Just change they type you are trying to print out, and cast <code>mem_ptr</code> to an <code>unsigned int</code>.</p>\n\n<pre><code>printf(\"\\n\\t%zuu\\t%d\\t\\t%x\", curr->size, curr->is_available, (unsigned int) mem_ptr);\n</code></pre></li>\n<li><p>You aren't using standard naming conventions with your <code>typedef struct</code>.</p>\n\n<blockquote>\n<pre><code>typedef struct chunk_header chunk_header;\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p>You should be giving the <code>typedef</code> a specific name, different from the abstract <code>struct</code> name.</p></li>\n<li><p>You should be capitalizing the name of the type, or adding a <code>_t</code> to the end (though this is reserved in POSIX)</p></li>\n</ol></li>\n<li><p><code>typedef</code> your <code>struct</code>s when you declare them.</p>\n\n<blockquote>\n<pre><code>struct chunk_header {\n struct chunk_header *next; // next pointer on free list\n size_t size; // the size of this chunk\n bool is_available; // indicates if this chunk is MEMORY_AVAILABLE or MEMORY_USED\n};\ntypedef struct chunk_header chunk_header;\n</code></pre>\n</blockquote>\n\n<p>The <code>typedef</code> means you no longer have to write <code>struct</code> all over the place, as you have used it. But you can combine these two parts to make things more simple:</p>\n\n<pre><code>typedef struct chunk_header\n{\n struct chunk_header *next; // next pointer on free list\n size_t size; // the size of this chunk\n bool is_available; // indicates if this chunk is MEMORY_AVAILABLE or MEMORY_USED\n} ChunkHeader;\n</code></pre></li>\n<li><p>You can simplify your <code>NULL</code> checks.</p>\n\n<blockquote>\n<pre><code> if(mem1 == NULL)\n</code></pre>\n</blockquote>\n\n<p>Since <code>NULL</code> is defined as <code>(void *)0</code>, we can treat is as a comparison to <code>0</code>.</p>\n\n<pre><code>if(!mem1)\n</code></pre></li>\n</ul>\n\n<h3>Parameters/Returns:</h3>\n\n<ul>\n<li><p>You don't accept any parameters for some of your functions, such as <code>main()</code>. If you do not take in any parameters, declare them as <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>You should still <code>return</code> from a function, even if it is declared to <code>return void</code>.</p>\n\n<pre><code>void my_free(void *firstbyte) {\n ...\n return;\n}\n</code></pre></li>\n</ul>\n\n<h3>Compilation:</h3>\n\n<ul>\n<li>I can see from some warnings I received that you have not enabled all of your compiler warnings, which you should do.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T03:09:15.923",
"Id": "75527",
"Score": "0",
"body": "\"You return NULL in some places where you have declared that you would return void\" The return type is `void *`, not `void`. `NULL` is a valid return value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T03:12:44.027",
"Id": "75528",
"Score": "0",
"body": "@Corbin Thanks, I've edited in a revision."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T03:26:46.807",
"Id": "75529",
"Score": "0",
"body": "@Corbin: I do see why it's good to put unary operators next to the type rather than the function or variable. I probably would've missed it as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T03:31:24.733",
"Id": "75530",
"Score": "0",
"body": "@Jamal Yeah, I thought about mentioning that. For some reason though, in C, it's fairly prevalent to use the `void *` format. As a person with a heavy C++ bias, it drives me insane :o."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T03:32:32.717",
"Id": "75531",
"Score": "0",
"body": "@Corbin: Same here. :-) It was because of another C++ reviewer here that I started using `const&` instead of `const Class &obj`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:55:54.500",
"Id": "75540",
"Score": "0",
"body": "Why do you need a `return` in `void my_free()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:13:31.553",
"Id": "75541",
"Score": "0",
"body": "@Gerald It is considered good practice since you can see where you are returning, just like with all your other functions that return actual values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:28:06.800",
"Id": "75585",
"Score": "0",
"body": "\"You should still return from a function, even if it is declared to return void\" -- really?? Please cite a[ny] style guide which recommends that. It's recommended to declare the function's return type; but I've not seen it recommended to end a function with a (useless but harmless) `return;` when the return type is void."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:05:30.817",
"Id": "75665",
"Score": "0",
"body": "@ChrisW There are some answers in [this question](http://stackoverflow.com/q/3227755/1937270) that point to do that. You are right that there isn't a lot of point to include it, but if you don't your compiler includes it automatically. Including it cuts down on a smidgen of compile time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:42:48.590",
"Id": "75673",
"Score": "0",
"body": "@Gerald The question which syb0rg referenced is about whether it's legal to return nothing from a non-void function. He says that you \"should\" explicitly return at the end of a void function; I don't agree with that (I don't think that's normal nor a 'required' or 'recommended' good practice)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-16T06:21:08.127",
"Id": "223673",
"Score": "0",
"body": "Why must typedefs use different identifiers from their associated struct tag? In your example, you omitted the tag from the definition, btw."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-16T15:34:07.160",
"Id": "223790",
"Score": "0",
"body": "@luserdroog The code in the yellow isn't mine and is the version being corrected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-16T23:13:05.133",
"Id": "223948",
"Score": "0",
"body": "Suggested an edit. I think using the same identifier is an advantage: one should not needlessly multiple terms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T00:23:54.750",
"Id": "223957",
"Score": "0",
"body": "@luserdroog Ah, I see what you mean now. I would actually like to leave it as is, I find your version more confusing to read for younger programmers (I know I was confused by it back in the day) and it only adds code with no benefit IMO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T03:14:37.800",
"Id": "223976",
"Score": "0",
"body": "But the next line refers to a struct which is (now) nowhere defined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T03:16:53.287",
"Id": "223977",
"Score": "0",
"body": "@luserdroog That line would be removed, as it is now useless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T03:18:39.607",
"Id": "223978",
"Score": "0",
"body": "This line? `struct chunk_header *next; // next pointer on free list\n`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T03:38:14.763",
"Id": "223979",
"Score": "0",
"body": "@luserdroog *facepalm*... I'm an idiot. Sorry, you most certainly are right. My apologies!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T03:38:49.087",
"Id": "223980",
"Score": "0",
"body": "For the naming question, I asked over on [programmers](http://programmers.stackexchange.com/questions/310292/why-would-you-want-different-identifiers-for-a-typedef-and-its-associated-struct)."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T01:57:46.037",
"Id": "43666",
"ParentId": "43663",
"Score": "14"
}
},
{
"body": "<p>I'd find it neater without chunk_header_begin and heap_size as global variables: instead, assume that chunk_header_begin is at <code>&buffer[0]</code> and assume that the heap size is defined by the several <code>chunk_header->size</code> values.</p>\n\n<p>I'm worried about what happens when you free-and-then-reallocate memory: the implementation doesn't look correct to me.</p>\n\n<p>I'm having trouble with statements like <code>curr + sizeof(chunk_header);</code>: if <code>curr</code> were type <code>char*</code> then <code>curr+3</code> would mean \"3 chars beyond curr\"; but when <code>curr</code> is type <code>chunk_header *</code> then <code>curr+3</code> mean \"3 chunk header beyond curr\" and so <code>curr + sizeof(chunk_header);</code> means \"<code>sizeof(chunk_header)*sizeof(chunk_header)</code> chars beyond curr\" which isn't what you want.</p>\n\n<p>IMO you should improve your unit-tests/assertions to verify that:</p>\n\n<ul>\n<li>next is at the expected place for a given size</li>\n<li>The sum of all size values (plus the size of the corresponding chunk header) matches the total heap size.</li>\n</ul>\n\n<p>It's conventional to put some magic number e.g. 0xdeadbeef at the start and end of each chunk header:</p>\n\n<pre><code>struct chunk_header {\n int magic_start; // 0xdeadbeef \n struct chunk_header *next; // next pointer on free list\n size_t size; // the size of this chunk\n bool is_available; // indicates if this chunk is MEMORY_AVAILABLE or MEMORY_USED\n int magic_end; // 0xdeadbeef\n};\n</code></pre>\n\n<ul>\n<li>Initialize the magic numbers when you create a chunk header</li>\n<li>Assert the magic numbers when you use a chunk header</li>\n<li>That will help detect chunk headers being overwritten by anyone using bad pointer arithmetic</li>\n</ul>\n\n<p>You can also write some magic byte value (e.g. <code>0xa3</code>) into all free/unused memory chunks, and later (when you walk the list of unallocated blocks) verify/assert than no-one has over-written those byte values.</p>\n\n<p>To avoid <a href=\"http://en.wikipedia.org/wiki/Fragmentation_%28computing%29\">fragmentation</a> some heap managers use <a href=\"http://en.wikipedia.org/wiki/Memory_allocation#Fixed-size-blocks_allocation\">a different algorithm</a>: e.g. have a list of 32-byte chunks and another list of 256-byte chunks; if you ask for 43 bytes then you get one of the 256-byte chunks.</p>\n\n<hr>\n\n<p>FYI I think your malloc implementation should be more like this:</p>\n\n<pre><code>void *my_malloc(unsigned int nbytes) {\n static bool init_flag = false;\n\n if(!init_flag) {\n init();\n init_flag = true;\n }\n\n int alloc_size = nbytes + sizeof(chunk_header); \n chunk_header *curr = chunk_header_begin;\n\n while(curr) {\n if(curr->is_available && curr->size >= alloc_size) {\n // we will use this chunk\n curr->is_available = MEMORY_USED;\n // is it big enough that we can split it into two chunks\n // i.e. use the start of this chunk and create a new free chunk afterwards?\n size_t min_chunk_size = sizeof(chunk_header) + 1; // big enough to allocate 1 byte\n if (cur->size - alloc_size >= min_chunk_size)\n {\n // yes so create a new chunk ...\n // ... new chunk is smaller than this one\n size_t new_size = cur->size - alloc_size;\n // ... new chunk is a few bytes beyond this one\n chunk_header *new_chunk = (chunk_header*)((char*)curr + alloc_size);\n init_next_chunk(new_chunk, new_size);\n // fit the new chunk into the existing chain of chunks\n new_chunk->next = curr->next;\n curr->next = new_chunk;\n // this chunk is smaller because its end is now a different/new chunk\n curr->size = alloc_size;\n }\n else\n {\n // can't split this into two chunk\n // don't adjust curr->next\n // don't adjust curr->size even if it's slightly too big\n }\n // return memory region\n // curr = curr + sizeof(chunk_header); I think this is wrong\n ++curr; // I think this is right\n return curr;\n }\n\n curr = curr->next;\n }\n\n return NULL;\n}\n</code></pre>\n\n<p>Similarly, when you free a chunk you should see whether:</p>\n\n<ul>\n<li>It has another chunk chained after it</li>\n<li>That next chunk is also already free</li>\n</ul>\n\n<p>If so then you should merge the two chunks to make a single, bigger free chunk.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T11:27:08.907",
"Id": "43691",
"ParentId": "43663",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T01:19:17.357",
"Id": "43663",
"Score": "11",
"Tags": [
"optimization",
"c",
"memory-management"
],
"Title": "malloc implementation"
} | 43663 |
<p>I put together this implementation after playing around with various partitioning- and pivot-strategies, and it runs fine. I wrote this off a version which seemed a bit different from the majority of implementations, so I'm curious on what you guys think. It works and handles duplicates.</p>
<pre><code>def quicksort(a, min=0, max=a.length-1)
if min < max
index = partition(a, min, max)
quicksort(a, min, index-1)
quicksort(a, index+1, max)
end
end
def partition(a, l, r)
m=(l+r)/2
piv = a[m]
a[m], a[r] = a[r], a[m]
cur = l
for i in l..r-1
if a[i] <= piv
a[i], a[cur] = a[cur], a[i]
cur+=1
end
end
a[cur], a[r] = a[r], a[cur]
return cur
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T10:23:02.697",
"Id": "75876",
"Score": "0",
"body": "It's amusing just how terse Quicksort can be in Ruby. For a functional (that is, not in-place) version of Quicksort that is just a few lines, see [this page on Ward's wiki](http://c2.com/cgi/wiki?QuickSortInRuby)"
}
] | [
{
"body": "<p>You code looks nice, my main problem with it is <strong>naming</strong>:</p>\n\n<p>Don't use single letters as member names, unless they are trivial. I couldn't figure out what <code>l</code> and <code>r</code> stand for until I read your code a couple of times (length? range?).</p>\n\n<p>Even more so, don't <em>ever</em> use the letter <code>l</code> as a variable name - it is much too similar to <code>1</code>, and is notoriously known to obfuscate code.</p>\n\n<p><strong>Don't re-use too familiar names for different purposes</strong> - <a href=\"http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-partition\" rel=\"nofollow\"><code>partition</code></a> is a well known method in ruby enumerables. Using this name for your code, especially when it involves arrays is <em>very</em> confusing. Don't do that. Call it <code>reorder_partition</code> or <code>pivot_partition</code>.</p>\n\n<p><strong>Expressiveness goes a long way</strong> - <code>a[l], a[r] = a[r], a[l]</code> works perfectly, but is hard to read, a much more readable way would be if you had a helper method <code>swap(a, l, r)</code>. Even better might look to implement it into <code>Array</code> <a href=\"http://www.dzone.com/snippets/swap-elements-array-ruby\" rel=\"nofollow\"><code>a.swap!(l, r)</code></a></p>\n\n<p><strong>Use the power of ruby</strong> - instead of <code>l..r-1</code>, use <a href=\"http://www.tutorialspoint.com/ruby/ruby_ranges.htm\" rel=\"nofollow\">non-inclusive range operator</a> - <code>l...r</code></p>\n\n<p>So, my version may look a little more verbose, but I believe it is much more readable. It did teach me a lot about quicksort :-)</p>\n\n<pre><code>def quicksort(array, min=0, max=array.length-1)\n if min < max\n index = reorder_partition(array, min, max)\n quicksort(array, min, index-1)\n quicksort(array, index+1, max)\n end\nend\n\ndef reorder_partition(array, left_index, right_index)\n middle_index = (left_index + right_index)/2\n pivot_value = array[middle_index]\n\n array.swap!(middle_index, right_index)\n\n less_array_pointer = left_index\n\n (left_index...right_index).each do |greater_array_pointer|\n if array[greater_array_pointer] <= pivot_value\n array.swap!(greater_array_pointer, less_array_pointer)\n less_array_pointer+=1\n end\n end\n\n array.swap!(less_array_pointer, right_index)\n\n return less_array_pointer\nend\n\nclass Array\n def swap!(a,b)\n self[a], self[b] = self[b], self[a]\n self\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:03:50.017",
"Id": "75552",
"Score": "0",
"body": "+1. Just some comments: 1) I'd use `each` instead of `for` (more idiomatic). 2) Some spaces seem to be missing (for example on `middle_index=(...`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:05:08.147",
"Id": "43677",
"ParentId": "43667",
"Score": "5"
}
},
{
"body": "<h1>Integer Overflow</h1>\n\n<p>I'm not very confident with ruby but I'm assuming this is integer arithmetic (otherwise you could have a floating point index, which doesn't make sense):</p>\n\n<pre><code> m=(l+r)/2\n</code></pre>\n\n<p>If it indeed is integer arithmetic you will have an integer overflow if you're dealing with large arrays.</p>\n\n<p>You should implement it as:</p>\n\n<pre><code> m = l + (r - l)/2; \n</code></pre>\n\n<p>which will not overflow for any <code>0 <= l <= r</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-28T19:32:22.633",
"Id": "88266",
"ParentId": "43667",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T02:22:54.020",
"Id": "43667",
"Score": "8",
"Tags": [
"algorithm",
"ruby",
"sorting",
"quick-sort"
],
"Title": "Quicksort implementation"
} | 43667 |
<p>I have been trying to create a class that would list prime numbers forever. I know it has already been done but I think I learned some valuable principles during my trials.</p>
<p>This project helped me understand (to a better extent) return values, arguments for methods, simple math arithmetic and what I personally enjoyed working with was the power of the <code>for</code> and <code>if</code>/<code>else</code> statements.</p>
<p>I would appreciate any insight into improvements that would increase this code performance and/or any obvious flaws with my code structure.</p>
<pre><code>//first the class is declared
public class startListingPrimeNumbers {
// method is created to start the prime number listing from 1 to infinity
// and beyond
public void startFromOneListingPrimeNumbers() {
// Create the primary for loop using doubles so the program will
// continue on infinitely
for (double x = 1; x > 0.000; x = x + 1.000) {
// The double c is for determining numbers that only have 2 factors
// are prime
double c = 2.000;
// I use the primeLogger to keep track of each numbers amount of
// factors it contains, to later compare this value to c to know if
// it's prime or not
double primeLogger = 0.000;
// the multiplier is used to iterate through the for loop below
double multiplier;
// this is the bread and butter, I take multiplier and iterate it
// until it is greater than x, if a remainder exists from x divided
// by multiplier then my primeLogger adds nothing to itself
// if there is no remainder then primeLogger adds one, meaning
// multiplier is a factor of x.
for (multiplier = 1.000; multiplier <= (x); multiplier = multiplier + 1.000) {
if (x % multiplier == 0) {
primeLogger = primeLogger + 1.000;
} else {
primeLogger = primeLogger + 0.000;
}
}
// here we see if there are only 2 factors for x, and the console
// prints the number
if (c == primeLogger) {
System.out.println(x + " is a prime number");
}
// primeLogger is set back to zero to go on to the next x value
// based on the primary for loop description
primeLogger = 0.000;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:53:18.927",
"Id": "75652",
"Score": "0",
"body": "I never programmed in Java, but when I did it in C, I used an Int64. Is there a reason to use a double here?"
}
] | [
{
"body": "<p>The major problem here is using imprecise floating point values. Not only does it slow the entire process (minor quibble), but it will produce incorrect results once the values pass the integral cutoff of the field width. If you truly want to allow calculations approaching infinity (or what? 24 bits?) you need to switch to <code>BigInteger</code> which can model \"exact\" integers of any size.</p>\n\n<blockquote>\n <p>Okay, they probably cap out at a very, very large number...much larger than doubles, but will likely last past the life of your PC.</p>\n</blockquote>\n\n<p>This issue is so critical to the correctness of the solution that I'll leave it to stand on its own and leave any other review issues for others.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:44:56.417",
"Id": "43669",
"ParentId": "43668",
"Score": "22"
}
},
{
"body": "<ol>\n<li><p>+1 to <em>@David Harkness</em> and here is an example:</p>\n\n<pre><code>final double original = 123456789123456789.0;\ndouble d = original;\nd = d + 1.000; // or d++\nSystem.out.println(d == original); // true\nSystem.out.printf(\"%f%n\", original); // 123456789123456784,000000\nSystem.out.printf(\"%f%n\", d); // 123456789123456784,000000\n</code></pre>\n\n<p>And two references:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n</ul></li>\n<li><blockquote>\n<pre><code>if (x % multiplier == 0) {\n primeLogger = primeLogger + 1.000;\n} else {\n primeLogger = primeLogger + 0.000;\n}\n</code></pre>\n</blockquote>\n\n<p>The else branch seems superfluous, I guess you could remove it:</p>\n\n<pre><code>if (x % multiplier == 0) {\n primeLogger = primeLogger + 1.000;\n}\n</code></pre></li>\n<li><pre><code>//first the class is declared\npublic class startListingPrimeNumbers {\n</code></pre>\n\n<p>Later you'll find that comments like this one are just noise. It says nothing more than the code already does, it's obvious from the code itself that it's a class declaration, so I'd remove it. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><blockquote>\n<pre><code>double multiplier;\n...\nfor (multiplier = 1.000; multiplier <= (x); multiplier = multiplier + 1.000) {\n</code></pre>\n</blockquote>\n\n<p>The multiplier could be declared in the <code>for</code> loop. </p>\n\n<pre><code>for (double multiplier = 1.000; multiplier <= (x); multiplier = multiplier + 1.000) {\n</code></pre>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Class names should be nouns, instead of verbs and the first letter should be uppercase:</p>\n\n<blockquote>\n <p>Class and Interface Type Names</p>\n \n <p>Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed\n case with the first letter of each word capitalized.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html\" rel=\"nofollow noreferrer\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a></p>\n\n<p><code>PrimeGenerator</code> could be a good name for this class.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:17:11.833",
"Id": "75667",
"Score": "1",
"body": "I think this can be illustrated even cleaner with `System.out.println(123456789123456789.0)` and watch it print `...784.0`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:03:25.730",
"Id": "43676",
"ParentId": "43668",
"Score": "15"
}
},
{
"body": "<p>The others have pointed out many things, but I have one thing to add:</p>\n\n<p>Instead of using the <code>+</code> operator for accumulating a total, thus having to write the left-hand operand twice, you can use the <code>+=</code> operator instead.</p>\n\n<p>For instance, instead of</p>\n\n<pre><code>number = number + 2;\n</code></pre>\n\n<p>you'll have</p>\n\n<pre><code>number += 2;\n</code></pre>\n\n<p>The relevant statements would look like this. I'll also apply some of @palacsint's suggestions so that you can see the improved code together.</p>\n\n<pre><code>for (double x = 1; x > 0.000; x += 1.000) {\n // ...\n for (double multiplier = 1.000; multiplier <= (x); multiplier += 1.000) {\n // ...\n primeLogger += 1.000;\n // ...\n }\n}\n</code></pre>\n\n<p>Although those three variables should just be incremented by one with <code>++</code> (based on @Uri Agassi's advice), I've shown the use of <code>+=</code> here just for demonstration. For values other than one (which only works with <code>++</code> or <code>--</code>), you would use <code>+=</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:32:13.733",
"Id": "43678",
"ParentId": "43668",
"Score": "11"
}
},
{
"body": "<p>@DavidHarkness and @palacsint warned about the general mis-use of <code>double</code>, because of precision, but I wonder why would you even consider it when looking for prime numbers? Do you know any non-integer prime number?</p>\n\n<p>Ok, so you say - I want it to be able to calculate <em>really</em> big numbers, and I was not aware of the cutoff. But why use <code>double</code> for <code>c</code> (the constant <code>2.000</code>)? or for <code>primeLogger</code>? It makes the code less readable, since it implies non-integer numbers. Personally, I got dizzy from all the <code>1.000000</code> in a <em>prime number</em> algorithm - <code>1.0</code> is more than enough...</p>\n\n<p>Some other issues:</p>\n\n<p><strong>Infinite for loops</strong> - </p>\n\n<pre><code>for (double x = 1; x > 0.000; x = x + 1.000) {\n</code></pre>\n\n<p>very cumbersome and hard to read</p>\n\n<pre><code>for (double x = 1; ; x++) {\n</code></pre>\n\n<p>does exactly the same, easier on the eyes</p>\n\n<p><strong>Fail fast!</strong></p>\n\n<p>In your algorithm, you iterate over all the numbers smaller than <code>x</code>, count <em>all</em> its divisors, and then check if there are less than two of those.</p>\n\n<p>This is a very <em>inefficient</em> algorithm - you should stop counting at two! Big numbers may have thousands of divisors, but you only need one to know they are not primes!</p>\n\n<p>Even more so, you count <code>1</code> as a divisor. As I don't know of any prime who <em>doesn't</em> have <code>1</code> as a divisor, you can skip it, and look for any <em>non</em> 1 divisor to conclude the number is not a prime.</p>\n\n<p><strong>Redundant code</strong></p>\n\n<pre><code>primeLogger = 0.000;\n</code></pre>\n\n<p>is totally redundant, as you declare it inside the block, and set it at the beginning of it. No need to 'reset' it.</p>\n\n<p><strong>Comments</strong></p>\n\n<p>@palacsint mentioned superfluous comments, I'd like to add that when there are more comments than code it is a big smell - your code should be descriptive enough for a reader to comprehend:</p>\n\n<pre><code>// I use the primeLogger to keep track of each numbers amount of\n// factors it contains, to later compare this value to c to know if\n// it's prime or not\ndouble primeLogger = 0.000;\n</code></pre>\n\n<p>...this probably means the <code>primeLogger</code> is <em>not</em> a good name... how about <code>numOfFactors</code>? Less needed to explain...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:34:14.347",
"Id": "43680",
"ParentId": "43668",
"Score": "12"
}
},
{
"body": "<p>To provide another view on the use of double to represent integer numbers. If you run the following code (<a href=\"https://ideone.com/EHGs9l\">ideone link</a>) you will find that around 2^53 double will fail you. The reason is that double is a 64 bit floating point type with 53 bit mantissa which gives you around 16 significant decimal digits.</p>\n\n<p>Test code:</p>\n\n<pre><code> public static void main (String[] args) throws java.lang.Exception\n {\n long l = 1;\n double d = 1.0;\n for (int i = 0; i < 63; ++i)\n {\n l *= 2;\n d *= 2.0;\n\n System.out.format(\" n: %d\\n\", i + 1);\n System.out.format(\" long: %d (+1 = %d)\\n\", l, l + 1);\n System.out.format(\"double: %.0f (+1 = %.0f)\\n\", d, d + 1.0);\n System.out.println();\n }\n }\n</code></pre>\n\n<p>At <code>i = 52</code> the output is:</p>\n\n<pre><code> n: 53\n long: 9007199254740992 (+1 = 9007199254740993)\ndouble: 9007199254740992 (+1 = 9007199254740992)\n</code></pre>\n\n<p>So all of a sudden <code>x + 1 = x</code> when using double because on floating point adding a small value to a very large value just results in the very same large value. </p>\n\n<p>Conclusion: Using <code>long</code> would give you a larger range than double.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:13:19.173",
"Id": "43681",
"ParentId": "43668",
"Score": "10"
}
},
{
"body": "<p>You are testing many many more divisions that necessary. The number is always divisible by itself, and if it's not divisible by anything up to sqrt(x), it must be prime:</p>\n\n<p>Like this:</p>\n\n<pre><code>for (multiplier = 2; multiplier*multiplier <= x; multiplier = multiplier + 1)\n</code></pre>\n\n<p>It's easier and cleaner to square left side than to root right side. Number 1 is a special case anyway. This does change counting the divisors a little bit. Every divisor above sqrt(x) has a symmetric pair below sqrt(x). Which means that your <code>primeLogger</code> should be multiplied by 2 at the end, and additionally subtract 1, if x was a perfect square (in that case you counted the middle one twice). However, this GREATLY reduces the number of trial divisions.</p>\n\n<p>Additionally, if you are not factoring numbers, only finding primes, you can stop checking immediately after finding a factor. You don't even need <code>primeLogger</code> in that case.</p>\n\n<p>If you are happy to excercise coding abilities as a hobby, you can have a lot of fun making an arbitrary-precision integer class from scratch (hold an array of unsigned integers and override casting, multiplication, addition and division operators to perform carry and other required operations).</p>\n\n<p>Prime number generation is usually one of the first interesting things one does when learning programming. There are A LOT of optimizations that you can do without advanced math, but I won't bother you with that right now. Have fun.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:43:14.750",
"Id": "75589",
"Score": "0",
"body": "\"the largest non-self divisor possible is sqrt(x)\". This is not true; the correct statment is \"If a non-self divisor larger than sqrt(x) exists then a divisor smaller than sqrt(x) also exists\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:50:46.783",
"Id": "75591",
"Score": "0",
"body": "Well yes that's what I meant. What remains after dividing out up to sqrt(x), what's left must be prime. So if you are checking primality, it doesn't matter but counting divisors may be wrong. Fixing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:10:31.403",
"Id": "43688",
"ParentId": "43668",
"Score": "11"
}
},
{
"body": "<p>You've gotten a number of hints about how to speed up the code, but a few points seem to have been missed.</p>\n\n<p>The first and biggest is that once you've determined that the number isn't divisible by 2, you've also determined that it can't possibly be a multiple of any other even number, so you can skip testing against any other even numbers.</p>\n\n<pre><code>if (x % 2 == 0)\n return false;\n\nfor (long multiplier = 3; multiplier * multiplier <= number; multiplier += 2)\n if (number % multiplier == 0)\n return 0;\n</code></pre>\n\n<p>Although it departs from the nature of the code you posted, it's also worth considering using the sieve of Eratosthenes<sup>1</sup> to generate the first several million primes or so. After you've generated the first primes that way, you can use the table of primes it produces in trial division to produce larger primes--instead of doing trial division by all odd numbers, you can do trial division only by the primes (from the table) up to the square root of the number being tested.</p>\n\n<hr>\n\n<ol>\n<li>There are alternatives such as the sieve of Atkins, but they're quite a bit more difficult to code, and the sieve of Eratosthenes is already dramatically faster than trial division.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:14:09.933",
"Id": "43726",
"ParentId": "43668",
"Score": "11"
}
},
{
"body": "<p>I did a similar project myself, and there's a few rules you can use (one of which was already mentioned by @orion:</p>\n\n<ol>\n<li>A number will never have a prime factor > FLOOR( SQRT( number ))</li>\n<li>After 2, no even number is prime.</li>\n<li>After 5, no number ending in 5 is prime.</li>\n<li>Since the primes are factors of larger #'s, you can save the primes, and iterate over the array of primes to test if a number is prime.</li>\n</ol>\n\n<p>Here's what I ended up using:</p>\n\n<pre><code>static void Main(string[] args)\n {\n long sqrtFloor;\n List<long> curPrimes = new List<long>(100000000);\n curPrimes.Add(2);\n curPrimes.Add(3);\n curPrimes.Add(5);\n curPrimes.Add(7);\n bool found;\n int j;\n System.Diagnostics.Debug.Print(\"Start Time=\" + DateTime.Now.ToString());\n for (long k = 11; k < 1000000000; k += 2)\n {\n if (k % 10 == 5)\n continue;\n\n found = false;\n\n sqrtFloor = (long)Math.Floor(Math.Sqrt(k));\n\n j = 0;\n while (curPrimes[j] < sqrtFloor && found == false)\n {\n if (k % curPrimes[j] == 0)\n found = true;\n ++j;\n }\n\n if (!found)\n curPrimes.Add(k);\n }\n System.Diagnostics.Debug.Print(\"End Time=\" + DateTime.Now.ToString());\n found = true; \n }\n</code></pre>\n\n<p>As I'm sure someone else has pointed out, there's no way even a double could go on forever printing out primes, as it would eventually overflow the mantissa, so it's irrelevant that my example only goes to 1,000,000,000 - You could increase it, but you start running into how long it takes to run. I think it took a little over an hour on an i3 laptop for this, and it would increase by multitudes for each factor of 10. Anyways, using 128 bit numbers would be your best bet...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:43:10.170",
"Id": "75707",
"Score": "0",
"body": "why stop at skipping over every multiple of 2 and 5? And why did you choose 2 and 5, but not 3? I feel like at that point, you might as well take it to its logical conclusion, which is the sieve of eratosthenes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T14:10:01.797",
"Id": "76016",
"Score": "0",
"body": "Actually, until I read the other answers here, I wasn't aware of the sieve of eratosthenes. Overall, I think it's a really clever approach, but I did have concerns w/ the added storage; However, @Orion has an excellent example below w/ wheel factorization!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:43:36.303",
"Id": "43727",
"ParentId": "43668",
"Score": "12"
}
},
{
"body": "<p>Follow up on HungryBeagle's excellent answer:</p>\n\n<p>The generalization of excluding factors of 2 and 3 (and so on) from search is called Wheel factorization. In my opinion the best is to do it for 2,3 and 5. It has a period of 30 (relatively small), and exactly 8 jumps between prime candidates: (6,4,2,4,2,4,6,2). You see the appeal: only 8 candidates out of 30 are tested, and 8 is perfect for iteration (for binary reasons).</p>\n\n<p>You output 2,3,5 as primes, then start jumping (testing 1+6,1+6+4,1+6+4+2,...). If you include 7 or higher you have a bigger jump table and less and less improvement. The formula is: <code>number_of_jumps=number_of_candidates=phi(2*3*5*...)=(2-1)*(3-1)*(5-1)*...</code>, where phi is Euler's Totient function. So for 2, your trade-off is 1/2, for 3 it's <code>(1/2)*(2/3)</code>, for 5 it's <code>(1/2)*(2/3)*(4/5)=8/30=26.7%</code>, and for 7 it's <code>(1/2)*(2/3)*(4/5)*(6/7)=48/210=22.8%</code> which is slightly better, but requires BIGGER jump table, which also isn't of size 2^n. It's true, when you are doing primes sequentially from 2 up, you can use full sieve (remember all previous primes) but usually you need a test for a specific prime.</p>\n\n<p>Here's quite a fast and short code in c:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <stdint.h>\n\nint main(){\n static const uint64_t jumptable[]={6,4,2,4,2,4,6,2};\n printf(\"%ld\\n%ld\\n%ld\\n\",2,3,5);//output first three\n uint64_t index=1;//for cycling through jumptable\n for(uint64_t n=7;1;n+=jumptable[0x7&(index++)]){//infinite loop\n //wheel test\n int is_prime=1;\n uint64_t index2=1;//inner wheel\n for(uint64_t m=7;m*m<=n;m+=jumptable[0x7&(index2++)]){\n if(n%m==0){is_prime=0;break;}\n }\n if(is_prime)printf(\"%ld\\n\",n);\n }\n return 0;\n}\n</code></pre>\n\n<p>These are the basic improvements. After this step, you can employ advanced primality tests, such as Miller-Rabin test or Pollard's Rho test, which bring orders of magnitude of improvements. But this first step still eliminated a lot of unnecessary tests.</p>\n\n<p>You can guess I've done this before :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:58:25.103",
"Id": "43787",
"ParentId": "43668",
"Score": "4"
}
},
{
"body": "<p>The biggest speedup, to agree with others, is that you don't have to brute force test every number. There are really only two things to keep in mind:</p>\n\n<ol>\n<li><p>You need to test up to the square root of the number you're trying to prove is prime, since the square root of a number will be the center of its set of divisors (ie, any factors of a number will have one number less than the square root, and one number greater than the square root). </p></li>\n<li><p>You only need to test the primes that are less than the square root of said number. </p></li>\n</ol>\n\n<p>Example: Let's say the number you're trying to test is 37. First, you find the square root, which is slightly greater than 6. Then determine the primes <=6, which are 2, 3, and 5, and then divide 37 by these numbers. </p>\n\n<p>Here's my own version to show you what I'm talking about. It'll only stop when you run out of memory ;) :</p>\n\n<pre><code>#include<iostream>\n#include<vector>\n#include<math.h>\nusing namespace std;\n\nint main(){\n vector<long long> primes; //stores primes that have been found\n long long totest = 5;\n long long median = ceil(sqrt(totest));\n long long count = 0; //counts the number of tests on each number\n bool running = true;\n primes.push_back(2);\n primes.push_back(3);\n cout <<\"Output takes the form prime, number of tests, size of prime database.\\n\";\n cout << \"2, 0, 1\" << endl << \"3, 0, 2\" << endl;\n while(running){\n long np =-1;\n for(long long index = 0; primes.at(index) <= median; index++){\n np = totest % primes.at(index);\n count++; //so for every test, i increment the test counter\n if(np == 0){ count = 0; break;}\n }\n if(np != 0){\n primes.push_back(totest); //if none of the existing primes can divide the current number, add it to the list of primes to test for bigger primes.\n cout << totest << \", \" << count << \", \" << primes.size() << endl;\n }\n totest++;\n count = 0;\n median = ceil(sqrt(totest));\n }\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T01:31:58.850",
"Id": "43833",
"ParentId": "43668",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:12:54.130",
"Id": "43668",
"Score": "15",
"Tags": [
"java",
"primes"
],
"Title": "Prime number generator exercise"
} | 43668 |
<p>Please review the code.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RGB to HEX (and vice versa) converter</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.0/normalize.min.css">
<style>
body{
color: #222;
font-family: "Segoe UI", sans-serif;
}
#main {
margin: 10% auto;
max-width: 300px;
}
input[type="text"] {
padding: 10px;
width: 100%;
outline: 0;
border: 0;
border-bottom: 1px dashed;
background: inherit;
text-shadow: 0 1px 0 #f0f0f0;
font-size: 18px;
}
::-webkit-input-placeholder { color: #a9a9a9; }
:-moz-placeholder { color: #a9a9a9; }
::-moz-placeholder { color: #a9a9a9; }
:-ms-input-placeholder { color: #a9a9a9;}
</style>
</head>
<body>
<div id="main">
<p><input id="rgb" type="text" placeholder="rgb(255, 255, 255)"></p>
<p><input id="hex" type="text" placeholder="#ffffff"></p>
</div>
<script>
(function() {
"use strict";
var inputRgb = document.getElementById("rgb"),
inputHex = document.getElementById("hex"),
converter = {
// help: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
toHex: function() {
function componentToHex(c) {
var hex = parseInt(c).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
var rgb = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(inputRgb.value);
inputHex.value = rgb ? "#" + componentToHex(rgb[1]) + componentToHex(rgb[2]) + componentToHex(rgb[3]) : "";
converter.changeBgColor(inputRgb.value);
},
toRgb: function() {
// expand shorthand form (e.g. "03f") to full form (e.g. "0033ff")
var hex = inputHex.value.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) {
return r + r + g + g + b + b;
}),
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
inputRgb.value = result ? "rgb(" + [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)].join(", ") + ")" : "";
converter.changeBgColor(inputHex.value);
},
changeBgColor: function(color) {
document.body.style.backgroundColor = color;
}
};
inputRgb.addEventListener("input", converter.toHex, false);
inputHex.addEventListener("input", converter.toRgb, false);
}());
</script>
</body>
</html>
</code></pre>
<p>Jsbin - <a href="http://jsbin.com/fokayomo/1/">http://jsbin.com/fokayomo/1/</a></p>
| [] | [
{
"body": "<p>Two things jump out at me.</p>\n\n<ol>\n<li><p>Decouple from the HTML elements.</p>\n\n<pre><code>var inputRgb = document.getElementById(\"rgb\"),\n inputHex = document.getElementById(\"hex\"),\n</code></pre>\n\n<p>I would do something like:</p>\n\n<pre><code>function RGB2Hex (inputRgb, inputHex){\n var converter = {\n toHex: ...\n toRGB: ...\n };\n\n inputRgb.addEventListener(\"input\", converter.toHex, false);\n inputHex.addEventListener(\"input\", converter.toRgb, false);\n\n return converter;\n}\n\n// Usage:\nvar mainHexConversion = new RGB2Hex(document.getElementById(\"rgb\"), document.getElementById(\"hex\"));\nvar secondHexConversion = new RGB2Hex(document.getElementById(\"mini-rgb\"), document.getElementById(\"mini-hex\"));\n</code></pre></li>\n<li><p>keep the background colour changing code outside the converter.</p>\n\n<pre><code>function RGB2Hex (inputRgb, inputHex, onColourChange)\n{\n var converter = {\n toHex: ...\n toRGB: ...\n colourChanged: function(colourValue){\n if(typeof onColourChanged == \"function\")\n {\n onColourChange(colourValue);\n }\n }\n };\n}\n\n// Usage: \nvar mainHexConversion = new RGB2Hex(\n document.getElementById(\"rgb\")\n , document.getElementById(\"hex\")\n , function(color)\n {\n document.body.style.backgroundColor = color;\n }\n);\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:13:28.797",
"Id": "75553",
"Score": "0",
"body": "would you please edit your answer with the final code... thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:26:59.057",
"Id": "75748",
"Score": "0",
"body": "I think my answer is not complete enough to have \"the final code\". I encourage you to read it and take the parts from it as you like."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:34:38.143",
"Id": "43672",
"ParentId": "43670",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43672",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:49:40.633",
"Id": "43670",
"Score": "6",
"Tags": [
"javascript",
"converting"
],
"Title": "RGB to HEX (and vice versa) converter"
} | 43670 |
<p>Is there a better (functional or more idiomatic) way to get the first positive number that is not included in a set?</p>
<pre><code>val set = Set(4, 1, 2, 0, 5)
var x = 0
while(set(x)) x += 1
println(x) // Should print 3
</code></pre>
| [] | [
{
"body": "<p>Your solution could hardly be more simple which is good.</p>\n\n<p>Also, it will loop at most <code>n</code> times (worst case when integers from the set start at 0 and are consecutive). Each loop should take a constant time on average (property of a set). Worst case complexity is <code>O(n)</code> (actually in a really worst case, testing if a value is in a set takes a linear time but let's ignore this for the time being) which cannot be beaten because in the worst case, one will always need to inspect all n elements.</p>\n\n<p>If you are a bit paranoid and don't want to rely on the unpredictable performance of set, you can look for other solutions but I'm not sure it's worth the pain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:21:13.520",
"Id": "75554",
"Score": "0",
"body": "Thanks for your answer. Performance is not an issue. I am simply new to Scala so I was curious if there is a neat functional way to do this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T06:49:19.820",
"Id": "43674",
"ParentId": "43673",
"Score": "2"
}
},
{
"body": "<p>You could try for a more functional expression that matches problem description more closely:</p>\n\n<pre><code> Stream.from(1).filter(!set.contains(_)).head\n</code></pre>\n\n<p>[Caveat: I'm not a scala programmer, I have no idea how idiomatic this is]</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:51:32.480",
"Id": "75556",
"Score": "1",
"body": "I'am not a Scala programmer but it looks much more idiomatic than anything I could have done. Nice solution!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:48:45.683",
"Id": "43682",
"ParentId": "43673",
"Score": "5"
}
},
{
"body": "<p><code>0</code> is considered positive? I think you should change the second line to:</p>\n\n<pre><code>var x = 1\n</code></pre>\n\n<p>If you want to get idiomatc, you can use tail recursion:</p>\n\n<pre><code>@tailrec def minNumNotInSet(s: Set, acc: Int):Int =\n if (s(acc)) minNumNotInSet(s, acc + 1) else acc\n\nprintln(minNumNotInSet(Set(4, 1, 2, 0, 5), 1)\n# 3\n</code></pre>\n\n<p>This goes with scala being a <em>functional</em> language. This version of the function is <em>immutable</em> - no elements change their value within it (no <code>x += 1</code>). This is more relevant to algorithms you might want to scale on a multi-processor multi-machine environment since it adhers to the <a href=\"http://en.wikipedia.org/wiki/Actor_model\" rel=\"nofollow\"><code>Actor</code> model</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:58:36.060",
"Id": "75576",
"Score": "0",
"body": "This being Scala, you would of course use `lowerCamelCase` instead of underscores ([sauce](http://docs.scala-lang.org/style/naming-conventions.html#constants_values_variable_and_methods)). And use the `@tailrec` annotation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T11:12:08.867",
"Id": "75577",
"Score": "0",
"body": "@amon - of course, you are right, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T22:43:17.720",
"Id": "75696",
"Score": "0",
"body": "Thanks, for the additional answer! `0` is not positive indeed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:32:03.043",
"Id": "43689",
"ParentId": "43673",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43682",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T06:14:40.183",
"Id": "43673",
"Score": "1",
"Tags": [
"scala"
],
"Title": "Get lowest integer that is not in set"
} | 43673 |
<p>I have a server application using <code>TcpListener</code> in <code>BackgroundWorker</code>, where my application is doing some work, and in the background listening to a IP:PORT.</p>
<p>The <code>DoWork</code> of the <code>BackgroundWorker</code>:</p>
<pre><code>private void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (true) //infinit loop : listen
{
var clientSocket = _serverSocket.AcceptTcpClient();
e.Result = clientSocket;
m_oWorker.ReportProgress(1, clientSocket);
}
}
</code></pre>
<p>At the progress change event, I do notify the form (launcher of the <code>BackgroundWorker</code>) that a new <code>TcpClient</code> is available:</p>
<p>The <code>ProgressChanged</code> of the <code>BackgroundWorker</code>:</p>
<pre><code>private void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_luncher.NotifyFormNewTcpClient((TcpClient)e.UserState);
MessageBox.Show("new TcpClient Connected...");
}
</code></pre>
<p>Now for each form that wants to use that background worker, I need to add the method <code>NotifyFormNewTcpClient</code>, and in that method, I have a list of <code>TcpListening</code>, and I added the returned TcpClient to that list:</p>
<pre><code>public void NotifyFormNewTcpClient(TcpClient tcpClient)
{
TcpClientsList.Add(tcpClient);
lNumberOfClient.Text = TcpClientsList.Count.ToString() " Clients";
}
</code></pre>
<p><strong>Question:</strong></p>
<p>What I am doing works until now, but I wanted to know if I am doing it the right way. I want my application to keep doing some work, while it's listening in a LAN for clients that request it, and have a list of the clients (TcpClient) at any moment. Any ideas are welcome.</p>
| [] | [
{
"body": "<p>Your code looks OK, though I think there is some redundant code - <code>e.Result = clientSocket;</code> is never used, since work is never completed...</p>\n\n<p>You might also want to consider a different approach to <code>BackgroundWorker</code> - <code>TcpListener.AcceptTcpClientAsync</code>. Instead of creating a worker thread you can do this:</p>\n\n<pre><code>private Task<TcpClient> listen() {\n\n return _serverSocket.AcceptTcpClientAsync().ContinueWith(clientSocket => {\n _launcher.NotifyFormNewTcpClient(clientSocket);\n MessageBox.Show(\"new TcpClient Connected...\");\n return listen();\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:23:42.060",
"Id": "43685",
"ParentId": "43679",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "43685",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:34:05.093",
"Id": "43679",
"Score": "3",
"Tags": [
"c#",
"tcp"
],
"Title": "Is this the right way to use TcpListener in the background?"
} | 43679 |
<p>Could you suggest ways of writing this code better?</p>
<pre><code>bool success = true;
if(x == 0)
{
if(do_up)
run_do_up();
else if(do_a)
run_do_a();
else if(do_n)
run_do_n();
else
success = false;
}
else if(x == 1)
{
if(do_n)
run_do_n();
else if(do_a)
run_do_a();
else
success = false;
}
else//x == 2
{
if(do_a)
run_do_a();
else if(do_n)
run_do_n();
else
success = false;
}
</code></pre>
| [] | [
{
"body": "<p>You could try anything like this:</p>\n\n<pre><code>bool success = true;\n\nif(x == 1)\n{\n if(do_n)\n run_do_n();\n else if(do_a)\n run_do_a();\n else\n success = false;\n}\nelse//x == 2 || x == 0\n{\n if(do_up && x == 0)\n run_do_up();\n else if(do_a)\n run_do_a();\n else if(do_n)\n run_do_n();\n else\n success = false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:50:51.153",
"Id": "43687",
"ParentId": "43683",
"Score": "2"
}
},
{
"body": "<p>switch clause is usually used to clean this up, at least at the outer level:</p>\n\n<pre><code>switch(x){\n case 0:{\n if(do_up)\n run_do_up();\n else if(do_a)\n run_do_a();\n else if(do_n)\n run_do_n();\n else\n success = false;\n break;\n }\n case 1:{\n if(do_n)\n run_do_n();\n else if(do_a)\n run_do_a();\n else\n success = false;\n break;\n }\n default: {\n if(do_a)\n run_do_a();\n else if(do_n)\n run_do_n();\n else\n success = false;\n }\n}\n</code></pre>\n\n<p>Alternatively, you can just realize you have 3 things to run an put in the logic:</p>\n\n<pre><code>if(x==0 && do_up)run_do_up(); //the only case this happens\nelse //case 1 does n first, other cases do a first\nif(do_a && (x!=1 || (x==1 && !do_n)))run_do_a();\nelse\nif(do_n && (x==1 || (x!=1 && !do_a)))run_do_n();\nelse success=false;\n</code></pre>\n\n<p>Check if I messed it up. The main question is: do you want from the flow to be apparent which one is checked first (in which case just use switch statement) or you want to avoid duplication of calls. You can also go take the hybrid way and just set flags in the main if block and then just conditionally call them at the end. Like this</p>\n\n<pre><code> ...\n if(do_up) which_to_call=0;\n else if(do_a) which_to_call=1;\n else if(do_n) which_to_call=2;\n else which_to_call=-1; //error flag\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:54:57.210",
"Id": "75592",
"Score": "1",
"body": "+1 for the 3 things with logic in the if statement. I had that idea also but didn't put enough effort in thinking about the logic. Nice answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:53:11.297",
"Id": "43690",
"ParentId": "43683",
"Score": "5"
}
},
{
"body": "<p>I think I'd encode this into something on the order of a state machine--a table holding the conditions and actions associated with each, and a tiny bit of code to walk through those to carry out the tests:</p>\n\n<pre><code>#include <iostream>\n#include <functional>\n\n#ifdef TEST\nbool do_n, do_a, do_up;\nbool success;\nbool T = true;\n\nvoid run_do_up() { std::cout << \"did up\\n\"; }\nvoid run_do_a() { std::cout << \"did a\\n\"; }\nvoid run_do_n() { std::cout << \"did n\\n\"; }\n#endif\n\nstruct conditional_action { \n bool const &condition;\n std::function <void()> action;\n\n template <class F>\n conditional_action(bool const &b, F &a) : condition(b), action(a) {}\n\n conditional_action() : condition(T), action([&]{success = false; }) {}\n};\n\nconditional_action actions[4][3] { \n { { do_up, run_do_up }, { do_a, run_do_a }, { do_n, run_do_n } },\n { { do_n, run_do_n }, { do_a, run_do_a } },\n { { do_a, run_do_a }, { do_n, run_do_n } }\n};\n\nvoid exec(size_t x) { \n for (auto const &a : actions[x])\n if (a.condition) {\n a.action();\n return;\n }\n}\n\n#ifdef TEST\n\nint main() { \n do_n = true;\n exec(0);\n\n do_a = true;\n exec(2);\n}\n#endif\n</code></pre>\n\n<p>Depending on viewpoint, you might want to add a <code>{ T, [&]{success = false; }}</code> to the end of each row in the <code>actions</code> table. That's what the default ctor will fill those entries with anyway, but there's a fair argument to be made that since it was explicit in the original logic, it should remain explicit here as well.</p>\n\n<p>There is probably at least a little argument to be made that this is kind of a borderline case. A case where there were more conditions and actions would favor this technique more strongly. Whether really it makes sense when you have only three conditions and actions may be open to a little more question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:50:21.273",
"Id": "75590",
"Score": "0",
"body": "Isn't that to much for such a small task?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T13:07:04.523",
"Id": "75594",
"Score": "2",
"body": "@exilit: Well, let's compare it to your answer. The combined total of `exec`, `actions` and `conditional_action` is *exactly* the same number of lines of code as you give in your answer. Your answer got that short, however, by breaking the original logic (`do_up` should not be considered when x==2). So, mine is not only much more scalable, but even for this small case is already the shortest code posted that actually works. It mostly looks longer because I added in demo/mock/test code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T13:43:27.807",
"Id": "75597",
"Score": "0",
"body": "I am not talking about loc. What I am talking about is the time and effort needed for the logic that sits behind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:24:44.500",
"Id": "75607",
"Score": "1",
"body": "@exilit: What time and effort? The effort of a single `for` loop or of a struct of two whole members? The effort to fully understand and verify something like `if(do_a && (x!=1 || (x==1 && !do_n)))run_do_a();` alone exceeds the effort involved in writing and verifying my entire program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:43:11.310",
"Id": "75609",
"Score": "0",
"body": "I am just asking. Don't get me wrong, it is a nice way to solve complex problems of that kind (+1 for that). But in my opinion this more difficult to understand and to follow this code than an (complex) if statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:07:42.307",
"Id": "75614",
"Score": "1",
"body": "@exilit: Maybe I just think in terms of larger, more complex problems, but I have to admit that I just don't see the difficulty or complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:31:24.620",
"Id": "75671",
"Score": "0",
"body": "I do like this better. It may look a bit longer, but it also looks cleaner *and* C++-like. I would've otherwise thought the OP's code was meant to be C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T20:24:34.680",
"Id": "75819",
"Score": "0",
"body": "@exilit investing this kind of tiny effort in table-driven code is a good way to ensure that the task is not bound to stay small (i.e. it scales a lot better)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:46:56.827",
"Id": "43700",
"ParentId": "43683",
"Score": "11"
}
},
{
"body": "<p>Put the maximum number of cases together in the same conditional. In this case, it means lumping values of x and do_...</p>\n\n<pre><code>bool success = true;\nif (x == 0 && do_up) run_do_up();\nelse if (x == 1 && do_n) run_do_n();\nelse if (do_a) run_do_a();\nelse if (do_n) run_do_n();\nelse success = false;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:16:10.080",
"Id": "43720",
"ParentId": "43683",
"Score": "1"
}
},
{
"body": "<p>If you write a few boolean returning wrapper functions:</p>\n\n<pre><code>bool cond_do_a(bool do) {\n if (do) run_do_a();\n return do;\n}\nbool cond_do_n(bool do) {\n if (do) run_do_n();\n return do;\n}\nbool cond_do_up(bool do) {\n if (do) run_do_up();\n return do;\n}\n</code></pre>\n\n<p>Than you can express the code with a few simple logical or operators:</p>\n\n<pre><code>switch(x){\n case 0: success = cond_do_up(do_up) || cond_do_a(do_a) || cond_do_n(do_n);\n break;\n case 1: success = cond_do_n(do_n) || cond_do_a(do_a);\n break;\n case 2: success = cond_do_a(do_a) || cond_do_n(do_n);\n break;\n default:\n success = false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:14:52.300",
"Id": "43746",
"ParentId": "43683",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43690",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T09:16:10.503",
"Id": "43683",
"Score": "6",
"Tags": [
"c++",
"game"
],
"Title": "Movement code from a game"
} | 43683 |
<p>Given a mongodb collection that stores trees as nodes with parent references this methods returns a deep nested tree where every child nodes are stored in a property childs[Seq]</p>
<pre><code> def getTree(rootId: BSONObjectID): Future[CategoryTreeNode] = {
def collect(parent: CategoryTreeNode): Future[CategoryTreeNode] = {
// Query the database - returns a Future[Seq[CategoryTreeNode]]
getChilds(parent._id.get).map {
// Seq[CategoryTreeNode]
childs =>
Future.sequence(
childs.map(child => collect(child)) // Recursion
).map(childSeq => parent.copy(childs = Some(childSeq)))
}.flatMap(x => x).map(y => y)
}
// Find the root node and start the recursion
findOne[CategoryTreeNode](Json.obj("_id" -> rootId)).map(maybeNode => maybeNode match {
case None => throw new RuntimeException("Current node not found by id!")
case Some(node) => collect(node)
}).flatMap(x => x)
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T11:50:59.010",
"Id": "75581",
"Score": "0",
"body": "What are your concerns about the code? Or do you simply want general comments about your implementation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T11:54:41.767",
"Id": "75582",
"Score": "0",
"body": "Basically I want to know if it can be done better/more idiomatic - especially the map.flatmap cascades look odd to me."
}
] | [
{
"body": "<ul>\n<li><p><code>flatMap (x => x)</code> would probably better be written as <code>flatten</code>.</p></li>\n<li><p><code>map (x => x)</code> is essentially a no-op, and could be removed.</p></li>\n<li><p><code>map ( ... ) flatten</code> is equivalent to <code>flatMap (...)</code></p></li>\n<li><p>It doesn't seem useful to put a type into a comment – you can specify the type for parameters of lambdas as well:</p>\n\n<pre><code>{ (childs: Seq[CategoryTreeNode]) => ...\n</code></pre>\n\n<p>However, this style is generally discouraged. It would be more useful to store the future from the DB in a variable which gets typed explicitly.</p></li>\n<li><p>Higher-order method like <code>map</code> should not be invoked with a leading <code>.</code>: do <code>collection map (x => ...)</code> instead of <code>collection.map(x => ...)</code> (<a href=\"http://docs.scala-lang.org/style/method-invocation.html#higherorder_functions\" rel=\"nofollow\">source</a>).</p></li>\n<li><p><code>(foo => foo match { ... })</code> can be simplified to <code>(_ match { ... })</code></p></li>\n<li><p><code>(child => collect(child))</code> can be simplified to <code>(collect(_))</code> or even just <code>collect</code></p></li>\n</ul>\n\n<p>Together, I'd clean up your code to this:</p>\n\n<pre><code>def getTree(rootId: BSONObjectID): Future[CategoryTreeNode] = {\n def collect(parent: CategoryTreeNode): Future[CategoryTreeNode] = {\n // Query the database\n val ourChilds: Future[Seq[CategoryTreeNode]] = getChilds(parent._id.get)\n ourChilds flatMap { childs =>\n Future.sequence(childs map collect) map { childSeq =>\n parent.copy(childs = Some(childSeq))\n }\n }\n }\n\n // Find the root node and start the recursion\n findOne[CategoryTreeNode](Json.obj(\"_id\" -> rootId)) flatMap (_ match {\n case None => throw new RuntimeException(\"Current node not found by id!\")\n case Some(node) => collect(node)\n })\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:39:19.607",
"Id": "43699",
"ParentId": "43692",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "43699",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T11:28:00.867",
"Id": "43692",
"Score": "1",
"Tags": [
"scala",
"tree",
"mongodb"
],
"Title": "Transform a MongoDb parent reference tree into a deep nested tree"
} | 43692 |
<p>In my latest project I am using fullscreen background images for each page. I decided to write some code to fetch the different thumbnail sizes and then use it as a background for the appropriate viewport size using media queries. I also made sure that in the case of big screens the smallest image loads first so that the visitor is mostly never greeted with a blank or loading background. I set the image as the featured image of the page and then call it using this code-</p>
<pre><code>$args = array(
'post_type' => 'attachment',
'numberposts' => 1,
'post_status' => null,
'post_parent' => $post->ID,
'post_mime_type' => 'image'
);
$attachments = get_posts( $args );
if ( $attachments ) :
foreach ( $attachments as $attachment ) :
$img_thelargeArr = wp_get_attachment_image_src( $attachment->ID, "full");
$img_medArr = wp_get_attachment_image_src( $attachment->ID, "med");
$img_mediumArr = wp_get_attachment_image_src( $attachment->ID, "medium");
$img_thelarge = $img_thelargeArr[0];
$img_med = $img_medArr[0];
$img_medium = $img_mediumArr[0];
endforeach;
endif;
</code></pre>
<p>And then in the page.php (or whichever template file with full background) itself I added the following style tag to display images providing fallback for bigger screen sizes so that the background loads progressively.</p>
<pre><code><style media="screen">
@media (min-width: 1800px) {
body { background: url(<?php echo $img_thelarge; ?>) no-repeat center center fixed;
background-size: cover; }
html.multiplebgs body { background: url(<?php echo $img_thelarge; ?>), url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }
}
@media (min-width: 1000px) and (max-width: 1799px) {
body { background: url(<?php echo $img_thelarge; ?>) no-repeat center center fixed;
background-size: cover; }
html.multiplebgs body { background: url(<?php echo $img_thelarge; ?>), url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }
}
@media (min-width: 400px) and (max-width: 999px) {
body { background: url(<?php echo $img_med; ?>) no-repeat center center fixed;
background-size: cover; }
html.multiplebgs body { background: url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }
}
@media (max-width: 399px) {
body { background: url(<?php echo $img_medium; ?>) no-repeat center center fixed;
background-size: cover; }
}
</style>
</code></pre>
<p>This works as expected but I am using this for a bunch of other page templates as well and was wondering if I can move this code to a single PHP file and reference it from each of these templates. I don't know OOP so need help to figure this out. There is only one variation in one of the templates I am using <code>$post->ID</code> instead of <code>$attachment->ID</code>.</p>
<p>How do I set this up as a function that can be referenced from an external PHP file in the theme folder itself? Is it possible to use JavaScript to add inline styles instead of a style tag on the pages? How do I go about this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:53:15.680",
"Id": "75630",
"Score": "0",
"body": "Your \"how do I do this\" questions will have to be answered on SO, Code Review is just for reviewing working code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:32:37.177",
"Id": "75749",
"Score": "0",
"body": "I posted it on SO too. But just got a couple of downvotes and no answers. I am quite new to SE so can't understand why this is happening...I am guessing that if you review this code you can help me make it better...is that alright?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:30:27.697",
"Id": "75763",
"Score": "0",
"body": "If you clearly define the problem and chop it down to just enough code to reproduce it, your question will be better received. Long questions tend to intimidate potential answerees (just don't be so brief that it is difficult to tell what you're asking for)."
}
] | [
{
"body": "<p>I'm not familiar with Wordpress, so it's just a minor note about duplication. You could extract out some duplication to a method:</p>\n\n<pre><code>function get_attachment_image($attachment, $type) {\n $img_array = wp_get_attachment_image_src($attachment->ID, $type);\n return $img_array[0];\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>foreach ( $attachments as $attachment ) :\n $img_thelarge = get_attachment_image($attachment, \"full\");\n $img_med = get_attachment_image($attachment, \"med\");\n $img_medium = get_attachment_image($attachment, \"medium\");\nendforeach;\n</code></pre>\n\n<p>Another note: If I'm right the code only uses the last attachment, therefore the foreach loop could be changed to direct access to the last element of <code>$attachments</code>.</p>\n\n<p>And a final one: what's the difference between <code>med</code> and <code>medium</code>? Isn't <code>med</code> an abbreviation for <code>medium</code>? It's confusing, better names might help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:38:46.207",
"Id": "75750",
"Score": "0",
"body": "Ah! I should name it better. Actually med and medium are just size names I assigned. The wp_get_attachment_image() takes a size argument which I have defined elsewhere. med has a width of 500px while medium is WordPress default and has a width of 300px."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:40:12.090",
"Id": "75751",
"Score": "1",
"body": "if I can shift this code to just one other PHP file then I don't there is a need for that function you are suggesting. But I agree it is much more elegant. Will try that. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:19:12.523",
"Id": "43696",
"ParentId": "43693",
"Score": "1"
}
},
{
"body": "<p>If the browser doesn't support the property/value combination in its entirety, it will ignore it. There's no need to do feature detection for this.</p>\n\n<pre><code>body { background: url(<?php echo $img_med; ?>) no-repeat center center fixed; }\nbody { background: url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);\nbackground-size: cover;\nbackground-repeat: no-repeat; }\n</code></pre>\n\n<p>If you care about older Android devices, you'll want to provide prefixed versions of background-size.</p>\n\n<p>Make use of the cascade! The first media query is no media query at all</p>\n\n<pre><code>body {\n background: url(<?php echo $img_medium; ?>) no-repeat center center fixed;\n -webkit-background-size: cover;\n background-size: cover;\n}\n\n@media (min-width: 400px) {\n body {\n background-image: url(<?php echo $img_med; ?>);\n background-image: url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);\n }\n}\n\n@media (min-width: 1000px) {\n body {\n background-image: url(<?php echo $img_thelarge; ?>);\n background-image: url(<?php echo $img_thelarge; ?>), url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);\n }\n}\n\n/* cut out the 1800px media query since it looked identical to the 1000px one */\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:43:16.793",
"Id": "75752",
"Score": "0",
"body": "Ah! that does make sense. I should get rid of the query in the first one. And haven't tested it on older android devices. Is there a site I can do that? Or is the emulator on Chrome good enough. Which devices should I target?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:18:58.190",
"Id": "75760",
"Score": "0",
"body": "I've not used the Chrome emulator, but I have used the Android emulator. It is *super super slow* (and you need to jump through a bunch of hoops to get more than 1 version available). I find that Safari 5 (there's one for Windows) is fairly close to Android 2.3's browser. I think 2.3 is the only old one worth caring about (it had 40% of the Android share last year, not sure on current numbers)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:48:53.217",
"Id": "43715",
"ParentId": "43693",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T11:37:06.543",
"Id": "43693",
"Score": "2",
"Tags": [
"php",
"css",
"wordpress"
],
"Title": "How do I refactor this responsive background images code?"
} | 43693 |
<p>I need to know whether I am doing the best way of binding click event through elements in jQuery. I need to avoid duplicate code in my function (since lot of duplicate code is repeated in all functions).</p>
<p>How can I clean this up and do it in a better way?</p>
<pre><code> $(".nna-icon-excel").click(function (e) {
var $this = $(this);
$this.parent().attr("href", "?excel=1")
var href = $this.parent().attr("href");
if (activeTab.toLowerCase() == "table") {
action = "expand";
}
else {
action = "expandheatmap";
}
$this.parent().attr("href", href + "&from=" + action + "&expand=" + Expand + "");
});
$(".nna-icon-pdf").click(function (e) {
var $this = $(this);
$this.parent().attr("href", "?savehtml=1&openpdf=1&orientation=@ViewBag.PdfOrientation")
var href = $this.parent().attr("href");
if (activeTab.toLowerCase() == "table") {
action = "expand";
}
else {
action = "expandheatmap";
}
$this.parent().attr("href", href + "&from=" + action + "&tabactive=" + action + "&expand=" + Expand + "");
});
$(".gridoptions-anchor").click(function (e) {
var $this = $(this);
$this.attr("href", "/home/xx/Index" + "/?columnchooser=1");
var href = $(this).attr("href");
var action = "";
if (activeTab.toLowerCase() == "table") {
action = "expand";
}
else {
action = "expandheatmap";
}
$this.attr("href", href + "&from=" +action + "&expand=" + Expand+ "");
});
</code></pre>
| [] | [
{
"body": "<p>You are right, the code could be tigher</p>\n\n<ul>\n<li><p>This</p>\n\n<pre><code>var action = \"\";\nif {\n action = \"expand\";\n}\nelse {\n action = \"expandheatmap\";\n}\n</code></pre>\n\n<p>could be reduced with a ternary operation to:</p>\n\n<pre><code>var action = (activeTab.toLowerCase() == 'table') ? 'expand' : 'expandheatmap`;\n</code></pre>\n\n<p>Since you repeat this in every handle, you should consider building a <code>function</code> for this, in case the logic ever changes.</p></li>\n<li><p>I am a bit confused by your code, you seem to build the href, get the href, modify that string and then set the href again ? Why ? The following should work in my mind ( I took the last click handler ) :</p>\n\n<pre><code>$(\".gridoptions-anchor\").click(function (e) {\n var href = \"/home/xx/Index\" + \"/?columnchooser=1\"\n var action = (activeTab.toLowerCase() == 'table') ? 'expand' : 'expandheatmap`;\n $(this).attr(\"href\", href + \"&from=\" +action + \"&expand=\" + Expand + \"\");\n});\n</code></pre></li>\n<li>This brings me to my next point; <code>activeTab</code>, <code>action</code>, and <code>Expand</code> are not defined with <code>var</code> in this code</li>\n<li><p>Finally you could consider a dedicated URL building function to have the string concatenation in one place:</p>\n\n<pre><code>function buildURL( href, action, expand, addTabActive )\n{\n var tabActiveParameter = addTabActive ? ( '&tabactive=' + action ) : '';\n return href + \"&from=\" + action + \"&expand=\" + expand + tabActiveParameter;\n}\n</code></pre></li>\n<li>Which brings me to my last point if <code>tabactive</code> shows the action, then <code>activetab</code> would be a better name.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:21:21.947",
"Id": "75619",
"Score": "0",
"body": "whether am doing correct way of binding event to element? or need to use latest \".on\" in jquery. i am bit confused about this binding technique. am i using standard way ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:21:22.273",
"Id": "75620",
"Score": "0",
"body": "Feel free to select this as the answer (green checkmark)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:21:48.730",
"Id": "75621",
"Score": "0",
"body": "`.click()` is fine, just dont use `.live()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:23:01.613",
"Id": "75622",
"Score": "0",
"body": "Accepted!!! cheers!!!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:03:15.300",
"Id": "43705",
"ParentId": "43695",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43705",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:08:35.527",
"Id": "43695",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"url"
],
"Title": "Binding click event through elements"
} | 43695 |
<p>The code below will split environment variables from a command line (always appear at the end of the command line). Environment variables are represented by '-E key=value'. I've achieved this like so, but I'm wondering if there's a more elegant way</p>
<pre><code>public class TestSplit {
public static void main(String... args) {
String command = "-ps 4 -pe 5 -E opInstallDir=/home/paul -E opWD=/home/paul/remake -E opFam=fam -E opAppli=appli";
int startPosition = command.indexOf("-E") + 2;
String envVars = command.substring(startPosition);
for(String pair: envVars.split("-E")) {
String[] kv = pair.split("=");
System.out.println(kv[0] + " " +kv[1]);
}
}
}
</code></pre>
<p>EDIT Just to clarify these aren't command line arguments for launching the program from the console, they are command line arguments for launching an external program. The details of which I haven't included.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:27:01.040",
"Id": "75584",
"Score": "0",
"body": "Have you taken a conscious decision not to use the JVM's -D option, or were you unaware of it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:29:59.500",
"Id": "75586",
"Score": "0",
"body": "Sorry I should clarify the application isn't launched with these, so these aren't command line arguments to launch the java application, rather command line arguments to launch an external program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T13:28:02.013",
"Id": "75596",
"Score": "0",
"body": "Paul, when launching an external command, you should use the multi-argument input mechanism available in Java. See the details in the last part of my answer which I have just edited in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T13:53:00.777",
"Id": "75600",
"Score": "0",
"body": "@rolfl thanks, but I have no influence in the launching of the external program, that is already dealt with, I'm merely sitting in the middle and picking up part of the command."
}
] | [
{
"body": "<ol>\n<li><p>Currently it prints something like this:</p>\n\n<blockquote>\n<pre><code> opInstallDir /home/paul \n opWD /home/paul/remake \n</code></pre>\n</blockquote>\n\n<p>Note that there is a space before the key. You might want to trim that.</p></li>\n<li><p>I guess the parameters comes from a user. Starting the program with invalid arguments, like this</p>\n\n<pre><code>final String command = \"-E testNoValue -E opInstallDir=/home/paul\";\n</code></pre>\n\n<p>only prints a stacktrace to the console. It could be more user friendly.</p>\n\n<pre><code>Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 1\n at TestSplit.main(TestSplit.java:15)\n</code></pre></li>\n<li><p>If you have so complicated parameters I suggest you <a href=\"http://commons.apache.org/proper/commons-cli/\" rel=\"nofollow\">Apache Commons CLI</a>.</p>\n\n<p>It supports</p>\n\n<blockquote>\n <p>Java like properties (ie. <code>java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo</code>)</p>\n</blockquote>\n\n<p>It's almost the same as you have in the example (except the space between <code>-E</code> and <code>key</code>). It's advantage that it provides better error-handling, it could generate help/usage messages.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:36:38.083",
"Id": "43698",
"ParentId": "43697",
"Score": "3"
}
},
{
"body": "<p>Like @palacsint I will recommend an external library. Apache commons-cli is a decent choice. Another choice (my preference) is <a href=\"http://www.urbanophile.com/arenn/coding/download.html\" rel=\"nofollow\">java gnu-getopt</a> ... I like it because I am familiar with the notations and standards from previous work. It can be a little complicated the first time around otherwise.</p>\n\n<p>On the other hand, I tend not to use an external library unless the code is already going to be relatively complicated....</p>\n\n<p>But, back to your code.</p>\n\n<p>Why do you have everything in a single String? Why is it not part of the <code>String...args</code> ?</p>\n\n<p>The first thing about command-line arguments is that they get complicated very fast. What if the argument was:</p>\n\n<blockquote>\n<pre><code>String command = \"-ps 4 -pe 5 -E opInstallDir=/opt/OSS-EVAL/thiscode -E opWD=/home/paul/remake -E opFam=fam -E opAppli=appli -Edocs='My Documents' -Eparse=key=value\";\n</code></pre>\n</blockquote>\n\n<p>I have thrown in a few things there.</p>\n\n<p>First up, on our one machine at work, we really do have the directory /opt/OSS-EVAL/ which we use to install/evaluate OSS software/libraries.</p>\n\n<p>The above will break your parsing because it has the <code>-E</code> embedded in the name.</p>\n\n<p>Next up, is 'POSIX-style' commandline arguments can have quoted values, and also values with an <code>=</code> in the value.</p>\n\n<p>So, things I would recommend to you:</p>\n\n<p>Locate the source of your command-line values. It will likely be available as an array, not a single string. Keep the data as an array!</p>\n\n<p>Second, with the array, it is easier to look for stand-alone values that are <code>-E</code>, or, if the input is <code>-Ekey=value</code> then you look for values that <em>start</em> with -E.</p>\n\n<p>Finally, when you split the key/value on the <code>=</code>, limit the split to 2.</p>\n\n<pre><code>String[] kv = pair.split(\"=\", 2);\n</code></pre>\n\n<p>Which will preserve any of the <code>=</code> tokens inside the value part.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>You have suggested in your edit that this is for sending data to an external command.</p>\n\n<p>If you are using Java to initialize the external command, then please, please, please use the version of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String%5B%5D%29\" rel=\"nofollow\">exec() that takes a command array</a>, or use the ProcessBuilder which allows you to send <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#ProcessBuilder%28java.lang.String...%29\" rel=\"nofollow\">all the command-line parameters as separate values in an array</a>!!!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:53:41.783",
"Id": "43701",
"ParentId": "43697",
"Score": "4"
}
},
{
"body": "<p>@rolfl recommends keeping the arguments as an array, and I agree. I'd like to explain <em>why</em> that advice is important.</p>\n\n<p>When the array is stringified, it is transformed into a \"degraded\" format. What if, one of the environment variables should contain a literal space? Then you need an escaping/quoting mechanism. Then you need to be able to quote the quotes, too, in case you want to express a literal quote character or backslash. Very soon, you would be implementing a complex parser, and it will be still be more error-prone than passing an array.</p>\n\n<p>Keep your arguments as an array, and your whole problem goes away!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:25:04.843",
"Id": "43739",
"ParentId": "43697",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "43701",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T12:21:45.033",
"Id": "43697",
"Score": "6",
"Tags": [
"java",
"child-process"
],
"Title": "Splitting a command line into key/value pairs"
} | 43697 |
<p>I am trying to make a thread test in which 4 threads are all trying to set a <code>bool</code>. Only one should be allowed to set it. After the first thread has set the <code>bool</code> (<code>m_isRunning</code>) to <code>true</code>, no other threads should set it to <code>true</code> because of the check <code>isRunning()</code>.</p>
<p>This implementation works, but I wonder if this is the best/most efficient approach to this common situation. </p>
<pre><code>#include<iostream>
#include<thread>
#include<mutex>
std::mutex mut;
bool m_running = false;
bool isRunning()
{
return m_running;
}
void setRunning(bool running)
{
m_running = running;
}
void func1(bool isSet)
{
mut.lock();
if(!isRunning())
{
setRunning(true);
}
mut.unlock();
}
int main()
{
std::thread t1(func1,true);
std::thread t2(func1,true);
std::thread t3(func1,true);
std::thread t4(func1,true);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
</code></pre>
<p><strong>Edit:</strong> Changed <code>!isRunning</code> to <code>!isRunning()</code> (typo)</p>
| [] | [
{
"body": "<p>In this case, you really just need an atomic variable, and you can do a <code>compare_exchange_strong</code> to set the value once:</p>\n\n<pre><code>#include <thread>\n#include <iostream>\n\nstd::atomic_bool m_running;\nbool wrote[4];\n\nvoid func1(int num) {\n bool f{ false };\n if (m_running.compare_exchange_strong(f, true))\n wrote[num] = true;\n}\n\nint main(){\n std::vector<std::thread> t;\n\n for (int i = 0; i < 4; i++)\n t.emplace_back(func1, i);\n\n for (auto &t1 : t)\n t1.join();\n\n for (bool b : wrote)\n std::cout << std::boolalpha << b << \"\\n\";\n}\n</code></pre>\n\n<p>Given that thread 1 starts running first, and it's not doing very much, chances are that the first thread will do the write to the variable virtually every time. In case you're not familiar with it, <code>atomic_bool</code> is (obviously enough) an atomic Boolean type, and <code>compare_exchange_strong</code> does an atomic comparison and exchange. Specifically, it compares the current value to the first parameter, then if (and only if) they're equal, sets the value to the second parameter. The first parameter has to be passed by reference, because it also writes the new value to that variable. Finally, it returns <code>true</code> if and only if it actually wrote to the variable. In this case I've used that to record which thread actually wrote to the variable, so the final printout should show <code>true</code> once, and <code>false</code> three times.</p>\n\n<p>Looking at the code as you've written it:</p>\n\n<pre><code>void func1(bool isSet)\n{\n mut.lock();\n if (!isRunning())\n {\n setRunning(true);\n }\n mut.unlock();\n}\n</code></pre>\n\n<p>You almost certainly want to use an <code>std::lock_guard</code> to automate unlocking the mutex. Right now, the code also ignores the <code>isSet</code> parameter, and always sets the value to <code>true</code>. I'd assume you really want to compare to <code>isSet</code>, and set it to that value if it's not already equal to it. Combining these, the code would come out something like:</p>\n\n<pre><code>void func1(bool isSet) { \n std::lock_guard g(mut);\n\n if (isRunning() != isSet)\n setRunning(isSet);\n}\n</code></pre>\n\n<p>That's somewhat simpler, but I still think the <code>atomic_bool</code> with <code>compare_exchange_strong</code> is neater. The atomic variable can degenerate to pretty much what you've done with a mutex in the worst case, <em>but</em> in quite a few cases, it'll be substantially more efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:54:40.427",
"Id": "43717",
"ParentId": "43708",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43717",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:26:11.840",
"Id": "43708",
"Score": "6",
"Tags": [
"c++",
"optimization",
"beginner",
"multithreading",
"c++11"
],
"Title": "Thread test mutex implementation"
} | 43708 |
<p>I have recently written the program for the <a href="https://www.hackerrank.com/contests/sep13/challenges/sherlock-and-the-beast">Sherlock and The Beast' HackerRank challenge</a>. That's working fine, but the problem is that it takes too much time if a big number is given as a input. I would like you to help me out in optimizing my code so that it could run under 16 seconds, which is needed.</p>
<pre><code>from collections import Counter
def isDecent(n):
digits = list(map(int, str(n)))
if not set(str(n)).issubset('35'): return False
threes = Counter(digits)[3]
fives = Counter(digits)[5]
if threes % 5 == 0 and fives % 3 == 0: return True
else: return False
inps = []
decents = []
t = int(input())
for i in range(t): inps.append(int(input()))
for inp in inps:
if inp == 1:
decents.append(-1)
continue
n=2
while True:
if(isDecent(n) and len(str(n)) == inp): break
n+=1
if n != 2: decents.append(n)
else: decents.append(-1)
for decent in decents: print(decent)
</code></pre>
<p>Is there any thing that could be used to optimize it?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:04:00.790",
"Id": "75612",
"Score": "0",
"body": "Can't you just people answer it rather than editing? :P nevamind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:15:19.093",
"Id": "75617",
"Score": "0",
"body": "How long did it take you to write the above code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:51:54.090",
"Id": "75629",
"Score": "0",
"body": "10 min @rolfl :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:34:35.053",
"Id": "75636",
"Score": "0",
"body": "FYI, the [Java solution below ranked with score 30](https://www.hackerrank.com/contests/sep13/submissions/code/1362357)... apparently the maximum."
}
] | [
{
"body": "<p>Your approach seems all wrong, throw all that code away <- that's the code review.</p>\n\n<p>You have to think about combinations, this is not like finding prime numbers.</p>\n\n<p>n:1 -> Because you can only build numbers with <code>33333</code> and <code>555</code> you cannot find anything</p>\n\n<p>n:2 -> same as <code>1</code></p>\n\n<p>n:3 -> Can only be '555', again because your building blocks for the number are <code>555</code> and <code>33333</code></p>\n\n<p>n:4 -> Impossible, you cant use <code>33333</code> ( too long ) and if you used <code>555</code> then you have 1 digit left which is useless</p>\n\n<p>n:5 -> Can only be <code>33333</code>, that's the only thing that fits</p>\n\n<p>etc. etc.</p>\n\n<p>You have to fit in blocks of 5 and 3 digit strings to get to <code>n</code>'.</p>\n\n<p>The last tip as per the question, for n=8 you could have</p>\n\n<p><code>55533333</code> or <code>33333555</code>, obviously you need to try to put <code>555</code> in front because <code>5</code> > <code>3</code>.</p>\n\n<p>Hope this helps.</p>\n\n<p>Edit: The code of @rolfl should do the trick otherwise you can perhaps find inspiration in the JS version ( <a href=\"http://jsbin.com/dalor/2/edit\" rel=\"nofollow\">http://jsbin.com/dalor/2/edit</a> ):</p>\n\n<pre><code>function repeatString( s , n )\n{\n return n ? new Array( n + 1 ).join( s ) : \"\";\n}\n\nfunction getDecentNumber( n )\n{\n var threes = 0,\n fives = 0,\n remainingDigits = +n;\n while (remainingDigits > 2) {\n if (remainingDigits % 3 === 0) {\n fives = remainingDigits;\n break;\n }\n remainingDigits -= 5;\n }\n threes = n - fives;\n if (remainingDigits < 0 || threes % 5)\n return \"-1\";\n\n return repeatString( '5', fives ) + repeatString( '3', threes );\n}\n\nconsole.log( getDecentNumber( 1 ) );\nconsole.log( getDecentNumber( 3 ) );\nconsole.log( getDecentNumber( 5 ) );\nconsole.log( getDecentNumber( 8 ) );\nconsole.log( getDecentNumber( 11 ) );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:51:17.377",
"Id": "75628",
"Score": "0",
"body": "I didn't understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:11:48.737",
"Id": "75645",
"Score": "0",
"body": "This fails in some cases if you pass in a string to `getDecentNumber()`. Try it with `'3'` rather than `3`. Obviously the fix is to use `n = parseInt(n)` before the first `var` in `getDecentNumber`. The reason I mention this is using the code as-is in the hackerrank javascript boilerplate may lead to the issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:24:10.383",
"Id": "75647",
"Score": "0",
"body": "Agreed, solved, but more subtly ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:15:45.003",
"Id": "43712",
"ParentId": "43709",
"Score": "5"
}
},
{
"body": "<p>Your algorithm is way off.... ;-)</p>\n\n<p>Let's consider the solution to a decent number.</p>\n\n<p>For any decent number, the more 5's we put at the front, the better.</p>\n\n<p>So, let's break it down to some maths....:</p>\n\n<ul>\n<li>d => number of digits in the decent number</li>\n<li>f => number of fives in the decent number</li>\n<li>t => number of threes in the decent number</li>\n</ul>\n\n<p>also</p>\n\n<ul>\n<li>d = f + t</li>\n<li>f % 3 == 0</li>\n<li>t % 5 == 0</li>\n</ul>\n\n<p>We have:</p>\n\n<pre><code>d = f + t\n</code></pre>\n\n<p>Algorithm:</p>\n\n<pre><code>// tmp number of five values is the number of digits\nftmp = d\n// decrease the number of fives (by the number of threes in a batch)\n// until both the rules f % 3 == 0 and t % 5 == 0 are satisfied\nwhile ftmp % 3 != 0 : ftmp -= 5\n\ncheck the ftmp is a valid value\nif ftmp % 3 != 0 : return -1;\n\nf = ftmp;\nt = d - f\n\nreturn \"5\" x f + \"3\" x t\n</code></pre>\n\n<p>Writing it in Java, I have the following:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String sherlock(final int target) {\n int threes = 0;\n int fives = 0;\n int digits = target;\n while (digits > 0) {\n if (digits % 3 == 0) {\n fives = digits;\n break;\n }\n digits -= 5;\n }\n threes = target - digits;\n if (digits < 0 || threes % 5 != 0) {\n return \"-1\";\n }\n StringBuilder sb = new StringBuilder(target);\n while (fives-- > 0) {\n sb.append(\"5\");\n }\n while (threes-- > 0) {\n sb.append(\"3\");\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>For me, on my laptop, this solves the 100000 digit problem in less than 1 millisecond. First I 'warm up' Java with the first 10,000 solutions....</p>\n\n<p>Then I run some big ones....</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n int cnt = 0;\n long ms = System.currentTimeMillis();\n for (int i = 0; i < 10000; i++) {\n cnt += sherlock(i).length();\n }\n ms = System.currentTimeMillis() - ms;\n System.out.println(\"Warmup created \" + cnt + \" characters in \" + ms + \" Milliseconds\");\n for (int i : new int[] { 1, 3, 5, 11, 19, 100000 }) {\n long nanos = System.nanoTime();\n String val = sherlock(i);\n nanos = System.nanoTime() - nanos;\n System.out.printf(\" request digits %d : actual digits %d Value %s in (%.3fms)%n\",\n i, val.length(), val.length() > 20 ? \"too long\" : val, nanos / 1000000.0);\n }\n}\n</code></pre>\n\n<p>This produces the output:</p>\n\n<blockquote>\n<pre><code>Warmup created 49995011 characters in 703 Milliseconds\nrequest digits 1 : actual digits 5 Value 33333 in (0.004ms)\nrequest digits 3 : actual digits 3 Value 555 in (0.012ms)\nrequest digits 5 : actual digits 5 Value 33333 in (0.003ms)\nrequest digits 11 : actual digits 11 Value 55555533333 in (0.002ms)\nrequest digits 19 : actual digits 19 Value 5555555553333333333 in (0.002ms)\nrequest digits 100000 : actual digits 100000 Value too long in (0.622ms)\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-20T00:44:10.300",
"Id": "235534",
"Score": "0",
"body": "There is an easier solution that does not involve loops.\nBut it seems you may already know this... http://codereview.stackexchange.com/questions/67837/generating-decent-numbers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-27T14:58:42.973",
"Id": "273048",
"Score": "0",
"body": "@rolfl Thank you for the great explanation. After I gave up trying this problem, I started looking for solutions and found several, but nothing that helped me understand how exactly to go about it. This is perfect!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:03:02.790",
"Id": "43718",
"ParentId": "43709",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "43718",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:52:56.737",
"Id": "43709",
"Score": "7",
"Tags": [
"python",
"optimization",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Sherlock and The Beast"
} | 43709 |
<p>Challenges offer good insights into combinations, permutations, prime number generation, look-up tables, matching, regular expressions, etc. A well reviewed programming-challenge can be very educational.</p>
<h2>Challenge Providers</h2>
<p>Programming challenges can be found on sites such as:</p>
<ul>
<li><a href="http://hackerrank.com" rel="nofollow noreferrer">hackerrank.com</a></li>
<li><a href="http://coderbytes.com" rel="nofollow noreferrer">coderbytes.com</a></li>
<li><a href="http://projecteuler.net" rel="nofollow noreferrer">projecteuler.net</a></li>
<li><a href="http://osix.net" rel="nofollow noreferrer">osix.net</a></li>
<li><a href="http://reddit.com/r/dailyprogrammer" rel="nofollow noreferrer">reddit.com/r/dailyprogrammer</a></li>
<li><a href="http://enigmagroup.org%E2%80%8E" rel="nofollow noreferrer">enigmagroup.org</a></li>
<li><a href="http://codility.com" rel="nofollow noreferrer">codility.com</a></li>
<li><a href="http://codechef.com" rel="nofollow noreferrer">codechef.com</a></li>
<li><a href="http://spoj.com" rel="nofollow noreferrer">spoj.com</a></li>
<li><a href="http://topcoder.com" rel="nofollow noreferrer">topcoder.com</a></li>
<li><a href="http://www.talentbuddy.co/" rel="nofollow noreferrer">talentbuddy.co</a></li>
<li><a href="http://adventofcode.com/" rel="nofollow noreferrer">adventofcode.com</a></li>
<li><a href="https://leetcode.com/" rel="nofollow noreferrer">leetcode.com</a></li>
<li><a href="https://www.theodinproject.com/" rel="nofollow noreferrer">theodinproject.com</a></li>
</ul>
<p>and many more.</p>
<h2>Tag Guidelines</h2>
<p>Note that this tag is not for questions about golfed/golfing code, as that is off-topic here.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-07T15:29:15.540",
"Id": "43713",
"Score": "0",
"Tags": null,
"Title": null
} | 43713 |
Programming challenges are off-site challenges meant to offer programmers educational experiences while testing their abilities. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:29:15.540",
"Id": "43714",
"Score": "0",
"Tags": null,
"Title": null
} | 43714 |
<p>HTML form field names must be equal to SQL table field names.</p>
<p>Changing only table name and allowed fields can be used in many other update pages.</p>
<p>How can I improve this?</p>
<pre><code>$allowed = array("name","surname","email","rank");
$items = '';
foreach($_POST as $key => $value) {
if (in_array($key , $allowed)) {
$items.="`".str_replace("`","``",$key)."`". "='$value', ";
}
}
$items = substr($items, 0, -2);
$table = "users" ;
$userId = $_POST['userId'];
$sql = "UPDATE $table SET $items WHERE ID = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param('i', $userId);
$stmt->execute();
}
</code></pre>
<p><strong>CODE REVIEW with PDO prepare statement</strong></p>
<p>In accord with the answer, my first code was open to SQL injection and i change it
with PDO prepared statement like a suggestion.</p>
<pre><code>$dbh = new PDO('mysql:host=localhost;port=0000;dbname=xxx','yyy','zzz',
array(PDO::ATTR_PERSISTENT => false,PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false));
$allowed = array("name","surname","email","rank");
$params = array();
$items = null;
foreach($_POST as $key => $value) {
if (in_array($key , $allowed)) {
$items .= "$key=:$key ,"; // create parametrized string
$params[$key] = $value; // populate the array with allowed $_POST values
}
}
$items = substr($items, 0, -2); // escaping the last coma
$table = "users" ;
$sql = "UPDATE $table SET $items WHERE ID = :userId ";
$params['userId'] = $_POST['userId']; // add the WHERE param value to array
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
</code></pre>
<p>In this way, the variable $items doing all job :) </p>
| [] | [
{
"body": "<p>As it stands right now, you are wide open to sql injection injection attacks because you are copying posted data directly into your sql update statement. All kinds of nasty things could be injected.</p>\n\n<p>I started to rewrite it but it became a pain since mysqli requires you to bind each parameter individually. Way too much work. I'd suggest shifting to PDO which supports binding by arrays as well as named parameters. Not to mention exceptions.</p>\n\n<p>Something like:</p>\n\n<pre><code>// Some test data\n$_POST = array('name' => 'New Name', 'email' => 'New Email', 'something' => 'nothing', 'userId' => 1);\n\n$allowed = array(\"name\",\"surname\",\"email\",\"rank\"); \n\n$params = array();\n$items = null;\n\nforeach($_POST as $key => $value) {\n if (in_array($key , $allowed)) {\n if ($items) $items .= ', ';\n $items .= \"$key=:$key\";\n $params[$key] = $value;\n }\n}\nif (!$items) die(\"Nothing to update\");\necho $items . \"\\n\"; // name=:name, email=:email\n\n$sql = sprintf('UPDATE %s SET %s WHERE ID = :userId','users',$items);\n\necho $sql . \"\\n\"; // UPDATE users SET name=:name, email=:email WHERE ID = :userId\n\n$params['userId'] = $_POST['userId'];\n\n$stmt = $pdo->prepare($sql);\n$stmt->execute($params); // This is reason enough to shift to PDO\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:19:16.480",
"Id": "75674",
"Score": "0",
"body": "With `bind_param` you can bind as much params as you want. (http://php.net/manual/de/mysqli-stmt.bind-param.php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:29:08.527",
"Id": "75676",
"Score": "0",
"body": "In theory but go ahead and show your code for binding a variable number of parameters. Unless something has changed, you can't just feed bind an array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:58:13.663",
"Id": "75766",
"Score": "0",
"body": "@Cerad i understand and i change the code with PDO. Only 1 question : why you use sprintf in your code instead of : \"UPDATE $table set $items WHERE ID = :userId\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:01:10.567",
"Id": "75767",
"Score": "0",
"body": "Personal preference. Long time C programmer. I find sprintf's easier to read. Either approach is fine."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:08:39.643",
"Id": "43736",
"ParentId": "43716",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:51:20.750",
"Id": "43716",
"Score": "3",
"Tags": [
"php",
"mysqli"
],
"Title": "UPDATE SQL with prepared stmt using only 1 variable"
} | 43716 |
<p>I'd like some additional assistance on refactoring. This is my latest update for this iteration.</p>
<pre><code>#region WMI Classes
/// <summary>
/// The Win32_OperatingSystem WMI class represents a Windows-based OS installed on a computer. Any OS that can be
/// installed on a computer that can run a Windows-based OS is a descendent or member of this class.
/// Win32_OperatingSystem is a singleton class. To get the single instance, use "@" for the key.
/// </summary>
public class Win32OperatingSystem
{
public Win32OperatingSystem() { }
PropertyGetter pg = new PropertyGetter("Win32_OperatingSystem");
/// <summary>
/// Number, in megabytes, of physical memory currently unused and available.
/// </summary>
public ulong FreePhysicalMemory()
{
return pg.GetUnsignedInt64("FreePhysicalMemory");
}
/// <summary>
/// Number, in megabytes, of virtual memory currently unused and available.
/// </summary>
public ulong FreeVirtualMemory()
{
return pg.GetUnsignedInt64("FreeVirtualMemory");
}
/// <summary>
/// Number, in megabytes, of virtual memory.
/// </summary>
public ulong TotalVirtualMemorySize()
{
return pg.GetUnsignedInt64("TotalVirtualMemorySize");
}
}
/// <summary>
/// The Win32_ComputerSystem WMI class represents a computer system running Windows.
/// </summary>
public class Win32ComputerSystem
{
public Win32ComputerSystem() { }
PropertyGetter pg = new PropertyGetter("Win32_ComputerSystem");
/// <summary>
/// Key of a CIM_System instance in an enterprise environment.
/// This property is inherited from CIM_ManagedSystemElement.
/// </summary>
public string Name()
{
return pg.GetString("Name");
}
/// <summary>
/// Name of a computer manufacturer.
/// </summary>
public string Manufacturer()
{
return pg.GetString("Manufacturer");
}
/// <summary>
/// Product name that a manufacturer gives to a computer. This property must have a value.
/// </summary>
public string Model()
{
return pg.GetString("Model");
}
}
/// <summary>
/// The Win32_Processor WMI class represents a device that can interpret a sequence of instructions on a computer
/// running on a Windows operating system. On a multiprocessor computer, one instance of the Win32_Processor class
/// exists for each processor.
/// </summary>
public class Win32Processor
{
public Win32Processor() { }
PropertyGetter pg = new PropertyGetter("Win32_Processor");
/// <summary>
/// Processor architecture used by the platform.
/// </summary>
public ushort Architecture()
{
return pg.GetUnignedInt16("Architecture");
}
/// <summary>
/// Description of the object. This property is inherited from CIM_ManagedSystemElement.
/// </summary>
public string Description()
{
return pg.GetString("Description");
}
}
/// <summary>
/// The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS)
/// that are installed on a computer.
/// </summary>
public class Win32BIOS
{
PropertyGetter pg = new PropertyGetter("Win32_BIOS");
public Win32BIOS() { }
/// <summary>
/// Version of the BIOS. This string is created by the BIOS manufacturer.
/// This property is inherited from CIM_SoftwareElement.
/// </summary>
public string Version()
{
return pg.GetString("Version");
}
/// <summary>
/// Assigned serial number of the software element. This property is inherited from CIM_SoftwareElement.
/// </summary>
public string SerialNumber()
{
return pg.GetString("SerialNumber");
}
/// <summary>
/// Internal identifier for this compilation of this software element.
/// This property is inherited from CIM_SoftwareElement.
/// </summary>
public string BuildNumber()
{
return pg.GetString("BuildNumber");
}
/// <summary>
/// Name of the current BIOS language.
/// </summary>
public string CurrentLanguage()
{
return pg.GetString("CurrentLanguage");
}
/// <summary>
/// Manufacturer of this software element.
/// </summary>
public string Manufacturer()
{
return pg.GetString("Manufacturer");
}
/// <summary>
/// BIOS version as reported by SMBIOS.
/// </summary>
public string SMBIOSBIOSVersion()
{
return pg.GetString("SMBIOSBIOSVersion");
}
/// <summary>
/// Current status of the object. Various operational and nonoperational statuses can be defined.
/// Operational statuses include: "OK", "Degraded", and "Pred Fail" (an element, such as a SMART-enabled
/// hard disk drive, may be functioning properly but predicting a failure in the near future). Nonoperational
/// statuses include: "Error", "Starting", "Stopping", and "Service". The latter, "Service", could apply during
/// mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such
/// work is online, yet the managed element is neither "OK" nor in one of the other states.
/// This property is inherited from CIM_ManagedSystemElement.
/// </summary>
/// <returns></returns>
public string Status()
{
return pg.GetString("Status");
}
/// <summary>
/// Number of languages available for installation on this system. Language may determine properties such as
/// the need for Unicode and bidirectional text.
/// </summary>
public ushort InstallableLanguages()
{
return pg.GetUnignedInt16("InstallableLanguages");
}
/// <summary>
/// Major SMBIOS version number. This property is NULL if SMBIOS is not found.
/// </summary>
/// <returns></returns>
public ushort SMBIOSMajorVersion()
{
return pg.GetUnignedInt16("SMBIOSMajorVersion");
}
/// <summary>
/// Minor SMBIOS version number. This property is NULL if SMBIOS is not found.
/// </summary>
public ushort SMBIOSMinorVersion()
{
return pg.GetUnignedInt16("SMBIOSMinorVersion");
}
/// <summary>
/// If true, the SMBIOS is available on this computer system.
/// </summary>
public bool SMBIOSPresent()
{
return pg.GetBool("SMBIOSPresent");
}
/// <summary>
/// Release date of the Windows BIOS converted from UTC format to DateTime.
/// </summary>
public DateTime ReleaseDate()
{
return pg.GetDateTimeFromDmtf("ReleaseDate");
}
}
#endregion
#region PropertyGetter
/// <summary>
/// Handles the actual WMI queries for the other classes in this file
/// </summary>
public class PropertyGetter
{
public PropertyGetter() { }
private string _win32Class;
/// <summary>
///
/// </summary>
/// <param name="win32Class"></param>
public PropertyGetter(string win32Class)
{
this._win32Class = win32Class;
}
/// <summary>
/// Converts kilobyte values to megabytes for readability.
/// </summary>
/// <param name="kiloBytes">Value to be converted</param>
/// <returns>Kilobytes converted to megabytes as ulong</returns>
private static ulong KiloBytesToMegaBytes(ulong kiloBytes)
{
return kiloBytes / (ulong)1024;
}
/// <summary>
/// Performs WMI queries on objects which return Int64 bit values
/// </summary>
/// <param name="propertyName">Property value to be returned</param>
/// <param name="win32Class">WMI class which contains desired property</param>
/// <returns>The property value of the Int64 bit object queried for</returns>
public ulong GetUnsignedInt64(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + _win32Class))
{
using (var collection = moSearcher.Get())
{
using (var enu = collection.GetEnumerator())
{
if (!enu.MoveNext() || enu.Current[propertyName] == null)
{
return (ulong)0;
}
return KiloBytesToMegaBytes((ulong)enu.Current[propertyName]);
}
}
}
}
public string GetString(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + _win32Class))
{
using (var collection = moSearcher.Get())
{
using (var enu = collection.GetEnumerator())
{
if (!enu.MoveNext() || enu.Current[propertyName] == null)
{
return String.Empty;
}
return enu.Current[propertyName].ToString();
}
}
}
}
public ushort GetUnignedInt16(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + _win32Class))
{
using (var collection = moSearcher.Get())
{
using (var enu = collection.GetEnumerator())
{
if (!enu.MoveNext() || enu.Current[propertyName] == null)
{
return (ushort)0;
}
return (ushort)enu.Current[propertyName];
}
}
}
}
public bool GetBool(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + _win32Class))
{
using (var collection = moSearcher.Get())
{
using (var enu = collection.GetEnumerator())
{
if (!enu.MoveNext() || enu.Current[propertyName] == null)
{
return false;
}
return true;
}
}
}
}
public DateTime GetDateTimeFromDmtf(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + _win32Class))
{
using (var collection = moSearcher.Get())
{
using (var enu = collection.GetEnumerator())
{
if (!enu.MoveNext() || enu.Current[propertyName] == null)
{
return DateTime.Today;
}
return ManagementDateTimeConverter.ToDateTime(enu.Current[propertyName].ToString());
}
}
}
}
}
#endregion
</code></pre>
<h3>Questions in this series</h3>
<p><a href="https://codereview.stackexchange.com/questions/43432/class-seperation-vs-polymorphism">Class Seperation vs Polymorphism.</a></p>
<p><a href="https://codereview.stackexchange.com/questions/43598/should-i-refactor-for-dry">First iteration of DRY refactoring.</a></p>
<p>You're currently viewing the third question in the series</p>
<p><a href="https://codereview.stackexchange.com/questions/43777/adding-generics-and-or-enums">Genericizing PropertyValues</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:09:41.760",
"Id": "75632",
"Score": "1",
"body": "I feel like this needs generics and enums rather badly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:56:29.053",
"Id": "75690",
"Score": "0",
"body": "Are you willing to give some examples? I'm not great with generics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:57:59.520",
"Id": "75691",
"Score": "0",
"body": "No, dreza did a better job of it than I would have."
}
] | [
{
"body": "<ol>\n<li><p>What is the point of empty <code>public</code> constructors? If there's no logic in them, remove them.</p></li>\n<li><p>The <code>PropertyGetter</code> class member in multiple classes is never assigned to after it is initialized. Mark them <code>readonly</code>. Same goes for <code>_win32Class</code> in the <code>PropertyGetter</code> class itself.</p></li>\n<li><p>There are a number of methods which follow a particular pattern in the <code>PropertyGetter</code> class. I am a fan of brevity and fewer lines of code, so I made it look like this (for example):</p>\n\n<pre><code>public DateTime GetDateTimeFromDmtf(string propertyName)\n{\n using (var searcher = new ManagementObjectSearcher(\"SELECT \" + propertyName + \" FROM \" + this._win32Class))\n using (var collection = searcher.Get())\n using (var enu = collection.GetEnumerator())\n {\n return !enu.MoveNext() || (enu.Current[propertyName] == null)\n ? DateTime.Today\n : ManagementDateTimeConverter.ToDateTime(enu.Current[propertyName].ToString());\n }\n}\n</code></pre></li>\n<li><p>Since all these things have the word \"property\" in them, possibly make them properties instead of methods? Example:</p>\n\n<pre><code>/// <summary>\n/// Manufacturer of this software element.\n/// </summary>\npublic string Manufacturer()\n{\n return this.pg.GetString(\"Manufacturer\");\n}\n</code></pre></li>\n</ol>\n\n<p>becomes:</p>\n\n<pre><code> /// <summary>\n /// Manufacturer of this software element.\n /// </summary>\n public string Manufacturer\n {\n get\n {\n return this.pg.GetString(\"Manufacturer\");\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:54:45.683",
"Id": "75641",
"Score": "0",
"body": "Was going to upvote, but I don't agree with making WMI calls in a property getter... Ah, WTH, +1 for the rest of it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:59:44.487",
"Id": "75643",
"Score": "0",
"body": "@Mat'sMug I added that one on afterward. Really on the fence with regards to it. It *feels* property-ish, but yes, I agree WMI adds a layer of pitfalls that are contraindicative of the use of properties."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:12:23.147",
"Id": "75646",
"Score": "0",
"body": "As for point 1, there can be reasons to enforce the existence of a default constructor, such as avoiding incompatibility when a non-default constructor is added later on - worth considering at least. As for the repeated pattern you noticed in 3, I'd be inclined to see if it could be converted to `Get<T>([CallerMemberName] string property = null)` or something of the sort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:13:25.767",
"Id": "75661",
"Score": "0",
"body": "@Magus also, some serializers need a default constructor to work properly. But I would add a comment explaining that this was the reason for the empty constructor"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:32:05.763",
"Id": "43722",
"ParentId": "43719",
"Score": "5"
}
},
{
"body": "<p>The first thing that I thought about was how could we get rid of the duplication in the <strong>PropertyGetter</strong> class public methods. </p>\n\n<p>So I first went about creating a common method to do just this</p>\n\n<pre><code>private T TypeConvert<T>(\n string propertyName, \n Func<object, T> convertIfNotNull,\n T defaultIfNullOrEmpty) where T: class\n{\n using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM \" + _win32Class))\n {\n using (var collection = moSearcher.Get(propertyName))\n {\n using (var enu = collection.GetEnumerator())\n {\n return !enu.MoveNext() || enu.Current[propertyName] == null\n ? defaultIfNullOrEmpty\n : convertIfNotNull(enu.Current[propertyName]);\n }\n }\n }\n} \n</code></pre>\n\n<p>This led me to have public methods such as</p>\n\n<pre><code>public string GetString(string propertyName)\n{\n return TypeConvert<string>(\n propertyName,\n convertIfNotNull: value => value.ToString(),\n defaultIfNullOrEmpty: String.Empty); \n}\n\npublic ulong GetUnsignedInt64(string propertyName)\n{\n return TypeConvert<ulong>(\n propertyName,\n convertIfNotNull: value => KiloBytesToMegaBytes((ulong)value),\n defaultIfNullOrEmpty: (ulong)0); \n}\n\npublic DateTime GetDateTimeFromDmtf(string propertyName)\n{\n return TypeConvert<DateTime>(\n propertyName,\n convertIfNotNull: value => ManagementDateTimeConverter.ToDateTime(value.ToString()),\n defaultIfNullOrEmpty: DateTime.Today); \n}\n\npublic bool GetBool(string propertyName)\n{\n return TypeConvert<bool>(\n propertyName,\n convertIfNotNull: value => true,\n defaultIfNullOrEmpty: false); \n}\n\npublic ushort GetUnignedInt16(string propertyName)\n{\n return TypeConvert<ushort>(\n propertyName,\n convertIfNotNull: value => (ushort)value,\n defaultIfNullOrEmpty: 0); \n}\n</code></pre>\n\n<p>Then I thought. It would be nice to be able to unit test this class as it seems a good candidate for just this. And considering it might be a well used class a unit test might be beneficial.</p>\n\n<p>However looking at this I came across a couple of pitfalls.</p>\n\n<ol>\n<li>Use of ManagementObjectSearcher. </li>\n<li>Use of ManagementDateTimeConverter</li>\n</ol>\n\n<p>Ideally we would remove these however I'm not sure exactly the best way to approach this might be. I'm thinking the <strong>ManagementObjectSearcher</strong> would be the likely first candidate.</p>\n\n<p>Perhaps injecting via a constructor. Something like:</p>\n\n<pre><code>public interface IObjectSearcher : IDisposable\n{\n IObjectCollection Get(string propertyName); \n\n}\n\npublic interface IObjectSearchFactory\n{\n IObjectSearcher Create();\n}\n</code></pre>\n\n<p>So the <code>TypeConvert</code> method now becomes:</p>\n\n<pre><code>using (IObjectSearcher moSearcher = _searchFactory.Create())\n{\n // ....\n}\n</code></pre>\n\n<p>However I'm interested to see other thoughts on potentially removing these dependencies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T06:54:31.263",
"Id": "75722",
"Score": "0",
"body": "I'm having trouble following your 'private T TypeConvert' method. Could you explain it a bit more or point me in the direction of a link I could read? I'm also considering posting a fourth question about Generics and/or Enums should we discuss it there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:44:00.187",
"Id": "75729",
"Score": "0",
"body": "@GabrielW http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx Maybe that might help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:50:20.900",
"Id": "75730",
"Score": "0",
"body": "I don't really like this. The public Get methods are perfectly capable of doing the null default and not-null conversion themselves, why should they have to write their own functionality as a lambda and inject it into another method that's now doing too much?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:52:48.107",
"Id": "75731",
"Score": "0",
"body": "@BenAaronson Sorry I don't follow? What's doing too much now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:56:16.090",
"Id": "75732",
"Score": "0",
"body": "@dreza TypeConvert. It's not the end of the world or anything, it just seems that getting the property object and going through the type conversion logic are different enough to warrant their own methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:59:11.580",
"Id": "75733",
"Score": "0",
"body": "@BenAaronson Just saw your answer so understand now. Yep, that's a good alternative solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T09:02:03.643",
"Id": "75734",
"Score": "0",
"body": "Potentially you could have GetProperty(string propertyName) as in my solution which returns the property object, then Convert<T>(object property, T defaultIfNull, Func<object,T> convertIfNotNull) to do the conversion, as in yours. That might be a best of both worlds, though my personal taste is that it's not worth it to remove the extremely simple repeated logic"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:20:51.730",
"Id": "75824",
"Score": "0",
"body": "I can't build with `Object` as a constraint."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:29:08.163",
"Id": "75825",
"Score": "0",
"body": "@GabrielW Sorry that was supposed to be class not Object"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:58:16.430",
"Id": "43735",
"ParentId": "43719",
"Score": "5"
}
},
{
"body": "<p>At this point, the most obvious candidate for refactoring seems to be your public methods on <code>PropertyGetter</code>, as they contain a lot of repeated logic. Note that for these examples I'm going to continue using the <code>using</code> statements from your posted coded, but from your last question I remember you were using these unnecessarily. You should only use <code>using</code> in this situation if the classes you're instantiating for <code>moSearcher</code>, <code>collection</code> and <code>enu</code> implements <code>IDisposable</code>. Otherwise all it does is make your code harder to read.</p>\n\n<p>The simple refactoring would probably be as follows. Move the common logic to a private method, like:</p>\n\n<pre><code>private object GetProperty(string propertyName)\n{\n using (var moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM \" + _win32Class))\n {\n using (var collection = moSearcher.Get())\n {\n using (var enu = collection.GetEnumerator())\n {\n if (!enu.MoveNext() || enu.Current[propertyName] == null)\n return null;\n return enu.Current[propertyName];\n }\n }\n }\n}\n</code></pre>\n\n<p>Just for reference, without the <code>using</code> statements (if they do turn out to be unnecessary), this could be:</p>\n\n<pre><code>private object GetProperty(string propertyName)\n{\n var moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM \" + _win32Class));\n var collection = moSearcher.Get()\n var enu = collection.GetEnumerator())\n\n if (!enu.MoveNext() || enu.Current[propertyName] == null)\n return null;\n return enu.Current[propertyName];\n}\n</code></pre>\n\n<p>Then your public methods can look like:</p>\n\n<pre><code>public DateTime GetDateTimeFromDmtf(string propertyName)\n{\n var property = GetProperty(propertyName)\n if(property==null)\n return DateTime.Today;\n return ManagementDateTimeConverter.ToDateTime(property.ToString());\n}\n</code></pre>\n\n<p>The public methods will still all follow that common logic (get the property, if it's null return a default, otherwise convert to the desired format and return), but it's far more tolerable. The actual meat of the logic has been moved to its own method, which is exactly what you want for DRY.</p>\n\n<p>Now, there's possible scope for further cutting down on the amount of code you have here using generics, but it depends a bit on taste whether you actually like this. The idea here would be to write a single public method:</p>\n\n<pre><code>public TProp Get<TProp>(string propertyName);\n</code></pre>\n\n<p>You may not like that name, feel free to change it, I'll keep using it for now. This would be fine if, for example, for null properties you returned <code>default(T)</code> and for non-null you returned <code>(T)property</code>. Unfortunately, you seem to have different ways of handling null and non-null results for your different types. This means you'd need to write something like:</p>\n\n<pre><code>public TProp Get<TProp>(string propertyName)\n{\n var property = GetProperty(propertyName)\n if(property==null)\n return DefaultValue<T>();\n return Convert<T>(property);\n}\n</code></pre>\n\n<p>Here, <code>DefaultValue<T>()</code> and <code>Convert<T>(object property)</code> would be methods that handled the conversion. Unfortunately this would mean a big ugly if or switch statement checking the type of <code>T</code>, which while not having unnecessary repetition, is hardly very nice either. </p>\n\n<p>There is a way you could avoid this, and that's to have something like a 'PropertyConverter' class which handles the null and non-null conversion. You'd I could go into more detail on this, but at this point it seems to be adding a lot of complexity and really getting very little value out of it. My suggested solution would be to stick with the version in the first two chunks of code I posted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:48:06.483",
"Id": "43779",
"ParentId": "43719",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "43735",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:03:32.650",
"Id": "43719",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Next Instance of DRY Refactoring"
} | 43719 |
<p>I have an Olympics database from each Olympic year and I want to find the person that has won the most medals. The main problem is that I'm basically querying the same sub-query twice in <code>SUBSET1</code> and <code>SUBSET2</code>. How would I go about making this more efficient?</p>
<pre><code>Select athlete FROM ( Select athlete, Sum(total_medals) as total_medals
from Olympics Group by athlete) as SUBSET1 Where total_medals =
( Select Max( total_medals ) FROM ( Select Sum(total_medals) as total_medals
from Olympics Group by athlete ) as SUBSET2);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:41:45.593",
"Id": "75637",
"Score": "0",
"body": "Can you add which database you are actually using (vendor/version)... SQLServer, DB2, MySQL, Oracle, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:48:27.723",
"Id": "75651",
"Score": "1",
"body": "Updated answer to include PostgreSQL"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:16:56.400",
"Id": "75662",
"Score": "3",
"body": "Rolled back Rev 8 to Rev 7. (Please don't edit questions in a way that invalidates answers.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T07:06:30.677",
"Id": "96886",
"Score": "0",
"body": "@200_success: Why does Revision 7 invalidate answers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-21T16:01:51.137",
"Id": "359030",
"Score": "0",
"body": "@miracle173, because Malachi had already written *\"difficult to read ... because ... the reserved words weren't capitalized\"* (presumably meaning *upcased* rather than *capitalized*, but you get the meaning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-21T17:55:54.470",
"Id": "359041",
"Score": "0",
"body": "@TobySpeight I missed that this is codereview.stackexchange.com and not dba.stackexchange.com"
}
] | [
{
"body": "<p>In PostgreSQL, you can use the <code>rank()</code> mechanism to help.</p>\n\n<p>It still requires a subselect, but consider the following query:</p>\n\n<pre><code>Select o.athlete,\n sum(o.total_medals) as sumtotal_medals\nfrom Olympics o,\n ( select r.athlete as toprank,\n rank() over ( order by sum(r.total_medals) desc ) as rank\n from Olympics r\n group by r.athlete\n ) rankings\nwhere o.athlete = rankings.toprank\n and rankings.rank = 1\ngroup by o.athlete\norder by o.athlete\n</code></pre>\n\n<p>I have put this in to <a href=\"http://www.sqlfiddle.com/#!15/4e9c5/16/0\">the SQLFiddle here</a>....</p>\n\n<hr>\n\n<p>Previous MySQL exampl</p>\n\n<p>This can be done as top-count with a grouped select with a having clause.</p>\n\n<pre><code>Select TOP 1 athlete\nfrom Olympics\ngroup by athlete\norder by Sum(total_medals) DESC\n</code></pre>\n\n<p>if you want the actual medal haul, add the sum to the select.</p>\n\n<pre><code>Select TOP 1 athlete, Sum(total_medals) as total_medals\nfrom Olympics\ngroup by athlete\norder by Sum(total_medals) DESC\n</code></pre>\n\n<p>I have <a href=\"http://www.sqlfiddle.com/#!2/965db/2/0\">put together a fiddle using MySQL</a> (which has the LIMIT key-word)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:50:00.300",
"Id": "75639",
"Score": "0",
"body": "Had a similar answer, but what if more than 1 person have the top-count?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:51:42.737",
"Id": "75640",
"Score": "0",
"body": "Good question... @user35265 - what konijn says.... ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:03:51.327",
"Id": "75644",
"Score": "0",
"body": "If there is more than one athlete with the same medal count in my query I believe it would select all athletes with the medal count"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T17:56:22.650",
"Id": "75654",
"Score": "0",
"body": "The runtime of your new sql query is 66.962 ms while the runtime of my query is 38.919 ms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:00:47.640",
"Id": "75655",
"Score": "0",
"body": "@user35265 by the sounds of it, you need to be adjusting your expectations, 38 milliseconds is not 'slow', or inefficient... is there a real problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:05:16.050",
"Id": "75656",
"Score": "0",
"body": "I just didn't like the fact that I was \"basically querying the same sub-query twice in SUBSET1 and SUBSET2\" - I felt like it was redundant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:06:44.363",
"Id": "75657",
"Score": "1",
"body": "@user35265 if you really need better performance on this query then you should consider a separate table with pre-computed aggregations ... perhaps a [materialized view...](http://wiki.postgresql.org/wiki/Materialized_Views) or a table that pre-aggregates the data...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:09:44.950",
"Id": "75659",
"Score": "0",
"body": "Will definitively look into your suggestions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:12:07.320",
"Id": "75660",
"Score": "0",
"body": "Materialized view is probably overkill. Check that you have good indexes first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:37:15.697",
"Id": "75677",
"Score": "0",
"body": "just for the record I +1'd the MySQL answer because I could read it and it looks like my SQL Server based Answer...."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:49:02.103",
"Id": "43724",
"ParentId": "43721",
"Score": "10"
}
},
{
"body": "<p>This alternative to @rolfl's answer is more readable, in my opinion. It also has a more efficient execution plan.</p>\n\n<pre><code>WITH medal_count AS (\n SELECT athlete\n , SUM(total_medals) AS grand_total_medals\n , RANK() OVER (ORDER BY SUM(total_medals) DESC) AS rank\n FROM Olympics\n GROUP BY athlete\n)\nSELECT athlete\n , grand_total_medals\n FROM medal_count\n WHERE rank = 1\n ORDER BY athlete;\n</code></pre>\n\n<p><a href=\"http://www.sqlfiddle.com/#!15/4e9c5/23\">SQLFiddle</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:18:54.960",
"Id": "75682",
"Score": "0",
"body": "In my experience, CTEs are slower than using a subquery since it is about the same as creating a temporary table (ie. you lose your indexes)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:09:58.500",
"Id": "43728",
"ParentId": "43721",
"Score": "11"
}
},
{
"body": "<p>I think that you are over thinking this, in SQL Server I would do something like this</p>\n\n<pre><code>SELECT TOP (10) athlete \nFROM ( SELECT athlete, Sum(total_medals) AS total_medals\n FROM Olympics\n ORDER BY total_medals DESC\n GROUP BY athlete) \n</code></pre>\n\n<p>And then I would use my Reporting Software to decide if there are 2 or more people at the top.</p>\n\n<p>This is probably more of what you want anyway, a top 10 list of all time.</p>\n\n<hr>\n\n<p><strong>Side Note</strong></p>\n\n<p>I found it rather difficult to read your query because it wasn't indented and the reserved words weren't capitalized. I would recommend that you do those things when writing a query.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T18:11:10.177",
"Id": "43729",
"ParentId": "43721",
"Score": "6"
}
},
{
"body": "<p>\nI'm a little late to the party, but I think you can make it less complicated.</p>\n\n<p>Wouldn't this be what you need:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT athlete\nFROM Olympics \nGROUP BY athlete\nORDER BY SUM(total_medals) DESC\nLIMIT 1\n</code></pre>\n\n<p>Here is the obligitory <a href=\"http://www.sqlfiddle.com/#!15/4e9c5/35/0\" rel=\"nofollow noreferrer\">SQL Fiddle</a>.</p>\n\n<p>EDIT: Previous version didn't account for multiple people with the same number of medals.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT athlete\nFROM Olympics\nGROUP BY athlete\nHAVING SUM(total_medals) = \n(\n SELECT SUM(total_medals)\n FROM Olympics\n GROUP BY athlete\n ORDER BY SUM(total_medals) DESC\n LIMIT 1\n)\n</code></pre>\n\n<p>At a quick glance, the execution plan for this seems a little nicer than the other suggestions, feel free to correct me if I am wrong though.</p>\n\n<p><a href=\"http://www.sqlfiddle.com/#!15/4e9c5/47\" rel=\"nofollow noreferrer\">Here is the SQL Fiddle.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-20T02:06:56.473",
"Id": "109637",
"Score": "1",
"body": "This isn't correct because you could have more than one athlete that has the \"highest\" number of medals"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-20T09:33:51.067",
"Id": "109691",
"Score": "0",
"body": "@TheBear \nThanks, I think I misread the question, I've updated the answer now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T15:12:02.013",
"Id": "58660",
"ParentId": "43721",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:29:58.230",
"Id": "43721",
"Score": "15",
"Tags": [
"optimization",
"sql",
"postgresql"
],
"Title": "Finding person with most medals in Olympics database"
} | 43721 |
<p>I have long been looking for an elegant, one-line solution to map <code>enum</code> to strings automatically, for use with the <code><<</code> and <code>>></code> stream operators.</p>
<p>I know that a lot of macros have been proposed to achieve that, but I never found a really simple scheme, with only one macro call.</p>
<p>This is my attempt, and I would be interested to discuss the advantages and limitations of this approach...</p>
<p>Definitions:</p>
<pre><code>#include <string>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>
#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)
#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)
#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)
#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)
#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)
#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)
#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)
#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)
#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)
#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)
#define MAKE_STRING10_(str) #str
#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)
#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)
#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \
attribute std::istream& operator>>(std::istream& is, name& e) { \
const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
std::string str; \
std::istream& r = is >> str; \
const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \
const std::vector<std::string> enumStr(name##Str, name##Str + len); \
const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \
if (it != enumStr.end())\
e = name(it - enumStr.begin()); \
else \
throw std::runtime_error("Value \"" + str + "\" is not part of enum "#name); \
return r; \
}; \
attribute std::ostream& operator<<(std::ostream& os, const name& e) { \
const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
return (os << name##Str[e]); \
}
</code></pre>
<p>Usage:</p>
<pre><code>enum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);
class Essai {
public:
enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);
};
int main() {
std::cout << Essai::Item1 << std::endl;
Essai::Test ddd = Essai::Item1;
std::cout << ddd << std::endl;
std::istringstream strm("Item2");
strm >> ddd;
std::cout << (int) ddd << std::endl;
std::cout << ddd << std::endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:10:01.373",
"Id": "75666",
"Score": "0",
"body": "Shouldn't `Essai` just be a `struct` since its only member is `public`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T02:07:51.753",
"Id": "75710",
"Score": "0",
"body": "You may want to see this template version I wrote. http://codereview.stackexchange.com/a/14315/507 It maps enum to strings and strings back to enums. All you need to do is define an array of strings for each enum and the template magic does the rest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T02:12:11.463",
"Id": "75711",
"Score": "0",
"body": "There are only a few real uses for macros in C++ this is not one of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:13:53.603",
"Id": "75738",
"Score": "0",
"body": "@Jamal: it's just an example to show an usage within a class...\n@LokiAstari: your template version is really nice. But, it requires conversion functions `enumToString()` and `enumFromString()`. The goal here was to provide `enum` directly with the stream serialization operators `<<` and `>>`."
}
] | [
{
"body": "<p>I agree with the comments: macros are a mess. Avoid them when possible.</p>\n\n<p>If you're willing to make certain sacrifices (a little repetition), it's possible to avoid macros here. Doing so will also avoid some of the arbitrary limitations in your macro implementation, such as the 10 or so cap on enum values.</p>\n\n<p>Using C++11, it's not hard to wire up <a href=\"https://codereview.stackexchange.com/a/14315/507\">Loki Astari's approach</a> to <code>operator<<</code> and <code>operator>></code> with some type traits template metaprogramming. I personally think enums are much cleaner with the strongly typed <code>enum class ...</code> variant introduced by C++11, so I would suggest that anyway, but the <code>enum_serializable</code> approach I show here works on both strongly and weakly typed enums.</p>\n\n<pre><code>#include <type_traits>\n#include <iostream>\n#include <https://codereview.stackexchange.com/a/14315/507 by reference>\n\ntemplate <typename Enum>\nstruct enum_serializable : std::false_type\n{};\n\n// enable operator<< and operator>> for `Essai` values\ntemplate <>\nstruct enum_serializable<Essai> : std::true_type\n{};\n\ntemplate <typename Enum>\ntypename std::enable_if<enum_serializable<Enum>::value, std::ostream&\n>::type operator<<(std::ostream& os, Enum e)\n{\n return os << enumToString(e);\n}\n\ntemplate <typename Enum>\ntypename std::enable_if<enum_serializable<Enum>::value, std::istream&\n>::type operator>>(std::istream& is, Enum& e)\n{\n return is >> enumFromString(e);\n}\n</code></pre>\n\n<p>It's also not hard to pull Loki Astari's approach into the <code>operator<<</code> and <code>operator>></code> functions above, removing the separate <code>enumToString</code> and <code>enumFromString</code> functions and the <code>enumRefHolder</code> and <code>enumConstRefHolder</code> structs entirely.</p>\n\n<p>This general approach should be available before C++11 as well, but <code>std::enable_if</code> will have to be implemented instead of <code>#include</code>d.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T15:46:57.903",
"Id": "43862",
"ParentId": "43725",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T16:53:57.417",
"Id": "43725",
"Score": "3",
"Tags": [
"c++",
"enum"
],
"Title": "Automatic C++ enum to string mapping macro"
} | 43725 |
<p><strong>The original question where the general concept of this implementation was discussed:</strong> <a href="https://codereview.stackexchange.com/questions/41989/using-ids-with-a-scope-like-hierarchy">Using ID's with a "scope" -like hierarchy</a></p>
<p>I have designed a resource manager as part of a game programming project that I have been working on as a hobby. Implementing as much functionality as possible in the least amount of time and effort is not my goal, instead my focus has been on learning how to design and implement a relatively large software project by myself.</p>
<p>An usage example for the submitted code:</p>
<pre><code>//We will first create three resource contexts: the global context, and
//..two local contexts specific to each window
auto globalCtx = ResourceContext::makeGlobalContext();
auto gameCtx = globalCtx.makeLocalContext();
auto editorCtx = globalCtx.makeLocalContext();
//The virtual filesystem maps file ID:s to system paths. Since there is no
//..reason to create two separate virtual filesystems (one for each window)
//..we will make a new VirtualFs object in the global context.
auto vFilesys = globalCtx->make<VirtualFs>("/data/index.xml");
//The game's main window is created in the game's context (gameCtx).
auto mainWindow = gameCtx->make<Window>("Game", 800, 600, SDL_WINDOW_SHOWN,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
//The editor window is created in the editor context (editorCtx). If both
//..windows were simply created in the global context, the second call to
//..globalContext->make<Window>(...) would simply return a shared_ptr to
//..the previously created game window.
auto editorWindow = editorCtx->make<Window>("Editor", 300, 600,
SDL_WINDOW_SHOWN, SDL_RENDERER_ACCELERATED);
//The hero belongs to the main window. Instead of passing a reference to
//..the window, we pass the game context. The Sprite code first searches
//..for a Window instance in the gameContext, and finds mainWindow, then
//..searches for a VirtualFs, which it does not find at first, but after
//..automatically searching in the parent context (globalCtx) too a
//..VirtualFs instance vFilesys is found.
Sprite hero(gameCtx, "textures/hero.png");
//The same applies to the GuiButton, but code in GuiButton gets a pointer
//..to editorWindow instead.
GuiButton startStop(editorCtx, "Start simulation", 10, 10, 280, 50);
</code></pre>
<p>In short, the idea is that instead of having a single, massive, flat hierarchy containing all resources being used in the game (textures, sounds, ...), the resources are organized in a tree-shaped hierarchy similar in concept to the scope of programming languages. This also makes it quite attractive to use the same system for concepts normally not viewed as "resources" such as a window handle. For a more troughout explanation of the idea see the original question.</p>
<pre><code>#include <map>
#include <memory>
#include <vector>
class ResourceContext;
///////////////////////////////////////////////////////////////////////////////
// class Resource
//================
//class Resource is a common base class that has to be inherited by all classes
//..that are to be managed using the "ResourceContext" system. All classes
//..inheriting Resource will inherit member ResourceContext &context_ that can
//..be used to access the ResourceContext object managing said class.
//Usage:
// Class DerivedResource : public Resource
// {
// DerivedResource(ResourceContext &context, ...) : Resource(context)
// {
// ...
///////////////////////////////////////////////////////////////////////////////
class Resource
{
public:
Resource(ResourceContext &context) : context_(context){}
//Virtual dtor required as shared_ptr will delete trough a base class ptr
virtual ~Resource(){}
protected:
ResourceContext &context_;
};
///////////////////////////////////////////////////////////////////////////////
// class ResourceContext
//=======================
//All classes inheriting "Resource" are to be managed by class ResourceContext.
//ResourceContexts form a treelike hierarchy, where the root node is called
//.."globalContext", a parent node is called "parentContext", and a child node
//..is called "localContext". A resource created in a given context is visible
//..in all localContexts (child nodes) of the context and any localContexts
//..of those localContexts. This means that a resource created in the
//..globalContext is also visible everywhrere else. However, if a localContext
//..contains a resource with an identical type and name as a global (or parent
//..level) resource, the parent level resource will be hidden, and in a search
//..the local resource is returned instead. Resources in a localContext are
//..never visible in it's parentContext or any sibling contexts.
//ResourceContext is not guaranteed to own any resources it manages. The
//..ownership of the managed resources is transferred to the object calling
//..make(), makeNamed, find() or findNamed(), by returning a std::shared_ptr to
//..the requested object.
///////////////////////////////////////////////////////////////////////////////
class ResourceContext : public std::enable_shared_from_this<ResourceContext>
{
public:
//The static member function "makeGlobalContext" creates a new resource
//..management system. Calling it constructs and initializes a new
//..ResourceContext object (independent of any existing ResourceContext
//..objects), and returns a std::shared_ptr to the object.
static std::shared_ptr<ResourceContext> makeGlobalContext()
{
return std::shared_ptr<ResourceContext>(
new ResourceContext());
}
//"makeLocalContext" creates a new ResourceContext whose parent is the
//..current context, and returns a std::shared_ptr to the new object.
std::shared_ptr<ResourceContext> makeLocalContext()
{
if(globalContext_ == nullptr)
return std::shared_ptr<ResourceContext>(
new ResourceContext(shared_from_this(), shared_from_this()));
else
return std::shared_ptr<ResourceContext>(
new ResourceContext(shared_from_this(), globalContext_));
}
//"getParentContext" returns a std::shared_ptr to the parent context of
//..the current context. If the current context is the global context, a
//..pointer to the current context is returned instead.
std::shared_ptr<ResourceContext> getParentContext()
{
if(parentContext_ == nullptr)
return shared_from_this();
else
return parentContext_;
}
//"getGlobalContext" returns a std::shared_ptr to the global context.
std::shared_ptr<ResourceContext> getGlobalContext()
{
if(globalContext_ == nullptr)
return shared_from_this();
else
return globalContext_;
}
//"makeNamed" searches for a resource with a matching type and ID. If a
//..matching resource is found in the current context, a shared_ptr to the
//..resource is returned, otherwise the constructor arguments passed to
//..this function are forwarded to the constructor of the resource class,
//..and a new resource object is instantiated.
template<typename T, typename...Arg>
std::shared_ptr<T> makeNamed(std::string id, Arg...ctorArgs)
{
int index = getIndex<T>();
ResById &resourceMap = mapByIndex_[index];
auto keyValPair = std::make_pair(id, std::weak_ptr<Resource>());
auto &mappedPtr = resourceMap.insert(keyValPair).first->second;
if(mappedPtr.expired())
{
auto newResource = std::make_shared<T>(*this, ctorArgs...);
mappedPtr = std::static_pointer_cast<Resource>(newResource);
return newResource;
}
else
return std::static_pointer_cast<T>(mappedPtr.lock());
}
//"make" searches for a resource with a matching type. If a matching
//..resource is found in the current context, a shared_ptr to the resource
//..is returned, otherwise the constructor arguments passed to this
//..function are forwarded to the constructor of the resource class, and
//..a new resource object is instantiated.
template<typename T, typename...Arg>
std::shared_ptr<T> make(Arg...ctorArgs)
{
return makeNamed<T>(std::string(), ctorArgs...);
}
//"findNamed" returns a std::shared_ptr to a resource if a resource with a
//..matching type and ID can be found in the current context or the current
//..context's parent contexts, while returning a nullptr if no matching
//..resource exists.
template<typename T>
std::shared_ptr<T> findNamed(std::string id)
{
int index = getIndex<T>();
ResById &resourceMap = mapByIndex_[index];
auto it = resourceMap.find(id);
if(it != resourceMap.end())
{
if(!it->second.expired())
return std::static_pointer_cast<T>(it->second.lock());
}
if(parentContext_ != nullptr)
return parentContext_->find<T>(id);
return nullptr;
}
//"find" returns a std::shared_ptr to a resource if a matching resource
//..can be found in the current context or the current context's parent
//..contexts, while returning a nullptr if no matching resource exists.
template<typename T>
std::shared_ptr<T> find()
{
return findNamed<T>(std::string());
}
private:
//The constructors are only intended to be called by
//..ResourceContext::makeGlobalContext()
ResourceContext() : parentContext_(nullptr), globalContext_(nullptr){}
ResourceContext(std::shared_ptr<ResourceContext> parent,
std::shared_ptr<ResourceContext> global)
: parentContext_(parent), globalContext_(global){}
//Copy constructors and the assignment operator disabled
ResourceContext(const ResourceContext&) = delete;
ResourceContext& operator=(const ResourceContext&) = delete;
//getIndex generates an index that is unique for each template
//..specialization of the function, and resizes the vector of resource
//..maps when needed. For internal use only.
template<typename T>
int getIndex()
{
static int id = -1;
if(id < 0)
{
id = resourceTypeCount;
resourceTypeCount++;
}
if(id >= (int)mapByIndex_.size())
mapByIndex_.resize(resourceTypeCount);
return id;
}
//The number of different resources currently supported.
static int resourceTypeCount;
//The resources managed by the current context, mapped by ID and resource
//..type.
typedef std::map<std::string, std::weak_ptr<Resource>> ResById;
std::vector<ResById> mapByIndex_;
//A ResourceContext object owns its parent context. This guarantees that
//..the parent context does not go out of scope while a local context
//..still exists.
std::shared_ptr<ResourceContext> parentContext_;
std::shared_ptr<ResourceContext> globalContext_;
};
int ResourceContext::resourceTypeCount = 0;
</code></pre>
<p>I would appreciate getting feedback on the following:</p>
<ul>
<li>The use of C++11 features: smart pointers, (currently missing) move semantics, variadic templates and the auto keyword</li>
<li>Commenting style: Too little, too much, hard to follow?</li>
<li>Programming style: Structuring, legibility, possible mistakes, optimizations, code smell?</li>
<li>Most importantly, the general concept: It's implications on design complexity and performance</li>
<li>How to get rid of the ugly static variables? should I resort to RTTI (runtime type identification) in place of the current ID generator?</li>
</ul>
| [] | [
{
"body": "<p>I can't answer all your questions, but here are some things you can improve or some guidelines you can follow:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/2502454/1364752\">Always pass <code>std::shared_ptr</code> by const reference</a>. There are several reasons for this, some of them are explained in <a href=\"http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/\" rel=\"nofollow noreferrer\">GOTW #91</a> by Herb Sutter.</li>\n<li><p>In your function <code>make</code>, you problem want to take the parameters by <a href=\"https://stackoverflow.com/a/3582313/1364752\">universal reference</a> and use <code>std::forward</code> instead of simply passing them. Therefore, you can tranform this:</p>\n\n<pre><code>template<typename T, typename...Arg>\nstd::shared_ptr<T> make(Arg... ctorArgs)\n{\n return makeNamed<T>(std::string(), ctorArgs...);\n}\n</code></pre>\n\n<p>into that:</p>\n\n<pre><code>template<typename T, typename...Arg>\nstd::shared_ptr<T> make(Arg&&... ctorArgs)\n{\n return makeNamed<T>(std::string(), std::forward<Arg>(ctorArgs)...);\n}\n</code></pre></li>\n<li><p>Whenever possible, try to replace your <code>insert</code> functions by <code>emplace</code> functions, especially when you created an object to immediately store it. You can turn this:</p>\n\n<pre><code>auto keyValPair = std::make_pair(id, std::weak_ptr<Resource>());\nauto &mappedPtr = resourceMap.insert(keyValPair).first->second;\n</code></pre>\n\n<p>into that:</p>\n\n<pre><code>auto &mappedPtr = resourceMap\n .emplace(id, std::weak_ptr<Resource>())\n .first->second;\n</code></pre>\n\n<p>Technically speaking, you can go even further and use the <code>std::pair</code> piecewise construction to create your values directly in the <code>std::pair</code> directly in the <code>std::map</code>:</p>\n\n<pre><code>auto &mappedPtr = resourceMap\n .emplace(\n std::piecewise_construct,\n std::forward_as_tuple(id),\n std::forward_as_tuple(std::weak_ptr<Resource>())\n ).first->second;\n</code></pre></li>\n<li><p>You could try to be consistent and use <code>std::make_shared</code> everywhere instead of using <code>new</code> from time to time. I know that <code>std::make_shared</code> has problems to interact with <code>private</code> or <code>protected</code> constructors. However, <a href=\"https://stackoverflow.com/q/8147027/1364752\">there are some workarounds</a> that you can use if you want to consistently use <code>std::make_shared</code> whenever possible.</p></li>\n</ul>\n\n<p>All of those tips are only guidelines to properly use c++11 and nothing is actually specific to your code. I unfortunately did not managed to really dive into your code and think about its logic. You will have to wait for another answer if you want to improve it too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:31:26.227",
"Id": "43830",
"ParentId": "43733",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43830",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:07:27.927",
"Id": "43733",
"Score": "6",
"Tags": [
"c++",
"game",
"c++11"
],
"Title": "Resource manager implementation, with resources being organized in a scope-like hierarchy"
} | 43733 |
<p>I keep seeing <code>/subsite/../global/css/file.css</code> when I look at my website's source code, and today I decided that I want to get rid of the unnecessary traversal in the path itself, so it becomes <code>/global/css/file.css</code>. I made myself a function which I now use for all paths. Here is the base of my function that accomplishes this:</p>
<pre><code>function djpth($pth){
// Split path at slashes (always receives path with forward slash)
$pth = explode('/',$pth);
// Iterate through the new array
foreach ($pth as $i => $part)
// If we find a traversal mark
if ($part == '..')
// We get rid of the folder name before the mark and the mark itself
array_splice($pth,$i-1,2);
// We join the array back together
$pth = implode('/',$pth);
// Then we return the resolved path
return $pth;
}
</code></pre>
<p>I want to know if there's a better way to go about this, or if this is the best I can get.</p>
| [] | [
{
"body": "<ol>\n<li><pre><code>djpth('/parent/subsite/../../global/css/file.css')\n</code></pre>\n\n<p>returns</p>\n\n<pre><code>/parent/../file.css \n</code></pre>\n\n<p>I guess that is not what you want.</p></li>\n<li><p>If the file exists I'd use the built-in <a href=\"http://php.net/realpath\" rel=\"nofollow\"><code>realpath</code></a> function. I guess it handles corner case like this and another ones better.</p>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em>)</p></li>\n<li><p><code>$pth</code> is used for multiple purposes. It would be easier to read a <code>$path</code> and a <code>$path_array</code>.</p></li>\n<li><p>Abbreviations are hard to read, like <code>$pth</code>. Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses.</p>\n\n<p>Furthermore, it's hard to pronounce (as well as <code>djpth</code>).</p>\n\n<blockquote>\n <p>If you can’t pronounce it, you can’t discuss it without sounding like an idiot. “Well,\n over here on the bee cee arr three cee enn tee we have a pee ess zee kyew int, see?” This\n matters because programming is a social activity.</p>\n</blockquote>\n\n<p>Source: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Use Pronounceable Names</em>, p21</p></li>\n<li><p>Comments like this are just noise:</p>\n\n<blockquote>\n<pre><code>// Iterate through the new array\n</code></pre>\n</blockquote>\n\n<p>It's obvious from the code itself. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><blockquote>\n<pre><code>$pth = implode('/',$pth);\n// Then we return the resolved path\nreturn $pth;\n</code></pre>\n</blockquote>\n\n<p>The comment above could be eliminated with a better variable name:</p>\n\n<pre><code>$resolved_path = implode('/', $path_array);\nreturn $resolved_path;\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T22:36:12.053",
"Id": "75695",
"Score": "0",
"body": "I tested it and it seems to return `/global/css/file.css`. Thanks for the information, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:24:20.660",
"Id": "75715",
"Score": "0",
"body": "@DJDavid98: Hm, I've also cheked it again. The result is the same as in the answer. PHP 5.3, if that's count."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T09:25:39.030",
"Id": "75736",
"Score": "0",
"body": "You're right. This is just part of the function, so maybe I missed something that would fix this, but since then I modified it entirely. Here is the fixed up, current code: https://gist.github.com/DJDavid98/9427789"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:14:11.583",
"Id": "43738",
"ParentId": "43734",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "43738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T19:32:19.287",
"Id": "43734",
"Score": "4",
"Tags": [
"php"
],
"Title": "Resolving directory traversal"
} | 43734 |
<p>I've built a web site that uses AJAX to update a div. Most of the data displayed in the div is drawn from a MySQL database. All the pages are PHP. </p>
<p>I've tried to follow best practices. I put all the query strings into stored procedures in the database. The PHP files call the stored procedures with parameters that JavaScript functions pass via AJAX. Does this meet best practices? Is it RESTful? </p>
<p>Is someone said, "Write me an example that uses PHP, JavaScript, and MySQL to build a web app that integrates MVC and REST design principles", would this example suffice?</p>
<p>Here's some source code. First, index.php</p>
<pre><code><html>
<head>
<script language="JavaScript" type="text/javascript">
//Update innerHTML of middle div
function update(target){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var middleDisplay = document.getElementById('middle');
middleDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", target, true);
ajaxRequest.send(null);
}
</script>
<script language="javascript" type="text/javascript">
//Call a PHP file which creates a new order.
function neworder(id){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
var url = "create_order.php?id="+id;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
update('step1.php');
}
</script>
</head>
<body>
<div id=”header”>Welcome message, menu bar, etc.</div>
<div id=”middleDisplay”><?php include “step1.php” ?></div>
</body>
</html>
</code></pre>
<p>Here's the contents of "step1.php":</p>
<pre><code><?php
include “../util.php”; //Includes the Session_Start() command and SQL connect strings.
$order = mysqli_query($connect,”CALL open_orders()”);
$order_table = “<table>”;
while($row = mysqli_fetch_array($query)){
$order_table .= “<tr><td>’.$row[‘date’].’</td><td>’.$row[‘name’].’</td></tr>
}
$order_table .=”</table>”;
echo’
<form name=”myForm”>
<label>Enter id for a new order</label>
<input type=”text” name=”id_input”><input>
<button onclick=”neworder(document.GetElementById(myForm.id_input).value)”>Click here to make a new order</button>
</form><br/>
‘;
echo $order_table;
?>
</code></pre>
<p>Here's the contents of create_order.php:</p>
<pre><code><?php
include “../util.php”;
$id = $_GET[‘id’]’
//code to prevent SQL injection.
$query=mysqli_query($connect, “CALL new_order($id)”);
?>
</code></pre>
<p>Finally, here are the two procedures in MySQL:</p>
<pre><code>CREATE PROCEDURE AS open_orders()
BEGIN
SELECT date, name FROM order WHERE status <> 0;
END
CREATE PROCEDURE AS new_order(user_id TINYINT)
BEGIN
INSERT INTO order (id) VALUES user_id
END
</code></pre>
<p>index.php has a <code>header</code> div and a <code>middleDisplay</code> div. The <code>header</code> div has a welcome message and a navigation menu. It should never change. The JavaScript function <code>update</code> uses AJAX to change the <code>InnerHTML</code> of the <code>middle</code> div, where all navigation will take place.</p>
<p>The middle div is pre-populated by stage1.php. Stage1.php executes a SQL query to get open orders. It places the results in a table. It also has a form for creating new orders.</p>
<p>Here’s where I’m unsure of myself: I can’t set the form to POST to another PHP file. That would change the URL. I want the URL to stay the same so I can keep the header div and update only the <code>middleDisplay</code> div. Instead, I call a JavaScript function, <code>neworder</code>.</p>
<p><code>neworder</code> does two things. First, it sends an AJAX request to <code>create_order.php?id=foo</code>. Then, it calls the update function, which uses AJAX to update the middle div.</p>
<p>There are many other JavaScript functions in index.php, and many other PHP files that populate middle div. But these files represent the concept:</p>
<ul>
<li>One PHP file that builds the structure with divs.</li>
<li>Multiple PHP files that display data in the middle div.</li>
<li>Multiple PHP files that call SQL routines. Sometimes these SQL routines return data, which the PHP files set as session variables. Sometimes (as in the above example), they don’t return anything at all.</li>
<li>Multiple JavaScript functions (all located in index.php) that take data from the "display" PHP files and pass data to the "SQL routine" PHP files.</li>
</ul>
<hr>
<ol>
<li>Have I made an example of MVC design?</li>
<li>Would the PHP that calls SQL routines be the model, the display PHP file the View, and the JavaScript functions the Controller?</li>
<li>Is this an example of RESTful design?</li>
<li>I use the GET parameter in the AJAX call and access the <code>$_GET</code> array in the PHP files. But the function doesn't expect to GET any data. It just wants the PHP file to call a routine on the database. Is that a violation of RESTful design?</li>
</ol>
| [] | [
{
"body": "<p>First lets define MVC design and break apart your question:</p>\n\n<p>M: Model (datastructure or business logic)</p>\n\n<p>V: View (the display of your information)</p>\n\n<p>C: Controller (the one that connects the M to the V)</p>\n\n<ol>\n<li><p><strong>Have I made an example of MVC design?</strong></p>\n\n<p>I'm sorry but negative (unless someone wants to point in and say its right). Your not using any OOP design to achieve the MVC. Rather your components aren't standalone. Example: step1.php has both ECHO (which is a display) and some DB logic to it. Your create_order.php could be a model where you do a DB entry however your not giving it back. Furthermore your DIV includes a PHP file.</p></li>\n<li><p><strong>Would the PHP that calls SQL routines be the model, the display PHP file the View, and the JavaScript functions the Controller?</strong></p>\n\n<p>Somewhat a bit ok on the logic despite the mess. However let's clarify something:</p>\n\n<ol>\n<li>Ideally if the JavaScript injected the response code into index.php's DIV it would have been a controller. Think the controller as \"can you deal with the logic for me and when you're done, give it back\".</li>\n<li>Your model logic is ok to assume as DB connection and manipulation is old school but its a good stepping stone. However, a MODEL itself is anything that deals with heavy manipulation of logic and data. He is the guy that does something.</li>\n<li>The view is the PHP, HTML, or could be JavaScript again that once get the data gives it in a nice bow-tie. </li>\n</ol></li>\n<li><p><strong>Is this an example of RESTful design?</strong></p>\n\n<p>REST-ful means API call if you want an analogy. You are using forms to put data in.</p></li>\n<li><p><strong>I use the GET parameter in the AJAX call and access the <code>$_GET</code> array in the PHP files. But the function doesn't expect to GET any data. It just wants the PHP file to call a routine on the database. Is that a violation of RESTful design?</strong></p>\n\n<p>Read #3 for the answer.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T01:11:21.900",
"Id": "44313",
"ParentId": "43737",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "44313",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:11:03.013",
"Id": "43737",
"Score": "3",
"Tags": [
"php",
"sql",
"ajax"
],
"Title": "Website for updating a div"
} | 43737 |
<p>I've decided to go with OOP style and prepared statements, and so far I like it a lot more than the procedural style. It's much more understandable in my opinion.</p>
<p>For this code review, I've just included my PHP code that interacts with my MySQL database. Everything is working how it should, but I'd like to know if you see anything that could be improved upon. Also, I'd like a <em>security</em> analysis/review of the code. Is my code safe from SQL injection since I'm using prepared statements? Is there anything else I should be doing?</p>
<hr>
<p>I have this function in a folder/file above public_html, and just require it on the pages that need it.</p>
<pre><code>function connectToDatabase() {
$connect = new mysqli('localhost', 'myUserName123', 'myPassword123', 'myDatabaseName');
if ($connect->connect_error) {
exit;
}
return $connect;
}
</code></pre>
<p>This is the function I use to pull the question <em>text</em>, and answer <em>integers</em> from the database to display on the website.</p>
<pre><code>function getQuestionsAndAnswers($connect) {
$questionArray = array();
$answersArray = array();
$getStuff = $connect->prepare('SELECT `question`, `answer` FROM `Quizzes` WHERE `questionNumber`<? ORDER BY `questionNumber` ASC');
$getStuff->bind_param('i', $questnum);
$questnum = 21;
$getStuff->execute();
$getStuff->bind_result($singleQuestion, $singleAnswer);
while ($getStuff->fetch()) {
array_push($questionArray, $singleQuestion);
array_push($answersArray, $singleAnswer);
}
$getStuff->close();
$connect->close();
return array($questionArray, $answersArray);
}
</code></pre>
<p>This is the code that gets run after the user takes the math quiz, submits his answers, and I validate that the answers are all integers, etc.</p>
<pre><code>$connect = connectToDatabase(); // open database connection here
$stmt1 = $connect->prepare("SELECT MAX(`id`) FROM QuizAdministration");
$stmt1->execute();
$stmt1->bind_result($maxId);
$stmt1->fetch();
$stmt1->close();
$stmt2 = $connect->prepare("INSERT INTO PlayerAnswers (`QuizAdministrationId`, `questionNumber`, `playerAnswer`) VALUES (?, ?, ?)");
for ($yty = 1; $yty < 21; $yty += 1) {
$stmt2->bind_param('iii', $QuizAdministrationid, $questnum, $questansw);
$QuizAdministrationid = $maxId + 1;
$questnum = $yty;
$questansw = $_POST['qora'.$yty];
$stmt2->execute();
}
$stmt2->close();
$stmt3 = $connect->prepare("INSERT INTO QuizAdministration (`quizNumber`, `cookie`, `ip`, `score`) VALUES (?, ?, ?, ?)");
$stmt3->bind_param('issi', $quizNumber, $playerCookie, $playerIP, $playersPercent);
$quizNumber = 1;
$playerCookie = session_id();
$playerIP = getUserIp();
$playersPercent = 90;
$stmt3->execute();
$stmt3->close();
$connect->close(); // close database connection here
header('Location: http://www.myWebsite.com/quizResults.php');
exit;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T16:21:33.813",
"Id": "75774",
"Score": "0",
"body": "It looks like you are using prepared statements correctly. However, I'd suggest rewriting using PDO prepared statements with named parameters. All of those binding statements can go away. I can give you a short example if you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:10:57.933",
"Id": "76533",
"Score": "0",
"body": "Why do you separate questions and answers into two separate arrays? It seems to me that working with one array of question-answer pairs is much easier. But we'd have to see the code where you use those arrays to be sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-11T06:43:35.203",
"Id": "93929",
"Score": "1",
"body": "One thing, the first query you make should not be a prepared statement. The rule of thumb: *If your query has **parameters**, it needs to be a prepared statement*. Just selecting something from a table with no constraints or parameters can and should be a normal query (Prepared statements have a slight hit on performance)."
}
] | [
{
"body": "<p>With PDO, you could have:</p>\n\n<pre><code>$getStuff = $pdo->prepare('SELECT `question`, `answer` FROM `Quizzes` WHERE `questionNumber`< :questionNumber ORDER BY `questionNumber` ASC');\n\n$getStuff->execute(array('questionNumber' => 21));\n\n$rows = $getStuff->fetchAll();\n\nforeach($rows as $row)\n{\n $questions[] = $row['question'];\n $answers[] = $row['answer'];\n}\n</code></pre>\n\n<p>It's up to you to decide if removing the binding stuff makes the code any easier to read and maintain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T16:32:53.180",
"Id": "43794",
"ParentId": "43740",
"Score": "4"
}
},
{
"body": "<p>The security aspect of things looks fine, but there are some areas for improvement,\nI have provided inline comments where possible.</p>\n\n<p>The whole quiz could be coded as a class, and would be a lot nicer, however I didn't want to go too far from what you started with so you can see what changes I have done.</p>\n\n<p>Overall, I have split the code into functions, and tried to make each function do 1 thing only, and renamed variables for readability. This will become more important when you go to maintain the code.</p>\n\n<p>The first bit of code is what I used to test all the functions and catches exceptions that occur. You could improve by adding more error checks after each prepare and execute, but I will leave that to you, as they are only really necessary if the database structure doesn't match the sql.</p>\n\n<p>\n\n<pre><code>try {\n $conn = connectToDatabase();\n\n list($questions, $answers) = getQuestionsAndAnswers($conn);\n\n // lets handle user data, separate of database calls\n $answers = extractPostAnswers($_POST);\n\n // not sure this is the best idea, if we have 2 simultaneous calls, both will get the same $maxId\n // i am unsure of your database design, but the way I am assuming it should work is\n // have an autoincrement column on the quiz administration table\n // insert into the quiz administration table and get the last_insert_id back\n // then use that id value to store in the answer table\n $maxId = selectMaxId($conn);\n\n $QuizAdministrationid = $maxId + 1;\n saveAnswers($conn, $QuizAdministrationid, $answers);\n\n $quizNumber = 1;\n saveQuizAdministration($conn, $quizNumber);\n\n $conn->close(); // close database connection here\n\n header('Location: http://www.myWebsite.com/quizResults.php');\n\n} catch (Exception $ex) {\n\n // you should log the messages, and display a nice error for the user, this is just to give you idea of exception handling\n die($ex->getMessage());\n}\n\n\nexit;\n\n\n\n\nfunction extractPostAnswers($post) {\n\n $answers = array();\n\n for ($questnum=1; $questnum<21; $questnum++) {\n\n // what if the $_POST doesn't exist? what is your default value\n //$questansw = $_POST['qora'.$yty];\n\n $key = \"qora{$questnum}\";\n $answers[$questnum] = isset($_POST[$key]) ? $_POST[$key] : NULL ; // assuming null is ok as a default?\n }\n\n return $answers;\n}\n\n\nfunction connectToDatabase() {\n $connect = new mysqli('localhost', 'root', '', 'test');\n\n if ($connect->connect_error) {\n // exit doesn't help anyone, at least let the user know there is a database error,\n // and perhaps log the error for your own use\n // exit;\n throw new Exception('Database Connection Error: ' . $connect->connect_error);\n }\n\n return $connect;\n}\n\n\nfunction getQuestionsAndAnswers($connect) {\n $questionArray = array();\n $answersArray = array();\n\n // is getStuff a really good description of what the variable is?\n // $getStuff = $connect->prepare('SELECT `question`, `answer` FROM `Quizzes` WHERE `questionNumber`<? ORDER BY `questionNumber` ASC');\n $stmt = $connect->prepare('SELECT `question`, `answer` FROM `Quizzes` WHERE `questionNumber`<? ORDER BY `questionNumber` ASC');\n\n // what no error checking?\n if (!$stmt) {\n throw new Exception(\"Database Error: {$connect->error}\");\n }\n\n // not quite sure why $questnum is a constant value, if so why bother having is as a bind param, it could go directly into the stmt\n $questnum = 21;\n\n $stmt->bind_param('i', $questnum);\n\n $stmt->execute();\n\n $stmt->bind_result($singleQuestion, $singleAnswer);\n\n\n while ($stmt->fetch()) {\n\n // array_push is great adding whole arrays, but a little overkill for single items, this is personal preference, not essential\n //array_push($questionArray, $singleQuestion);\n //array_push($answersArray, $singleAnswer);\n $questionArray[] = $singleQuestion;\n $answersArray[] = $singleAnswer;\n }\n $stmt->close();\n\n // are you sure you want to close the connection here, it is passed in as a param, what if it something else needs to use it after this function?\n // $connect->close();\n\n // i am not a big fan of returning multiple values like this, but I have no suggestion as I am not sure how you are using the values\n return array($questionArray, $answersArray);\n}\n\nfunction saveQuizAdministration($conn, $quizNumber) {\n $cookie = session_id();\n $ip = getUserIp();\n $score = 90;\n\n $stmt = $conn->prepare(\"INSERT INTO QuizAdministration (`quizNumber`, `cookie`, `ip`, `score`) VALUES (?, ?, ?, ?)\");\n\n // lets make things easier to read, name the variables the same as the columns\n // $stmt->bind_param('issi', $quizNumber, $playerCookie, $playerIP, $playersPercent);\n $stmt->bind_param('issi', $quizNumber, $cookie, $ip, $score);\n\n $stmt->execute();\n}\n\n\nfunction saveAnswers($connection, $quizAdministrationId, $answers) {\n $stmt = $connection->prepare(\"INSERT INTO PlayerAnswers (`QuizAdministrationId`, `questionNumber`, `playerAnswer`) VALUES (?, ?, ?)\");\n\n $questionNumber = NULL;\n $playerAnswer = NULL;\n\n // why not use the col names for variable names, then it would be a whole lot easier for me when I read the code for the first time\n $stmt->bind_param('iii', $quizAdministrationId, $questionNumber, $playerAnswer);\n\n // $yty is a cryptic variable name, what does it mean?\n // i have moved the loop into the function extractPostAnswers as it shouldn't be mixed with database code\n // for ($yty = 1; $yty < 21; $yty += 1) {\n foreach ($answers as $questionNumber => $playerAnswer) {\n\n // bind outside the for loop, that is whole point of binding to variables, the variables can change without needing to be re-binded\n // $stmt->bind_param('iii', $QuizAdministrationid, $questnum, $questansw);\n\n // we are re-assigning the same value over and over, put it outside the loop, outside the function even\n // $QuizAdministrationid = $maxId + 1;\n\n // assignment not required, use $questnum as the loop variable\n // $questnum = $yty;\n\n // if $questansw is null do we even want to execute the stmt? why store a null value\n $stmt->execute();\n }\n\n $stmt->close();\n}\n\n\nfunction selectMaxId($connection) {\n\n // whats the point of using prepared statements for a static statement that is being called once???\n $stmt = $connection->prepare(\"SELECT MAX(`id`) FROM QuizAdministration\");\n $stmt->execute();\n $stmt->bind_result($maxId);\n $stmt->fetch();\n $stmt->close();\n\n // if no row exists, $maxId = null, is that what you are expecting?\n\n return $maxId;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T02:52:56.290",
"Id": "44119",
"ParentId": "43740",
"Score": "6"
}
},
{
"body": "<p>This looks pretty good. I'm glad to see the improvement.</p>\n\n<p>You inexplicably call <code>$connect->bind_params()</code> using variables that have not yet been set.</p>\n\n<p>The main issue I see now is <code>$QuizAdministrationid = $maxId + 1</code>, which is prone to a race condition. If two users submit the form simultaneously, it's possible that both pages could see the same result from <code>SELECT MAX(id) …</code> and generate the same next <code>$QuizAdministrationid</code>.</p>\n\n<p>The solution is to ask the database to generate the next ID. Every SQL database supports this in a slightly different way. For MySQL, you should declare the <code>id</code> column of <code>QuizAdministration</code> to be <a href=\"http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id\" rel=\"nofollow noreferrer\"><code>AUTO_INCREMENT</code></a>. Then, leave <code>id</code> column unspecified when you do the <code>INSERT</code>. MySQL will automatically fill in the <code>id</code> column with the next available number. To find out what number MySQL picked for you, use <a href=\"https://stackoverflow.com/a/20696499/1157100\"><code>$connect->insert_id</code></a>.</p>\n\n<p>To make this work for you, you'll need to insert a row into <code>QuizAdministration</code> first, then use the <code>id</code> of the new row to insert the <code>PlayerAnswers</code>.</p>\n\n<pre><code>$stmt2 = $connect->prepare(\"INSERT INTO QuizAdministration (`quizNumber`, `cookie`, `ip`, `score`) VALUES (?, ?, ?, ?)\");\n$quizNumber = 1;\n$playerCookie = session_id();\n$playerIP = getUserIp();\n$playersPercent = 90;\n$stmt2->bind_param('issi', $quizNumber, $playerCookie, $playerIP, $playersPercent);\n$stmt2->execute();\n$stmt2->close();\n\n$quizAdministrationid = $connect->insert_id;\n\n$stmt3 = $connect->prepare(\"INSERT INTO PlayerAnswers (`QuizAdministrationId`, `questionNumber`, `playerAnswer`) VALUES (?, ?, ?)\");\nfor ($yty = 1; $yty <= 20; $yty += 1) {\n $questnum = $yty;\n $questansw = $_POST['qora'.$yty];\n $stmt3->bind_param('iii', $QuizAdministrationid, $questnum, $questansw);\n $stmt3->execute();\n}\n$stmt3->close();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T03:35:39.853",
"Id": "44120",
"ParentId": "43740",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "44120",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T20:29:20.337",
"Id": "43740",
"Score": "17",
"Tags": [
"php",
"beginner",
"security",
"mysqli"
],
"Title": "Prepared statements from security viewpoint"
} | 43740 |
<p>I guess I'm a little late with my entry to <a href="https://codereview.meta.stackexchange.com/questions/1201/cr-weekend-challenge">this code challenge mentioned here</a>, but I decided the world must need yet another RPSLS implementation to critique.</p>
<pre><code>#include <vector>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
/* Here are your rules:
"Scissors cuts paper,
paper covers rock,
rock crushes lizard,
lizard poisons Spock,
Spock smashes scissors,
scissors decapitate lizard,
lizard eats paper,
paper disproves Spock,
Spock vaporizes rock.
And as it always has, rock crushes scissors."
-- Dr. Sheldon Cooper */
class gesture {
size_t val;
static char const *names[5];
public:
gesture() : val(rand() % 5) {}
bool operator<(gesture const &other) const {
bool winners [5][5] = {
/* rock */ /* paper */ /* scissors */ /* lizard */ /* Spock */
/*rock*/ { false, true, false, false, true },
/*paper*/{ false, false, true, false, false },
/*scissors*/{ true, false, false, false, true },
/*Lizard */{ true, false, true, false, false },
/* spock */ { false, true, false, true, false }
};
return winners[val][other.val];
}
friend std::ostream &operator<<(std::ostream &os, std::pair<gesture, gesture> const &p) {
char const *titles [5][5] = {
/* rock */ /* paper */ /* scissors */ /* lizard */ /* Spock */
/*rock*/ { "ties", "covers", "crushes", "crushes", "vaporizes" },
/*paper*/ { "covers", "ties", "cuts", "eats", "disproves" },
/*scissors*/{ "crushes", "cuts", "ties", "decapitates", "smashes" },
/*Lizard */{ "crushes", "eats", "decapitates", "ties", "Poisons" },
/* spock */{ "vaporizes", "disproves", "smashes", "Poisons", "Ties" }
};
gesture const &a = std::max(p.first, p.second);
gesture const &b = std::min(p.first, p.second);
return os << a << " " << titles[a.val][b.val] << " " << b;
}
friend std::istream &operator>>(std::istream &is, gesture &g) {
char const **pos;
std::string user_choice;
do {
std::getline(std::cin, user_choice);
} while ((pos = std::find(std::begin(names), std::end(names), user_choice)) == std::end(names)
&& std::cout << "Unrecognized choice. Please re-enter: ");
g.val = pos - std::begin(names);
return is;
}
friend std::ostream &operator<<(std::ostream &os, gesture const &g) {
return std::cout << names[g.val];
}
};
char const *gesture::names[5] = { "rock", "paper", "scissors", "lizard", "Spock" };
int main() {
srand(time(NULL));
std::vector<size_t> scores(3);
std::string again;
do {
gesture user;
std::cout << "Choose your weapon: ";
std::cin >> user;
gesture computer;
std::cout << "user: " << user << "\tcomputer: " << computer << "\n";
std::cout << std::make_pair(user, computer) << "\n";
if (user < computer)
++scores[0];
else if (computer < user)
++scores[1];
else
++scores[2];
std::cout << "Score: Computer: " << scores[0] << "\tYou: " << scores[1] << "\tties: " << scores[2] << "\n";
std::cout << "Play again (y/n)?";
std::getline(std::cin, again);
} while (again == "y");
}
</code></pre>
<p>I <em>do</em> expect some real critiques here--this code definitely isn't perfect. :-)</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:20:51.360",
"Id": "75683",
"Score": "0",
"body": "Safe to assume you're not using C++11?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:24:20.717",
"Id": "75684",
"Score": "0",
"body": "@Jamal: I don't think it currently requires C++11, but suggestions to improve it that use C++11 are entirely welcome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:31:24.797",
"Id": "75686",
"Score": "0",
"body": "You're much more experienced than me, so I don't think I'll have anything new to add. Plus, the only thing that sticks out to me now, regarding C++11, is `NULL`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T12:03:15.597",
"Id": "77107",
"Score": "0",
"body": "Nitpick: `<ctime>` instead of `<time.h>`, same for stdlib"
}
] | [
{
"body": "<p>Not sure I like the use of <code>operator<</code> to test for a winner.</p>\n\n<pre><code>bool operator<(gesture const &other) const\n</code></pre>\n\n<p>Here</p>\n\n<pre><code> if (user < computer) \n ++scores[0]; \n else if (computer < user) \n ++scores[1]; \n else \n ++scores[2]; \n</code></pre>\n\n<p>I suppose it works but not that intuitive. I would have gone for a named method.</p>\n\n<p>Your data stores of constant data could also be static.</p>\n\n<pre><code>static bool winners [5][5] \n\nstatic char const *titles\n</code></pre>\n\n<p>I doubt it makes a difference. But semantically it reads better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T02:19:13.557",
"Id": "43764",
"ParentId": "43743",
"Score": "6"
}
},
{
"body": "<p>Running it through <code>g++</code> using <code>-Wall -Wextra</code> we see:</p>\n\n<blockquote>\n <p>rpsls.cpp:66:26: warning: unused parameter 'os' [-Wunused-parameter]<br>\n friend std::ostream &operator<<(std::ostream &os, gesture const &g) {</p>\n</blockquote>\n\n<p>Which is a bit of a \"whoopsie\":</p>\n\n<pre><code> friend std::ostream &operator<<(std::ostream &os, gesture const &g) {\n return std::cout << names[g.val];\n ^^^^^^^^\n // Should be os\n}\n</code></pre>\n\n<p>I'd prefer to use <code>std::array<std::string></code> over <code>char *</code> arrays, mainly because this way there's no mucking around with both <code>std::string</code> and <code>char *</code> (or <code>char **</code>):</p>\n\n<pre><code>const static std::array<std::string, 5> names;\n\nconst std::array<std::string, 5> gesture::names = { \"rock\", \"paper\", \"scissors\", \"lizard\", \"Spock\" };\n</code></pre>\n\n<p>This also changes <code>std::istream& operator>></code> a bit: you can either do the (verbose):</p>\n\n<pre><code>std::array<std::string, 5>::const_iterator pos;\n</code></pre>\n\n<p>Or if you're feeling a little bit lazy:</p>\n\n<pre><code>decltype(&names[0]) pos;\n</code></pre>\n\n<p>I agree with Loki that I'm not a big fan of using <code>operator<</code> to make a decision, and I'd rather make a named function (like <code>compare</code>). </p>\n\n<p>I think there's a bug: Lizard is supposed to eat paper, so this row:</p>\n\n<pre><code>/*paper*/ { false, false, true, false, false }\n</code></pre>\n\n<p>should probably be:</p>\n\n<pre><code>/*paper*/ { false, false, true, true, false }\n</code></pre>\n\n<p>I'm actually not a big fan of the 2D array of <code>bool</code> to decide on a winner. Sure, it's simple, but it's a bit of a pain to read. There's also a separation between <code>winners</code> and <code>titles</code> when they have the same structure, just different types. </p>\n\n<p>I'd change this to use an <code>enum class</code> for the outcome, and a combination of outcome and title for the result (these should probably be private to the <code>gesture</code> class):</p>\n\n<pre><code>enum class outcome { WIN, DRAW, LOSS };\n\nstruct result\n{\n outcome out;\n std::string title;\n};\n</code></pre>\n\n<p>(The naming of these is actually pretty poor, I admit, but I made sure my changes compile with this, and I can't be bothered changing them to something better now).\nWe can then define a map of possibilities, and exploit the fact that they are antisymmetric in win/loss: if A wins against B, then necessarily B loses against A. So we can cut down on the number of possibilities we need to cover (and also gives us less chance to make mistakes):</p>\n\n<pre><code>using string_pair = std::pair<std::string, std::string>;\nstatic std::map<string_pair, result> possibilities; \n\nstd::map<typename gesture::string_pair, result> gesture::possibilities = \n{\n {{\"rock\", \"paper\"}, {outcome::LOSS, \"covers\"}},\n {{\"rock\", \"scissors\"}, {outcome::WIN, \"crushes\"}},\n {{\"rock\", \"lizard\"}, {outcome::WIN, \"crushes\"}},\n {{\"rock\", \"Spock\"}, {outcome::LOSS, \"vaporizes\"}},\n {{\"paper\", \"scissors\"}, {outcome::LOSS, \"cuts\"}},\n {{\"paper\", \"lizard\"}, {outcome::LOSS, \"eats\"}},\n {{\"paper\", \"Spock\"}, {outcome::WIN, \"disproves\"}},\n {{\"scissors\", \"lizard\"}, {outcome::WIN, \"decapitate\"}},\n {{\"scissors\", \"Spock\"}, {outcome::LOSS, \"smash\"}},\n {{\"lizard\", \"Spock\"}, {outcome::WIN, \"poisons\"}}\n};\n</code></pre>\n\n<p>I'd rather a gesture had a <code>name</code> rather than a <code>val</code> that is tied to an array value:</p>\n\n<pre><code>class gesture {\n std::string name;\n const static std::array<std::string, 5> names;\n\n using string_pair = std::pair<std::string, std::string>;\n static std::map<string_pair, result> possibilities; \n\npublic:\n gesture() : name(names[rand() % names.size()]) { }\n explicit gesture(const std::string& nm) : name(nm) { }\n\n ...\n}\n</code></pre>\n\n<p>This makes the comparison function a bit more complex, but I think it's worth it:</p>\n\n<pre><code>result compare(gesture const& other) const {\n if (name == other.name) {\n return {outcome::DRAW, \"ties\"};\n }\n\n auto it = possibilities.find(std::make_pair(name, other.name));\n if(it == possibilities.end()) {\n // Wasn't in our map, so parameters must be in the opposite order\n auto res = possibilities[std::make_pair(other.name, name)];\n // Don't forget to invert the result\n return {(res.out == outcome::WIN ? outcome::LOSS : outcome::WIN),\n res.title};\n }\n return it->second;\n}\n</code></pre>\n\n<p><code>operator<<</code> also changes a bit:</p>\n\n<pre><code>friend std::ostream &operator<<(std::ostream &os, std::pair<gesture, gesture> const &p) {\n result r = (p.first).compare(p.second);\n if(r.out == outcome::WIN || r.out == outcome::DRAW) {\n return os << p.first << \" \" << r.title << \" \" << p.second;\n }\n return os << p.second << \" \" << r.title << \" \" << p.first;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T19:00:38.263",
"Id": "76346",
"Score": "0",
"body": "Lizards eat bugs too don't they?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:55:56.097",
"Id": "43775",
"ParentId": "43743",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "43775",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:08:25.447",
"Id": "43743",
"Score": "10",
"Tags": [
"c++",
"game",
"community-challenge",
"rock-paper-scissors"
],
"Title": "RPSLS yet again"
} | 43743 |
<p>My code works, but the aesthetic of the code seems to need some real work. The logic is simple enough: </p>
<ul>
<li>Create three lists of words that will be used throughout the conversion</li>
<li>Create three functions:
<ul>
<li>One for sub-1000 conversion</li>
<li>Another for 1000-and-up conversion</li>
<li>Another function for splitting and storing into a list of numbers above 1000.</li>
</ul></li>
</ul>
<p>First the code:</p>
<pre><code># Create the lists of word-equivalents from 1-19, then one for the tens group.
# Finally, a list of the (for lack of a better word) "zero-groups".
ByOne = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
]
ByTen = [
"zero",
"ten",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
]
zGroup = [
"",
"thousand",
"million",
"billion",
"trillion",
"quadrillion",
"quintillion",
"sextillion",
"septillion",
"octillion",
"nonillion",
"decillion",
"undecillion",
"duodecillion",
"tredecillion",
"quattuordecillion",
"sexdecillion",
"septendecillion",
"octodecillion",
"novemdecillion",
"vigintillion"
]
strNum = raw_input("Please enter an integer:\n>> ")
# A recursive function to get the word equivalent for numbers under 1000.
def subThousand(inputNum):
num = int(inputNum)
if 0 <= num <= 19:
return ByOne[num]
elif 20 <= num <= 99:
if inputNum[-1] == "0":
return ByTen[int(inputNum[0])]
else:
return ByTen[int(inputNum[0])] + "-" + ByOne[int(inputNum[1])]
elif 100 <= num <= 999:
rem = num % 100
dig = num / 100
if rem == 0:
return ByOne[dig] + " hundred"
else:
return ByOne[dig] + " hundred and " + subThousand(str(rem))
# A looping function to get the word equivalent for numbers above 1000
# by splitting a number by the thousands, storing them in a list, and
# calling subThousand on each of them, while appending the correct
# "zero-group".
def thousandUp(inputNum):
num = int(inputNum)
arrZero = splitByThousands(num)
lenArr = len(arrZero) - 1
resArr = []
for z in arrZero[::-1]:
wrd = subThousand(str(z)) + " "
zap = zGroup[lenArr] + ", "
if wrd == " ":
break
elif wrd == "zero ":
wrd, zap = "", ""
resArr.append(wrd + zap)
lenArr -= 1
res = "".join(resArr).strip()
if res[-1] == ",": res = res[:-1]
return res
# Function to return a list created from splitting a number above 1000.
def splitByThousands(inputNum):
num = int(inputNum)
arrThousands = []
while num != 0:
arrThousands.append(num % 1000)
num /= 1000
return arrThousands
### Last part is pretty much just the output.
intNum = int(strNum)
if intNum < 0:
print "Minus",
intNum *= -1
strNum = strNum[1:]
if intNum < 1000:
print subThousand(strNum)
else:
print thousandUp(strNum)
</code></pre>
<p><strong>Sample run:</strong></p>
<pre><code>>>>
Please enter an integer:
>> 95505896639631893
ninety-five quadrillion, five hundred and five trillion, eight hundred and ninety-six billion, six hundred and thirty-nine million, six hundred and thirty-one thousand, eight hundred and ninety-three
>>>
</code></pre>
<p><strong>Issues:</strong></p>
<p>Basically, the peeves I'm having are as follows:</p>
<ul>
<li>My first two functions seems to be taking up too many lines. The first one, <code>subThousand</code>, seems to be this way because of the check made against the last digit of a number from 20 to 99. The logic I applied was, if it ends in <code>0</code>, use the <code>ByTen</code> list. If it doesn't combined <code>ByTen</code> and <code>ByOne</code>. While effective, I feel like it could use some real work since I think it qualifies as a DRY-violation. Even the final part checking for numbers from 100 to 999 seems to follow the same pattern. Alas, I've tried paring it down but I've honestly hit a roadblock on this one insofar as trying to come up with a creative and clean solution.</li>
<li><p>My second function, <code>thousandUp</code> is quite the disaster. I tried coming up with a looping function that creates a list of one to three-digit numbers, so that I can call <code>subThousand</code> on each of them from the front to the back (hence the <code>arrZero[::-1]</code>. At the same time, after converting each element in the list to a word, I concatenate it with the appropriate equivalent in the <code>zGroup</code> list, or the list of the "zero-groups". However, I personally can't find a safer and more precise way of landing on the "correct" spot in the <code>zGroup</code> list to start concatenating.</p>
<p>To get around this, I took the length of the <code>splitByThousands</code> array, adjusted for <code>0</code>-index, and used it to get the appropriate "zero-append" (<code>zap</code>). Before the loop ends, I subtract one from its current value so that it's adjusted accordingly.</p></li>
<li><p><em>In addition</em>, as I'm attempting to make the output as clean as possible, I add a <code>" "</code> to the <code>wrd</code> variable so it doesn't concatenate poorly with the zero-append, as well as add a <code>", "</code> to the zero-append to separate it from the next zero-group. However, there will be instances that there are no values for some zero-groups. To avoid showing stuff like <code>zero million</code>, I added a check inside. This is the part that makes me die a little inside:</p>
<pre><code>for z in arrZero[::-1]:
wrd = subThousand(str(z)) + " "
zap = zGroup[lenArr] + ", "
if wrd == " ":
break
elif wrd == "zero ":
wrd, zap = "", ""
resArr.append(wrd + zap)
lenArr -= 1
</code></pre></li>
</ul>
<p>It works, but it just doesn't look good. Is it possible to do this in list-comprehension form or a better for-loop without turning it into more confusing mush?</p>
<p>I must admit as well that the last part of the code sucks a little. I've done a lot of <code>str-->int</code> conversions inside the functions, then I did one more <em>outside</em> of them. On top of that, my approach to negative numbers is <em>hackish</em> at best (<code>print "Minus"</code>).</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:06:53.493",
"Id": "80773",
"Score": "0",
"body": "I recently tried the same task, but took a different approach. I wonder how you think it compares. Yours looks more sophisticated, ive not quite got to grips with the logic yet, but i am going ot try to.http://codereview.stackexchange.com/questions/46273/numbers-to-text-program-python-training?noredirect=1#comment80769_46273"
}
] | [
{
"body": "<p>A couple of thoughts:</p>\n\n<ul>\n<li>You only want to output <code>zero</code> in the special case when the number is 0. It would be easiest to handle that special case at the outermost level.</li>\n<li>Use <code>\" and \".join</code> and <code>\", \".join</code> to construct strings from parts. The delimiter will be automatically left out when there are less than two parts.</li>\n</ul>\n\n<p>Here's how I would rewrite <code>subThousand</code> as two functions:</p>\n\n<pre><code>def subThousand(inputNum):\n \"\"\"Convert a number < 1000 to words, and 0 to the empty string\n \"\"\"\n num = int(inputNum) #this should be done at higher level\n hundreds, ones = divmod(num, 100)\n\n parts = []\n if hundreds:\n parts.append(ByOne[hundreds] + \" hundred\")\n if ones:\n parts.append(subHundred(ones))\n\n return \" and \".join(parts)\n\ndef subHundred(num):\n \"\"\"Convert a number < 100 to words, and 0 to the empty string\n \"\"\"\n if num >= 20:\n tens, ones = divmod(num, 10)\n else:\n tens, ones = 0, num\n\n parts = []\n if tens:\n parts.append(ByTen[tens])\n if ones:\n parts.append(ByOne[ones])\n\n return \"-\".join(parts)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:04:31.990",
"Id": "75757",
"Score": "0",
"body": "+1: Amazing modification! I think missing `divmod` and failing to realize it exists within Python seems to be a glaring issue. In C, I pretty much use the logic I used in my original code, hence carrying it over here as well. Also, love the use of the `\" and \".join` -- it's so smart I tear up looking at it right now. Thanks a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:54:56.580",
"Id": "43755",
"ParentId": "43744",
"Score": "5"
}
},
{
"body": "<p>Try to extract the different pieces of logic in functions to make things clearer. In your case, you have defined little functions but the place where you are using them is a bit in the middle of nowhere.</p>\n\n<p>Here's what you could do :</p>\n\n<pre><code>def get_number_as_words(strNum):\n intNum = int(strNum)\n if intNum < 0:\n print \"Minus\", # I didn't see this at the beginning but I'll fix it at the end\n intNum *= -1\n strNum = strNum[1:]\n\n if intNum < 1000:\n return subThousand(strNum)\n else:\n return thousandUp(strNum)\n</code></pre>\n\n<p>Also, all these functions should be properly documented using <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstrings</a>.</p>\n\n<hr>\n\n<p>If your code can potentially be used as a module, it is advised to put the part which actually does stuff in a function and guard the call to this function behind a <a href=\"http://docs.python.org/3.2/library/__main__.html\" rel=\"noreferrer\"><code>if __name__ == \"__main__\":</code></a> condition.\nIn your case, here's what I have :</p>\n\n<pre><code>def main():\n strNum = '95505896639631893' #raw_input(\"Please enter an integer:\\n>> \")\n expected='ninety-five quadrillion, five hundred and five trillion, eight hundred and ninety-six billion, six hundred and thirty-nine million, six hundred and thirty-one thousand, eight hundred and ninety-three '\n print(get_number_as_words(strNum))\n print(expected)\n assert(get_number_as_words(strNum)==expected)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>As I am messing around with your code, I use <code>assert</code> to detect quickly if I break the test case you have provided. Also, it shows something that we might want to fix on the long run : the trailing whitespace.</p>\n\n<hr>\n\n<p><strong>subThousand</strong>: You can use <a href=\"http://docs.python.org/3.3/library/functions.html#divmod\" rel=\"noreferrer\">divmod</a> to divide integers and get the quotient and the remainder.</p>\n\n<hr>\n\n<p><strong>subThousand</strong>: In successive <code>if</code>, <code>else if</code>, <code>else if</code>, etc, you do not need to check the same condition multiple times. Also, you can use <code>assert</code> to check that your function is used on proper values (described in the documentation).</p>\n\n<hr>\n\n<p><strong>subThousand</strong>: This function (and it might be the case for the others as well but I have to progress one function at a time) should probably be fed an integer and not a string. Operation on numbers should be enough for pretty much everything.</p>\n\n<hr>\n\n<p><strong>subThousand</strong>: You can use implicit evaluation of integers as boolean : <code>0</code> is <code>False</code>, anything else is <code>True</code>. </p>\n\n<hr>\n\n<p><strong>subThousand</strong>: As explained in Janne Karila's comment, it might be worth returning an empty string when the input is 0.</p>\n\n<p>After taking into account the comments (except the last), the function looks like :</p>\n\n<pre><code>def subThousand(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n <= 999)\n if n <= 19:\n return ByOne[n]\n elif n <= 99:\n q, r = divmod(n, 10)\n return ByTen[q] + (\"-\" + subThousand(r) if r else \"\")\n else:\n q, r = divmod(n, 100)\n return ByOne[q] + \" hundred\" + (\" and \" + subThousand(r) if r else \"\")\n</code></pre>\n\n<p>I am a big fan of the ternary operator but it's purely personal. Also I used a recursive call to make things more consistent.</p>\n\n<hr>\n\n<p><strong>splitByThousands</strong>: By taking into account previous comments (types, divmode, etc), you can already get something more concise :</p>\n\n<pre><code>def splitByThousands(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n) \n res = []\n while n:\n n, r = divmod(n, 1000)\n res.append(r)\n return res\n</code></pre>\n\n<hr>\n\n<p><strong>thousandUp</strong>: The same comments are still relevant.</p>\n\n<hr>\n\n<p><strong>thousandUp</strong>: We maintain one list <code>resArr</code> and a number <code>lenArr</code> through the function but we can see that the property <code>lenArr + len(resArr) + 1 == len(arrZero)</code> is (almost) always true. One can easily get convinced of this or add <code>assert(lenArr + len(resArr) + 1 == len(arrZero))</code> everywhere. Thus <code>lenArr = len(arrZero) - len(resArr) - 1</code>.</p>\n\n<hr>\n\n<p><strong>thousandUp</strong>: The block </p>\n\n<pre><code> wrd = subThousand(z) + \" \"\n zap = zGroup[len(arrZero) - len(resArr) - 1] + \", \"\n if wrd == \" \":\n break\n elif wrd == \"zero \":\n wrd, zap = \"\", \"\"\n resArr.append(wrd + zap)\n</code></pre>\n\n<p>can be simplified a lot :</p>\n\n<ol>\n<li>there is not point in adding a whitespace to <code>wrd</code> at this stage.</li>\n<li>you do not need to use <code>zGroup</code> in all cases.</li>\n<li>as <code>subThousand(X)</code> is \"zero\" only if <code>X==0</code>, <code>wrd == \"zero\"</code> becomes <code>z == 0</code></li>\n<li>as <code>subThousand(X)</code> is never an empty string, this test has no reason to be there. (If you ever perform the change described above, <code>subThousand(X)</code> will be empty when <code>X==0</code> which is a case already handled).</li>\n</ol>\n\n<p>Thus the block becomes :</p>\n\n<pre><code> if z:\n wrd = subThousand(z)\n zap = zGroup[len(arrZero) - len(resArr) - 1] + \", \"\n else:\n wrd, zap = \"\", \"\"\n resArr.append(wrd + \" \" + zap)\n</code></pre>\n\n<p>which can then be rewritten :</p>\n\n<pre><code> if z:\n wrd_zap = subThousand(z) + \" \" + zGroup[len(arrZero) - len(resArr) - 1] + \", \"\n else:\n wrd_zap = \" \"\n resArr.append(wrd_zap)\n</code></pre>\n\n<p>Then, because there is not point in adding spaces because all elements of the array already end with a space, we can do :</p>\n\n<pre><code> if z:\n wrd_zap = subThousand(z) + \" \" + zGroup[len(arrZero) - len(resArr) - 1] + \", \"\n else:\n wrd_zap = \"\"\n resArr.append(wrd_zap)\n</code></pre>\n\n<hr>\n\n<p><strong>thousandUp</strong>: Once the code is simplified, we realise that as described in Janne Karila's comment, we could use <code>\", \"</code> to call <code>join()</code>, killing many birds with one stone :</p>\n\n<ul>\n<li>the hack to remove the trailing comma is not required anymore</li>\n<li>the trailing whitespace also disappears (this is a nice side-effect as the <code>strip()</code> now performs what is was supposed to do in the first place but was then prevented by the commas)</li>\n<li>everything becomes easier</li>\n</ul>\n\n<p>We now have :</p>\n\n<pre><code>for z in arrZero[::-1]:\n resArr.append(subThousand(z) + \" \" + zGroup[len(arrZero) - len(resArr) - 1] if z else \"\")\nreturn \", \".join(resArr).strip()\n</code></pre>\n\n<hr>\n\n<p><strong>thousandUp</strong>: Something that wasn't obvious at first but starts to be : for each element in <code>arrZero</code>, we add an element in <code>resArr</code> so that <code>len(arrZero) - len(resArr) - 1</code> goes from <code>len(arrZero)-1</code> to <code>0</code>. It looks like we could achieve this with <code>enumerate()</code>. We <a href=\"http://christophe-simonis-at-tiny.blogspot.fr/2008/08/python-reverse-enumerate.html\" rel=\"noreferrer\">could do it in a complicated way</a> but let's keep things simple instead : let's iterate in the obvious order and call <code>reversed</code> at the very end when joining.</p>\n\n<pre><code>resArr = []\nfor i,z in enumerate(arrZero):\n resArr.append(subThousand(z) + \" \" + zGroup[i] if z else \"\")\nreturn \", \".join(reversed(resArr))\n</code></pre>\n\n<p>But he, what do we have here ?! A typical list comprehension</p>\n\n<pre><code>def thousandUp(n):\n assert(isinstance(n,(int, long)))\n return \", \".join(reversed([subThousand(z) + \" \" + zGroup[i] if z else \"\" for i,z in enumerate(splitByThousands(n))]))\n</code></pre>\n\n<p><em>Oops, I might have gone too far</em> . Actually, we can go even further to handle the trailing whitespaces in a smart way :</p>\n\n<pre><code>def thousandUp(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n)\n return \", \".join(reversed([subThousand(z) + (\" \" + zGroup[i] if i else \"\") if z else \"\" for i,z in enumerate(splitByThousands(n))]))\n</code></pre>\n\n<p>I have kept this mistake for too long to fix the whole answer but :</p>\n\n<pre><code>def thousandUp(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n)\n return \", \".join(reversed([subThousand(z) + (\" \" + zGroup[i] if i else \"\") for i,z in enumerate(splitByThousands(n)) if z]))\n</code></pre>\n\n<p>is probably a better version (we don't get repetitions of the separator).</p>\n\n<hr>\n\n<p><strong>get_number_as_words</strong>: Finally, this should also take an integer as a parameter. Also, it is probably the right place to handle 0 as a special value. Morehover, <code>thousandUp()</code> handles properly inputs smaller than 1000.</p>\n\n<hr>\n\n<p>At the end, here's what my code is like :</p>\n\n<pre><code>def subThousand(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n <= 999)\n if n <= 19:\n return ByOne[n]\n elif n <= 99:\n q, r = divmod(n, 10)\n return ByTen[q] + (\"-\" + subThousand(r) if r else \"\")\n else:\n q, r = divmod(n, 100)\n return ByOne[q] + \" hundred\" + (\" and \" + subThousand(r) if r else \"\")\n\ndef thousandUp(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n)\n return \", \".join(reversed([subThousand(z) + (\" \" + zGroup[i] if i else \"\") if z else \"\" for i,z in enumerate(splitByThousands(n))]))\n\ndef splitByThousands(n):\n assert(isinstance(n,(int, long)))\n assert(0 <= n) \n res = []\n while n:\n n, r = divmod(n, 1000)\n res.append(r)\n return res\n\ndef get_number_as_words(n):\n assert(isinstance(n,(int, long)))\n if n==0:\n return \"Zero\"\n return (\"Minus \" if n < 0 else \"\") + thousandUp(abs(n))\n\ndef main():\n n = 95505896639631893 # int(raw_input(\"Please enter an integer:\\n>> \"))\n expected='ninety-five quadrillion, five hundred and five trillion, eight hundred and ninety-six billion, six hundred and thirty-nine million, six hundred and thirty-one thousand, eight hundred and ninety-three'\n print(get_number_as_words(n))\n print(expected)\n assert(get_number_as_words(n)==expected)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>I hope you will find it more pleasing and that my comments will help you. Also, despite the big number of comments, your initial code was pretty good.</p>\n\n<p><em>Disclaimer : I have done everything only based on your example (which was enough to spot mistakes as I was writing them). I might have missed a few things or done a few things wrong so I have tried to detail the different steps as much as possible just in case.</em></p>\n\n<p><strong>Edit</strong> I just thought that you could change <code>splitByThousands</code> to make it <code>yield</code> values instead of returning a list...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:08:39.600",
"Id": "75758",
"Score": "0",
"body": "+1: Marking and accepting this as answer. The sheet amount of standards and practices displayed here is invaluable. I will read this forensics work slowly and will be documenting part-by-part responses in my original post, all while improving my code. Also, suddenly, list comprehension looks a *little* too intimidating. I'll be weighing whether I go for readability or for conformity on that end. Off the top, though, thanks for the doctstrings suggestion. I'm reading up on it now. Very excited to apply the practices in your post soon! Thanks a lot, Josay. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T02:15:48.420",
"Id": "43763",
"ParentId": "43744",
"Score": "6"
}
},
{
"body": "<p>This is probably the best code i could design, it supports numbers upto 1 googol that is 10^100, it consumes 56 lines after removing all line gaps</p>\n<p>Here is the code:</p>\n<pre><code>print("Number To Words Converter:\\n\\n")\ny=int(input("Enter Number: "))\nx=str(y)# To remove unnecessary zeroes before the user initialized number\nprint("\\n")\n\n# For defining the range of the programme to limit user inputs\nimport sys\nif int(x)>10**100 or int(x)<0:sys.exit("Range Is From Zero To One Googol!")\n\ndef num1wrd(x):# For converting a number to words from 0 to 99\n w={0:"",1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"}\n f={2:"Twen",3:"Thir",4:"For",5:"Fif",6:"Six",7:"Seven",8:"Eigh",9:"Nine"}\n t={11:"Eleven",12:"Twelve",13:"Thirteen",14:"Fourteen",15:"Fifteen",16:"Sixteen",17:"Seventeen",18:"Eighteen",19:"Nineteen"}\n if len(x)==1:return(w[int(x)])\n elif len(x)==2 and x[0]=="0" and x[1]=="0":return("")\n elif len(x)==2 and x[0]=="0":return (w[int(x[1])])\n elif len(x)==2:\n if int(x) in range(11,20):return(t[int(x)])\n elif int(x[1])==0:\n if int(x)==10:return("Ten")\n else:return(f[int(x[0])]+"ty")\n else:return(f[int(x[0])]+"ty"+"-"+w[int(x[1])])\n\ndef hun_num(x):# For further conversion till 999\n w1={0:"",1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"}\n if len(x)==3 and x[0]!="0" and x[1]=="0" and x[2]=="0":\n return(w1[int(x[0])]+" "+"Hundred")\n elif len(x)==3 and x[0]!="0":\n a1=(x[1]+x[2])\n return(w1[int(x[0])]+" "+"Hundred "+"and "+num1wrd(a1))\n elif len(x)==3 and x[0]=="0":return(num1wrd(x[1]+x[2]))\n else:return(num1wrd(x))\ndef seg3(s):# segregating the input number in groups of 3 in a list\n out = []\n while len(s):\n out.insert(0, s[-3:])\n s = s[:-3]\n return out\n\ndef q(x):# manipulating the presence of zeroes and inturn leading to further modifications such as for 1000000 removing the other words preceding it\n if x=="000":return(0)\n elif x=="00":return(0)\n elif x=="0":return(0)\n else:return(1)\nv=seg3(x)# segregating in groups of 3 as explained in the recursion part and after that forming a list \naa={0:"",1:"Thousand",2:"Million",3:"Billion",4:"Trillion",5:"Quadrillion",6:"Quintillion",7:"Hextillion",8:"Septillion",9:"Octillion",10:"Nonillion",11:"Decillion",12:"Undecillion",13:"Duodecillion",15:"Quattuordecillion",16:"Quindecillion",17:"Hexdecillion",18:"Septdecillion",19:"Octodecillion",20:"Novemdecillion",21:"Vigintillion",14:"Tredecillion",22:"Unvigintillion",23:"Duovigintillion",24:"Trevigintillion",25:"Quattuorvigintillion",26:"Quinvigintillion",27:"Hexvigintillion",28:"Septvigintillion",29:"Octovigintillion",30:"Novemvigintillion",31:"Trigintillion",32:"Untrigintillion",33:"Duotrigintillion"}\ndef sr(x):# This function removes unwanted spaces by reversing the main string though slicing (lower limit is the index of "," +1) and again reverse slicing the required string.\n\n a=x[::-1]\n m=a[a.index(",")+1:]\n if m.index(" ")==0:\n s2=m[1:]\n s=s2[::-1]\n else:s=m[::-1]\n return s\nif int(x)==10**100: s="One Googol"\nelif int(x)==0: s="Zero"\nelse:\n s1=""\n # Looping the word manipulation of each character of the element in list v\n for i in range(len(v)):s1=s1+(hun_num(v[i]))+(" "+aa[len(v)-1-i]+", ")*q(v[i])\n s=sr(s1)# For removing unwanted spaces from the result \nprint("》 "+s+".")# applying "》" and full stop to make the result look neat.\n</code></pre>\n<p>This code is better because it is:</p>\n<p>▪Properly explained(see commented statements) and easy to understand.</p>\n<p>▪Tested over a thousand times from random inputs.</p>\n<p>▪Fully functional with no errors.</p>\n<p>▪Bigger range than other codes available (also consuming only 56 lines).</p>\n<p>Main Logic:</p>\n<p>》The input is accepted as a string.</p>\n<p>》It is then split into groups of 3 by slicing.</p>\n<p>》It is then put inside a loop in which each element of the sliced string is passed through a function which supports conversion upto 3 characters each.</p>\n<p>》Assignment of positional names(eg: million, billion) is also done by the same loop which a dictionary's(contains position names with numbers from 1 to 33 as their key values) key values are matched with the iteration value and added(Concatenated) with the progressing string(comprising of the words of the number).</p>\n<p>*NOTE: Additional logics for making the words of the number readable are provided as comments (beside the functions).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:46:30.487",
"Id": "492807",
"Score": "1",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:35:41.737",
"Id": "492812",
"Score": "0",
"body": "I have corrected my mistake so please remove the downvote"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:37:26.567",
"Id": "492813",
"Score": "0",
"body": "You still are not referencing the original code in your answer. It's much easier to follow your thoughts if you quote the original code and directly compare it with your improved version. I also don't think `eval(input(...))` is an acceptable way to read a number input from a user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:40:50.230",
"Id": "492815",
"Score": "0",
"body": "Yes, try it out yourself, (else the code won't work fully for any other data type like \"int\" as it supports upto the upper limit i.e. one googol) for example if the user inputs any arbitrary number of zeroes before the original number then this step will ignore those zeroes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:54:06.230",
"Id": "492834",
"Score": "2",
"body": "@AbhradeepDey If OP wanted this wouldn't he go to [github](https://github.com) and searched for the same problem and copy-pasted? No, instead he wanted a review of his code and possible improvements. If you think your code is better you need to give proper contrast between the two and explain it properly"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:10:54.333",
"Id": "250591",
"ParentId": "43744",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": "43763",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:12:47.463",
"Id": "43744",
"Score": "9",
"Tags": [
"python",
"converting",
"numbers-to-words"
],
"Title": "Number-to-word converter"
} | 43744 |
<p>I've got the following Elixir code:</p>
<pre><code>defmodule Envvar do
def exists?(env) do :os.getenv(env) != false end
def get(env) do
if exists?(env) do
{env, :os.getenv(env)}
else
{env, nil}
end
end
end
</code></pre>
<p>Two things:</p>
<ol>
<li>Am I using the <code>?</code> correctly here? I'm assuming that any predicate function should have the <code>?</code> on the end of the name by convention.</li>
<li>Is there a way to code the <em>get</em> function as a pattern match rather than a <code>if</code>/<code>else</code>? I'm asking here because I'm guessing that a pattern match would be more idiomatic Elixir code.</li>
</ol>
| [] | [
{
"body": "<p>Using the ? for a boolean predicate is fine. At least it is what I would do in\nRuby and Elixir.</p>\n\n<p>You won't be able to call exists?(env) in a guard clause so pattern matching does not win you much here.</p>\n\n<p>You are calling :os.getenv() twice unneccessarily. \nI'm not sure why you just want to convert 'false' to 'nil', here is a way:</p>\n\n<pre><code>defmodule Envvar do\n def get(env)\n do_get(:os.getenv(env))\n end\n\n defp do_get(false)\n {:env, nil}\n end\n\n defp do_get(result)\n {:env,result}\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:49:07.700",
"Id": "75689",
"Score": "0",
"body": "That's an interesting take on the pattern matching that I was looking for. Definitely seems a bit more idiomatic to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T22:00:49.507",
"Id": "75693",
"Score": "0",
"body": "By the way, I want the exists? function as a separate function--I would have done a _defp_ if I didn't want to expose it outside of the module. So I'm not really calling :os.getenv() twice unnecessarily."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T11:40:15.670",
"Id": "108388",
"Score": "0",
"body": "@OnorioCatenacci - actually in this solution calling `get` _without_ calling `exists?` will call `:os.getenv()` _less_ than with calling `exists?`. No matter if `env` exists or not - `:os.getenv()` is called exactly once."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:43:18.273",
"Id": "43753",
"ParentId": "43747",
"Score": "6"
}
},
{
"body": "<p>Is it necessary to return nil or is false enough? They both evaluate to false when using boolean operators.</p>\n\n<p>If false is good enough:</p>\n\n<pre><code>defmodule Envvar do\n def get(env) do\n {:env, :os.getenv(env)}\n end\nend\n</code></pre>\n\n<p>If the return value has to be nil, I would just convert the second element and leave the first one intact.</p>\n\n<pre><code>defmodule Envvar do\n def get(env) do\n {:env, false_to_nil(:os.getenv(env)) }\n end\n\n defp false_to_nil(false) do\n nil\n end\n\n defp false_to_nil(v) do\n v\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-12T11:05:05.847",
"Id": "73442",
"ParentId": "43747",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43753",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:20:42.523",
"Id": "43747",
"Score": "5",
"Tags": [
"functional-programming",
"error-handling",
"elixir"
],
"Title": "Fetching environment variables — can I use pattern matching?"
} | 43747 |
<p>Here's an attempt I've made of implementing the <a href="http://en.wikipedia.org/wiki/Barnes-Hut_simulation" rel="nofollow">Barnes-Hut</a> <a href="http://en.wikipedia.org/wiki/N-body_simulation" rel="nofollow">n-body</a> algorithm, or its initial stage - The quadtree. That there're lots of lengthy doc strings might excuse the lack of detailed explanation here.</p>
<p>My primary concerns as a beginner are to</p>
<ol>
<li>Avoid complexity</li>
<li>Avoid library imports</li>
<li>Make fast and short code whenever possible.</li>
</ol>
<p>Being said that, I think the code is bulky (and 'unpythonic'?). Advice me on how to improve it in terms of speed, design pattern and readability. Is functional programming even suitable here?</p>
<p><strong>Summary of the code</strong></p>
<ol>
<li>Every node and body is identified by a global ID.</li>
<li>A body is added to the quadtree by registering its mass, position and velocity. It is assigned an ID (called bid).</li>
<li>A node is made by specifying the South-West vertex and box length (an ID is issued here too - called nid).</li>
<li><code>updatecom</code> is called for updating the quadtree's (or individual nodes') centre of mass.</li>
<li><code>walk</code> is called throughout the script for navigating the quadtree.</li>
<li>Accelerating the bodies, updating position for each time-frame and plotting are yet to be established.</li>
</ol>
<p>The docstrings are what makes the code lengthy which otherwise would be short. Since there're no special areas to which attention needs to be drawn, I've added the complete code here.</p>
<pre><code>"""Quadtree construction module.
ESSENTIAL TERMINOLOGY
a. Quadtree : A tree structure with four quadrants that are
coplanar. Quadrants are named SW, NW, NE and SE as
in compass directions, and are usually adressed in
the same order.
b. Node : Same as a quadrant; it can be internal or external.
c. Internal Node : A node that has child nodes inside. It contains no
bodies since they are distributed among the child
nodes.
d. External Node : A node that doesn't have child nodes inside. It
contains a body.
e. Empty Node : A node which has neither child nodes nor a body
inside it.
f. Root Node : The topmost node (parent) of all nodes.
g. Occupant : A body bound within a node (lowest host node).
h. nid : Node ID
i. bid : Body ID
j. Centre of mass : The weighted average of mass distribution.
X = (m1x1+m2x2+...mnxn) / (m1+m2+...mn)
This must be replaced with centre of gravity if the
bodies are non-uniform mass distributions, unlike a
point object.
"""
from __future__ import division
# Dictionaries to map body parameters
masses = {}
positions = {}
velocities = {}
# Dictionaries to map node parameters
lengths = {0: None}
vertices = {0: None}
occupants = {0: None}
childnodes = {0: []}
totalmasses = {0: 0}
centremasses = {0: None}
# Global ID counter starts with 1 (0 is dedicated for root node)
ID = 1
def newid(reset=False):
"""newid(reset=False)
Returns an unused ID of type 'int'. Consequtive integers starting from one
are returned avoiding repetition.
If optional argument 'reset' is True, ID counter restarts from one. Those
IDs which aren't active anymore can be retrieved by this manner.
"""
global ID
if reset:
ID = 1
while any(ID in maps for maps in (masses, childnodes)):
ID += 1
return ID
def initiate(vertex, length):
"""initiate(vertex, length)
Initiates the quadtree by specifying the SW vertex and side length.
"""
lengths[0] = length
vertices[0] = vertex
def isexternal(node):
"""isexternal(node)
Returns True if the node is external.
"""
if occupants[node]:
return True
def isinternal(node):
"""isinternal(node)
Returns True if the node is internal.
"""
if childnodes[node]:
return True
def isempty(node):
"""isempty(node)
Returns True if the node is empty.
"""
if (not occupants[node]) and (not childnodes[node]):
return True
def addbody(mass, position, velocity, bid=None):
"""addbody(mass, position, velocity, bid=None)
Adds a body to the quadtree.
'mass' must be a positive quantity of type 'int' or 'float'.
'position' must be a tuple or list of two values representing the two
dimensional position coordinates: (x, y).
'velocity' must be a tuple or list of two values representing the two
dimensional velocity coordinates: (vx, vy).
Optional argument bid, if specified, must be unique (auto-generated
otherwise).
"""
if not bid or bid in masses:
bid = newid()
masses[bid] = mass
positions[bid] = position
velocities[bid] = velocity
attach(bid)
def canfit(body, node):
"""canfit(body, node)
Checks wheather the body could be accomodated inside the node. Returns
suitable status mesages;
a. EXTERNAL : Can't fit because there is another body inside.
b. INTERNAL : Can't fit because this node has child nodes.
c. EMPTY : Can fit (yay!)
d. None : Can't fit at all (out of bounds).
"""
bx, by = positions[body]
nx, ny = vertices[node]
l = lengths[node]
if (0<=bx-nx<=l) and (0<=by-ny<=l):
if isexternal(node):
return 'EXTERNAL'
if isinternal(node):
return 'INTERNAL'
return 'EMPTY'
def split(node, rearrange=True):
"""split(node, rearrange=True)
Splits the given node (external or empty) and divides it in to four
quadrants (internal).
If 'rearrange' is True, the body (if any) contained within this node will
be redistributed to its appropriate childnode and thereby will get detached
from the node itself.
"""
nx, ny = vertices[node]
h = lengths[node] / 2
hx, hy = nx + h, ny + h
for vertex in ((nx,ny), (nx,hy), (hx,hy), (hx,ny)):
nid = newid()
lengths[nid] = h
vertices[nid] = vertex
occupants[nid] = None
childnodes[nid] = []
totalmasses[nid] = 0
centremasses[nid] = None
childnodes[node].append(nid)
# Detach the body, distribute it to a child node.
if rearrange:
body = occupants[node]
occupants[node] = None
for child in childnodes[node]:
if attach(body, child):
break
def attach(body, node=0):
"""attach(body, node=0)
Attaches body to its host node and returns True upon success.
Note: If recursion is initiated, and two bodies happens to be so close to
each other, it could take considerable depth until both the bodies are
individually distributed.
"""
for nid in walk(node):
status = canfit(body, nid)
if status == 'EMPTY':
occupants[nid] = body
return True
elif status == 'EXTERNAL':
split(nid)
for child in childnodes[nid]:
if attach(body, child):
return True
def walk(top=0, topdown=True, gettop=True):
"""walk(top=0, topdown=True, gettop=True)
Walks through the quadtree generating nids.
If 'top' is not specified, the generator will walk through the entire
quadtree (only top node otherwise).
If 'topdown' is True, parent nodes will be generated before child nodes.
Otherwise, child nodes will be generated before all their parents are. eg:
parent : child nodes
0 : 1, 2, 3, 4
3 : 5, 6, 7, 8
4 : 9, 10, 11, 12
7 : 13, 14, 15, 16
topdown mode - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
bottomup mode - 1, 2, 5, 6, 13, 14, 15, 16, 7, 8, 3, 9, 10, 11, 12, 4, 0
if optional argument 'gettop' is False, the top node will not be yielded.
"""
if topdown:
if gettop:
yield top
# Holding a queue list is memory inefficient, needs workaround.
queue = list(childnodes[top])
for child in queue:
yield child
queue.extend(childnodes[child])
# This part is recursive.
else:
for child in childnodes[top]:
for node in walk(child, topdown, gettop=True):
yield node
if gettop:
yield top
def updatecom(node=0):
"""updatecom(node=0)
Updates centre of mass of the node and its childnodes if any.
If optional argument 'node' is not provided, the entire quadtree's centre
of mass will be updated.
"""
for nid in walk(node, topdown=False):
# Empty node, reset to None
if isempty(nid):
totalmasses[nid] = 0
centremasses[nid] = None
# External node, com is where the body is.
if isexternal(nid):
body = occupants[nid]
totalmasses[nid] = masses[body]
centremasses[nid] = positions[body]
# Internal node, add children's com to parent.
elif isinternal(nid):
tmass, comx, comy = 0, None, None
for child in childnodes[nid]:
if isinternal(child) or isexternal(child):
ccomx, ccomy = centremasses[child]
ctmass = totalmasses[child]
if comx is None:
tmass, comx, comy = ctmass, ccomx, ccomy
continue
comx += ccomx*ctmass
comy += ccomy*ctmass
tmass += ctmass
totalmasses[nid] = tmass
centremasses[nid] = (comx/tmass, comy/tmass)
def distance(pointA, pointB):
"""distance(pointA, pointB)
Calculates the distance between two points and returns a tuple of
(dx, dy, r); where r is the radial separation, dx and dy are the axial
separation.
"""
ax, ay = pointA
bx, by = pointB
dx, dy = ax - bx, ay - by
r = (dx*dx+dy*dy)**0.5
return dx, dy, r
def summary(brief=False, linecolour=False):
""" Prints a tabulated version of the quadtree information.
(for debugging only)
Body parameters:
BID, MASS, POSITION, VELOCITY
Node parametres:
NID, LENGTH, VERTEX, OCCUPANT, CHILDREN, MASS, COM
"""
def history():
global period
print ("{0} nodes were created to fit {1} bodies in {2} seconds."
.format(len(childnodes), len(masses), style[2]%period))
if brief:
history()
return
# Styles and formats
style = ['{:>7}', '{:>15}', '%.2f', '(%.2f, %.2f)', '{:>19}', '\x1b[0m',
'\x1b[7m', '\x1b[0m', '{:>9}', '{:>31}']
form1 = style[0]*2 + style[1]*2
form2 = style[0]*2 + style[4] + style[8] + style[9] + style[8] + style[1]
head1 = ["BID", "MASS", "POSITION", "VELOCITY"]
head2 = ["NID", "LENGTH", "VERTEX", "OCCUPANT", "CHILDREN", "MASS", "COM"]
print form1.format(*head1)
for i, bid in enumerate(masses):
if linecolour:
if i % 2 == 0: bg = style[6]
else: bg = style[7]
else: bg = ''
print bg+form1.format(bid, style[2]%masses[bid],
style[3]%positions[bid],
style[3]%velocities[bid])
print style[5]
print form2.format(*head2)
for i, nid in enumerate(childnodes):
if linecolour:
if i % 2 == 0: bg = style[6]
else: bg = style[7]
else: bg = ''
if centremasses[nid] is None: printcom = None
else: printcom = style[3]%centremasses[nid]
print bg+form2.format(nid, style[2]%lengths[nid],
style[3]%vertices[nid], occupants[nid],
childnodes[nid], style[2]%totalmasses[nid],
printcom)
print style[5]
history()
if __name__ == '__main__':
from random import uniform
import time
theta = 1
G = 6.673e-1
dt = 0.1
start = time.time()
# Initialize the quadtree
initiate((-5,-5), 10)
n = xrange(8)
m = (uniform(1,100) for i in n)
p = ((uniform(-5,5),uniform(-5,5)) for i in n)
v = ((uniform(-10,10),uniform(-10,10)) for i in n)
# Add bodies
for mass, pos, vel in zip(m, p, v):
addbody(mass, pos, vel)
# Refresh centre of mass
updatecom()
period = time.time() - start
summary(linecolour=True)
</code></pre>
| [] | [
{
"body": "<p>You may well have a good reason for using Python 2.x. If you don't, I'd suggest that using the latest version is more Pythonic. In particular, as you describe yourself as a beginner, it may be easier to use the latest version now rather than having to unlearn certain quirks of 2.x at some point in future. I would also describe myself as a beginner, and of course I'm biased by having learned Python 3.3 first...</p>\n\n<p>If you prefer to keep it as Python 2.x it might be worth adding the tag <a href=\"/questions/tagged/python-2.7\" class=\"post-tag\" title=\"show questions tagged 'python-2.7'\" rel=\"tag\">python-2.7</a> to attract answers from people expert in it.</p>\n\n<pre><code>\"\"\"Quadtree construction module.\n\nESSENTIAL TERMINOLOGY\n\n a. Quadtree : A tree structure with four quadrants that are\n coplanar. Quadrants are named SW, NW, NE and SE as\n in compass directions, and are usually adressed in\n the same order.\n b. Node : Same as a quadrant; it can be internal or external.\n c. Internal Node : A node that has child nodes inside. It contains no\n bodies since they are distributed among the child\n nodes.\n d. External Node : A node that doesn't have child nodes inside. It\n contains a body.\n e. Empty Node : A node which has neither child nodes nor a body\n inside it.\n f. Root Node : The topmost node (parent) of all nodes.\n g. Occupant : A body bound within a node (lowest host node).\n h. nid : Node ID\n i. bid : Body ID\n j. Centre of mass : The weighted average of mass distribution.\n X = (m1x1+m2x2+...mnxn) / (m1+m2+...mn)\n This must be replaced with centre of gravity if the\n bodies are non-uniform mass distributions, unlike a\n point object.\n\"\"\"\n</code></pre>\n\n<p>You are right, this comprehensive docstring does indeed make the code longer. I don't see that as a bad thing. Anyone in a hurry can skip over it easily as it is self contained, and anyone confused by the code can refer back to this rather than having to work it all out for themselves. Helpful docstrings are definitely Pythonic. In particular, I wouldn't have been able to write this review without the insight provided by the docstrings.</p>\n\n<pre><code>from __future__ import division\n\n\n# Dictionaries to map body parameters\nmasses = {}\npositions = {}\nvelocities = {}\n# Dictionaries to map node parameters\nlengths = {0: None}\nvertices = {0: None}\noccupants = {0: None}\nchildnodes = {0: []}\ntotalmasses = {0: 0}\ncentremasses = {0: None}\n# Global ID counter starts with 1 (0 is dedicated for root node)\nID = 1\n\n\ndef newid(reset=False):\n \"\"\"newid(reset=False)\n\n Returns an unused ID of type 'int'. Consequtive integers starting from one\n are returned avoiding repetition.\n\n If optional argument 'reset' is True, ID counter restarts from one. Those\n IDs which aren't active anymore can be retrieved by this manner.\n \"\"\"\n</code></pre>\n\n<p>The misspelling of 'Consequtive' (correct spelling <code>Consecutive</code>) will only have a minor effect on someone reading the code, but I point it out since Python is all about readability.</p>\n\n<pre><code> global ID\n if reset:\n ID = 1\n while any(ID in maps for maps in (masses, childnodes)):\n ID += 1\n return ID\n</code></pre>\n\n<p>This function is called when assigning a new nid and also when assigning a new bid. I'm not sufficiently familiar with your algorithm to say for certain, but I'm guessing that the numbering of nodes (nid) and the numbering of bodies (bid) are unrelated. If so, then there is no need to check for an existing node id in masses, and no need to check for an existing body id in childnodes. I would be inclined to replace the function <code>newid</code> with two similar functions <code>newnid</code> and <code>newbid</code>. This will make assigning new ids slightly more efficient, and allow all numbers to be available (currently any given number can only be used as either a nid or a bid, not both, if I understand correctly).</p>\n\n<p>This will also be more readable, as both functions will be simpler and more intuitive than <code>newid</code>. Currently the question of why a new nid can't have the same number as an existing bid makes the algorithm appear more complex than it needs to.</p>\n\n<p>If you split the function this way, you will also need to have two global variables so that they don't share ID. For example, nextBodyID and nextNodeID. I would avoid all upper case as this is usually used for constants.</p>\n\n<pre><code>def initiate(vertex, length):\n \"\"\"initiate(vertex, length)\n\n Initiates the quadtree by specifying the SW vertex and side length.\n \"\"\"\n lengths[0] = length\n vertices[0] = vertex\n</code></pre>\n\n<p>You don't need to include the name of the function at the start of the docstring. The suggested approach is to start with a one line description of the function. Changing this will save you two lines per function, making your code more readable while still keeping all of the useful content of the docstrings. I mention this to save you some space. If you want more detail on suggested docstring structure, see <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">PEP 257</a>.</p>\n\n<pre><code>def isexternal(node):\n \"\"\"isexternal(node)\n\n Returns True if the node is external.\n \"\"\"\n if occupants[node]:\n return True\n\n\ndef isinternal(node):\n \"\"\"isinternal(node)\n\n Returns True if the node is internal.\n \"\"\"\n if childnodes[node]:\n return True\n\n\ndef isempty(node):\n \"\"\"isempty(node)\n\n Returns True if the node is empty.\n \"\"\"\n if (not occupants[node]) and (not childnodes[node]):\n return True\n</code></pre>\n\n<p>These three functions are very simple and easy to read. They also keep the rest of the code uncluttered and easier to read.</p>\n\n<pre><code>def addbody(mass, position, velocity, bid=None):\n \"\"\"addbody(mass, position, velocity, bid=None)\n\n Adds a body to the quadtree.\n\n 'mass' must be a positive quantity of type 'int' or 'float'.\n\n 'position' must be a tuple or list of two values representing the two\n dimensional position coordinates: (x, y).\n\n 'velocity' must be a tuple or list of two values representing the two\n dimensional velocity coordinates: (vx, vy).\n\n Optional argument bid, if specified, must be unique (auto-generated\n otherwise).\n \"\"\"\n if not bid or bid in masses:\n bid = newid()\n masses[bid] = mass\n positions[bid] = position\n velocities[bid] = velocity\n attach(bid)\n</code></pre>\n\n<p>The only thing I would change here is to replace <code>newid</code> with <code>newbid</code>, as described earlier.</p>\n\n<pre><code>def canfit(body, node):\n \"\"\"canfit(body, node)\n\n Checks wheather the body could be accomodated inside the node. Returns\n suitable status mesages;\n a. EXTERNAL : Can't fit because there is another body inside.\n b. INTERNAL : Can't fit because this node has child nodes.\n c. EMPTY : Can fit (yay!)\n d. None : Can't fit at all (out of bounds).\n \"\"\"\n bx, by = positions[body]\n nx, ny = vertices[node]\n l = lengths[node]\n if (0<=bx-nx<=l) and (0<=by-ny<=l):\n if isexternal(node):\n return 'EXTERNAL'\n if isinternal(node):\n return 'INTERNAL'\n return 'EMPTY'\n</code></pre>\n\n<p>The code in this function is clear, but the usage of the function is potentially misleading. Since the function is called <code>canfit</code> I'm expecting it to return <code>True</code> if the body can fit, but instead it returns <code>EMPTY</code>. The return values that you use are obviously a good fit to the rest of your program, so I would suggest simply changing the name of this function to avoid any confusion. For example, you could call it <code>node_state</code> since all the return values are describing the state of the node. Or <code>nodestate</code> for consistency with your naming style. Personally I find separated words slightly more readable, but a consistent approach is also useful.</p>\n\n<pre><code>def split(node, rearrange=True):\n \"\"\"split(node, rearrange=True)\n\n Splits the given node (external or empty) and divides it in to four\n quadrants (internal).\n\n If 'rearrange' is True, the body (if any) contained within this node will\n be redistributed to its appropriate childnode and thereby will get detached\n from the node itself.\n \"\"\"\n nx, ny = vertices[node]\n h = lengths[node] / 2\n hx, hy = nx + h, ny + h\n for vertex in ((nx,ny), (nx,hy), (hx,hy), (hx,ny)):\n nid = newid()\n lengths[nid] = h\n vertices[nid] = vertex\n occupants[nid] = None\n childnodes[nid] = []\n totalmasses[nid] = 0\n centremasses[nid] = None\n childnodes[node].append(nid)\n # Detach the body, distribute it to a child node.\n if rearrange:\n body = occupants[node]\n occupants[node] = None\n for child in childnodes[node]:\n if attach(body, child):\n break\n</code></pre>\n\n<p>This is all readable. The only thing I would change here is to replace <code>newid</code> with <code>newnid</code>, as described earlier.</p>\n\n<pre><code>def attach(body, node=0):\n \"\"\"attach(body, node=0)\n\n Attaches body to its host node and returns True upon success.\n\n Note: If recursion is initiated, and two bodies happens to be so close to\n each other, it could take considerable depth until both the bodies are\n individually distributed.\n \"\"\"\n for nid in walk(node):\n status = canfit(body, nid)\n if status == 'EMPTY':\n occupants[nid] = body\n return True\n elif status == 'EXTERNAL':\n split(nid)\n for child in childnodes[nid]:\n if attach(body, child):\n return True\n</code></pre>\n\n<p>The only thing I would change here is to replace <code>canfit</code> with <code>node_state</code>, as described earlier.</p>\n\n<pre><code>def walk(top=0, topdown=True, gettop=True):\n \"\"\"walk(top=0, topdown=True, gettop=True)\n\n Walks through the quadtree generating nids.\n\n If 'top' is not specified, the generator will walk through the entire\n quadtree (only top node otherwise).\n\n If 'topdown' is True, parent nodes will be generated before child nodes.\n Otherwise, child nodes will be generated before all their parents are. eg:\n parent : child nodes\n 0 : 1, 2, 3, 4\n 3 : 5, 6, 7, 8\n 4 : 9, 10, 11, 12\n 7 : 13, 14, 15, 16\n topdown mode - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16\n bottomup mode - 1, 2, 5, 6, 13, 14, 15, 16, 7, 8, 3, 9, 10, 11, 12, 4, 0\n\n if optional argument 'gettop' is False, the top node will not be yielded.\n \"\"\"\n if topdown:\n if gettop:\n yield top\n # Holding a queue list is memory inefficient, needs workaround.\n queue = list(childnodes[top])\n for child in queue:\n yield child\n queue.extend(childnodes[child])\n</code></pre>\n\n<p>If you want to avoid holding the queue in memory (as your comment suggests), you can use recursion but this will give you a top down <em>depth</em> first walk rather than a top down <em>breadth</em> first walk which you have here. It will still be top down, if that's all you require. The order based on your numbering in the docstring would be:\n0, 1, 2, 3, 5, 6, 7, 13, 14, 15, 16, 8, 4, 9, 10, 11, 12. If you require the exact order shown in your docstring then I can't think of a more straightforward way than the queue you use.</p>\n\n<pre><code> # This part is recursive.\n else:\n for child in childnodes[top]:\n for node in walk(child, topdown, gettop=True):\n yield node\n if gettop:\n yield top\n</code></pre>\n\n<p>The recursive part only happens if <code>topdown</code> is <code>False</code>. You don't need to say <code>walk(child, topdown ...</code> - you can just say <code>walk(child, False ...</code>.</p>\n\n<p>Similarly you don't need to say <code>gettop=True</code> as this is the default anyway. You could simply say <code>walk(child, False)</code>. This is entirely up to you. If you want to leave the default showing explicitly that is just as correct. Most readable might be <code>walk(child, topdown=False)</code>.</p>\n\n<pre><code>def updatecom(node=0):\n \"\"\"updatecom(node=0)\n\n Updates centre of mass of the node and its childnodes if any.\n\n If optional argument 'node' is not provided, the entire quadtree's centre\n of mass will be updated.\n \"\"\"\n for nid in walk(node, topdown=False):\n # Empty node, reset to None\n if isempty(nid):\n totalmasses[nid] = 0\n centremasses[nid] = None\n # External node, com is where the body is.\n if isexternal(nid):\n body = occupants[nid]\n totalmasses[nid] = masses[body]\n centremasses[nid] = positions[body]\n # Internal node, add children's com to parent.\n elif isinternal(nid):\n tmass, comx, comy = 0, None, None\n for child in childnodes[nid]:\n if isinternal(child) or isexternal(child):\n ccomx, ccomy = centremasses[child]\n ctmass = totalmasses[child]\n if comx is None:\n tmass, comx, comy = ctmass, ccomx, ccomy\n continue\n comx += ccomx*ctmass\n comy += ccomy*ctmass\n tmass += ctmass\n totalmasses[nid] = tmass\n centremasses[nid] = (comx/tmass, comy/tmass)\n</code></pre>\n\n<p>This all looks good. Will you ever have need to recalculate all of the nodes above a given child node (its parent nodes rather than its child nodes)? If not then this function covers all you need.</p>\n\n<pre><code>def distance(pointA, pointB):\n \"\"\"distance(pointA, pointB)\n\n Calculates the distance between two points and returns a tuple of\n (dx, dy, r); where r is the radial separation, dx and dy are the axial\n separation.\n \"\"\"\n ax, ay = pointA\n bx, by = pointB\n dx, dy = ax - bx, ay - by\n r = (dx*dx+dy*dy)**0.5\n return dx, dy, r\n</code></pre>\n\n<p>This function isn't used in your code (you said you had pasted in the whole program), so I can't review its usage. It seems to do what the docstring describes perfectly well. I would question why a single function is calculating both kinds of distance. If you ever need to use just one or other of the distance types, you may improve efficiency by having two separate functions, for example <code>xy_distances</code> and <code>euclid_distance</code>.</p>\n\n<p>If you intend to only call this from another function that uses both distances together, then the combined function is probably more efficient, as it avoids having to calculate the vertical and horizontal distances twice.</p>\n\n<p>I think it's perfectly readable either way.</p>\n\n<pre><code>def summary(brief=False, linecolour=False):\n \"\"\" Prints a tabulated version of the quadtree information.\n (for debugging only)\n Body parameters:\n BID, MASS, POSITION, VELOCITY\n Node parametres:\n NID, LENGTH, VERTEX, OCCUPANT, CHILDREN, MASS, COM\n \"\"\"\n</code></pre>\n\n<p>If you use more than one line for a docstring, leaving the second line blank (as you have in all the others) will allow ease of automation. For example, Python's <code>help</code> function will still work without the blank line but the output won't be quite as tidy.</p>\n\n<pre><code> def history():\n global period\n print (\"{0} nodes were created to fit {1} bodies in {2} seconds.\"\n .format(len(childnodes), len(masses), style[2]%period))\n if brief:\n history()\n return\n # Styles and formats\n style = ['{:>7}', '{:>15}', '%.2f', '(%.2f, %.2f)', '{:>19}', '\\x1b[0m',\n '\\x1b[7m', '\\x1b[0m', '{:>9}', '{:>31}']\n form1 = style[0]*2 + style[1]*2\n form2 = style[0]*2 + style[4] + style[8] + style[9] + style[8] + style[1]\n head1 = [\"BID\", \"MASS\", \"POSITION\", \"VELOCITY\"]\n head2 = [\"NID\", \"LENGTH\", \"VERTEX\", \"OCCUPANT\", \"CHILDREN\", \"MASS\", \"COM\"]\n\n print form1.format(*head1)\n for i, bid in enumerate(masses):\n if linecolour:\n if i % 2 == 0: bg = style[6]\n else: bg = style[7]\n else: bg = ''\n print bg+form1.format(bid, style[2]%masses[bid],\n style[3]%positions[bid],\n style[3]%velocities[bid])\n print style[5]\n print form2.format(*head2)\n for i, nid in enumerate(childnodes):\n if linecolour:\n if i % 2 == 0: bg = style[6]\n else: bg = style[7]\n else: bg = ''\n if centremasses[nid] is None: printcom = None\n else: printcom = style[3]%centremasses[nid]\n print bg+form2.format(nid, style[2]%lengths[nid],\n style[3]%vertices[nid], occupants[nid],\n childnodes[nid], style[2]%totalmasses[nid],\n printcom)\n print style[5]\n history()\n</code></pre>\n\n<p>A minor point in case it's of interest: writing <code>if i%2 == 0:</code> is equivalent to writing <code>if not i%2:</code>. If you swap the order of the results you can simply say <code>if i % 2:</code>.</p>\n\n<pre><code>if __name__ == '__main__':\n from random import uniform\n import time\n\n theta = 1\n G = 6.673e-1\n dt = 0.1\n\n start = time.time()\n\n # Initialize the quadtree\n initiate((-5,-5), 10)\n n = xrange(8)\n m = (uniform(1,100) for i in n)\n p = ((uniform(-5,5),uniform(-5,5)) for i in n)\n v = ((uniform(-10,10),uniform(-10,10)) for i in n)\n # Add bodies\n for mass, pos, vel in zip(m, p, v):\n addbody(mass, pos, vel)\n # Refresh centre of mass\n updatecom()\n\n period = time.time() - start\n summary(linecolour=True)\n</code></pre>\n\n<p>I would describe your code as pretty Pythonic already. If you want any further detail on suggested style I'd recommend <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T09:00:50.570",
"Id": "76669",
"Score": "2",
"body": "Thank you very much! As you've mentioned, my prolonged use of python 2.7 made me uneducated about v 3.x, but I must begin to use it anyway. You've thoroughly reviewed this code and to answer some of the questions you've asked: the `distance` function is for future implementation of `acceleration`. `updatecom` doesn't have update functionality for parent nodes (might require an entire makeover, but not needed at the moment). Your suggestions on changing names, spellings, `newnid` and `newbid` and others are excellent! I'll modify the code accordingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T09:50:03.257",
"Id": "76673",
"Score": "2",
"body": "@user3058846 glad to hear it helped. It's still perfectly valid to use Python 2.7. If you wanted to try out Python 3.3 all you'd need to change in this code is to use `range` instead of `xrange` (identical usage here) and to use print as a function: `print(x)` instead of `print x`. Everything else works in either version, except you'll no longer need to import from future..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T02:55:11.400",
"Id": "44222",
"ParentId": "43749",
"Score": "5"
}
},
{
"body": "<p>As general comments, I would find more pythonic to avoid the use of unique identifier. You can implement the same algorithm using the quadrants' informations ((x,y),width) directly. This would produce a more readable code by avoiding indirections and the need to generate indices.</p>\n\n<p>Additionally, I would find more pythonic to propose an interface similar to existing data structure in python. I would find easier to use <code>qt = QuadTree(points)</code> to build the tree and attach a set of points; to be able to use <code>qt.append(point)</code> instead of <code>attach</code>; to be able to iterate over points (like <code>[point for point in quadtree]</code>) or even to permits query as an item getter: <code>points = quadtree[my_quadrant]</code>.</p>\n\n<p>Incidentally, this last example shows the advantage of using quadrants themselves instead of indices.</p>\n\n<p>To do so, either you build a proxy class that just call the correct functions while showing a pythonesque API, either you directly use a class embedding your data structures. I would find the later better than the existing global variables, because most of your functions does just depend on your very specific data structures and can probably not be used in other algorithms.</p>\n\n<pre><code>def canfit(body, node):\n bx, by = positions[body]\n nx, ny = vertices[node]\n l = lengths[node]\n if (0<=bx-nx<=l) and (0<=by-ny<=l):\n if isexternal(node):\n return 'EXTERNAL'\n if isinternal(node):\n return 'INTERNAL'\n return 'EMPTY'\n</code></pre>\n\n<p>Here you may use python's <code>enum.Enum</code> for the returned status. Also, an <code>'OUT'</code> status may help you when you will do queries (as in the <code>attach</code> function).</p>\n\n<p>The way you test if the position is within the quadrant may be more sensible to floating point errors. Maybe it would be better to test <code>if nx <= bx <= nx+l …</code> (to be checked).</p>\n\n<pre><code>def attach(body, node=0):\n for nid in walk(node):\n status = canfit(body, nid)\n if status == 'EMPTY':\n occupants[nid] = body\n return True\n elif status == 'EXTERNAL':\n split(nid)\n for child in childnodes[nid]:\n if attach(body, child):\n return True\n</code></pre>\n\n<p>Here you may avoid walking the whole tree to find a node that fit the given body. You should avoid going through the nodes for which the points is out of scope. Just test if the body can fit within the node and proceed to its children only if it's the case.</p>\n\n<pre><code> initiate((-5,-5), 10)\n n = xrange(8)\n m = (uniform(1,100) for i in n)\n p = ((uniform(-5,5),uniform(-5,5)) for i in n)\n v = ((uniform(-10,10),uniform(-10,10)) for i in n)\n # Add bodies\n for mass, pos, vel in zip(m, p, v):\n addbody(mass, pos, vel)\n</code></pre>\n\n<p>As a user, I would want to be able to initialize the tree without having to pre-compute the quadrant. To give a set of points should be sufficient for the algorithm to compute the root quadrant by itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T12:36:40.253",
"Id": "58375",
"ParentId": "43749",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "44222",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:25:14.733",
"Id": "43749",
"Score": "8",
"Tags": [
"python",
"tree",
"python-2.x"
],
"Title": "Barnes-Hut n-body quadtree"
} | 43749 |
<p>Previous version:</p>
<p><a href="https://codereview.stackexchange.com/questions/43655/updating-grid-on-webpage">Updating Grid on Webpage</a></p>
<p><strong>Task:</strong></p>
<blockquote>
<p>Draw a grid with a given number of rows and columns. Each cell can be
any color. The same grid should also be updated at a predetermined
time interval. The grid should cover the entire visible portion of the
page in the browser. Add a context menu with which you can change the
parameters of the lattice.</p>
</blockquote>
<p>I would really like to hear feedback on the code: syntax, logic and general any comments and tips.</p>
<p>I'm a young programmer so I want to hear real reviews for further development.</p>
<p>Corrected:</p>
<ol>
<li>object passed to the constructor with parameters</li>
<li>variables moved inside the constructor grid </li>
<li>function <code>createGrid</code> as a method of object inside the constructor</li>
<li>use style CSS</li>
<li>added function that keeps track of dynamic resizing the browser window</li>
</ol>
<p><strong>HTML:</strong> </p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="css/gridStyle.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/grid.js"></script>
<script type="text/javascript">
window.onload = function () {
var options = {
numRows : 20,
numColumns : 6,
updateInterval : 2000
}
var grid = new Grid (options);
}
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>function Grid(gridOptions) {
this.numRows = gridOptions.numRows;
this.numColumns = gridOptions.numColumns;
this.updateInterval = gridOptions.updateInterval;
var clientWidth = document.body.clientWidth;
var clientHeight = document.body.clientHeight;
var interval=0;
var checkInterval;
var stopUpdateGrid = false;
this.createGrid = function(){
var container = document.createElement("div");
document.body.appendChild(container);
container.className="container";
for (var i = 1; i <= this.numRows * this.numColumns; i++) {
var cell = document.createElement("div");
container.appendChild(cell);
cell.className="cell";
cell.style.width = (clientWidth - this.numRows - 1) / this.numRows + "px";
cell.style.height = (clientHeight - this.numColumns - 1) / this.numColumns + "px";
var n = randomColors();
cell.style.backgroundColor = "#" + n;
}
function randomColors() {
var min = 0;
var max = 15;
var colors = '';
for (var i = 1; i <= 6; i++) {
var rand = min - 0.5 + Math.random() * (max - min + 1);
rand = Math.round(rand);
rand = parseInt(rand, 10).toString(16);
colors = colors + rand;
}
return colors;
}
(function updateColorsGrid(updateInterval) {
if (interval) {
clearTimeout(interval);
}
interval = setTimeout(function() {
if (stopUpdateGrid === false) {
var container = document.getElementsByClassName("container")[0];
document.body.removeChild(container);
var grid = new Grid(gridOptions);
}
}, updateInterval);
})(this.updateInterval);
document.addEventListener("keyup", function(e) {
e = e || window.event;
if (e.keyCode === 13) {
stopUpdateGrid = true;
changeGridOptions();
}
}, false);
(function createNotification() {
var container = document.getElementsByClassName("container")[0];
var notificationContainer = document.createElement("div");
container.appendChild(notificationContainer);
notificationContainer.className = "notification";
notificationContainer.innerHTML = "Press Enter to show menu change!!!";
})();
function changeGridOptions() {
var container = document.getElementsByClassName("container")[0];
var changeOptionsForm = document.createElement("form");
container.appendChild(changeOptionsForm);
changeOptionsForm.className = "changeOptionsForm";
changeOptionsForm.style.left = clientWidth - 220 + "px";
changeOptionsForm.style.top = "15px";
var changeRowsText = document.createElement("div");
changeOptionsForm.appendChild(changeRowsText);
changeRowsText.className = "changeParametersTitle";
changeRowsText.innerHTML = "Rows:";
var changeRows = document.createElement("input");
changeOptionsForm.appendChild(changeRows);
changeRows.type = "text";
changeRows.className = "changeParametersValue";
var changeColumnsText = document.createElement("div");
changeOptionsForm.appendChild(changeColumnsText);
changeColumnsText.className = "changeParametersTitle";
changeColumnsText.innerHTML = "Columns:";
var changeColumns = document.createElement("input");
changeOptionsForm.appendChild(changeColumns);
changeColumns.type = "text";
changeColumns.className = "changeParametersValue";
var changeDelayUpdateGridText = document.createElement("div");
changeOptionsForm.appendChild(changeDelayUpdateGridText);
changeDelayUpdateGridText.className = "changeParametersTitle";
changeDelayUpdateGridText.innerHTML = "Delay Update:";
var changeDelayUpdateGrid = document.createElement("input");
changeOptionsForm.appendChild(changeDelayUpdateGrid);
changeDelayUpdateGrid.type = "text";
changeDelayUpdateGrid.className = "changeParametersValue";
var changeButton = document.createElement("input");
changeOptionsForm.appendChild(changeButton);
changeButton.type = "button";
changeButton.value = "change";
changeButton.className = "changeButton";
changeButton.addEventListener("click", function() {
gridOptions.numRows = changeRows.value || gridOptions.numRows;
gridOptions.numColumns = changeColumns.value || gridOptions.numColumns;
gridOptions.updateInterval = changeDelayUpdateGrid.value || gridOptions.updateInterval;
changeOptionsForm.style.display = "none";
stopUpdateGrid = false;
document.body.removeChild(container);
var grid = new Grid(gridOptions);
}, false);
}
(function checkSizeWindowBrowser() {
document.body.onresize = function() {
var container = document.getElementsByClassName("container")[0];
document.body.removeChild(container);
clearTimeout(interval);
var grid = new Grid(gridOptions);
};
})();
};
this.createGrid();
}
</code></pre>
<p><strong>CSS:</strong> </p>
<pre><code>html, body {
width: 100%;
height: 100%;
margin: 0;
}
.container {
width: 100%;
height: 100%;
}
.cell {
float: left;
margin: -1px 0 0 -1px;
border: 1px solid #000;
}
.notification {
width: 500px;
height: 50px;
color: #fff;
font-size: 30px;
position: absolute;
}
.changeOptionsForm {
width: 200px;
height: 200px;
border: 2px solid #fff;
background-color: #808080;
position: absolute;
}
.changeParametersTitle {
width: 50px;
height: 20px;
margin: 10px;
float: left;
}
.changeParametersValue {
width: 100px;
height: 20px;
margin: 10px;
border: 2px solid #000;
}
.changeButton {
width: 100px;
height: 25px;
margin: 20px 50px;
float: left;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T23:11:43.087",
"Id": "75698",
"Score": "0",
"body": "Indent that CSS code properly! The JavaScript code looks so much better now, I will definitely get back to this."
}
] | [
{
"body": "<p>Overall it looks pretty clean,</p>\n\n<ol>\n<li>I'd like to see some comments on the functions so I know what they do without having to read the code, you could use <a href=\"http://usejsdoc.org\">JSDoc</a> for this.</li>\n<li>I'd recommend explicitly using <a href=\"http://en.wikipedia.org/wiki/Design_by_contract\">Design By Contract</a> or Defensive Programming so the users of the code know what to expect. Which one of these you choose will determine what you put in the comments.</li>\n<li>Get the tabbing fixed on the CSS file.</li>\n<li>Use constants where you have code like this: <code>e.keyCode === 13</code> to make the meaning clearer.</li>\n<li>Ideally pull the text that is shown to the user out into a language file that defines appropriate variables, so that if you want to port to another language, you only have to send that to the translator, not the code.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T19:22:43.917",
"Id": "46317",
"ParentId": "43751",
"Score": "6"
}
},
{
"body": "<p>I would not hard code 'container', instead make it an attribute of gridOptions : </p>\n\n<pre><code>var options = { \n ....\n containerClass = 'container',\n ....\n}\n</code></pre>\n\n<p>I would consider extending the options to include an id or selector of a parent (an anchor) where to add the grid (if null then use document.body as you do now).You could also add to the options the ID of the grid being created, then you would be potentially be able to handle multiple grids in the same document).</p>\n\n<p>Every time the window is resized the grid is recreated, meaning that the keyup listener is attached to the document multiple times, and similarly changeGridOptions() is called every time the user presses the enter key, resulting in multiple calls to changeButton.addEventListener(). </p>\n\n<p>All these listeners should be removed (see <a href=\"https://stackoverflow.com/questions/14040386/should-i-remove-event-handlers-from-element-before-removechild\">https://stackoverflow.com/questions/14040386/should-i-remove-event-handlers-from-element-before-removechild</a>) when the grid is cleared , ie when a new grid is created, by calling window.removeEventListener (See <a href=\"https://stackoverflow.com/questions/2991382/how-do-i-add-and-remove-an-event-listener-using-a-function-with-parameters\">https://stackoverflow.com/questions/2991382/how-do-i-add-and-remove-an-event-listener-using-a-function-with-parameters</a>)</p>\n\n<p>There are 2 things that should happen when clearing the grid:</p>\n\n<ol>\n<li>the timeout should be cleared (only done in onresize())</li>\n<li>the container DOM element must be removed (implemented in 2 different places: the timer and on resize)</li>\n</ol>\n\n<p>This duplication and inconsistency can be avoided by moving this code to the constructor of the grid: check if the container is already created (by class or by id if you provide one as I suggest above) and first clear the interval if it is set, then remove any registered listeners, then remove the DOM element, and then instantiate the Grid.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:20:50.393",
"Id": "46335",
"ParentId": "43751",
"Score": "5"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/46317/14370\">Chris Thomson's answer</a> makes some very good points about the overall quality, and <a href=\"https://codereview.stackexchange.com/a/46335/14370\">Leopoldo Salvo's answer</a> points out several hidden issues with the timer(s) and event handling. My comments will be more about alternative approaches to various parts. Not much code, more of a reinterpretation of the stated task.</p>\n\n<p>The first thing I notice is that each update creates an entirely new grid. Even window resizing. It's a simple solution, but a pretty brute-force one.</p>\n\n<p>A simpler solution is to let the browser do a lot of the work:<br>\nMake the container fill the window (e.g. absolute position and a 0px offset from all four sides with width/height set to auto).</p>\n\n<p>Then style each cell with <code>float: left</code>, and all you have to worry about is their width and height. They'll automatically flow to fill the container, without you ever having to calculate their position.</p>\n\n<p>And use percentages for the cells' width and height. That way, you never have to worry resizing either. You'll simply have a flat list of DIVs that automagically arrange themselves as a grid and fill the window.</p>\n\n<p>This also makes it much simpler to have just 1 <code>Grid</code> instance that you update, instead of constantly destroying the entire thing, and building a new one. <a href=\"http://jsfiddle.net/56934/\" rel=\"nofollow noreferrer\">Here's a small example</a> that does all that.</p>\n\n<p>Now, another thing is that the task is unclear: Must the \"context menu\" be built entirely in JavaScript? The grid obviously must be, but the options aren't dynamic in the same way. I mean, if it's OK to use predefined CSS, and the page isn't supposed to do anything else, I'd absolutely create the options menu in the markup, because it's just easier, cleaner, and <em>much</em> more maintainable than using the DOM. All you'd have to do is hook up some event listeners, and bingo.</p>\n\n<p>Yes, there'll be a lot more coupling between the markup and the javascript, but as mentioned it's already coupled to the CSS anyway, and the task, as defined, doesn't prohibit it. In terms of simply solving the task, adding the extra coupling just makes things much simpler. There are many ways to complicate things, but there's no reason to do so if it isn't required.</p>\n\n<p>A completely separate issue is that \"context menu\" usually means a right-click menu - but building such a thing - and have it behave properly - is tricky, and would seem out of scope compared to the other parts of the task. Besides, it'd be an action menu; not editable fields.</p>\n\n<p>Some other stuff I happened to notice:</p>\n\n<ol>\n<li><p>On the timed updates, it'd be better to simply loop though and update the colors of the existing DIVs, instead of removing <em>everything</em> and building a new grid. The number of elements or their positions haven't changed, so it's really only a question of setting the background color.</p></li>\n<li><p>Speaking of, you're working too hard to get a random color. <a href=\"http://www.paulirish.com/2009/random-hex-color-code-snippets/\" rel=\"nofollow noreferrer\">Here's a nice one-liner</a> you can use instead:</p>\n\n<pre><code>'#' + Math.floor(Math.random()*0xFFFFFF).toString(16);\n</code></pre></li>\n<li><p>Make the container absolutely positioned in CSS, and give it a 0px offset from all of the four sides. That'll make it fill the window (in modern browsers). Then style each cell with <code>float: left</code>, and all you have to worry about is their width and height - they'll automatically flow to fill the container.</p></li>\n<li><p>You're using a form for the \"menu\", but you're only handling the input when the button is clicked; not when the <code>submit</code> event of the form. The button doesn't submit the form either. As such, the form isn't really necessary - it could be any element. A form is of course semantically correct, but it should be used to your advantage.</p></li>\n<li><p>The way the form is being built also feels too complicated: Much more can be accomplished in CSS. The input and labels do not need classes, since more generic selectors (e.g. <code>form input[type=text]</code>) will be enough to style the correct elements.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:33:55.337",
"Id": "46389",
"ParentId": "43751",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46335",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:36:31.923",
"Id": "43751",
"Score": "11",
"Tags": [
"javascript",
"object-oriented",
"html",
"dom"
],
"Title": "Updating Grid on Webpage (new version)"
} | 43751 |
<p>I'd like some advice about any better or cleaner way to implement this class, if there's any. </p>
<p>I made it using <a href="https://stackoverflow.com/questions/5204578/is-it-possible-to-implement-events-in-c/5204594#5204594">this answer</a>, posted on Stack Overflow, as reference. A lot of problems arose when I switched C function pointers to <code>std::function</code> due to the lack of the equality operator on it, so I ended up implementing a internal class to hold a pointer to the function and make it comparable.</p>
<pre><code>#include <list> // std::list
#include <algorithm> // std::find
#include <functional> // std::function
#include <memory> // std::auto_ptr
template<typename FuncTemplate>
class Event
{
public: // Type declarations
class Delegate;
public:
Event() = default;
~Event() = default;
Event& operator+=(const Delegate& func)
{
events.push_back(func);
return *this;
}
/**
* Removes the first occurence of the given delegate from the call queue.
*/
Event& operator-=(const Delegate& func)
{
auto index = std::find(events.begin(), events.end(), func);
if(index != events.end() )
{
events.erase(index);
}
return *this;
}
/**
* Fires this event.
*
* @param args Arguments to be passed to the called functions. Must have the exact same
* number of arguments as the given event template.
*/
template<typename... Args>
void operator()(Args... args)
{
for (typename std::list<Delegate>::iterator i = events.begin(); i != events.end(); ++i)
{
(*i)(args...);
}
}
private: // Private variables
std::list<Delegate> events;
public:
class Delegate
{
private: // Type declarations
typedef std::function<FuncTemplate> Func;
public:
Delegate (const Func& func) : functionPtr(new Func(func))
{
/* NOP */
}
inline bool operator== (const Delegate& other) const
{
return (functionPtr.get() == other.functionPtr.get() );
}
template<typename... Args>
void operator()(Args... args)
{
(*functionPtr)(args...);
}
private:
std::shared_ptr<Func> functionPtr;
};
};
</code></pre>
<p>This is the code I used to test it:</p>
<pre><code>void prints(const std::string& e)
{
std::cout << "From prints: " << e << std::endl;
}
int main(int argc, char *argv[])
{
Event<void(const std::string&)> messageReceived;
auto printLambda = [](const std::string& e) -> void
{
std::cout << "From print lambda: " << e << std::endl;
};
Event<void(const std::string&)>::Delegate printDelegate1(printLambda); // Testing lambda
Event<void(const std::string&)>::Delegate printDelegate2(prints); // Testing standard functions
Event<void(const std::string&)>::Delegate printDelegate3(printLambda); // Testing lamda on another delegate instance
Event<void(const std::string&)>::Delegate printDelegate4(printDelegate1); // Testing cloning constructor
Event<void(const std::string&)>::Delegate printDelegate5 = printDelegate1; // Testing assignation
std::cout << "Is Delegate 1 = Delegate 1? " << (printDelegate1 == printDelegate1) << std::endl;
std::cout << "Is Delegate 1 = Delegate 2? " << (printDelegate1 == printDelegate2) << std::endl;
std::cout << "Is Delegate 1 = Delegate 3? " << (printDelegate1 == printDelegate3) << std::endl;
std::cout << "Is Delegate 1 = Delegate 4? " << (printDelegate1 == printDelegate4) << std::endl;
std::cout << "Is Delegate 1 = Delegate 5? " << (printDelegate1 == printDelegate5) << std::endl;
std::cout << std::endl << std::endl;
messageReceived += printDelegate1;
messageReceived += printDelegate2;
messageReceived += printDelegate3;
messageReceived += printDelegate4;
messageReceived += printDelegate5;
messageReceived("This should be printed five times");
std::cout << std::endl;
messageReceived -= printDelegate1;
messageReceived -= printDelegate2;
messageReceived -= printDelegate3;
messageReceived("This should be printed two times");
std::cout << std::endl;
messageReceived -= printDelegate4;
messageReceived -= printDelegate5;
messageReceived("Whoops! Something is wrong");
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Before looking at the code, and just having a quick read-through, the first thing that sticks out to me are the comments:</p>\n\n<pre><code>private: // Private variables\n\nDelegate (const Func& func) : functionPtr(new Func(func))\n{\n /* NOP */\n}\n\n#include <memory> // std::auto_ptr\n</code></pre>\n\n<p>The first is obvious, the second is slightly misleading, and the third is completely wrong (I know you meant <code>std::shared_ptr</code>, but having an incorrect comment is worse than no comment at all).</p>\n\n<p>Your <code>operator()</code> should probably be using perfect forwarding instead of passing a copy of all the arguments. Also, since you're already using lambdas and variadic templates, you might as well take advantage of auto and/or range based for loops:</p>\n\n<pre><code>template<typename... Args>\nvoid operator()(Args... args)\n{\n for (typename std::list<Delegate>::iterator i = events.begin(); i != events.end(); ++i)\n {\n (*i)(args...);\n }\n}\n</code></pre>\n\n<p>I'd change this to:</p>\n\n<pre><code>template<typename... Args>\nvoid operator()(Args&&... args)\n{\n for (auto i = events.begin(); i != events.end(); ++i)\n {\n (*i)(std::forward<Args>(args)...);\n }\n}\n</code></pre>\n\n<p>Similarly for the <code>operator()</code> in <code>Delegate</code>.</p>\n\n<p>Instead of using <code>new</code> in:</p>\n\n<pre><code>Delegate (const Func& func) : functionPtr(new Func(func))\n</code></pre>\n\n<p>You should prefer <code>std::make_shared</code>, as it is potentially slightly more efficient, and good practice to get into, as if you ever use <code>new</code> multiple times\nbefore a sequence point, there can be memory leaks if (say) the second <code>new</code> throws before the <code>shared_ptr</code> is fully constructed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:31:51.523",
"Id": "75716",
"Score": "0",
"body": "I wouldn't have noticed the `std::auto_ptr` comment had you not mentioned it. I use the first comment you mentioned as labels, since the code folding on Sublime 3 doesn't hide them (the _Private_ part is redundant, though). I made the changes you suggested, and I might make a benchmark later to see the differences. Anyway, thanks for your feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:58:54.840",
"Id": "75719",
"Score": "0",
"body": "@RaphaelC. Honestly, unless you're passing a number of really expensive parameters, you're unlikely to see much of a difference here. It's (potentially) a construction + move (which for a lot of classes is just swapping pointers) instead of a construction + copy construction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T09:30:45.027",
"Id": "75737",
"Score": "0",
"body": "You can cut down that for loop still with a range-based for."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T03:41:32.560",
"Id": "43766",
"ParentId": "43752",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "43766",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:36:41.927",
"Id": "43752",
"Score": "6",
"Tags": [
"c++",
"optimization",
"c++11",
"event-handling"
],
"Title": "Generic event class - am I over-complicating it?"
} | 43752 |
<p>From Coderbyte:</p>
<blockquote>
<p>Have the function StringReduction(str) take the str parameter being
passed and return the smallest number you can get through the
following reduction method. The method is: Only the letters a, b, and
c will be given in str and you must take two different adjacent
characters and replace it with the third. For example "ac" can be
replaced with "b" but "aa" cannot be replaced with anything. This
method is done repeatedly until the string cannot be further reduced,
and the length of the resulting string is to be outputted. For
example: if str is "cab", "ca" can be reduced to "b" and you get "bb"
(you can also reduce it to "cc"). The reduction is done so the output
should be 2. If str is "bcab", "bc" reduces to "a", so you have "aab",
then "ab" reduces to "c", and the final string "ac" is reduced to "b"
so the output should be 1.</p>
</blockquote>
<p>Source ( passed all validations ):</p>
<pre><code>var replacements =
{
"ab" : "c",
"ac" : "b",
"bc" : "a",
"ba" : "c",
"ca" : "b",
"cb" : "a"
};
function StringReduction(s)
{
var original, key;
while( s != original )
{
original = s;
for( key in replacements )
s = s.replace( key , replacements[key] );
}
return s.length;
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
StringReduction(readline());
</code></pre>
<p>The funny part of this challenge is that you write against time, so the first version was a terrible, recursive approach. Since then I rewrote it a few times before posting to CR, thinking each time mistakenly that it was perfect, at this point I would like to get your feedback on it.</p>
| [] | [
{
"body": "<p>A few minor notes:</p>\n\n<ol>\n<li><blockquote>\n <blockquote>\n <p>Have the function StringReduction(str)</p>\n </blockquote>\n</blockquote>\n\n<p>strictly speaking, the parameter name is different:</p>\n\n<blockquote>\n<pre><code>function StringReduction(s) \n</code></pre>\n</blockquote>\n\n<p>:-)</p></li>\n<li><blockquote>\n<pre><code>var original, key;\n</code></pre>\n</blockquote>\n\n<p>I'd put the variable declarations to separate lines. From <em>Code Complete 2nd Edition</em>, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote>\n\n<p>It could prevent some diff/merge conflicts (you modify the first variable, a coworker the second one at the same time).</p></li>\n<li><p><del><code>key</code> could be declared inside the <code>while</code> loop.</del></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3684923/843804\">JavaScript variables declare outside or inside loop?</a></li>\n<li><em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em></li>\n</ul>\n\n<p>As <em>@konijn</em> pointed out in his comment, that may <a href=\"https://github.com/airbnb/javascript#hoisting\" rel=\"nofollow noreferrer\">confuse maintainers</a>. Anyway, extracting it out into a separate function solves the issue (#6).</p></li>\n<li><p>The name <code>original</code> could be <code>lastString</code> or <code>lastValue</code> since it's not the original string, it's the result of the last loop.</p></li>\n<li><p>Indentation is not consistent. Most of the places it's two spaces but the <code>while</code> loop is only one space indented, the body of the <code>for</code> loop has three spaces.</p></li>\n<li><p>I'd extract out the <code>for</code> loop to a <code>string translate(string, replacements)</code> function for better readability.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:30:53.537",
"Id": "75771",
"Score": "0",
"body": "3. is interesting, I avoid it due to the hoisting feature in JS which can confuse maintainers (https://github.com/airbnb/javascript#variables) 5. I'm an idiot ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:43:11.223",
"Id": "75772",
"Score": "0",
"body": "@konijn: 3. Thanks, good point, answer updated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T06:00:15.703",
"Id": "43776",
"ParentId": "43754",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "43776",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:43:55.853",
"Id": "43754",
"Score": "6",
"Tags": [
"javascript",
"strings"
],
"Title": "Coderbyte: String Reduction"
} | 43754 |
<p>I have a function that returns the index of the first alphabet letter found in a string, or -1 if no letter is found. It seems like there should be a way to do this with extension methods instead of looping, but I can't think of one:</p>
<pre><code>int findFirstLetter(string str)
{
for(int ctr=0;ctr<str.Length;ctr++)
{
if (Char.IsLetter(str[ctr]))
{
return ctr;
}
}
return -1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T23:56:12.707",
"Id": "75699",
"Score": "3",
"body": "return str.ToList().FindIndex(c => Char.IsLetter(c));"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T23:57:57.503",
"Id": "75700",
"Score": "0",
"body": "I'd like to vote-to-close this question, if you don't mind: it's more of a \"code golf\" question than a code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:01:23.250",
"Id": "75701",
"Score": "1",
"body": "@ChrisW, does that mean I should post questions like this to Code Golf?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:07:13.337",
"Id": "75702",
"Score": "2",
"body": "I don't know but I don't think it's on-topic there: it's not a puzzle or game. Perhaps it is on-topic here, I don't know: http://meta.codereview.stackexchange.com/a/711/34757 suggests \"no\" but http://meta.codereview.stackexchange.com/q/1583/34757 suggests \"yes\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:09:43.943",
"Id": "75703",
"Score": "0",
"body": "One problem with this question is that it's hard to make a valid answer except as a comment (because an answer which only contains code isn't usually a code review of the code in the OP). And you're \"asking for code to be written\" which is also off-topic here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:12:28.823",
"Id": "75704",
"Score": "0",
"body": "Looking at the top answer on http://meta.codereview.stackexchange.com/questions/943/do-we-need-to-revisit-code-golf-questions also suggests that my question is on-topic for Code Review. I think Code Golf is more specifically about character count; I just want to find an efficient solution. I'm not asking for code to be written; if you'd responded, \"Try using `ToList()`,\" that would be a good hint to get me going. I'd be happy to ask about it in Meta, if you'd like to get a more definitive answer from the community."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:16:08.007",
"Id": "75705",
"Score": "0",
"body": "You're welcome to ask about it in Meta; and/or see how other people vote on this question; and/or see whether they answer (if it isn't closed), or comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:17:41.250",
"Id": "75706",
"Score": "0",
"body": "I would guess that my solution is probably **not** efficient (because of the `ToList()`): it's only, a more compact source code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:43:30.293",
"Id": "75708",
"Score": "0",
"body": "[Meta discussion here](http://meta.codereview.stackexchange.com/questions/1601/does-this-question-belong-on-code-review-should-it-go-to-code-golf), if you're interested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T02:14:43.130",
"Id": "75712",
"Score": "0",
"body": "A trick such as @ChrisW 's first comment likely doesn't even eliminate the loop. It just hides it, but a \"FindIndex\" method in any language almost certainly uses a loop in its implementation. Arguably though, ChrisW's comment is actually worse because even given equivalent efficiency, his answer is far less readable than what is posted in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T07:08:34.377",
"Id": "75724",
"Score": "1",
"body": "@nhgrif - I think readability is subjective. If you are new to Linq ChrisW's solution is a little mind boggling. But after spending time with Linq, you start to \"think in Linq.\" I actually find his answer far more readable: take a string, make a list out of it, find the index of something in that list, that something is a letter."
}
] | [
{
"body": "<p>I have no issue with the loop. It is about as fast as it can be. I would recommend renaming the method to match the other IndexOf methods.... something like <code>IndexOfAlphaChar</code>.</p>\n\n<p>There is no reason to worry about this code. Move on to bigger problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-18T16:59:44.253",
"Id": "224307",
"Score": "0",
"body": "Maybe nitpicking but I do have an issue with the loop! It could be about 25% faster by storing `str.Length` in a temporary variable `strLen` and then using this in the loop condition `ctr<strLen`. No need to keep re-evaluating `str.Length` if the string length never changes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:21:44.647",
"Id": "43757",
"ParentId": "43756",
"Score": "9"
}
},
{
"body": "<p>I think that the biggest problem with the code you posted is not the structure, but variable naming and other stylistic issues:</p>\n\n<ol>\n<li>It took me a while to realize what <code>ctr</code> meant (control?). Don't shorten variable names like this, write them in full if you can.</li>\n<li>Opinions about the right indentation style vary wildly, but I think that one space is too little. The common values are 2 or 4 spaces or a single tab (<code>\\t</code>).</li>\n<li><p>Use spaces more often to make the structure of your code clearer:</p>\n\n<pre><code>for (int ctr = 0; ctr < str.Length; ctr++)\n</code></pre></li>\n<li><p>For types that can be written as a keyword, I always write them that way. That means I would write <code>char.IsLetter</code> (lowercase <code>c</code>).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:46:38.790",
"Id": "76052",
"Score": "0",
"body": "I agree with you about the tabs and spacing; when I use Ctrl+K,D in Visual Studio, the text gets formatted in accordance with your suggestions. With regard to `Char.IsLetter`, `Char` is a primitive in C# that has a static method `IsLetter`. So it has to be a capital `C` because C# is case-sensitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:50:45.053",
"Id": "76057",
"Score": "2",
"body": "@sigil Yes, C# is case-sensitive, but the type `char` is exactly the same as `System.Char`. So, both versions will work the same here (unlike e.g. in Java, where `char` and `Character` are different types)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:53:09.057",
"Id": "76060",
"Score": "0",
"body": "I didn't know that, thanks for pointing that out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:12:10.720",
"Id": "43805",
"ParentId": "43756",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43757",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T23:46:09.717",
"Id": "43756",
"Score": "9",
"Tags": [
"c#"
],
"Title": "Is there an easier way to find the index of the first letter in a string?"
} | 43756 |
<p>I am SURE this is somehow easy but reading the docs isn't bringing it to light.</p>
<p><strong>The problem:</strong> I am trying to setup a JMS message listener and what I need is for the first client to have exclusive message processing rights.</p>
<p>That is: Until a single client acknowledges the message the server will not notify any other consumers of the message.</p>
<p>I believe this is correct but I am looking for some verification. The whole 'transacted' part is throwing me off </p>
<p>As an aside: I posted it to regular SOF and got told to repost here. </p>
<pre><code> public class QueueMessengerMessageListener implements MessageListener {
protected Logger log = LoggerFactory.getLogger(getClass());
private Connection connection;
@Autowired
private Queue q;
@Autowired
private ConnectionFactory connectionFactory;
@Autowired
private DWHService dwhService;
@PostConstruct
private void listen() throws JMSException {
connection = connectionFactory.createConnection();
Session jmsSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = jmsSession.createConsumer(q);
consumer.setMessageListener(this);
connection.start();
}
@PreDestroy
public void destroy() throws JMSException {
connection.close();
}
@Override
@Transactional
public void onMessage(Message m) {
BytesMessage jmsMessage = (BytesMessage) m;
MyObject userMessage = null;
try {
byte[] in = new byte[(int) jmsMessage.getBodyLength()];
jmsMessage.readBytes(in);
ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(in));
userMessage = (MyObject) inStream.readObject();
dwhService.addDwhEntry(userMessage);
m.acknowledge();
}
catch (Exception e) {
/* I normally wouldn't catch *all* exceptions, but the JMS tutorial says Thou Shalt Not throw
* a RuntimeException from this method. */
log.error("Error sending message {}", e.getMessage());
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:09:54.130",
"Id": "75854",
"Score": "1",
"body": "Sorry for pointing back to Stack Overflow, but I guess asking there about how `Session.CLIENT_ACKNOWLEDGE` and `@Transactional` work together will get you (better) answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:12:37.720",
"Id": "75856",
"Score": "0",
"body": "I think Code Review is the best place for this particular question as it is currently phrased, let's hope that some expert in this area can come here and give some two cents about it. I personally haven't used Java Messaging Service (JMS) at all before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:13:51.023",
"Id": "75857",
"Score": "0",
"body": "But asking a specific and good SO question that is on-topic for SO will likely give you more knowledge about the workings of this, and might be more helpful for you."
}
] | [
{
"body": "<p>The code looks fine although I'm not familiar with JMS, so I can't say anything about it's correctness. Just three minor notes:</p>\n\n<ol>\n<li><p><code>userMessage</code> could be declared inside the <code>try</code> block:</p>\n\n<pre><code>try {\n byte[] in = new byte[(int) jmsMessage.getBodyLength()];\n jmsMessage.readBytes(in);\n ObjectInputStream inStream = new ObjectInputStream(new ByteArrayInputStream(in));\n MyObject userMessage = (MyObject) inStream.readObject();\n...\n</code></pre>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><blockquote>\n<pre><code>protected Logger log = LoggerFactory.getLogger(getClass());\n</code></pre>\n</blockquote>\n\n<p>The logger could be <code>private</code>.</p>\n\n<p>(<em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><p>The logger also could be static. There is a <a href=\"https://stackoverflow.com/a/1029304/843804\">good template for Eclipse</a> for generating <code>getLogger</code> calls with <code>MyType.class</code> classes instead of <code>getClass()</code>:</p>\n\n<pre><code>private static final Logger log = LoggerFactory.getLogger(QueueMessengerMessageListener.class);\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:47:54.477",
"Id": "76165",
"Score": "0",
"body": "You're right on both accounts. I ripped off this code from another example I had."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T00:20:21.797",
"Id": "43829",
"ParentId": "43758",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:29:19.843",
"Id": "43758",
"Score": "5",
"Tags": [
"java",
"spring",
"jms"
],
"Title": "JMS configuration -- client exclusive messages"
} | 43758 |
<p>I wrote this bit of python intending it to become some module to replace excel mapping programs like <a href="http://www.altova.com/mapforce.html">MapForce</a>. Right now it only does columns to columns. So the number of rows in always equals the number of rows out.</p>
<p>To declare a map, use a python <code>defaultdict(list)</code> object</p>
<pre><code>from collections import defaultdict
demoCmd = defaultdict(list)
demoCmd = {
'A': [mapOper.mapVal, 'Hello, World'],
'B': [mapOper.mapSum, 0, 1, 2],
'C': [mapOper.mapAss, 3, 4, 5],
'D': [mapOper.mapProd, [mapOper.mapSum, 1, 0], 0, 1],
'E': 5
}
</code></pre>
<p>The keys are the destination columns name or index. Integers can be used as keys but they must be zero offset. Strings are converted to zero offset integers. The Lists are the functions mapping to that column. It's in LISP style <code>[function arg1, arg2, etc]</code>, where integers are column indexes (zero offset) and strings are raw values. And you can nest the lists like in <code>'D'</code>. </p>
<p><code>mapOper</code> is just a file containing some commonly used functions. Some of them I don't think I need to include <em>eg</em></p>
<pre><code>def mapSum(*valueList):
filter(None, valueList)
return sum(valueList)
</code></pre>
<p>Anyways the main engine is this</p>
<pre><code>def evalOpList(opList, fromSheet, row):
if type(opList) is str: # treat arg as a value
return opList
elif type(opList) is int: # treat arg as index
return fromSheet.cell(row, opList).value
else: # its another function
args = list()
itOpList = iter(opList)
next(itOpList)
args = [evalOpList(it, fromSheet, row) for it in itOpList]
return opList[0](*args)
def interpColMap(mapCmd, fmSheet, toSheet, rTop=0, rBot=0, rToTop=0):
if rBot < 0:
rBot = fmSheet.nrows
MapCmdConvert(mapCmd)
assert rTop < rBot and rToTop >= 0
for row in range(rTop, rBot):
for key in list(mapCmd.keys()):
toSheet.write(row, key, evalOpList(mapCmd[key], fmSheet, row))
</code></pre>
<p>And you call it like this</p>
<pre><code>colMapper.interpColMap(demoCmd, fws, tws)
</code></pre>
<p>Where <code>fws</code> is an worksheet from <code>xlrd</code> to map from and <code>tws</code> is a workbook from <code>xlwt</code> to map to.</p>
<p>I have already tested it <em>some</em> and it works. It's just that coming from C++ this seems very odd style. Only two function make up my program and no classes. I also have the problem of having all <code>int</code>s be indexes and all <code>str</code>s be values. This means I can't do <code>+= 1</code> to a column without doing <code>[int, '1']</code>. And I don't even know if that would work.</p>
<p>It's just a very unique style and I need to know if it's too convoluted or not.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T15:06:15.583",
"Id": "106703",
"Score": "0",
"body": "I have a solution for it using a custom dictionary shown [on code review](https://codereview.stackexchange.com/questions/51247/python-dictionary-black-magic) and [on github](https://github.com/ptwales/xlmp). I don't know if I should close this or answer it myself now that someone as put a bounty on it. Seems immoral to claim a bounty on my own question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T15:19:51.683",
"Id": "106708",
"Score": "2",
"body": "Not at all! \"Selfies\" are well accepted in Stack Exchange. If your answer will answer your question and do a good review why not ? And with the bounty maybe someone else will add an answer too!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T15:22:03.833",
"Id": "106709",
"Score": "0",
"body": "someone will come along and post on it too, you should post a review of this code now that you have done it differently, but also be prepared someone might suggest doing it differently. you could also post your new code as a new question and link back to this one, and wait for other answers to this question to come in so you can see what else you can learn about this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-06T15:38:30.903",
"Id": "106718",
"Score": "0",
"body": "Go for it @ptwales, just keep in mind that any answer you post should be a code review, not just \"this is how I ended up doing it\". I put the bounty here because I thought it was a good question, and it's my way of [killing zombies](http://meta.codereview.stackexchange.com/questions/1510/whats-a-zombie-and-what-are-the-many-other-memes-of-code-review)."
}
] | [
{
"body": "<p>Generally camelCase is used for both locals and functions.\nBoth PEP 8 and Google style guide recommend underscore lower_caps for both.\ncamelCase isn't <em>wrong</em> in python, it's just sticking with global standards in more right.</p>\n\n<p>Also some names could be more descriptive.\n<code>rBot</code> could be <code>bottom_row</code>.\n<code>operator_list</code> is more verbose than <code>opList</code> but it's name is now exactly what it is and there is no question of the programmers intention of the variable.</p>\n\n<hr>\n\n<p>Initializing the demo command is done incorrectly despite it being functional code.\nIt shows a lack of understanding of how variables work in python.</p>\n\n<blockquote>\n<pre><code>demoCmd = defaultdict(list)\ndemoCmd = {\n 'A': [mapOper.mapVal, 'Hello, World'],\n 'B': [mapOper.mapSum, 0, 1, 2],\n 'C': [mapOper.mapAss, 3, 4, 5],\n 'D': [mapOper.mapProd, [mapOper.mapSum, 1, 0], 0, 1],\n 'E': 5\n }\n</code></pre>\n</blockquote>\n\n<p>Variables work differently in python than in C-ish languages.\nThere are better explanations of it that I will link to later,\nbut for now this will suffice: \nVariables in python are essentially C-pointers that can point to any object,\nwhich is everything in python.</p>\n\n<pre><code>demoCmd = defaultdict(list)\n</code></pre>\n\n<p>creates a new <code>defaultdict(list)</code> and assigns <code>demoCmd</code> to it.</p>\n\n<pre><code>demoCmd = { ... }\n</code></pre>\n\n<p>was intended to modify the data in the defaultdict object, <code>demoCmd</code>.\nHowever it reassigns the variable <code>demoCmd</code> to a new dict object (<code>{}</code> is equivalent to <code>dict()</code>).\nThis wasn't a problem because <code>demoCmd</code> never needed to be a defaultdict object in the first place.\nHowever, if it needed to be, the data could be entered using member functions or operators like so</p>\n\n<pre><code>demoCmd = defaultdict(list)\ndemoCmd.add('A': [1, 2, 3])\ndemoCmd['B'] = [4, 5, 6]\n</code></pre>\n\n<hr>\n\n<p>Type checking with <code>isinstance()</code> is preferred over <code>type()</code> as <code>isinstance()</code> will match the specified class and all of it's sub classes,\nwhile <code>type()</code> will only match the exact class.\n<a href=\"https://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python\">More here.</a></p>\n\n<p>Ergo,</p>\n\n<blockquote>\n<pre><code>def evalOpList(opList, fromSheet, row):\n if type(opList) is str: # treat arg as a value\n return opList\n elif type(opList) is int: # treat arg as index\n return fromSheet.cell(row, opList).value\n # ...\n</code></pre>\n</blockquote>\n\n<p>is more flexible as,</p>\n\n<pre><code>def evalOpList(opList, fromSheet, row):\n if isinstance(opList, str): # treat arg as a value\n return opList\n elif isinstance(opList, int): # treat arg as index\n return fromSheet.cell(row, opList).value\n # ...\n</code></pre>\n\n<hr>\n\n<p>The command dictionary has the structure of <code>{key : [func , arg1, arg2, arg3, ...]}</code>.\nSeparating the arguments from the function as a tuple,</p>\n\n<pre><code>{key: (func, (arg1, arg2, arg3, ...))}\n</code></pre>\n\n<p>may seem more verbose but it will make extracting the pair simpler,</p>\n\n<pre><code>else: # its another function\n func, arg_list = operator_tuple\n args = [evalOpList(arg, fromSheet, row) for arg in arg_list]\n return func(*args)\n</code></pre>\n\n<p>Allowing nesting of functions in the map commands creates an unnecessary complexity to the code.\nDropping that ability allows <code>evalOplist</code> to be split into smaller functions.</p>\n\n<pre><code>def evaluate_command(command, from_sheet, row):\n if isinstance(command, (tuple, list)):\n return evaluate_func(func, val_list, from_sheet, row)\n else:\n evaluate_value(command, from_sheet, row)\n\ndef evaluate_value(val, from_sheet, row):\n if isinstance(val, int):\n return from_sheet.cell(row, val).value\n else:\n return command\n\ndef evaluate_func(func, val_list, from_sheet, row):\n args = [evaluate_value(val, from_sheet, row) for val in val_list]\n return func(*args)\n</code></pre>\n\n<p>Two problems still exist:</p>\n\n<ol>\n<li><code>evaluate_value</code> is not recursing into any sequences to replace indexes, which is needed for functions like <code>sum</code>.</li>\n<li><code>evaluate_command</code> is unnecessarily re-interpreting items in the mapping command for each row of the sheet.\nCommands could be pre-emptively interpreted into functions that take the row values and return a value.</li>\n</ol>\n\n<p>I could walk readers through how to completely redesign the structure to pre-interpret the commands, but that seems out of codereveiw's scope. See <a href=\"https://codereview.stackexchange.com/questions/51247/python-dictionary-black-magic\">here</a> and <a href=\"https://github.com/ptwales/xlmp/blob/master/xlmp.py\" rel=\"nofollow noreferrer\">here</a> for those solutions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-08T16:53:08.530",
"Id": "59522",
"ParentId": "43759",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "59522",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T00:53:41.170",
"Id": "43759",
"Score": "8",
"Tags": [
"python",
"excel"
],
"Title": "Excel Mapping Module"
} | 43759 |
<p>I'm working on a <a href="https://github.com/SublimeText/CTags" rel="nofollow">CTags plugin for Sublime Text</a>. One of the <a href="https://github.com/SublimeText/CTags/issues/145" rel="nofollow">open issues</a> revolves around the fact that an in-memory sort of a tag file can cause some form of memory or buffer overflow errors (the stack in Sublime Text is limited to ~25 MB apparently). I've devised a simple external bucket sort to resolve this issue:</p>
<pre><code>#/usr/bin/env python
#
# CSV external bucket sort
import codecs
import tempfile
import os
# column indexes
SYMBOL = 0
FILENAME = 1
TAG_FILE = 'tags'
OUT_FILE = ''.join([TAG_FILE, '_sorted_by_file'])
def sort():
"""External bucket sort of tab delimited CTag files"""
temp_files = {}
def get_file(filename):
"""Get a file from the store of files"""
if not filename in temp_files:
temp_files[filename] = tempfile.NamedTemporaryFile(delete=False)
# close and reopen using codecs to avoid problems described here:
# http://stackoverflow.com/a/10490859/613428
temp_files[filename].close()
temp_files[filename] = codecs.open(
temp_files[filename].name, 'w+', 'utf-8', 'ignore')
return temp_files[filename]
try:
with codecs.open(TAG_FILE, 'r+', 'utf-8', 'ignore') as file_o:
for _ in range(6): # skip the header
next(file_o)
for line in file_o:
temp_file_o = get_file(line.split('\t')[FILENAME])
split = line.split('\t')
split[FILENAME] = split[FILENAME].lstrip('.\\')
temp_file_o.write('\t'.join(split))
with codecs.open(OUT_FILE, 'w+', 'utf-8', 'ignore') as file_o:
# we only need to sort the file names - the symbols were already
# sorted!
for key in sorted(temp_files):
temp_files[key].seek(0)
file_o.write(temp_files[key].read())
finally:
for key in temp_files:
temp_files[key].close()
os.remove(temp_files[key].name)
os.remove(OUT_FILE) # just for testing - remove when done
</code></pre>
<p>Here's what I intended to do:</p>
<pre><code>For each line (a.k.a. tag) in a tag file
Read line into memory
Get the filename from the line.
Use filename as key to a temp file and write whole this line to said file
Sort final list of keys (i.e. filenames)
For each file in sorted key list
Append contents of file to sorted tag file
Close all files and delete temp files
</code></pre>
<p>And the performance:</p>
<pre><code>$ python -m timeit -n 100 'import external_sort; external_sort.sort()'
100 loops, best of 3: 12 msec per loop
</code></pre>
<p>My question is this: <strong>is this as performant as it could be?</strong> Could I <strong>improve it in any way</strong>, e.g. missing corner cases?</p>
<p><strong>NOTE:</strong> I'm aware that it's not <em>really</em> a true bucket sort as the buckets aren't arbitrary or equally sized (a project with many small files and few large files would result in unbalanced buckets). However, I'm counting on there being many average sized files and none big-enough to fill memory by themselves.</p>
| [] | [
{
"body": "<ul>\n<li>It is not necessary to decode and encode UTF-8, as <code>split('\\t')</code> and <code>lstrip('.\\\\')</code> work fine on UTF-8-encoded strings. </li>\n<li>The programs keeps an unlimited number of temporary files open simultaneously and will fail after exceeding the platform's maximum for open files. An approach where only a certain number of most recently used files are kept open could be appropriate here.</li>\n<li><code>file_o.write(temp_files[key].read())</code> reads the entire file in memory. To conserve memory, use a loop and give a block size argument to <code>read</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T09:30:09.440",
"Id": "44426",
"ParentId": "43760",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T01:18:43.400",
"Id": "43760",
"Score": "5",
"Tags": [
"python",
"algorithm",
"sorting"
],
"Title": "External \"bucket\" sort"
} | 43760 |
<p>I am designing a new application to track sports statistics with code-first migration. I have the bare minimum POCO setup. The problem is that I am not happy with the design specifically how the players, teams and tournaments are relating to each other. </p>
<p>I appreciate any comments and suggestions.</p>
<p><strong>PlayerAccount class:</strong></p>
<pre><code>/// <summary>
/// Player account is a separate entity from the actual user account.
/// Player account allows a user to join teams and participate in a tournament.
/// </summary>
public class PlayerAccount
{
[Key]
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
/// <summary>
/// TournamentPlayerKeys tells us which team this player is competing with
/// in a certain tournament.
/// </summary>
public virtual ICollection<PlayerTeamKey> PlayerTeamKeys { get; set; }
public virtual ICollection<PlayerMatchStat> PlayerMatchStats { get; set; }
}
</code></pre>
<p><strong>Team class:</strong></p>
<pre><code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Team can be formed by a single user or a group of user. You'll need a team to join a tournament.
/// A single user can form his own team.
/// </summary>
public class Team
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<PlayerTeamKey> PlayerTeamKeys { get; set; }
public virtual ICollection<TeamTournamentKey> TeamTournamentKeys { get; set; }
}
</code></pre>
<p><strong>Tournament class:</strong></p>
<pre><code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Tournaments are basically a collection of games in one event.
/// For example, Summer 2014 Basketball League.
/// </summary>
public class Tournament
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<TeamTournamentKey> TeamTournamentKeys { get; set; }
public virtual ICollection<TournamentMatch> TournamentMatches { get; set; }
}
</code></pre>
<p>On a tournament there are multiple instances of matches (games):</p>
<pre><code>/// <summary>
/// Match represents one occurence of a game in a league.
/// </summary>
public class TournamentMatch
{
[Key]
public int Id { get; set; }
[Required]
public int Tournament_Id { get; set; }
[ForeignKey("Tournament_Id")]
public virtual Tournament Tournament { get; set; }
public virtual ICollection<TournamentMatchResult> TournamentMatchResults { get; set; }
}
</code></pre>
<p>And of course we have multiple instances of match results in one match. The <code>Score</code> property determines who is the winner.</p>
<pre><code>/// <summary>
/// This is the result of a league match.
/// </summary>
public class TournamentMatchResult
{
[Key]
public int Id { get; set; }
[Required]
public int Match_Id { get; set; }
[Required]
public int Team_Id { get; set; }
[Required]
public double Score { get; set; }
[ForeignKey("Match_Id")]
public virtual TournamentMatch TournamentMatch { get; set; }
[ForeignKey("Team_Id")]
public virtual Team Team { get; set; }
public virtual ICollection<PlayerMatchStat> PlayerMatchStat { get; set; }
}
</code></pre>
<p>I have a multipart key that creates the relationship between a player and a team:</p>
<pre><code>/// <summary>
/// This is a multipart key class that defines a player as part of a team.
/// Mind the naming convension, from smaller entity to a bigger entity; Player > Team.
/// </summary>
public class PlayerTeamKey
{
[Required]
public int PlayerAccount_Id { get; set; }
[Required]
public int Team_Id { get; set; }
[ForeignKey("PlayerAccount_Id")]
public virtual PlayerAccount Player { get; set; }
[ForeignKey("Team_Id")]
public virtual Team Team { get; set; }
}
</code></pre>
<p>And I have another like that for team and tournament:</p>
<pre><code>/// <summary>
/// This is a multipart key class that is a combination of a team id and a tournament id.
/// This basically tells us that the team with the given id is going to participating on a tournament with the given id.
/// </summary>
public class TeamTournamentKey
{
[Required]
public int Team_Id { get; set; }
[Required]
public int Tournament_Id { get; set; }
[ForeignKey("Team_Id")]
public virtual Team Team { get; set; }
[ForeignKey("Tournament_Id")]
public virtual Tournament Tournament { get; set; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T16:36:43.447",
"Id": "101291",
"Score": "1",
"body": "It's been a while since I've used EF but I don't recall having to create my own model for a N-N relationship. I'll take a look into it tonight after my Civ 5 game but I believe you can indeed make that much cleaner."
}
] | [
{
"body": "<p>Don't use underscores in identifiers. <s>If that's how the database has them, use a <code>ColumnAttribute</code> to specify the column name</s> <em>scratch that, you're going code-first</em>. This:</p>\n\n<pre><code>public int Tournament_Id { get; set; }\n\npublic int Match_Id { get; set; }\npublic int Team_Id { get; set; }\n\npublic int PlayerAccount_Id { get; set; }\n</code></pre>\n\n<p>Is much more <em>seesharpesque</em> like this:</p>\n\n<pre><code>public int TournamentId { get; set; }\n\npublic int MatchId { get; set; }\npublic int TeamId { get; set; }\n\npublic int PlayerAccountId { get; set; }\n</code></pre>\n\n<p>I like that most of these foreign key properties follow a very predictable naming pattern <code>[ForeignEntityTypeName]Id</code> - IIRC that's all EF needs to be able to <em>infer</em> the foreign keys.</p>\n\n<p>...With the exception of <code>TournamentMatchResult</code>, which breaks the pattern with its <code>MatchId</code> (/<code>Match_Id</code>) property:</p>\n\n<pre><code>public int Match_Id { get; set; }\npublic virtual TournamentMatch TournamentMatch { get; set; }\n</code></pre>\n\n<p>Would be more consistent like this:</p>\n\n<pre><code>public int TournamentMatchId { get; set; }\npublic virtual TournamentMatch TournamentMatch { get; set; }\n</code></pre>\n\n<hr>\n\n<p>You're <code>using System.ComponentModel.DataAnnotations;</code>; it <em>works</em>, but I find all these attributes <em>pollute</em> the POCO:</p>\n\n<blockquote>\n<pre><code>[Key]\npublic int Id { get; set; }\n[Required]\npublic int Match_Id { get; set; }\n[Required]\npublic int Team_Id { get; set; }\n[Required]\npublic double Score { get; set; }\n\n[ForeignKey(\"Match_Id\")]\npublic virtual TournamentMatch TournamentMatch { get; set; }\n[ForeignKey(\"Team_Id\")]\npublic virtual Team Team { get; set; }\n</code></pre>\n</blockquote>\n\n<p>EF is smart enough to know <code>Id</code> is your <code>[Key]</code> (by naming convention), and smart enough to know <code>Team</code> is a FK that uses <code>TeamId</code> (by naming convention) - I'm not sure whether <code>Team_Id</code> breaks it or not, but relying on EF's established conventions makes your POCO code less polluted:</p>\n\n<pre><code>public int Id { get; set; }\n\n[Required]\npublic int TournamentMatchId { get; set; }\n\n[Required]\npublic int TeamId { get; set; }\n\n[Required]\npublic double Score { get; set; }\n\npublic virtual TournamentMatch TournamentMatch { get; set; }\npublic virtual Team Team { get; set; }\n</code></pre>\n\n<p>Now all that's left is <code>[Required]</code> attributes. You could remove them too, if you moved POCO configurations/mappings elsewhere.</p>\n\n<hr>\n\n<p>One way of doing that would be in the <code>OnModelCreating</code> override of your <code>DbContext</code>:</p>\n\n<pre><code>modelBuilder.Entity<TournamentMatchResult>()\n .Property(t => t.TournamentMatchId).IsRequired();\nmodelBuilder.Entity<TournamentMatchResult>()\n .Property(t => t.TeamId).IsRequired();\nmodelBuilder.Entity<TournamentMatchResult>()\n .Property(t => t.Score).IsRequired();\n</code></pre>\n\n<p>Obviously this gets very verbose, very fast. An alternative is to use <code>EntityMappingConfiguration<TEntityType></code> classes. For each entity type, you create a mapping class:</p>\n\n<pre><code>public class TournamentMatchResultMap : EntityMappingConfiguration<TournamentMatchResult>\n{\n public TournamentMatchResultMap()\n {\n Property(t => t.TournamentMatchId).IsRequired();\n Property(t => t.TeamId).IsRequired();\n Property(t => t.Score).IsRequired();\n }\n}\n</code></pre>\n\n<p>You can also use these mapping classes to configure mapped column names and table, and relationships with other entities. See <a href=\"http://msdn.microsoft.com/en-us/library/gg696748(v=vs.113).aspx\" rel=\"nofollow noreferrer\"><code>EntityMappingConfiguration<TEntityType></code></a></p>\n\n<p>Then the <code>OnModelCreating</code> override simply loads all the configurations:</p>\n\n<pre><code>modelBuilder.Configurations.Add(new TournamentMatchResultMap());\n</code></pre>\n\n<p>I find that's the cleanest approach; it lets your POCO classes be POCO's, it leaves the <code>OnModelCreating</code> method free of verbose fluent API mappings, and it puts each entity's configurations into its own class.</p>\n\n<hr>\n\n<p>Let's look at the relationships. If I didn't make mistakes, this is what your code can be modeled as:</p>\n\n<p><a href=\"http://yuml.me/edit/5090cace\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tPU2h.png\" alt=\"http://yuml.me/edit/5090cace\"></a></p>\n\n<p>As @Jeroen explains, EF doesn't need junction tables to model a many-to-many relationship; <code>PlayerTeamKey</code> and <code>TeamTournamentKey</code> entities can be removed.</p>\n\n<p>I would believe this simplified model could very well suit your needs:</p>\n\n<p><a href=\"http://yuml.me/edit/15eb9eca\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dih4Q.png\" alt=\"http://yuml.me/edit/15eb9eca\"></a></p>\n\n<p>The idea is to use the navigation properties to <em>navigate</em> between entities - from a <em>business</em> standpoint it makes sense for tournament matches to know what teams are involved, but from a <em>data</em> standpoint, it doesn't: when your application creates a new tournament, it also creates a <code>TournamentMatchResult</code> for all teams involved, with each team's score at 0 - and that's enough for a <code>TournamentMatch</code> to know what teams are playing.</p>\n\n<p>As the game evolves, you can then update the <code>TournamentMatchResult</code> records, and if a <code>TournamentMatch</code> needs to know what teams are involved, it can easily find out by selecting its <code>.TournamentMatchResults.Select(result => result.Team)</code>.</p>\n\n<p>Notice this results in simple, easy-to-follow, one-to-many relationships everywhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-14T07:45:36.557",
"Id": "101612",
"Score": "0",
"body": "What is the meaning of arrows in your diagram? I beleive the arrow should signify \"A uses B\" and thus should be drawn in oposite direction, e.g. TournamentMatchResult uses Team."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-14T11:06:22.070",
"Id": "101656",
"Score": "0",
"body": "\"One to many\". The \"many\" end has a star (*). Maybe they are reversed, UML isn't my cup of tea. But one gets the idea I'd guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-14T11:11:21.930",
"Id": "101659",
"Score": "0",
"body": "FWIW I've drawn the arrows based on the yUML \"tutorial\": http://yuml.me/diagram/class/draw"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-14T21:47:22.303",
"Id": "101776",
"Score": "0",
"body": "Are you sure that all those associations should be really \"shared aggregations\"? It does not make sense to me. Most common types of associations can be seen here: http://msdn.microsoft.com/en-us/library/dd409437%28VS.100%29.aspx. And when I think about it - is it logical for TournamentMatchResult to belong to many different Tournaments? I beleive it is more common for a Match to belong to only one Tournament..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-14T22:25:59.900",
"Id": "101780",
"Score": "0",
"body": "@VDohnal you're reading it wrong. 1 tournaments -> * tournament matches; 1 tournament match -> * results. A TournamentMatchResult can only belong to one TournamentMatch, which can only belong to one Tournament. The only associations in that diagram, are one-to-many...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-15T08:02:54.770",
"Id": "101828",
"Score": "1",
"body": "Ok, thanks, I got it, it makes sense this way. It is based on a presumption, that N teams can participate in one match. Still shared aggregation is not the right assoication to be used here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-17T03:18:41.097",
"Id": "102280",
"Score": "0",
"body": "Thanks Mat. This reply is very informative. I've never used the EntityMappingConfiguration<T> before that will definitely help clean up the POCO. I have one problem though, the IsRequired method could not be found. Am I missing something here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-17T13:34:31.007",
"Id": "102362",
"Score": "0",
"body": "@PlatypusMaximus no, looks like EF6 has changed this part ([been using EF5](http://msdn.microsoft.com/en-us/library/system.data.entity.modelconfiguration.configuration.primitivepropertyconfiguration(v=vs.103).aspx)), not sure how exactly, but I'm sure there's still a way of specifying a [required] property in an `EntityMappingConfiguration<TEntity>` class."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T14:48:19.850",
"Id": "56846",
"ParentId": "43762",
"Score": "10"
}
},
{
"body": "<p>I made a small example to show you that all your worries are in the past. Before you implement this yourself though, keep Mat's remarks in mind: I made this as a quick sketch and separating the mappings from the context, naming conventions, etc are important for your code's clarity. </p>\n\n<p>That being said, this small setup shows you how you can change it:</p>\n\n<pre><code>public class Player\n{\n public int Id { get; set; }\n public string Firstname { get; set; }\n public string Lastname { get; set; }\n\n public virtual ICollection<Team> Teams { get; set; }\n}\n\npublic class Team\n{\n public int Id { get; set; }\n public string Name { get; set; }\n\n public virtual ICollection<Player> Players { get; set; }\n}\n</code></pre>\n\n<p>That's it. You're done! All we need to do now is configure our mapping so it will generate the intermediate table itself:</p>\n\n<pre><code>public class TournamentContext : DbContext\n{\n public DbSet<Player> Players { get; set; }\n public DbSet<Team> Teams { get; set; }\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n modelBuilder.Entity<Player>()\n .HasKey(x => x.Id)\n .HasMany(x => x.Teams);\n\n modelBuilder.Entity<Team>()\n .HasKey(x => x.Id)\n .HasMany(x => x.Players);\n } \n}\n</code></pre>\n\n<p>If you want to test it out yourself, you can use this sample code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n using (var context = new TournamentContext())\n {\n context.Database.ExecuteSqlCommand(\"delete from Players\");\n context.Database.ExecuteSqlCommand(\"delete from Teams\");\n\n var team1 = context.Teams.Add(new Team {Name = \"Power rangers\"});\n var team2 = context.Teams.Add(new Team { Name = \"Ninja turtles\" });\n\n context.Players.Add(new Player\n {\n Firstname = \"John\",\n Lastname = \"Johnson\",\n Teams = new List<Team> {team1, team2}\n });\n\n context.Players.Add(new Player\n {\n Firstname = \"Jack\",\n Lastname = \"Jackson\",\n Teams = new List<Team>{team1}\n });\n\n context.SaveChanges();\n\n foreach (var player in context.Players.ToList())\n {\n Console.WriteLine(\"Player: \" + player.Id);\n Console.WriteLine(\"Teams: \" + string.Join(\", \", player.Teams.Select(x => x.Name).ToArray()));\n }\n }\n\n Console.Read();\n}\n</code></pre>\n\n<p>Looking at our database using the Server Explorer we now see these tables:</p>\n\n<p><img src=\"https://i.stack.imgur.com/SvS1V.png\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/WrkLn.png\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/MBmYR.png\" alt=\"enter image description here\"></p>\n\n<p>With this output:</p>\n\n<p><img src=\"https://i.stack.imgur.com/YuHEB.png\" alt=\"enter image description here\"></p>\n\n<p>You'll find that you can configure this a lot and add restrictions to the table that gets generated but I'm too lazy to look them up myself; mapping isn't my best side. This should give you an idea though about how you can get rid of those not-so-pretty intermediate tables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T18:16:50.063",
"Id": "56860",
"ParentId": "43762",
"Score": "9"
}
},
{
"body": "<p>I suggest to use the same name for primary and foreign keys following some consistent pattern:</p>\n\n<p>It could be e.g. _id or Id, so you will have in PlayerAccount table the primary key PlayerAccountId (instead of just Id) and in PlayerTeamKey also PlayerAccountId as a foreign key.</p>\n\n<p>Naming of fields and classes is very important in non-small projects.</p>\n\n<p>I believe it does not matter whether you follow code-first or model-first or whatever approach, your problem is propper class design and naming. I personally like very much code-second pattern using PowerToys - you can do your data diagram 1] in a object design tool like Enterprise Architect 2] in SQL database like SQL Server. Then you export this design as code-first using PowerToys.</p>\n\n<p>You must organize the terms you use and convert them to meaningful class design, which is not allways easy.</p>\n\n<p>Here is the diagram of classes you presented:\n<img src=\"https://i.stack.imgur.com/csmGB.png\" alt=\"Diagram of your classes\"></p>\n\n<p>You can create quite easily this class diagram in Visual Studio.\nAppearently there is missing Match class. (Match_Id - foreign key) (OK it is not missing, it is a link to the very suspicious TournamentMatch class, I get it)</p>\n\n<p>Your basic classes are Player (originally PlayerAccount), Team, Match (originally TournamentMatchResult), Tournament. I have renamed the classes - it is more comprehensible this way I think. The other classes are empty association classes that are used to create M:N relation. Are all those M:N relations really necessary and OK?</p>\n\n<p>There are too many unanswered questions</p>\n\n<p><img src=\"https://i.stack.imgur.com/V8rMG.png\" alt=\"enter image description here\"></p>\n\n<p>Basically your main problem is that in your design you have too many atribute-less association classes (PlayerTeamKey, TournamentMatch ... I see 4 of them), which is very probably error in class design.</p>\n\n<p>You should first answer the kind of questions, which I wrote into second diagram, and then and only then start writing your code. Otherwise your design will fail.</p>\n\n<h2>EDIT:</h2>\n\n<p>To give an example how you can make proper design by answering analytical questions, I have created simplified version. You can as I believe, create your model with just 4 classes depending on how you answer the analytical questions. This model can be easily convereted to C# code first, but firts confirm whether this is the model you seek.</p>\n\n<p><img src=\"https://i.stack.imgur.com/r8Knp.png\" alt=\"SimplifiedVersion\"></p>\n\n<p>One more hint: if you use word Match for a match, do not call it Game, use just as few terms as it is absolutely necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T18:36:02.093",
"Id": "101314",
"Score": "0",
"body": "There's no `Match` entity - it's `TournamentMatch`: I almost fell in the same trap, it's the name of the foreign key property (`Match_Id`) that's confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T18:41:08.137",
"Id": "101316",
"Score": "0",
"body": "In that case TournamentMatch class should be deleted and replaced by composition 1:N Tournament - TournamentMatchResult. The names of classes are misleading which should be corrected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T18:42:36.413",
"Id": "102199",
"Score": "0",
"body": "You're right, `TournamentMatch` is not needed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-12T18:31:36.827",
"Id": "56861",
"ParentId": "43762",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "56846",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T02:03:58.670",
"Id": "43762",
"Score": "12",
"Tags": [
"c#",
"asp.net",
"entity-framework",
"asp.net-mvc-4",
"poco"
],
"Title": "Tracking sports statistics"
} | 43762 |
<p>In my Java code I have these three classes. Basically I have a User class, and also a GUI class that holds <code>TextView</code>s and other things (GUI related) for the properties that show on the screen.</p>
<p>The <code>SearchUser</code> is just a object that has the GUI properties. One of these per user object.
I noticed that both the user class and the <code>SearchUser</code> class share the same properties, so I took them out and made a <code>BaseUser</code> class, and then extended it to have that.</p>
<p>I don't think the way I structured this is good for Java programming practices. I think some sort of encapsulation or something will be better but I'm not sure what I can do here.</p>
<p>I need the user object and GUI object to also be separate for modularity purposes.</p>
<p>Does anyone see a better way of writing the below code?</p>
<p><strong>BaseUser.java</strong></p>
<pre><code>package sord.object;
public class BaseUser {
int userid;
String firstname;
String lastname;
String emailaddress;
int roleId;
Boolean active;
String picURL;
}
</code></pre>
<p><strong>User.java</strong></p>
<pre><code>package sord.object;
import java.util.Date;
import android.content.Context;
import sord.common.DateTimeFunctions;
public class User extends BaseUser {
private String password;
private String phoneNumber;
private String websiteLink;
private String statusText;
private String bioText;
private Date dateJoined;
private Date dateLastActive;
public User(int userid, String firstName, String lastName,
String password, String emailAddress, String phoneNumber,
String websiteLink, String statusText, String bioText, int roleId,
String dateJoined, String dateLastActive, int active,
String picURL, Context context) {
this.userid = userid;
this.firstname = firstName;
this.lastname = lastName;
this.password = password;
this.emailaddress = emailAddress;
this.phoneNumber = phoneNumber;
this.websiteLink = websiteLink;
this.statusText = statusText;
this.bioText = bioText;
this.roleId = roleId;
this.dateJoined = DateTimeFunctions.ConvertStringToDate(context, dateJoined, false);
this.dateLastActive = DateTimeFunctions.ConvertStringToDate(context, dateLastActive, true);
this.active = active == 1;
this.picURL = picURL;
}
public int getUserId() {
return userid;
}
public String getFirstName() {
return firstname;
}
public String getLastName() {
return lastname;
}
public String getPassword() {
return password;
}
public String getEmailAddress() {
return emailaddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getWebsiteLink() {
return websiteLink;
}
public String getStatusText() {
return statusText;
}
public String getBioText() {
return bioText;
}
public int getRoleId() {
return roleId;
}
public Date getDateJoined() {
return dateJoined;
}
public Date getDateLastActive() {
return dateLastActive;
}
public Boolean getActive() {
return active;
}
public String getPicURL() {
return picURL;
}
}
</code></pre>
<p><strong>SearchUser.java</strong></p>
<pre><code>package sord.object;
import java.util.ArrayList;
import android.widget.LinearLayout;
import android.widget.TextView;
public class SearchUser extends BaseUser {
public Boolean origActive;
public Boolean selected = false;
public Boolean deleted = false;
public Boolean edited = false;
public TextView nameView;
public LinearLayout userLayout;
private ArrayList<PlacementGUI> placementList = new ArrayList<PlacementGUI>();
public SearchUser(int userid, String firstname, String lastname,
String emailaddress, int roleId, int active, String picURL) {
this.userid = userid;
this.firstname = firstname;
this.lastname = lastname;
this.emailaddress = emailaddress;
this.roleId = roleId;
this.active = active == 1;
this.picURL = picURL;
this.origActive = active == 1;
}
public void AddPlacement(PlacementGUI placement) {
placementList.add(placement);
}
}
</code></pre>
| [] | [
{
"body": "<p>Designing is art we learn from experience. Object oriented paradigm is \"natural\" way to explain things.</p>\n\n<p>SearchUser extending BaseUser is wrong naturally, isn't it ? (because SearchUser is not special type of user so can't be subclass) You can have has-a-relation ship there (i.e. SearchUser can have member which is object BaseUser )</p>\n\n<p>BaseUser variables should be private; use methods to access them ( if and when required ).</p>\n\n<pre><code>private ArrayList placementList = new ArrayList<PlacementGUI>\n</code></pre>\n\n<p>can be rewritten as</p>\n\n<pre><code>private List<PlacementGUI> placementList = new ArrayList<PlacementGUI>\n</code></pre>\n\n<p>Always program through interface; so later you can change your mind with minimal changes.</p>\n\n<p>Design is something you always do on white paper and change many times.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T04:35:08.927",
"Id": "43768",
"ParentId": "43767",
"Score": "10"
}
},
{
"body": "<p>One of the lessons I came by the hard way is that you really really want to avoid inheritance unless it's absolutely and completely obvious that you need it.</p>\n\n<p>It's really hard to tell what you should do because you didn't put any code in there. The object as a data structure is not a great idea--it's for code.</p>\n\n<p>Honestly in your case everything you have looks like data to me--are you just using it to transfer data back and forth? If so it really doesn't matter much how you structure these fields--just do it in a way that matches your needs (probably one object per screen).</p>\n\n<p>Inheritance should only be used to support code. I've heard it said that the only time you should ever inherit is if you have two children that each override a method in the parent. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T04:50:10.753",
"Id": "43769",
"ParentId": "43767",
"Score": "3"
}
},
{
"body": "<p>+1 to <em>@Chirag</em>. Some additional, minor notes:</p>\n\n<ol>\n<li><p><code>Date</code> objects are mutable. An erroneous (or malicious) client of the class could change its internal state although the class does not provide a setter:</p>\n\n<pre><code>User user = ...\nuser.getDateLastActive().setTime(5);\n</code></pre>\n\n<p>(<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>) </p></li>\n<li><p>The code contains some duplication here:</p>\n\n<blockquote>\n<pre><code>this.active = active == 1;\nthis.picURL = picURL;\nthis.origActive = active == 1;\n</code></pre>\n</blockquote>\n\n<p>It could be:</p>\n\n<pre><code>this.active = active == 1;\nthis.picURL = picURL;\nthis.origActive = this.active;\n</code></pre></li>\n<li><p>Using a named constants for <code>1</code>˛in the snippet above would help readers/maintainers because named constanst could express the purpose of value (<code>STATE_ACTIVE</code>), readers might not know what the original author wanted to achieve with the number. Currently it's a <a href=\"https://stackoverflow.com/q/47882/843804\">magic number</a>.</p></li>\n<li><p>I usually use camelCase for variables like this too:</p>\n\n<blockquote>\n<pre><code>this.picURL = picURL;\n</code></pre>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n<li><blockquote>\n<pre><code>package sord.object;\n</code></pre>\n</blockquote>\n\n<p>You could use a better package name. <a href=\"http://c2.com/ppr/wiki/JavaIdioms/JavaPackageNames.html\" rel=\"nofollow noreferrer\">Java Package Names on c2.com</a></p></li>\n<li><p>A few references for <em>@Chirag</em>'s notes:</p>\n\n<ul>\n<li><em>Effective Java, Second Edition</em>, <em>Item 52: Refer to objects by their interfaces</em></li>\n<li><em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em></li>\n<li><em>Effective Java, Second Edition</em>, <em>Item 13: Minimize the accessibility of classes and members</em></li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:20:06.220",
"Id": "43771",
"ParentId": "43767",
"Score": "5"
}
},
{
"body": "<p>Comments and short explanations are in the code comments.\nHere's an example to demonstrate constructor chaining :</p>\n\n<pre><code>// make this abstract so it's not instantiable\npublic abstract class BaseUser {\n\n // limit access to the fields, use accessor & mutator methods instead\n private int userid;\n private String firstname;\n private String lastname;\n private String emailAddress;\n private int roleId;\n private Boolean active;\n private String picURL;\n\n // initializations of these fields should happen here since BaseUser is the owner of these fields\n public BaseUser(int userid, String firstName, String lastName, \n String emailAddress, int roleId, int active, String picURL) {\n this.userid = userid;\n this.firstname = firstName;\n this.lastname = lastName;\n this.emailAddress = emailAddress;\n this.roleId = roleId;\n this.active = active == 1;\n this.picURL = picURL;\n }\n\n ...(other baseUser specific methods to change/read/validate states)\n}\n\npublic class User extends BaseUser {\n\n private String password;\n private String phoneNumber;\n private String websiteLink;\n private String statusText;\n private String bioText;\n private Date dateJoined;\n private Date dateLastActive;\n\n public User(int userid, String firstName, String lastName, \n String password, String emailAddress, String phoneNumber, \n String websiteLink, String statusText, String bioText, int roleId, \n String dateJoined, String dateLastActive, int active, \n String picURL, Context context) {\n\n // calling the BaseUser's constructor\n // this way, there's no duplications on setting these fields in the subtypes of BaseUser\n super(userid, firstName, lastName, emailAddress, roleId, active, picURL);\n\n // initialize User specific fields\n this.password = password;\n this.phoneNumber = phoneNumber;\n this.websiteLink = websiteLink;\n this.statusText = statusText;\n this.bioText = bioText;\n this.dateJoined = DateTimeFunctions.ConvertStringToDate(context, dateJoined, false);\n this.dateLastActive = DateTimeFunctions.ConvertStringToDate(context, dateLastActive, true);\n } \n\n ...(other user specific methods to change/read/validate states)\n} \n\npublic class SearchUser extends BaseUser {\n\n // limit access to the fields, use accessor & mutator methods instead\n private Boolean origActive;\n private Boolean selected = false;\n private Boolean deleted = false;\n private Boolean edited = false;\n\n private TextView nameView;\n private LinearLayout userLayout;\n\n private List<PlacementGUI> placementList;\n\n public SearchUser(int userid, String firstname, String lastname, \n String emailaddress, int roleId, int active, String picURL) {\n\n // calling the BaseUser's constructor\n // this way, there's no duplications on setting these fields in the subtypes of BaseUser\n super(userid, firstName, lastName, emailAddress, roleId, active, picURL);\n\n // initialize SearchUser specific fields\n this.origActive = active == 1;\n this.placementList = new ArrayList<PlacementGUI>();\n }\n\n ...(other searchUser specific methods to change/read/validate states)\n}\n</code></pre>\n\n<p>From the design view, if your searchUser isnt actually a user type, it shouldnt extend the BaseUser.\nImagine also if in the future searchUser type needs to extend another type, perhaps the BaseSearch type.\nThere are other ways to share the fields through compositions other than doing inheritance.</p>\n\n<p>Example :</p>\n\n<pre><code>// a simple javabean class that can be reused by others\npublic class BasicUserData {\n\n private int userid;\n private String firstname;\n private String lastname;\n private String emailAddress;\n private int roleId;\n private Boolean active;\n private String picURL;\n\n public BasicUserData(int userid, String firstName, String lastName, \n String emailAddress, int roleId, int active, String picURL) {\n this.userid = userid;\n this.firstname = firstName;\n this.lastname = lastName;\n this.emailAddress = emailAddress;\n this.roleId = roleId;\n this.active = active == 1;\n this.picURL = picURL;\n }\n\n ...(other basicUserData specific methods to change/read/validate states)\n}\n\npublic abstract class BaseUser {\n // composition example, embedding another object into another object\n private BasicUserData userData;\n\n public User(int userid, String firstName, String lastName, \n String emailAddress, int roleId, int active, String picURL) {\n // initialize the bean\n this.userData = new BasicUserData(userId, firstName, lastName,\n emailAddress, roleId, active, picUrl);\n }\n public User(BasicUserData userData) {\n this.userData = userData;\n }\n\n ...(other baseUser specific methods to change/read/validate states)\n}\n\n// doesnt need to extend BaseUser anymore\npublic class SearchUser extends BaseSearch {\n\n // composition example, embedding another object into another object\n private BasicUserData userData;\n\n // limit access to the fields, use accessor & mutator methods instead\n private Boolean origActive;\n private Boolean selected = false;\n private Boolean deleted = false;\n private Boolean edited = false;\n\n private TextView nameView;\n private LinearLayout userLayout;\n\n private List<PlacementGUI> placementList;\n\n public SearchUser(int userid, String firstname, String lastname, \n String emailaddress, int roleId, int active, String picURL) {\n\n // initialize the bean\n this.userData = new BasicUserData(userId, firstName, lastName,\n emailAddress, roleId, active, picUrl);\n\n // initialize SearchUser specific fields\n this.origActive = active == 1;\n this.placementList = new ArrayList<PlacementGUI>();\n }\n\n ...(other searchUser specific methods to change/read/validate states)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:41:43.473",
"Id": "43773",
"ParentId": "43767",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T04:21:12.507",
"Id": "43767",
"Score": "7",
"Tags": [
"java",
"classes",
"android"
],
"Title": "User search implementation"
} | 43767 |
<p>I've written some code to brute-force enumerate the solution space of <a href="http://en.wikipedia.org/wiki/Nonograms" rel="noreferrer">nonogram puzzles</a> up to a certain size. It does a good job up to the first ~4 billion puzzles, but I run out of disk space to store any bigger collection of the solution space set.</p>
<p>Because of some incredibly interesting patterns within the encoded set of solvable instances, I'd appreciate my code being reviewed for correctness. This is an NP-complete problem, but shows self-similarity and self-affinity in the solution space with the current implementation. <strong>Please, help me shoot down this idea as quickly as possible</strong> -- I'd like to regain a productive life :)</p>
<p>Here's how the code is supposed to work. It outputs an XYZ point cloud of the nonogram solution space given a puzzle's maximum width, great for visualization.</p>
<p>The code generates all the possible permutations of an arbitrarily sized boolean image. Each permutation is a puzzle solution to at least one, if not many, boolean image input pairs. The input pairs are "projections" of the solution from each lattice direction, while having the same axis-constrained continuous runs of set bits. The only difference between solution and input is very subtle: the unset padding between contiguous runs is flexible along an axis.</p>
<p>Here's an example pairing of inputs and solution. Note that the pictured top-right solution may not be unique for the given input images, and the given input images don't necessarily construct only <em>that</em> solution. It's merely an example of the "nonogram property."</p>
<p><img src="https://i.stack.imgur.com/ed0Rp.png" alt="Nonogram property"></p>
<p>You'll notice in the code I have a peculiar encoding of the inputs and solutions as integers, essentially a traversal of the image's cells converted to a bitstring. This encoding is chosen as a visualization convenience, and I've attained similar patterns with different traversal orders. The main goal with the encoding is to reduce dimensionality for plotting with a one-to-one correspondence of images to integers, avoiding the problem of colliding identifiers.</p>
<p><img src="https://i.stack.imgur.com/kRFlU.png" alt="Concentric traversal encoding"></p>
<p>I'm including a montage of the first four iterations as subsets of the solution space shadow. The full shadow is essentially a look-up table for an NP oracle, so seeing patterns here could have remarkable consequences. Arranged from left to right are tables scaled to a common 512x512 resolution -- 4, 256, 262144, and 4294967296 puzzles accounted for, respectively. Each black pixel represents an input pair with no solution, white says a solution exists.</p>
<p><img src="https://i.stack.imgur.com/X7SbP.png" alt="Solution space montage"></p>
<pre><code>from sys import argv
from itertools import product, chain, groupby
from functools import partial
from multiprocessing import Pool
def indices(width):
for a in range(width):
for b in range(a+1):
yield (b, a)
for b in reversed(range(a)):
yield (a, b)
def encode(matrix, width):
return sum(1<<i for i, bit
in enumerate(matrix[i][j] for i, j in indices(width))
if bit)
def count_runs(row):
return [sum(group) for key, group in groupby(row) if key]
def flex(solution, width):
counts = list(map(count_runs, solution))
for matrix in product((False, True), repeat=width**2):
candidate = list(zip(*[iter(matrix)]*width))
if list(map(count_runs, candidate)) == counts:
yield candidate
def nonogram_solutions(solution, width):
xy = solution
yx = list(zip(*solution))
enc_sol = encode(solution, width)
return [(encode(xy, width), encode(yx, width), enc_sol)
for xy, yx in product(flex(xy, width), flex(yx, width))]
def main(width):
pool = Pool()
sol_matrices = (list(zip(*[iter(matrix)]*width)) for matrix
in product((False, True), repeat=width**2))
nonograms = partial(nonogram_solutions, width=width)
solutions = pool.imap_unordered(nonograms, sol_matrices, 1)
pool.close()
for xy, yx, solution in chain.from_iterable(solutions):
print(solution, xy, yx)
pool.join()
if __name__ == "__main__":
main(int(argv[1]))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:03:55.470",
"Id": "75768",
"Score": "0",
"body": "Are you deliberately trying to generate and store every solution, or just solve the puzzle?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T03:27:13.330",
"Id": "75866",
"Score": "0",
"body": "In that case, regardless how well written your code is, you're going to run out of disk space, which, as I understand it, is your real problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T23:37:12.803",
"Id": "75942",
"Score": "2",
"body": "A suggestion: Use a generator instead. Brute-forcing in any manner is dona according to a pattern. Therefore, you can make a program that generates a specific solution (say, solution number 1000) almost as fast as you could pull up the file for it, but uses minimal disk space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:54:45.680",
"Id": "76176",
"Score": "0",
"body": "I must have misunderstood your question, but if you're looking to fix broken code you want to post on SO."
}
] | [
{
"body": "<ol>\n<li><p>There are no docstrings. What do these functions do? Lack of docstrings make the code hard to review, because we don't know what the functions are supposed to do.</p></li>\n<li><p>The call <code>indices(n)</code> generates the Cartesian product of <code>range(n)</code> × <code>range(n)</code> in a particular order. A natural question is, does the order matter, or could we use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> instead:</p>\n\n<pre><code>itertools.product(range(width), repeat=2)\n</code></pre>\n\n<p>The post explains why you've chosen the order. But how is someone reading the code supposed to know that? There needs to be a comment.</p></li>\n<li><p><code>encode</code> could be simplified to avoid the <code>if</code>:</p>\n\n<pre><code>sum(bit<<i for i, bit in enumerate(...))\n</code></pre></li>\n<li><p>This code:</p>\n\n<pre><code>for matrix in product((False, True), repeat=width**2):\n candidate = list(zip(*[iter(matrix)]*width))\n</code></pre>\n\n<p>is effectively the same as:</p>\n\n<pre><code>sol_matrices = (list(zip(*[iter(matrix)]*width)) for matrix\n in product((False, True), repeat=width**2))\n</code></pre>\n\n<p>and so would benefit from having its own function (which would have a name and docstring that would explain what it does).</p></li>\n<li><p>The algorithm takes every nonogram puzzle, and then compares the run counts with the run counts for every nonogram puzzle of the same size. If <code>width</code> is \\$ n \\$, there are \\$ 2^{n^2} \\$ nonogram puzzles, and it takes \\$ Ω(n^2) \\$ to compute the run counts for a single puzzle, so the overall runtime is the ludicrous \\$ Ω(n^24^{n^2}) \\$.</p>\n\n<p>This could be brought down to \\$ Ω(n^22^{n^2}) \\$ if you prepared a dictionary mapping run counts to sets of encoded nonogram solutions, and down to \\$ Ω(n2^{n^2}) \\$ if you prepared the list of all rows, prepared a dictionary mapping each row to its run counts, and then generated the puzzles and their run counts simultaneously using the Cartesian product of the rows.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-26T13:02:31.113",
"Id": "91819",
"ParentId": "43770",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "91819",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:04:33.427",
"Id": "43770",
"Score": "14",
"Tags": [
"python",
"combinatorics",
"complexity"
],
"Title": "Nonogram puzzle solution space"
} | 43770 |
<p>This should be the last iteration for this code.</p>
<ol>
<li><p>Does this approach make sense or am I heading down the wrong path?</p></li>
<li><p>The only thing I can see to make this better is to genericize the <code>GetType</code> methods at the end so that I could eliminate the goofy <code>if</code> statement in the <code>GetProperties</code> method. Any suggestions?</p></li>
</ol>
<p>What I've done between the last question and now:</p>
<p>I've used a private method <code>GetProperty</code> as suggested in the last question in order to minimize the repeated code.</p>
<pre><code>private object GetProperty(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + WmiClassName))
using (var collection = moSearcher.Get())
using (var enu = collection.GetEnumerator())
return (!enu.MoveNext() || enu.Current[propertyName] == null) ? null : enu.Current[propertyName];
}
</code></pre>
<h3>Step 1</h3>
<p>I decided to edit the <code>PropertyValue</code> class along these lines to handle the dictionary</p>
<pre><code>public PropertyValue(Dictionary<string, string> propertyList, string wmiClassName).
</code></pre>
<p>Where the first string in the dictionary is the type the property will return and second in the dictionary is the <code>propertyName</code> as a string so that it is easy to work with. I'd like to genericize the type part so I could use a list or array instead of a dictionary. Really just to eliminate one of the string variables.</p>
<h3>Step 2</h3>
<p>I updated the calls to the <code>WMIClasses</code>:</p>
<pre><code>public class Win32Processor
{
public Win32Processor() { }
readonly PropertyValue propertyValue = new PropertyValue("Win32_Processor");
/// <summary>
/// Processor architecture used by the platform.
/// </summary>
public ushort Architecture()
{ return propertyValue.GetUnignedInt16("Architecture"); }
/// <summary>
/// Description of the object. This property is inherited from CIM_ManagedSystemElement.
/// </summary>
public string Description()
{ return propertyValue.GetString("Description"); }
}
</code></pre>
<p>To...</p>
<pre><code>public class Win32BaseBoard
{
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
///
/// </summary>
{"ushort", "AddressWidth"},
/// <summary>
///
/// </summary>
{"ushort", "Architecture"},};
// ...
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_BaseBoard");
return propertyValue.GetProperties();
}
}
</code></pre>
<p>Then I went about refactoring my <code>PropertyValue</code> class.</p>
<p>After implementing all of the above here's the full code as it stands:</p>
<pre><code>#region WMI Classes
/// <summary>
/// The Win32_BaseBoard WMI class represents a baseboard, which is also known as a motherboard or system board.
/// </summary>
public class Win32BaseBoard
{
public Win32BaseBoard() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
{"ushort", "AddressWidth"},
{"ushort", "Architecture"},
{"ushort", "Availability"},
{"ushort", "CpuStatus"},
{"uint", "CurrentClockSpeed"},
{"ushort", "DataWidth"},
{"string", "Description"},
{"string", "DeviceID"},
{"uint", "ExtClock"},
{"ushort", "Family"},
{"uint", "L2CacheSize"},
{"uint", "L2CacheSpeed"},
{"ushort", "Level"},
{"ushort", "LoadPercentage"},
{"string", "Manufacturer"},
{"uint", "MaxClockSpeed"},
{"string", "Name"},
{"uint", "NumberOfCores"},
{"string", "PNPDeviceID"},
{"string", "ProcessorId"},
{"ushort", "ProcessorType"},
{"ushort", "Revision"},
{"string", "Role"},
{"string", "SocketDesignation"},
{"ushort", "StatusInfo"},
{"string", "Stepping"},
{"string", "UniqueId"},
{"ushort", "UpgradeMethod"},
{"string", "Version"},
{"uint", "VoltageCaps"},
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_BaseBoard");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_BIOS WMI class represents the attributes of the computer system's basic input/output services (BIOS)
/// that are installed on a computer.
/// </summary>
public class Win32BIOS
{
public Win32BIOS() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
{"string", "BankLabel"},
{"string", "BuildNumber"},
{"ulong", "Capacity"},
{"string", "CurrentLanguage"},
{"ushort", "DataWidth"},
{"string", "Description"},
{"ushort", "FormFactor"},
{"bool", "HotSwappable"},
{"string", "InstallableLanguages"},
{"string", "Manufacturer"},
{"ushort", "MemoryType"},
{"string", "Name"},
{"string", "PartNumber"},
{"uint", "PositionInRow"},
{"datetime", "ReleaseDate"},
{"string", "SerialNumber"},
{"string", "SMBIOSMajorVersion"},
{"string", "SMBIOSMinorVersion"},
{"bool", "SMBIOSPresent"},
{"string", "SMBIOSBIOSVersion"},
{"uint", "Speed"},
{"string", "Status"},
{"string", "Tag"},
{"ushort", "TypeDetail"},
{"string", "Version"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_BIOS");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_DiskDrive WMI class represents a physical disk drive as seen by a computer running the Windows
/// operating system. Any interface to a Windows physical disk drive is a descendent (or member) of this class.
/// The features of the disk drive seen through this object correspond to the logical and management
/// characteristics of the drive. In some cases, this may not reflect the actual physical characteristics
/// of the device. Any object based on another logical device would not be a member of this class.
/// For security reasons, a user connecting from a remote computer must have the SC_MANAGER_CONNECT privilege
/// enabled to be able to enumerate this class.
/// </summary>
public class Win32DiskDrive
{
public Win32DiskDrive() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
///
/// </summary>
{"string", "Description"},
/// <summary>
///
/// </summary>
{"string", "Manufacturer"},
/// <summary>
///
/// </summary>
{"string", "Model"},
/// <summary>
///
/// </summary>
{"string", "Name"},
/// <summary>
///
/// </summary>
{"string", "OtherIdentifyingInfo"},
/// <summary>
///
/// </summary>
{"string", "PartNumber"},
/// <summary>
///
/// </summary>
{"string", "Product"},
/// <summary>
///
/// </summary>
{"string", "RequirementsDescription"},
/// <summary>
///
/// </summary>
{"string", "SerialNumber"},
/// <summary>
///
/// </summary>
{"string", "SKU"},
/// <summary>
///
/// </summary>
{"string", "SlotLayout"},
/// <summary>
///
/// </summary>
{"bool", "SpecialRequirements"},
/// <summary>
///
/// </summary>
{"string", "Tag"},
/// <summary>
///
/// </summary>
{"string", "Version"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_DiskDrive");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_DiskPartition WMI class represents the capabilities and management capacity of a partitioned area
/// of a physical disk on a computer system running Windows. Example: Disk #0, Partition #1.
/// </summary>
public class Win32DiskPartion
{
public Win32DiskPartion() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
///
/// </summary>
{"string", "Name"},
/// <summary>
///
/// </summary>
{"bool", "PrimaryBIOS"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_DiskPartion");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_ComputerSystem WMI class represents a computer system running Windows.
/// </summary>
public class Win32ComputerSystem
{
public Win32ComputerSystem() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
/// Key of a CIM_System instance in an enterprise environment.
/// This property is inherited from CIM_ManagedSystemElement.
/// </summary>
{"string", "Name"},
/// <summary>
/// Name of a computer manufacturer.
/// </summary>
{"string", "Manufacturer"},
/// <summary>
/// Product name that a manufacturer gives to a computer. This property must have a value.
/// </summary>
{"string", "Model"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_ComputerSystem");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_LogicalDisk WMI class represents a data source that resolves to an actual local storage device
/// on a computer system running Windows.
/// </summary>
public class Win32LogicalDisk
{
public Win32LogicalDisk() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
///
/// </summary>
{"uint", "BytesPerSector"},
/// <summary>
///
/// </summary>
{"ushort", "Capabilities"},
/// <summary>
///
/// </summary>
{"string", "Caption"},
/// <summary>
///
/// </summary>
{"string", "DeviceID"},
/// <summary>
///
/// </summary>
{"suint", "Index"},
/// <summary>
///
/// </summary>
{"string", "InterfaceType"},
/// <summary>
///
/// </summary>
{"string", "Manufacturer"},
/// <summary>
///
/// </summary>
{"bool", "MediaLoaded"},
/// <summary>
///
/// </summary>
{"string", "MediaType"},
/// <summary>
///
/// </summary>
{"string", "Model"},
/// <summary>
///
/// </summary>
{"string", "Name"},
/// <summary>
///
/// </summary>
{"uint", "Partitions"},
/// <summary>
///
/// </summary>
{"string", "PNPDeviceID"},
/// <summary>
///
/// </summary>
{"uint", "SCSIBus"},
/// <summary>
///
/// </summary>
{"ushort", "SCSILogicalUnit"},
/// <summary>
///
/// </summary>
{"ushort", "SCSIPort"},
/// <summary>
///
/// </summary>
{"ushort", "SCSITargetId"},
/// <summary>
///
/// </summary>
{"uint", "SectorsPerTrack"},
/// <summary>
///
/// </summary>
{"uint", "Signature"},
/// <summary>
///
/// </summary>
{"ulong", "Size"},
/// <summary>
///
/// </summary>
{"string", "Status"},
/// <summary>
///
/// </summary>
{"ulong", "TotalCylinders"},
/// <summary>
///
/// </summary>
{"uint", "TotalHeads"},
/// <summary>
///
/// </summary>
{"ulong", "TotalSectors"},
/// <summary>
///
/// </summary>
{"ulong", "TotalTracks"},
/// <summary>
///
/// </summary>
{"uint", "TracksPerCylinder"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_LogicalDisk");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_OperatingSystem WMI class represents a Windows-based OS installed on a computer. Any OS that can be
/// installed on a computer that can run a Windows-based OS is a descendent or member of this class.
/// Win32_OperatingSystem is a singleton class. To get the single instance, use "@" for the key.
/// </summary>
public class Win32OperatingSystem
{
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
/// Number, in megabytes, of physical memory currently unused and available.
/// </summary>
{"ulong", "FreePhysicalMemory"},
/// <summary>
/// Number, in megabytes, of virtual memory currently unused and available.
/// </summary>
{"ulong", "FreeVirtualMemory"},
/// <summary>
/// Number, in megabytes, of virtual memory.
/// </summary>
{"ulong", "TotalVirtualMemory"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_OperatingSystem");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_PhysicalMemory WMI class represents a physical memory device located on a computer system and
/// available to the operating system.
/// </summary>
public class Win32PhysicalMemory
{
public Win32PhysicalMemory() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
///
/// </summary>
{"ulong", "BlockSize"},
/// <summary>
///
/// </summary>
{"bool", "Bootable"},
/// <summary>
///
/// </summary>
{"bool", "BootPartition"},
/// <summary>
///
/// </summary>
{"string", "Description"},
/// <summary>
///
/// </summary>
{"string", "DeviceID"},
/// <summary>
///
/// </summary>
{"ushort", "DiskIndex"},
/// <summary>
///
/// </summary>
{"ushort", "Index"},
/// <summary>
///
/// </summary>
{"string", "Name"},
/// <summary>
///
/// </summary>
{"ulong", "NumberOfBlocks"},
/// <summary>
///
/// </summary>
{"bool", "PrimaryPartition"},
/// <summary>
///
/// </summary>
{"ulong", "Size"},
/// <summary>
///
/// </summary>
{"ulong", "StartingOffset"},
/// <summary>
///
/// </summary>
{"string", "Type"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_PhysicalMemory");
return propertyValue.GetProperties();
}
}
/// <summary>
/// The Win32_Processor WMI class represents a device that can interpret a sequence of instructions on a computer
/// running on a Windows operating system. On a multiprocessor computer, one instance of the Win32_Processor class
/// exists for each processor.
/// </summary>
public class Win32Processor
{
public Win32Processor() { }
public object GetValues()
{
Dictionary<string, string> propertyList = new Dictionary<string, string>(){
/// <summary>
/// Key of a CIM_System instance in an enterprise environment.
/// This property is inherited from CIM_ManagedSystemElement.
/// </summary>
{"ushort", "Architecture"},
/// <summary>
/// Name of a computer manufacturer.
/// </summary>
{"string", "Description"},
/// <summary>
///
/// </summary>
{"string", "DeviceID"},
/// <summary>
///
/// </summary>
{"uint", "DriveType"},
/// <summary>
///
/// </summary>
{"string", "FileSystem"},
/// <summary>
///
/// </summary>
{"uint", "MediaType"},
/// <summary>
///
/// </summary>
{"string", "Name"},
/// <summary>
///
/// </summary>
{"bool", "VolumeDirty"}
};
PropertyValue propertyValue = new PropertyValue(propertyList, "Win32_Processor");
return propertyValue.GetProperties();
}
}
#endregion
#region PropertyValue
/// <summary>
/// Handles the actual WMI queries for the other classes in this file
/// </summary>
public class PropertyValue
{
public PropertyValue() { }
public PropertyValue(Dictionary<string, string> propertyList, string wmiClassName)
{
this.PropertyList = propertyList;
this.WmiClassName = wmiClassName;
}
public string WmiClassName { get; set; }
public Dictionary<string, string> PropertyList { get; set; }
/// <summary>
/// Converts kilobyte values to megabytes for readability.
/// </summary>
/// <param name="kiloBytes">Value to be converted</param>
/// <returns>Kilobytes converted to megabytes as ulong</returns>
private static ulong KiloBytesToMegaBytes(ulong kiloBytes)
{ return kiloBytes / (ulong)1024; }
public object GetProperties()
{
foreach (var pair in PropertyList)
{
if (pair.Key.ToLower() == "datetime")
{ return GetDateTimeFromDmtf(pair.Value); }
if (pair.Key.ToLower() == "string")
{ return GetString(pair.Value); }
if (pair.Key.ToLower() == "ulong")
{ return GetUnsignedInt64(pair.Value); }
if (pair.Key.ToLower() == "bool")
{ return GetBool(pair.Value); }
if (pair.Key.ToLower() == "ushort")
{ return GetUnignedInt16(pair.Value); }
if (pair.Key.ToLower() == "uint")
{ return GetUnsignedInt32(pair.Value); }
}
return null;
}
private uint GetUnsignedInt32(string propertyName)
{
var property = FindProperty(propertyName);
return property == null ? (uint)(0) : (uint)(property);
}
private object FindProperty(string propertyName)
{
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM " + WmiClassName))
using (var collection = moSearcher.Get())
using (var enu = collection.GetEnumerator())
return (!enu.MoveNext() || enu.Current[propertyName] == null) ? null : enu.Current[propertyName];
}
private DateTime GetDateTimeFromDmtf(string propertyName)
{
var property = FindProperty(propertyName);
return property == null ? DateTime.Today : ManagementDateTimeConverter.ToDateTime(property.ToString());
}
private string GetString(string propertyName)
{
var property = FindProperty(propertyName);
return property == null ? String.Empty : property.ToString();
}
private ulong GetUnsignedInt64(string propertyName)
{
var property = FindProperty(propertyName);
return property == null ? (ulong)(0) : KiloBytesToMegaBytes((ulong)(property));
}
private bool GetBool(string propertyName)
{
var property = FindProperty(propertyName);
return property == null ? false : true;
}
private ushort GetUnignedInt16(string propertyName)
{
var property = FindProperty(propertyName);
return property == null ? (ushort)(0) : (ushort)(property);
}
}
#endregion
</code></pre>
<p><strong>Questions in this series</strong></p>
<p><a href="https://codereview.stackexchange.com/questions/43432/class-seperation-vs-polymorphism">Class Seperation vs Polymorphism.</a></p>
<p><a href="https://codereview.stackexchange.com/questions/43598/should-i-refactor-for-dry">First iteration of DRY refactoring.</a></p>
<p><a href="https://codereview.stackexchange.com/questions/43719/next-instance-of-dry-refactoring">Second iteration of DRY refactoring.</a></p>
<p>You are currently viewing the fourth question in the series.</p>
| [] | [
{
"body": "<p>First:</p>\n\n<pre><code> if (pair.Key.ToLower() == \"datetime\")\n { return GetDateTimeFromDmtf(pair.Value); }\n if (pair.Key.ToLower() == \"string\")\n { return GetString(pair.Value); }\n if (pair.Key.ToLower() == \"ulong\")\n { return GetUnsignedInt64(pair.Value); }\n if (pair.Key.ToLower() == \"bool\")\n { return GetBool(pair.Value); }\n if (pair.Key.ToLower() == \"ushort\")\n { return GetUnignedInt16(pair.Value); }\n if (pair.Key.ToLower() == \"uint\")\n { return GetUnsignedInt32(pair.Value); }\n</code></pre>\n\n<p>Screaming to be a <code>switch</code> statement.</p>\n\n<p>Second, these guys in every <code>GetValues</code> method:</p>\n\n<pre><code>Dictionary<string, string> propertyList = new Dictionary<string, string>(){\n\n /// <summary>\n /// \n /// </summary>\n {\"ushort\", \"AddressWidth\"},\n\n /// <summary>\n /// \n /// </summary>\n {\"ushort\", \"Architecture\"},};\n</code></pre>\n\n<p>a) are immutable once created, so it makes better sense to make them class-level variables. So they're initialized only once.\nb) should then be <code>readonly</code>.\nc) should be declared as <code>IDictionary<string, string></code> so that you're developing against an interface rather than an implementation. This will need to be changed throughout method signatures, etc.</p>\n\n<p>Third: <code>GetUnignedInt16</code> really should be spelled correctly. <code>GetUnsignedInt16</code>.</p>\n\n<p>Fourth: <code>GetProperties()</code> in the <code>PropertyValue</code> class does not \"get properties\". It gets a single property. It takes the <code>Dictionary</code>, but only returns the first property value (this is due to <code>return</code> being in the <code>foreach</code> loop. My guess is maybe you mean to add to a list or array?). Seems like a misnaming and a bug at the same time. Fix the code before the review.</p>\n\n<p>Those are initial thoughts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:43:19.910",
"Id": "76078",
"Score": "0",
"body": "If `GetProperties()` is actually supposed to return all properties, simply writing it with `yield return` will do the trick."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T17:53:56.440",
"Id": "76081",
"Score": "0",
"body": "And with the required `IEnumerable<object>` return type. `yield return` methods must have a collection return type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-31T02:35:24.580",
"Id": "79918",
"Score": "0",
"body": "A minor issue: You should use `.ToUpperInvariant`. It will probably never matter, but `ToUpper` is \"better\" than `ToLower` -- I don't have a link to the actual reason, but I believe it is really only an issue for some Unicode characters. And similarly using the `Invariant` culture mostly just avoids Code Analysis warnings, but they are there for a (most unlikely) reason."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:03:18.510",
"Id": "43945",
"ParentId": "43777",
"Score": "5"
}
},
{
"body": "<p>You haven't been online in quite some time, but anyway ..</p>\n\n<h3>Review</h3>\n\n<ul>\n<li>You are not using the <code>defaultValueIfEmpty</code> from previous post. This means <code>return (!enu.MoveNext() || enu.Current[propertyName] == null) ? null : enu.Current[propertyName];</code> can be shortened to <code>return !enu.MoveNext() ? null : enu.Current[propertyName];</code>.</li>\n<li>Use a better key as <code>String</code>, prefer <code>Type</code>. You don't need any shenanigans with casing keys. Refactor <code>Dictionary<string, string> propertyList</code> to <code>Dictionary<Type, string> propertyList</code>.</li>\n<li><code>public object GetValues()</code> returns a single value. This seems more a bug than as designed.</li>\n<li><code>ulong KiloBytesToMegaBytes</code> there is a lot of misconception about these units. Check out <a href=\"https://en.wikipedia.org/wiki/Mebibyte\" rel=\"nofollow noreferrer\">Megabyte vs Mebibyte</a>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T18:15:14.307",
"Id": "433858",
"Score": "1",
"body": "This mebibyte is a funny unit; and apparently nobody likes it :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T18:17:52.567",
"Id": "433859",
"Score": "1",
"body": "It was an attempt at generalising units. But even my teacher in uni, who worked at IBM haven't heard about it :-p It is interesting though, that many different variations of formulas are used."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T18:03:54.190",
"Id": "223764",
"ParentId": "43777",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:24:03.607",
"Id": "43777",
"Score": "4",
"Tags": [
"c#",
"generics",
"hash-map",
"enum"
],
"Title": "Genericizing PropertyValues"
} | 43777 |
<p>Is this class perfect for databases? All I want to know is what I should change to make it perfect.</p>
<pre><code>error_reporting(E_ALL);
class RESPETO{
private $_server = 'mysql';
private $_host = '';
private $_database = '';
private $db_username = '';
private $db_password = '';
private $db_charset = 'utf8';
private $conn = NULL;
const FETCH = 0;
const FETCHALL = 3;
const ID = 1;
const ROWCOUNT = 2;
const PARAM_LOB = 'largeObject';
public function SQL( $Query, $value = array(), $req = RESPETO::FETCHALL ){
try{
$pattern = "/^(SELECT)|^(INSERT)|^(UPDATE)|^(DELETE)/";
if(preg_match($pattern, $Query, $matches) === 1):
$ready = $this->conn->prepare($Query);
if( ! empty( $value ) ){
$i = 1;
foreach($value as $key => $keyValue):
if( ( is_string( $key ) ) && ( $key == $this::PARAM_LOB ) ):
$param = PDO::PARAM_LOB;
elseif( is_string( $keyValue ) ):
$param = PDO::PARAM_STR;
elseif( is_int( $keyValue ) ):
$param = PDO::PARAM_INT;
elseif( is_bool( $keyValue ) ):
$param = PDO::PARAM_BOOL;
elseif( is_null( $keyValue ) ):
$param = PDO::PARAM_NULL;
else:
$param = PDO::PARAM_STR;
endif;
$ready->bindValue($i++, $keyValue, $param);
endforeach;
}
$ready->execute();
if( ( $matches[0] === "SELECT" ) && ( $req === $this::FETCHALL ) ):
$value = $ready->fetchall( PDO::FETCH_ASSOC );
elseif( ( $matches[0] === "SELECT" ) && ( $req === $this::FETCH ) ):
$value = $ready->fetch( PDO::FETCH_ASSOC );
elseif( ( $matches[0] === "INSERT" ) && ( $req === $this::ID ) ):
$value = $this->conn->lastInsertId();
elseif( $req === $this::ROWCOUNT ):
$value = $ready->rowCount();
else:
$value = true;
endif;
return $value;
else:
return false;
endif;
}
catch(Exception $e){
print "WHAT ARE YOU DOING? see this Error (SQL) : " . $e->getMessage();
// use email functionality to send errors if your appication is online, not 'print' or 'echo' language construct to show it as html contents.
exit;
}
}
public function __toString(){
$data = sprintf('host = %s, database = %s, username = %s, password = %s, charset = %s', $this->_host, $this->_database, $this->db_username, $this->db_password, $this->db_charset);
return $data;
}
public function __construct($host = NULL, $database = NULL, $charset = NULL, $username = NULL, $password = NULL){
if(!is_null($host))
$this->_host = $host;
if(!is_null($database))
$this->_database = $database;
if(!is_null($charset))
$this->db_charset = $charset;
if(!is_null($username))
$this->db_username = $username;
if(!is_null($password))
$this->db_password = $password;
$connectionString = sprintf("%s:host=%s; dbname=%s; charset=%s",
$this->_server, $this->_host, $this->_database, $this->db_charset);
try {
$this->conn = new PDO($connectionString, $this->db_username, $this->db_password);
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
print "WHAT ARE YOU DOING? see this Error (CONN): " . $e->getMessage();
// use email functionality to send errors if your appication is online, not 'print' or 'echo' language construct to show it as html contents.
exit;
}
}
public function __destruct(){
$this->conn = null;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:20:14.433",
"Id": "75761",
"Score": "0",
"body": "As the local said \"If I was going there I wouldn't start from here\". \"Swiss Army\" functions are pointless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T16:41:48.133",
"Id": "75776",
"Score": "2",
"body": "You're asking if its perfect, but that doesn't get us anywhere. Perfect could mean many things."
}
] | [
{
"body": "<p>Due to the fact that a lot of the comments should have been answers - I will attempt to say what they are probably thinking.</p>\n\n<p>A jack-of-all-trade function is poor programming. It defeats the <strong>SOLID</strong> principles and doesn't enable you flexibility.</p>\n\n<p>I will give you a scenario as to why this would fail:</p>\n\n<p>What happens if the error occurs, you get the error message but what is your sql? What happens if this class is being used as a cron - there is no outputs in cron - how are you going to fetch this error? Right there you will need to change your class.</p>\n\n<p>Your constructor (despite logical) is too \"busy\": 5 variables? If it cross 3 (not a rule of thumb) you should pass an array instead (take a page out of the php.net man itself). You will need to pass these variables to initialize the class and coding and pass numerous variables to do so is tedious. Also your configuration file (typically an array) would be where you fetch these settings from.</p>\n\n<p>WHAT IF we use SQL's ON DUPLICATE KEY query. Its a valid query - but when on duplicate - you will not get a returned value so the rowCount return on insert will give you nil.</p>\n\n<p>Bottom line - nothing is perfect ... don't make things a swiss army knife. Even frameworks evolves.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T14:02:27.997",
"Id": "44351",
"ParentId": "43780",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T09:12:30.637",
"Id": "43780",
"Score": "3",
"Tags": [
"php",
"classes",
"pdo"
],
"Title": "Is this a complete PDO prepared class?"
} | 43780 |
<p>The linked code below is meant to be used in a user space file-system (fuse). Given that multiple processes may have multiple files opened on the file-system, the files on the specific user space file-system will map each of these open files to an (encrypted) file on a regular file-system, attempting to keep all mapped files open at the same time might fail pretty soon if there are many processes accessing the file-system. Doing an <code>open->action->close</code> on each file-system operation as an alternative would potentially have a rather big overhead.</p>
<p>The below container is meant to allow keeping a large set of files open while possible, hopefully the ones that are most likely to get once again accessed soon, and temporary low-level closing the ones that have been inactive for a while.</p>
<p>Is the design any good, or am I making bad assumptions that would result in trashing behaviour in real life usage scenarios? And if the design is OK, any other feedback on the code would be greatly appreciated. </p>
<pre><code>template <typename nodeType,size_t maxOpenFiles,size_t maxQueueSize>
class openfilecollection {
nodeType mNull;
uint64_t mLastHandle;
std::map<uint64_t, nodeType> mCollection;
std::map<uint64_t, size_t> mFullyOpen;
std::deque<uint64_t> mOpperQue;
uint64_t getFreeFhNumber() {
while ((mLastHandle == 0) || (mCollection.count(mLastHandle))) {
mLastHandle += 1;
}
return mLastHandle;
}
void cleanupQueFront() {
while ((mFullyOpen.count(mOpperQue.front()) == 0)||
(mFullyOpen[mOpperQue.front()]>1)||
(mOpperQue.size()>maxQueueSize)) {
if (mFullyOpen.count(mOpperQue.front()) != 0) {
mFullyOpen[mOpperQue.front()] -= 1;
if (mFullyOpen[mOpperQue.front()] == 0) {
mCollection[mOpperQue.front()].lowLevelClose();
mFullyOpen.erase(mOpperQue.front());
}
}
mOpperQue.pop_front();
}
}
void tempCloseIfNeeded() {
while (mFullyOpen.size() > maxOpenFiles) {
uint64_t candidate = mOpperQue.front();
mOpperQue.pop_front();
if (mFullyOpen.count(candidate)) {
mFullyOpen[candidate] -= 1;
if (mFullyOpen[candidate] == 0) {
mCollection[candidate].lowLevelClose();
mFullyOpen.erase(candidate);
}
}
}
this->cleanupQueFront();
}
openfilecollection(openfilecollection const &) = delete;
openfilecollection &operator=(openfilecollection const &) = delete;
public:
openfilecollection():mNull(),mLastHandle(0){}
~openfilecollection() {
for (std::map<uint64_t, size_t>::iteratori1=mFullyOpen.begin();
i1 != mFullyOpen.end();
++i1) {
uint64_t fh = i1->first;
mCollection[fh].lowLevelClose();
}
}
class node_handle {
openfilecollection<nodeType, maxOpenFiles, maxQueueSize> *mCol;
uint64_t mFh;
public:
node_handle(openfilecollection<nodeType, maxOpenFiles,maxQueueSize> *col,
uint64_t fh):mCol(col),mFh(fh){}
void close() {
mCol->close(mFh);
}
ssize_t read(void *buf, size_t count,off_t offset) {
return mCol->mCollection[mFh].read(buf,count);
}
ssize_t write(const void *buf, size_t count,off_t offset) {
return mCol->mCollection[mFh].write(buf,count);
}
int chmod(mode_t mode) {
return mCol->mCollection[mFh].chmod(mode);
}
};
node_handle operator[](uint64_t fh) {
if (mCollection.count(fh) == 0) { /
return node_handle(*this,0);
}
if (mFullyOpen.count(fh)) {
if (fh != mOpperQue.back()) {
mFullyOpen[fh] += 1;
mOpperQue.push_back(fh);
}
} else {
mFullyOpen[fh] = 1;
mOpperQue.push_back(fh);
this->tempCloseIfNeeded();
mCollection[fh].lowLevelOpen();
}
return node_handle(this,fh);
}
template<typename ... Args>
uint64_t open(Args&& ... args) {
uint64_t fh=this->getFreeFhNumber();
mCollection.emplace(std::piecewise_construct,
std::forward_as_tuple(fh),
std::forward_as_tuple(args...));
mFullyOpen[fh] = 1;
mOpperQue.push_back(fh);
this->tempCloseIfNeeded();
mCollection[fh].lowLevelOpen();
return fh;
}
void close(uint64_t fh) {
if (mFullyOpen.count(fh)) {
mFullyOpen.erase(fh);
mCollection[fh].lowLevelClose();
}
if (mCollection.count(fh)) {
mCollection.erase(fh);
}
this->cleanupQueFront();
}
};
</code></pre>
<p>Here is a <a href="https://github.com/pibara/MinorFs2/blob/master/util/openfilecollection.hpp">commented version of the above code</a></p>
| [] | [
{
"body": "<p>From a once-over:</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li><p>You seem to use all kinds of conventions, all lowercase, sometimes you use an underscore, sometimes you use lowerCamelCase. Perhaps you should stick to the underscore_style.</p></li>\n<li><p>The name <code>mOpperQue</code> is unfortunate, perhaps <code>closing_candidates</code> ?</p></li>\n<li>Could be me, but <code>operator</code> seems unfortunate as well, the name does not at all give away that it will actually open the file.</li>\n<li><code>tempCloseIfNeeded</code> is unfortunate, I am not sure which part is <code>temp</code>. I would call it <code>force_close_files</code>.</li>\n</ul>\n\n<p><strong>DRY</strong></p>\n\n<ul>\n<li><p><code>cleanupQueFront</code> and <code>tempCloseIfNeeded</code> share enough code that you could either make it 1 function or extract the common code into a utility function.</p></li>\n<li><p><code>node_handle operator[](uint64_t fh) {</code> and <code>uint64_t open(Args&& ... args) {</code> share the same code lines and comments, one more opportunity to merge or use a utility function.</p></li>\n</ul>\n\n<p><strong>Philosophy</strong></p>\n\n<ul>\n<li><p>I would much rather have a library that says <em>Sorry, you can't have this open file</em>, than a library that \"willy nilly\" can close a file so that I have to keep checking whether my <code>node_handle</code> is still valid.</p></li>\n<li><p><s>By only checking the front for handlers that might need to be closed, you can create artificial limit problems, closing files that don't need to be closed.</s></p></li>\n<li><p>If you called <code>tempCloseIfNeeded</code> first and enforced <code>(mFullyOpen.size() > maxOpenFiles - 1 )</code> and then call <code>lowLevelOpen()</code>, then you would never violate <code>maxOpenFiles</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T21:46:28.313",
"Id": "77058",
"Score": "0",
"body": "Point taken on naming.As this is meant to be used by a user space filesystem,normaly operator[] would equate one file system operation on an open file. Thats why mOpperQue has its name,its a queue of historic file handle 'operations'.The operator[] will conceptually just retrieve an virtually open file,its goal is to abstract the fact that there are closed files in the container.Point taken on DRY, tnx.Could you elaborate on the n2 philosophy bullet? For me that is the most essential part.At the moment I'm closing the files that have been idle for the longest time. Is that a misguided policy?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-15T17:44:42.240",
"Id": "77145",
"Score": "0",
"body": "I re-read your code, point 2 is not valid. Updating my question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T21:04:18.173",
"Id": "44400",
"ParentId": "43782",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T09:48:44.683",
"Id": "43782",
"Score": "10",
"Tags": [
"c++",
"c++11",
"cache",
"file-system",
"container"
],
"Title": "Allowing user space file-system to (kind-of) keep more than maximum number of files open"
} | 43782 |
<p>How to shorten up this code? I know there's a way that this kind of code could be shortened, but I don't know how by myself yet. Who can help me?</p>
<pre><code> //CHOOSE LEVEL: FROZEN
case 1213:
sendOption5("Level 1 " + (c.achievedFloor <= 1 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 2 " + (c.achievedFloor <= 2 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 3 " + (c.achievedFloor <= 3 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 4 " + (c.achievedFloor <= 4 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"More");
c.dialogueAction = 1213;
break;
case 1214:
sendOption5("Level 5 " + (c.achievedFloor <= 5 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 6 " + (c.achievedFloor <= 6 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 7 " + (c.achievedFloor <= 7 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 8 " + (c.achievedFloor <= 8 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"More");
c.dialogueAction = 1214;
break;
case 1215:
sendOption5("Level 9 " + (c.achievedFloor <= 9 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 10 " + (c.achievedFloor <= 10 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"Level 11 " + (c.achievedFloor <= 11 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
"",
"Choose Floor");
c.dialogueAction = 1215;
break;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T11:36:56.173",
"Id": "75744",
"Score": "4",
"body": "Welcome to Code Review! Can you explain a bit about the context of the code? What is it used for? What is it doing? Providing some context will likely give you better reviews."
}
] | [
{
"body": "<p>There's a good talk about it by a Google's employee (<a href=\"https://www.youtube.com/watch?v=4F72VULWFvc\" rel=\"nofollow\">https://www.youtube.com/watch?v=4F72VULWFvc</a>).\nIn fact these kind of conditions can be avoided using inheritance.\nYou could create 3 different implementations of an abstract class which all have a method sendOption5() and you could choose one of it using a case.\nA better way to do it, but it depends on your code is to create an abstract class (or interface) like</p>\n\n<pre><code>interface Option\n{\n public void sendOptions();\n public boolean haveToBeCalled(Integer number);\n}\n</code></pre>\n\n<p>where haveToBeCalled returns true if number if a certain value, false otherwise.\nAnd so if you have a list of \"Option\" you can use it as</p>\n\n<pre><code>for (Option o : options)\n{\n if (o.haveToBeCalled(number))\n {\n o.sendOptions();\n }\n}\n</code></pre>\n\n<p>Anyway, it really depends on the rest of your code. The kind of scheme you're can often be improved by refactoring a part of the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:31:20.163",
"Id": "75739",
"Score": "0",
"body": "I know this, but I was more talking about lines like these: \"Level 6 \" + (c.achievedFloor <= 6 ? \"@gre@(Achieved)\" : \"@red@(Not achieved)\") + \"\","
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:35:45.553",
"Id": "75740",
"Score": "1",
"body": "why don't you create a method that generate your string depending on \"c\"?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:29:25.773",
"Id": "43784",
"ParentId": "43783",
"Score": "3"
}
},
{
"body": "<p>My best guess will be create a method to build your <code>String</code>s and make <code>sendOption5</code> a method that takes <code>List</code> of <code>String</code>. You can also use var-args.</p>\n\n<pre><code>List<String> levelDescriptions;\nCase 1213:\n levelDescriptions = generateStringUponLevelNumber(c,1,2,3,4);\n levelDescriptions.add(\"More\");\n sendOption5(levelDescriptions);\n\n c.dialogueAction = caseNumber;\n// same goes for others\n\n------\n\npublic static List<String> generateStringUponLevelNumber(TypeOf c, int... levels) {\n List<String> levelDescription = new ArrayList<>();\n for(int level : levels) {\n String description = \"Level \" + level + \" \";\n description += c.achievedFloor <= level ? \"@green@(Achieved)\" : \"@red@(Not achieved)\";\n levelDescription.add(description);\n }\n return levelDescription;\n}\n</code></pre>\n\n<hr>\n\n<h2>After OP's comment</h2>\n\n<p>Change your method accordingly</p>\n\n<pre><code>public void sendOption5(List<String> levelDescriptions) {\n c.getPA().sendFrame126(\"Select an Option\", 2493);\n for(int level = 0, from = 2494; level <= 4; level++, from++) {\n c.getPA().sendFrame126(levelDescriptions.get(level), from);\n }\n c.getPA().sendFrame164(2492);\n}\n</code></pre>\n\n<p><strong>Some suggestion upon naming</strong></p>\n\n<ol>\n<li>The method name <code>sendOption5</code> is misleading. Cause if someone is seeing the code and see the name he/she will think there are <strong>N</strong> options and you are sending the 5<sup>th</sup> option as parameter, which is not true. You are sending 5 Strings or options. So the apt. name would be <code>sendFiveOptions</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T11:00:23.337",
"Id": "75741",
"Score": "0",
"body": "This was pretty helpful but my method wont work anymore which is: 'code'( public void sendOption5(String s, String s1, String s2, String s3, String s4) {\n c.getPA().sendFrame126(\"Select an Option\", 2493);\n c.getPA().sendFrame126(s, 2494);\n c.getPA().sendFrame126(s1, 2495);\n c.getPA().sendFrame126(s2, 2496);\n c.getPA().sendFrame126(s3, 2497);\n c.getPA().sendFrame126(s4, 2498);\n c.getPA().sendFrame164(2492);\n })"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T11:12:52.413",
"Id": "75742",
"Score": "1",
"body": "@user3395769 see the changes. Though I highly recommend you to further refactoring."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:50:16.380",
"Id": "43785",
"ParentId": "43783",
"Score": "3"
}
},
{
"body": "<p>In a first step I would extract a method to generate the string.</p>\n\n<p>changed code:</p>\n\n<pre><code> //CHOOSE LEVEL: FROZEN\ncase 1213:\n sendOption5(\n levelString( 1, c),\n levelString( 2, c),\n levelString( 3, c),\n levelString( 4, c),\n \"More\");\n c.dialogueAction = 1213; \n break;\ncase 1214:\n sendOption5(\n levelString( 5, c),\n levelString( 6, c),\n levelString( 7, c),\n levelString( 8, c),\n \"More\");\n c.dialogueAction = 1214;\n break;\ncase 1215:\n sendOption5(\n levelString( 9, c),\n levelString(10, c),\n levelString(11, c),\n \"\",\n \"Choose Floor\");\n c.dialogueAction = 1215;\n break;\n</code></pre>\n\n<p>extracted method:</p>\n\n<pre><code>private static String levelString(int i, TypeOfC c){\n return \"Level \" + i + (c.achievedFloor <= i ? \" @gre@(Achieved)\" : \" @red@(Not achieved)\");\n}\n</code></pre>\n\n<p>You should also think about changing the parameters of your <code>sendOption5</code> to get only <code>c</code> and two integers <code>from</code> <code>to</code> which define the inteval of values.</p>\n\n<p>And you can move the <code>c.dialogueAction = xxxx;</code> line behind the <code>switch</code> and assign the value you use for the <code>switch</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:51:53.983",
"Id": "43786",
"ParentId": "43783",
"Score": "8"
}
},
{
"body": "<p>There are two sets of repeating code here. The standard solution to DRY (Don't repeat yourself) is Function Extraction.</p>\n\n<p>Consider two functions:</p>\n\n<pre><code>private static String levelAchievedOption(int level, int achieved) {\n return String.format(\"Level %d @%s\", level,\n achieved >= level ? \"gre@(Achieved)\" : \"red@(Not Achieved)\");\n}\n</code></pre>\n\n<p>Then, the second function for setting the options:</p>\n\n<pre><code>private static void setLevelOptions(int levela, int levelb, int levelc, int leveld, String postfix, int levelAchieved) {\n sendOption5(\n levela >= 0 ? levelAchievedOption(levela, levelAchieved) : \"\",\n levelb >= 0 ? levelAchievedOption(levelb, levelAchieved) : \"\",\n levelc >= 0 ? levelAchievedOption(levelc, levelAchieved) : \"\",\n leveld >= 0 ? levelAchievedOption(leveld, levelAchieved) : \"\",\n postfix);\n}\n</code></pre>\n\n<p>Then, your case statement can become:</p>\n\n<pre><code>case 1213:\n setLevelOptions(1, 2, 3, 4, \"More\", c.achievedFloor);\n c.dialogueAction = 1213;\n break;\ncase 1214:\n setLevelOptions(5, 6, 7, 8, \"More\", c.achievedFloor);\n c.dialogueAction = 1214;\n break;\ncase 1215:\n setLevelOptions(9, 10, 11, -1, \"Choose Floor\", c.achievedFloor);\n c.dialogueAction = 1215;\n break;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:01:13.063",
"Id": "75756",
"Score": "1",
"body": "I think there is an error or maybe I am not understanding clearly. But, in `levelAchievedOption(levela >= 0 ? levelAchievedOption(levela, levelAchieved) : \"\")` `levelAchievedOption` takes one `int` and another `String` parameter. So howcome outer `levelAchievedOption` will be invoked with only one `String`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T11:54:38.767",
"Id": "43788",
"ParentId": "43783",
"Score": "5"
}
},
{
"body": "<p>This seems to me like it's probably easiest to pre-build all the strings, then select four to use. First, I think you probably want to re-check your logic on one minor point. Did you really mean <code><=</code> when you did the comparisons to <code>c.achievedFloor</code>? Typically you'd expect floors to be achieved in order, so if (for example) the player has achieved floor 7, that means they've also achieved floors 1 through 6. The way you've written seems to imply the reverse--that achieving (for example) level 4 means they've also achieved levels 5 though 10.</p>\n\n<p>Anyway, for the moment, let's assume the logic is correct and roll with it.</p>\n\n<p>In that case, I'd start by building a table of strings:</p>\n\n<pre><code>int i;\nfloors[12] = \"\";\nfor (i=11; i>=c.achievedFloor; i--)\n floors[i] = \"\"@gre@(Achieved)\";\nfor ( ; i>0; i--)\n floors[i] = \"@red@(Not achieved)\";\n</code></pre>\n\n<p>Since you haven't shown its name, I'm going to assume the value you're using in the <code>case</code> statements is named <code>input</code>.</p>\n\n<p>The values you're using (<code>1214</code>, <code>1215</code>, ...) should probably be given some sort of meaningful name. Right now, they're pretty much the essence of magic numbers. For the moment, I'm going to assign the name <code>first</code> to 1213 and <code>last</code> to 1215.</p>\n\n<p>Using that, we'd have something like:</p>\n\n<pre><code>int base = (input - first) / 4;\nSendOption5(floors[base], floors[base+1], floors[base+2], floors[base+3], \n input == last ? \"\" : \"More\");\nc.DialogAction = input;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T05:34:45.210",
"Id": "43903",
"ParentId": "43783",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T10:18:55.410",
"Id": "43783",
"Score": "4",
"Tags": [
"java"
],
"Title": "How to shorten this code or make it more efficient?"
} | 43783 |
<p>I am having this problem with my code. I have variables <code>firstnumber</code> and <code>secondnumber</code>, as well as <code>operand</code> and <code>result</code>. Then I am using the <code>string.Split</code> to know whether it's an operator or a number.</p>
<p>After that I have used a <code>while</code> loop if <code>a.Length</code> is over 2 and if it is, I declared an <code>double numbers</code> which is <code>a[i]</code>. <code>i</code> is <code>3</code> and gets <code>+ 2</code> every time the while loop executes. </p>
<p>Then I declared a variable called operands which is <code>a[b]</code>. <code>b = 4</code> and gets <code>+ 2</code> every time the loop executes. Then I want to compare the string operands and the string operator, to see if it is <code>+</code>, <code>-</code>, <code>*</code> or <code>/</code> in the end I have put an <code>if</code> statement, so that <code>if a[i] == null</code>, then the <code>while</code> loop breaks and the <code>result</code> is printed.</p>
<p>I know my code is messy, and I have probably done many things wrong here, so I would really appreciate every word of advice I can get.</p>
<pre><code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Calculator
{
static void Main(string[] args)
{
Console.WriteLine("This is a calculator. enter the numbers this way: Example(4 + 3)");
Console.WriteLine("!Use space between numbers!");
start : string s = Console.ReadLine();
overagain: string [] avgränsare = { " " };
string[] a = s.Split(avgränsare, StringSplitOptions.RemoveEmptyEntries);
while (a.Length > 2)
{
int i = 3;
int b = 4;
double numbers = double.Parse(a[i]);
i = i + 2;
b = b + 2;
double firstnumber = double.Parse(a[0]);
string operand = a[1];
double secondnumber = double.Parse(a[2]);
double result = 0;
string operands = a[b];
goto overagain;
if (a[i] == null)
{
Console.WriteLine(result);
break;
}
}
Console.WriteLine("Do you want to continue?");
s = Console.ReadLine().ToLower();
if (s == "y")
{
goto start;
}
else
{
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T12:53:13.577",
"Id": "75747",
"Score": "0",
"body": "Welcome to Code Review! I have written an answer that should help you clean up your code. Unfortunately, you shouldn't expect any answers to extend the functionality of your code. Code Review is for cleaning up existing code. Code Review is not for adding features to, or modify the results of, existing code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T15:26:52.037",
"Id": "75770",
"Score": "2",
"body": "http://xkcd.com/292/"
}
] | [
{
"body": "<h1>Using <code>goto</code> is not a good practice!!</h1>\n<p>Instead of using <code>goto</code>, use a do-while or a <code>while</code> loop. You want to do something as long as the answer to "Do you want to continue" is "Yes". This is perfect for a do-while loop.</p>\n<p>You should also avoid using <code>goto overagain</code> and instead use a for-loop to iterate through the array. It could also be solved with recursion. Use anything you want <strong>except the <code>goto</code> statement!</strong></p>\n<hr />\n<p>Make your code self-documenting. Your "explanation" of your code in the beginning of your question confuses me more than helps me.</p>\n<p>Self-document your code by using <strong>proper variable names</strong>. <code>s</code> can be called <code>input</code> instead, and i and b can be called something that explains what they are doing. Right now, I can't exactly understand what they are supposed to do.</p>\n<hr />\n<p>Your last block of <code>Console.WriteLine("Do you want to continue?");</code>, including the if-else that comes afterwards should be indented one step further.</p>\n<hr />\n<p>If you don't have anything to do in else, just skip that part. <code>if ... { ... }</code> is enough, you don't need else. You'd better remove this, <em>or else</em>...</p>\n<hr />\n<p>Use English names for variables, especially when characters outside the range of A-Z, a-z, 0-9, _ are included (such as "ä"). The Swedish word "avgränsare" translates to "delimiter" in English.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:44:26.087",
"Id": "75753",
"Score": "0",
"body": "Thanks. However i posted this in stackoverflow, and they Said i should go to this place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T13:53:09.427",
"Id": "75754",
"Score": "1",
"body": "@RickardB. That is most likely because your question is very unclear, **and** you are asking for a \"cleanup\" (which is on-topic here). Please show me the link of your StackOverflow question and I can see if there are any differences. Either way, if you would ask \"how can I add this functionality to my code\" on StackOverflow then they would likely tell you to try something first and then come back and ask a **specific** question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T12:49:58.227",
"Id": "43790",
"ParentId": "43789",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T11:58:17.450",
"Id": "43789",
"Score": "4",
"Tags": [
"c#",
"console",
"calculator"
],
"Title": "Calculator for more than two numbers"
} | 43789 |
<p>I have a C# function like below, and in the <code>else</code> block, the function must return something. I don't know whether returning null is a good practice or not.</p>
<pre><code>public Nullable<Point> GetSprite(int x, int y)
{
if (x <= xCount && y <= yCount)
{
return new Point(x * spriteHeight, y * spriteWidth);
}
else
{
return null;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T17:59:31.600",
"Id": "75789",
"Score": "6",
"body": "How is the `GetSprite` method **used**? And what is it **used for?**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:37:24.513",
"Id": "75793",
"Score": "2",
"body": "Isn't `Point` a value type? You'd have to return a `Nullable<Point>` for a null return value to work.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:40:28.273",
"Id": "75794",
"Score": "1",
"body": "Also the name is confusing, `GetSprite` doesn't return a \"Sprite\", but we'd need more context to recommend better alternatives."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T20:53:42.883",
"Id": "75821",
"Score": "0",
"body": "@Mat'sMug I edited it. Yes it does not return a Sprite but it returns Sprite's coords."
}
] | [
{
"body": "<p>Yes, you could just write:</p>\n\n<pre><code>public Point GetSprite(int x, int y)\n{\n if (x <= xCount && y <= xCount)\n {\n return new Point(x * spriteHeight, y * spriteWidth);\n }\n\n return null;\n}\n</code></pre>\n\n<p>And write in the documentation it could return null if <code>if (x <= xCount && y <= xCount)</code></p>\n\n<p>So who use your code could just write</p>\n\n<pre><code>Point point = GetSprite(x, y);\nif (point == null) { /* something went wrong, check variables! */ }\nelse { /* ok! go ahead! */ }\n</code></pre>\n\n<p>I found this syntax very useful, and could not lead to bugs if the programmer is alerted about the null.</p>\n\n<p>And, anyway you don't need the <code>else</code> block since the <code>return</code> call will stop the function (except if there are any finally blocks, but it's not the case.).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:41:46.857",
"Id": "75795",
"Score": "3",
"body": "“could not lead to bugs if the programmer is alerted about the null” How do you make sure they are alerted? Because people don't always read documentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:24:34.163",
"Id": "75812",
"Score": "3",
"body": "@svick You could throw an error if it's exceptional behavior. `if (...) { ... } else { thrown new InvalidArgumentException; }`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T17:29:07.700",
"Id": "43799",
"ParentId": "43798",
"Score": "14"
}
},
{
"body": "<p>Returning <code>null</code> is fine. You can check for <code>null</code> and decide what to do in the calling function.</p>\n\n<p>Multiple <code>return</code> statement in a function is not a good practise.</p>\n\n<p>So you can modify your function like:</p>\n\n<pre><code>public Point GetSprite(int x, int y)\n{\n Point pObj = null;\n if (x <= xCount && y <= xCount)\n {\n pObj = new Point(x * spriteHeight, y * spriteWidth);\n }\n\n return pObj ;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T17:46:20.293",
"Id": "75788",
"Score": "7",
"body": "“*Multiple return statement in a function is not a good practise*” – is this some official C# style guideline? It is universally accepted that multiple returns are a bad idea in C, because of resource cleanup on exit. However, C# is garbage-collected, so there is no technical reason to avoid multiple returns. In fact, I find multiple returns more elegant than using variables, especially for such a short function!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:43:09.720",
"Id": "75797",
"Score": "0",
"body": "I disagree with you @amon but I also agree. yes it is a short function, but this is clear about what the code is doing, it is returning a `Point` object. if you have a `return null;` then you wonder is it returning a null integer, a null pointer, a null coordinate. I know you classify the function as a `Point` Function but this code is clear as to what it is doing, Returning a `Point` object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:48:32.667",
"Id": "75799",
"Score": "4",
"body": "@Malachi I think that `return null` is very clear, and when you're reading a short enough function, it's hard to forget its return type. On the other hand, `return pObj` is less clear (even if the variable name was improved), because you have to look though the whole function to find out what it really means. (And I think finding all `return`s is easier than finding all usages of a variable.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T17:34:01.340",
"Id": "43800",
"ParentId": "43798",
"Score": "4"
}
},
{
"body": "<p>It depends whether arguments that are out of range may occur in a regular way or if such method calls are considered being abusive.</p>\n\n<ul>\n<li><p>If such arguments are regular, then return <code>null</code> (that's perfectly okay).</p></li>\n<li><p>If such arguments are abusive, then throw an exception.</p></li>\n</ul>\n\n<p>An exception should always catch an error and never be misused for a test.</p>\n\n<p>If the purpose of the method is not only to return a sprite, but also to test whether a sprite is available for a set of parameters, then you could use the same pattern as with <code>Dictionary<T>.TryGetValue</code>:</p>\n\n<pre><code>public bool TryGetSprite(int x, int y, out Sprite sprite)\n{\n ...\n}\n</code></pre>\n\n<p>Use it like this:</p>\n\n<pre><code>Sprite sprite;\nif (obj.TryGetSprite(x, y, out sprite)) {\n // Sprite available\n} else {\n // No sprite available\n}\n</code></pre>\n\n<p>When the return type is a non-nullable type, this is a good option. Magic numbers like <code>0</code>, <code>-1</code> or <code>Int32.MinValue</code> are not obvious and are not always available (if the full range of values is required as a regular result). Even <code>null</code> might be a regular result under certain circumstances; for instance, a dictionary is allowed to contain <code>null</code> values. If you need this distinction between <em>contains null</em> and <em>not found</em>, the <strong>TryGet...</strong> approach is perfect.</p>\n\n<p>The advantage over returning <code>null</code> is that you don't need additional knowledge apart from the method's signature in order to know how it works. Otherwise you are not sure whether an exception will be thrown or whether <code>null</code> or even an empty <code>Sprite</code> will be returned without reading the documentation. The disadvantage of <code>TryGetSomething</code> is that is looks somewhat cumbersome. However, starting with C#7.0 / Visual Studio 2017, you can declare the variable inline: <code>obj.TryGetSprite(x, y, out var sprite)</code> or <code>obj.TryGetSprite(x, y, out Sprite sprite)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:43:07.643",
"Id": "75796",
"Score": "1",
"body": "I'd say that values like `MinValue` or `-1` are very rarely obvious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T18:48:13.160",
"Id": "75798",
"Score": "0",
"body": "Yes they should be avoided, but even Microsoft does it with `System.String.IndexOf()`. If used, at least a constant should be declared for magical numbers: `public const int NotFound = -1;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T17:47:33.443",
"Id": "43801",
"ParentId": "43798",
"Score": "12"
}
},
{
"body": "<p><strong>Null is bad</strong>. It's a flaw in the type system, and its inventor <a href=\"https://stackoverflow.com/a/5149102/1272233\">deeply regrets unleashing it upon the world</a>. It adds an additional value to all reference types that <a href=\"https://stackoverflow.com/questions/3989264/best-explanation-for-languages-without-null/3990754#3990754\">you probably don't want</a>.</p>\n\n<p>If you don't want to throw an exception (because failing to return a Sprite is a common occurrence and will likely be handled immediately rather than several layers up), then the correct solution is to return <a href=\"https://stackoverflow.com/questions/2079170/what-is-the-point-of-the-class-optiont?lq=1\">a type that represents a value of type T that may or may not be there</a>. For value types, Nullable fills that need reasonably well, because it forces you to handle the case where the value is missing. For reference types <a href=\"https://softwareengineering.stackexchange.com/a/228125/116461\">you'll have to roll your own</a> since C# doesn't provide any.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T03:58:24.673",
"Id": "75867",
"Score": "0",
"body": "You probably don't want that additional value, unless you do. That's why C# has `Nullable` for structs and why F# has `option`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T16:31:58.127",
"Id": "75902",
"Score": "1",
"body": "@svick The difference is that `Nullable` and `Option` keep the \"nothing\" value out of the original type. A `Nullable int` is not an `int` and you can't blindly assign one to the other. `null` is not an integer and it would make no sense to be able to assign it to an integer variable. The same logic holds for every other type - `null` is not a `List`, or a `Point`, or anything at all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:24:27.923",
"Id": "43815",
"ParentId": "43798",
"Score": "11"
}
},
{
"body": "<p>I've read alot about returning null is not the best practice in the world, but like anything I think it will depend on it's usage and how often it might be called. So, in your case this might be ok. However, I'd just like to chuck out another way of doing things using the Null Object pattern.</p>\n\n<p>Using this you would not return null at all but rather return a Null/invalid object. Your calling code dependant on it's usage will be checking an instance type and so you might not need to even worry about whether it's null and potentially remove all those <code>== null</code> checks.</p>\n\n<pre><code>public Point GetSprite(int x, int y)\n{\n return x <= xCount && y <= xCount\n ? new Point(x * spriteHeight, y * spriteWidth);\n : Point.OffGrid();\n}\n</code></pre>\n\n<p>Then in your Point class itself you might have something like</p>\n\n<pre><code>public class Point\n{\n private static readonly Point _null = new Point(-9999,-9999);\n\n public static Point OffGrid\n {\n get\n {\n return _null;\n }\n }\n\n public bool IsOffGrid {\n get { return this.Equals(OffGrid); }\n }\n}\n</code></pre>\n\n<p>This way you might never even need to check for null at times. However if you did your statements might look something like this now</p>\n\n<pre><code>var point = GetSprite(x, y);\n\nif(point.IsOffGrid()) // equivalent to point == null\n{\n // how do we handle it when it's off grid?\n}\n\n// do stuff\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:25:57.667",
"Id": "43816",
"ParentId": "43798",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "43799",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T17:25:06.027",
"Id": "43798",
"Score": "12",
"Tags": [
"c#",
"null"
],
"Title": "Returning null or what?"
} | 43798 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.