body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I made the code, and it works, but it uses many <code>if</code> conditions and it looks ugly. I would really appreciate it if someone could give me a hand by pointing me in the right direction to make it more object-oriented.</p>
<pre><code>package ar.edu.uca.ceis.objetos.imperio;
import ar.uba.fi.algo3.batallaespacial.CabinaDeControl;
import ar.uba.fi.algo3.batallaespacial.Civilizacion;
import ar.uba.fi.algo3.batallaespacial.Piloto;
import ar.uba.fi.algo3.batallaespacial.Reporte.Espectro;
import ar.uba.fi.algo3.batallaespacial.Sustancia;
import ar.uba.fi.algo3.batallaespacial.comandos.Comando;
import ar.uba.fi.algo3.batallaespacial.Direccion;
public class PilotoImperial implements Piloto {
private CabinaDeControl cabina;
private Imperio civilizacion;
public PilotoImperial(Imperio civilizacion) {
super();
this.civilizacion = civilizacion;
}
public void setCabinaDeControl(CabinaDeControl cabina) {
this.cabina = cabina;
}
public Comando proximoComando() {
Direccion[] values = Direccion.values();
// for (int i = 1; i < values.length; i++) {
int i;
i = (int)Math.round(Math.random() *values.length-1) ;
//if border of an unknow position, go to a random place
if (Espectro.DESCONOCIDO == this.cabina.getRadar().getReporte( values[i] ).getEspectro()){
// generaremos numeros aleatorios entre 1 y values.length
int c = (int)Math.round(Math.random() *values.length) ;
if (Espectro.VACIO == this.cabina.getRadar().getReporte( values[c] ).getEspectro()){
return this.cabina.getControl().avanzar( values[c] );
}
}
// i found and enemy base, attack
if (Espectro.BASE == this.cabina.getRadar().getReporte( values[i] ).getEspectro()) {
if (this.cabina.getRadar().getReporte( values[i] ).getCivilizacion()!=this.civilizacion){
return this.cabina.getControl().atacar(values[i]);
}
}
// if found and enemy, attack
if (Espectro.NAVE == this.cabina.getRadar().getReporte( values[i] ).getEspectro()) {
if (this.cabina.getRadar().getReporte( values[i] ).getCivilizacion()!=this.civilizacion){
return this.cabina.getControl().atacar(values[i]);
}
}
// attack asteroid if (Espectro.ASTEROIDE == this.cabina.getRadar().getReporte( values[i] ).getEspectro()) {
return this.cabina.getControl().atacar(values[i]);
}
// if found a container, upload materia 100
if (Espectro.CONTENEDOR == this.cabina.getRadar().getReporte( values[i] ).getEspectro()) {
while (this.cabina.getRadar().getReporte( values[i] ).getCantidadDeSustancia(Sustancia.ANTIMATERIA)>0){
return this.cabina.getControl().transferirCarga(values[i], Direccion.ORIGEN, Sustancia.ANTIMATERIA, 100);
}
}
// if found a ally base, download anti-materia
if (Espectro.BASE == this.cabina.getRadar().getReporte( values[i] ).getEspectro()) {
while (this.cabina.getMonitor().getCarga(Sustancia.ANTIMATERIA)>0){
return this.cabina.getControl().transferirCarga(Direccion.ORIGEN,values[i], Sustancia.ANTIMATERIA, 100);
}
}
// if there is nothing, move to a position
int ii = (int)Math.round(Math.random() *values.length-1) ;
if (Espectro.VACIO == this.cabina.getRadar().getReporte( values[ii] ).getEspectro()){
return this.cabina.getControl().avanzar( values[ii] );
}
//}
// found none wait
return this.cabina.getControl().esperar();//.avanzar();
}
public Civilizacion getCivilizacion() {
return this.civilizacion;
}
public String getNombre() {
return "Piloto Imperial";
}
}
</code></pre>
<p>Considering this is a framework and I only show you the class I'm changing, the rest works fine. This is a homework, so no need for a super fancy code. Last but not least, if you could help me use a pattern, that would be amazing.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:26:18.033",
"Id": "42343",
"Score": "3",
"body": "would you be so kind and rewrite your code in english please. and as far as i can see you make no difference between allied and hostile bases"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:37:48.993",
"Id": "42347",
"Score": "0",
"body": "you meant the objects? I cant, basically they are defined on external classes that i cannot touch... and notice on the allied based, there is not attack, basically it checks its position to know which spot is empty and then return to the origin."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:38:59.673",
"Id": "42348",
"Score": "2",
"body": "i meant that the check whether there is an enemy or allied base is exactly the same. okay and to prepare my answer i need to know the types of `this.cabina.getRadar().getReporte(values[i]).getEspectro()` and `this.cabina.getControl()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:43:16.270",
"Id": "42350",
"Score": "0",
"body": "yeah, now that I see it, the compiler would never enter into the second one, thanks!"
}
] |
[
{
"body": "<p>Your Professor has assigned you code that fails to meet some basic tenets of object-oriented programming, including:</p>\n\n<ul>\n<li><a href=\"http://c2.com/cgi/wiki?EncapsulationIsNotInformationHiding\" rel=\"nofollow noreferrer\">Information Hiding</a></li>\n<li>The <a href=\"http://c2.com/cgi/wiki?LawOfDemeter\" rel=\"nofollow noreferrer\">Law of Demeter</a></li>\n<li>The <a href=\"http://c2.com/cgi/wiki?OpenClosedPrinciple\" rel=\"nofollow noreferrer\">Open-Closed Principle</a></li>\n<li>The <a href=\"http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html\" rel=\"nofollow noreferrer\">DRY Princple</a></li>\n</ul>\n\n<p>Effectively, your Professor is teaching you how to program with structures, not objects, using Java.</p>\n\n<p>For example, here's one problem with breaking the Law of Demeter:</p>\n\n<pre><code>if (Espectro.VACIO == this.cabina.getRadar().getReporte( values[ii] ).getEspectro()){\n</code></pre>\n\n<p>If any one of the following are <code>null</code>, the code will throw a <code>NullPointerException</code>:</p>\n\n<ul>\n<li><code>this.cabina</code></li>\n<li><code>getRadar()</code></li>\n<li><code>getReporte( ... )</code></li>\n</ul>\n\n<p>There are no try/catch blocks, nor does the method declare any exceptions, so the program will crash. A program that crashes can be quite frustrating for the users.</p>\n\n<p>The line should be either of the following:</p>\n\n<pre><code>if( getCabina().isEspectro( Espectro.VACIO ) ) {\n\nif( isEspectro( Espectro.VACIO ) ) {\n</code></pre>\n\n<p>In the second case, the method <code>isEspectro</code> would resemble:</p>\n\n<pre><code>public boolean isEspectro( Espectro e ) {\n return getCabina().isEspectro( e );\n}\n</code></pre>\n\n<p>This is called <em>delegation</em>. It avoids the cascading dot notation that is the source of so many bugs. See <a href=\"https://codereview.stackexchange.com/questions/26925/cleaning-up-multiple-if-statements/27186#27186\">this answer</a> for more details about <em>information hiding</em>.</p>\n\n<p>The method <code>getCabina()</code> would be wholly responsible for ensuring that the CabinaDeControl instance is set. Otherwise how do you <em>guarantee</em> that <code>this.cabina</code> is not <code>null</code> (without using a framework such as Spring, which supports <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">inversion of control</a>)? For example:</p>\n\n<pre><code>private synchronized CabinaDeControl getCabina() {\n if( this.cabina == null ) {\n this.cabinia = createCabina();\n }\n\n return this.cabina;\n}\n\n/** Subclasses can vary the CabinaDeControl instances used by this class. */\nprotected CabinaDeControl createCabina() {\n return new CabinaDeControl(); // ... or whatever is required to instantiate.\n}\n</code></pre>\n\n<p>This is called <em>lazy initialization</em>. Importantly, the pattern follows the <em>Open-Closed Principle</em> whereby you can change the behaviour of a class by overriding the <code>createCabina()</code> method inside a subclass. You don't have to change the original class to change its behaviour. That prevents introducing widely-scoped bugs (the new subclass can still introduce bugs, but the ripple effect should be less severe than by changing the original class).</p>\n\n<p>Using <code>this.cabina.method()</code> violates the DRY Principle because <code>this.cabina</code> is repeated several times. Programming means eliminating duplicate code and the reasons are many.</p>\n\n<p>Each occurrence of <code>this.cabina.method()</code> can throw a <code>NullPointerException</code> because there is no check to ensure <code>cabina</code> is not null. That should leave you with an uneasy feeling. Replace <code>this.cabina</code> with <code>getCabina()</code> (as I have implemented above) and that uneasy feeling should go away. It does not mean the code will be correct, but at least the program won't crash if <code>cabina</code> is ever set to <code>null</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T16:31:17.823",
"Id": "42358",
"Score": "1",
"body": "The law of Demeter is to be taken with a grain of salt... Sometimes it goes too far. But otherwise, +1!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T17:24:28.620",
"Id": "42360",
"Score": "0",
"body": "I´m very thankful for your help, I will take a look in deep. Thanks a ton"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T16:20:21.983",
"Id": "27273",
"ParentId": "27268",
"Score": "3"
}
},
{
"body": "<p>After Dave gave you some hints about increasing the style and stability of your code I think I can give you some advises concerning your design.</p>\n\n<p>In your method <code>proximoComando()</code> you do the same thing over and over which practically screams for refactoring:</p>\n\n<p>You check the <code>Direccion</code> you chose at the beginning and if your check succeeds you return an action. The design patterns the instantly spring to my mind to clean this up are <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy</a> and <a href=\"http://en.wikipedia.org/wiki/Chain_of_responsibility_pattern\" rel=\"nofollow\">Chain of Responsibility</a>.</p>\n\n<p>Here we go...</p>\n\n<p>First we use the strategy pattern to abstract the checks of the battleship's surroundings...</p>\n\n<pre><code>public interface SituationCheck {\n // check the situation and return true if the concrete conditions are met\n boolean isConditionMet(CabinaDeControl cabina, Direccion contactDireccion, Civilizacion ownCivilizacion);\n}\n</code></pre>\n\n<p>... and the same for the actions that the pilot can perform...</p>\n\n<pre><code>public interface PilotAction {\n // return the command that corresponds to the given action\n Comando issueCommand(Direccion[] direccions, Direccion contactDireccion, Control control);\n}\n</code></pre>\n\n<p>now we can use these interfaces to model the behaviour of the battleship following the Chain-of-Responsibility pattern. I named the class <code>Orders</code> since it represents a set of orders what your pilot has to do in specific situations:</p>\n\n<pre><code>public class Orders {\n private SituationCheck check = null;\n private PilotAction action = null;\n private Orders next = null;\n\n public Orders(SituationCheck check, PilotAction action) {\n this.check = check;\n this.action = action;\n this.next = null;\n }\n\n public Orders(PilotAction action) {\n this(null, action);\n }\n\n /**\n * Performs situation checks and issues the appropriate command\n * \n * @param contactDireccion\n * the direction that is checked\n * @param cabina\n * the radar report of a given direccion\n * @param ownCivilizacion\n * the ship's own civilizacion\n * @return the command the fits to the situation\n */\n public Comando checkSituationAndIssueCommand(Direccion[] direccions, Direccion contactDireccion, CabinaDeControl cabina, Civilizacion ownCivilizacion) {\n if (check == null || check.isConditionMet(cabina, contactDireccion, ownCivilizacion)) {\n if (action != null) { // adding null actions should be avoided ;)\n return action.issueCommand(direccions, contactDireccion, cabina.getControl());\n }\n } else if (next != null) {\n return next.checkSituationAndIssueCommand(direccions, contactDireccion, cabina, ownCivilizacion);\n }\n // if we reach the end of the chain and no situation check succeeded\n // or if there was no action assigned to the situation\n // this may be replaced by a dummy action e.g. DoNothing\n return null;\n }\n\n public Orders add(Orders orders) {\n if (next == null) {\n next = orders;\n return next;\n } else {\n return next.add(orders);\n }\n }\n\n public Orders add(SituationCheck newCheck, PilotAction newAction) {\n return add(new Orders(newCheck, newAction));\n }\n\n public void add(PilotAction finalAction) {\n add(new Orders(finalAction));\n }\n}\n</code></pre>\n\n<p>I'll explain that step by step:</p>\n\n<ul>\n<li><p>Each order consist of three things</p>\n\n<ul>\n<li>a check that will applied to the given situation</li>\n<li>an action that will be performed if the check succeeds and</li>\n<li>another order that is consider if the check fails (i.e. the next part in our chain)</li>\n</ul></li>\n<li><p>There are two constructors</p>\n\n<ul>\n<li>one with a check and an action to create a normal part of the chain</li>\n<li>one with only an action that marks the end of our chain</li>\n</ul></li>\n<li><p>I wrote few methods to add a new element to the chain. I let two of them return the current end of the chain so we can easily put it together. If you don't like this make them void methods.</p></li>\n</ul>\n\n<p>Two create the behaviour of your example we need a few concrete checks ...</p>\n\n<pre><code>public class CheckForEspectro implements SituationCheck {\n private Espectro espectro;\n\n public CheckForEspectro(Espectro espectro) {\n this.espectro = espectro;\n }\n\n @Override\n public boolean isConditionMet(CabinaDeControl cabina, Direccion contactDireccion, Civilizacion ownCivilizacion) {\n return cabina.isEspectro(espectro, contactDireccion);\n }\n}\n\npublic class CheckForEnemy implements SituationCheck {\n private Espectro enemyType; // e.g. BASE, NAVE\n\n public CheckForEnemy(Espectro enemyType) {\n this.enemyType = enemyType;\n }\n\n @Override\n public boolean isConditionMet(CabinaDeControl cabina, Direccion contactDireccion, Civilizacion ownCivilizacion) {\n return cabina.isEspectro(enemyType, contactDireccion) && cabina.contactIsHostileTo(contactDireccion, ownCivilizacion);\n }\n}\n\npublic class CheckForAlly implements SituationCheck {\n private Espectro allyType; // e.g. BASE, NAVE\n\n public CheckForAlly(Espectro allyType ) {\n this.allyType = allyType ;\n }\n\n @Override\n public boolean isConditionMet(CabinaDeControl cabina, Direccion contactDireccion, Civilizacion ownCivilizacion) {\n return cabina.isEspectro(allyType, contactDireccion) && cabina.contactIsAlliedTo(contactDireccion, ownCivilizacion);\n }\n}\n\npublic class CheckForContainer implements SituationCheck {\n private Sustancia sustancia;\n\n public CheckForContainer(Sustancia sustancia) {\n this.sustancia = sustancia;\n }\n\n @Override\n public boolean isConditionMet(CabinaDeControl cabina, Direccion contactDireccion, Civilizacion ownCivilizacion) {\n return cabina.isEspectro(Espectro.CONTAINER, contactDireccion) && cabina.contactContainsSubstance(contactDireccion, sustancia);\n }\n}\n</code></pre>\n\n<p>... and actions ....</p>\n\n<pre><code>public class Attack implements PilotAction {\n @Override\n public Comando issueCommand(Direccion[] direccions, Direccion contactDireccion, Control control) {\n return control.atacar(contactDireccion);\n }\n}\n\npublic class MoveToRandomPosition implements PilotAction {\n @Override\n public Comando issueCommand(Direccion[] direccions, Direccion contactDireccion, Control control) {\n int index = (int) Math.round(Math.random() * direccions.length);\n return control.avanzar(direccions[index]);\n }\n}\n\npublic class Wait implements PilotAction {\n @Override\n public Comando issueCommand(Direccion[] direccions, Direccion contactDireccion, Control control) {\n return control.esperar();\n }\n}\n\npublic class Transfer implements PilotAction {\n public enum Direction {\n UPLOAD, DOWNLOAD\n }\n\n private Direction direction;\n private Sustancia sustancia;\n private int amount;\n\n public Transfer(Direction direction, Sustancia sustancia, int amount) {\n this.direction = direction;\n this.sustancia = sustancia;\n this.amount = amount;\n }\n\n @Override\n public Comando issueCommand(Direccion[] direccions, Direccion contactDireccion, Control control) {\n switch (direction) {\n case UPLOAD:\n return control.transferirCarga(contactDireccion, Direccion.ORIGEN, sustancia, amount);\n case DOWNLOAD:\n return control.transferirCarga(Direccion.ORIGEN, contactDireccion, sustancia, amount);\n default: // currently unreachable\n return null;\n }\n }\n}\n</code></pre>\n\n<p>Please note that i assumed that you already implemented some of Dave's ideas e.g. i call a method</p>\n\n<pre><code>cabina.contactIsHostileTo(contactDireccion, ownCivilizacion)\n</code></pre>\n\n<p>that i assume to return the result of your check</p>\n\n<pre><code>this.cabina.getRadar().getReporte( values[i] ).getCivilizacion()!=this.civilizacion\n</code></pre>\n\n<p>where <code>contactDireccion</code> coresponds to <code>values[i]</code> and <code>ownCivilizacion</code> to <code>this.civilizacion</code>.</p>\n\n<p>This way you have that logic in exactly one place and can easily exchange that simple check to a more complex one e.g. by evaluating some diplomacy matrix.</p>\n\n<p>Now we can alter your class by adding a field for the Orders</p>\n\n<pre><code>private Orders orders;\n</code></pre>\n\n<p>and set them up in the constructor:</p>\n\n<pre><code>public PiloPilotoImperial() {\n super();\n\n Orders orders = new Orders(new CheckForEspectro(Espectro.DESCONOCIDO), new MoveToRandomPosition());\n orders.add(new CheckForEnemy(Espectro.NAVE), new Attack())\n .add(new CheckForEnemy(Espectro.BASE), new Attack())\n .add(new CheckForContainer(Sustancia.ANTIMATERIA), new Transfer(Direction.UPLOAD, Sustancia.ANTIMATERIA, 100))\n .add(new CheckForAlly(Espectro.BASE), new Transfer(Direction.DOWNLOAD, Sustancia.ANTIMATERIA, 100))\n .add(new CheckForEspectro(Espectro.VACACIO), new MoveToRandomPosition())\n .add(new Wait());\n}\n\npublic PilotoImperial(Imperio civilizacion) {\n this();\n this.civilizacion = civilizacion;\n}\n</code></pre>\n\n<p>and finally your method will be much shorter:</p>\n\n<pre><code>public Comando proximoComando() {\n Direccion[] direccions = Direccion.values();\n\n if (direccions == null || direccions.length == 0) {\n return null;\n }\n\n Direccion contactDireccion = direccions[Math.round(Math.random() * values.length-1)];\n\n return orders.checkSituationAndIssueCommand(direccions, contactDireccion, getCabina(), getCivilizacion());\n}\n</code></pre>\n\n<p>I hope this answer was not too long but i wanted to show you how you could rewrite your code by dividing it into little independent pieces that are easy to understand can be put together to form a more complex structure in many different variations.</p>\n\n<p>For example you could use different combinations of checks and actions to create a freighter that transfers other stuff and flees from enemies.</p>\n\n<p>You can find my source code <a href=\"http://db.tt/nkXHqtZm\" rel=\"nofollow\">here</a> - i added some dummy implementations of your classes to avoid compiler errors. feel free to alter anything you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:04:44.577",
"Id": "42422",
"Score": "0",
"body": "if you get used to this style i recommend another exercise for you: refactor `CheckForEnemy` and `CheckForAlly` into a single method that can be used to check for enemy, allied and neutral ships and bases ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:05:51.627",
"Id": "42439",
"Score": "0",
"body": "Note that this code also breaks the principles I mentioned, in exactly the same ways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:40:24.953",
"Id": "42513",
"Score": "0",
"body": "@DaveJarvis what else except the null checks i left out?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:12:35.747",
"Id": "42516",
"Score": "0",
"body": "Every internal reference to an internal variable must be hidden by an accessor call. So `return orders.checkSituation(...)` must be `return getOrders().checkSituation(...)`. Otherwise the DRY Principle is violated, as would be the Open-Closed Principle for adding features in the future."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T11:29:35.510",
"Id": "27300",
"ParentId": "27268",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27273",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:09:59.637",
"Id": "27268",
"Score": "4",
"Tags": [
"java",
"game",
"homework"
],
"Title": "Battleship type game in Java"
}
|
27268
|
<p>I have a program which is primarily illustrative in example to help me learn refactoring techniques and best practices. This program will take the <code>ActiveTabIndex</code> property of a <code>TabContainer</code> control and add a <code>GridView</code> control to the page and bind it to a database using a stored procedure. Each tab in the <code>TabContainer</code> will be bound to a different stored procedure with the tab that is clicked on being the event that creates the <code>GridView</code> and does the binding. I know that I have too much repeated code, but I'm not sure how to rectify it.</p>
<p>I thought about maybe having a method that takes the stored procedure name as a parameter and appends the <code>ActiveTabIndex</code> to the stored procedure name, but that seems just about as tightly coupled and tenuous at best. What are some methods I can employ to reduce the amount of duplicated code I have?</p>
<pre><code> public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnMakeGridView_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
if (TabContainer1.ActiveTabIndex == 0)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest0", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else if (TabContainer1.ActiveTabIndex == 1)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest1", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else if (TabContainer1.ActiveTabIndex == 2)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest2", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else
{
Label1.Text = "You must select a tab to create the GridView in";
}
}
}
}
</code></pre>
<p>My full intentions were to dynamically build the number of tabs as well based on how much <em>different</em> stored procedures the user selected. I think using the stored procedure name as a tag property would be how I would make the correct <code>GridView</code> to the correct <code>TabPanel</code>. I apologize if my given example seems too far off from my original intent. I wanted to make sure that I was at least somewhat on the right track before I gave a small code snippet and asked for the moon.</p>
<p>Maybe something like "select name from <code>sys.procedures</code>" where name like '%ProcsToChoose%', create a <code>List<string></code> out of that and give the query a <code>row_number()</code> -1 to bind to the ordinal index (but that seems like a poor idea) of the <code>TabPanel</code>.</p>
<p>Attempt at streamlining code:</p>
<pre><code>protected void btnMakeGridView_Click(object sender, EventArgs e)
{
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(GetData(cs, "spTest", TabContainer1.ActiveTabIndex));
}
public static GridView GetData(string connectionString,string spName, int activeIndex)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
gv.ID = "gv" + activeIndex.ToString();
gv.DataSource = rdr;
gv.DataBind();
return gv;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T22:11:09.487",
"Id": "42377",
"Score": "1",
"body": "Save \"spTest0\", \"spTest1\", \"spTest2\", etc. as a `Tag` property of a `Tab`. Get the active tab, get its tag, convert that to string and use it as a stored procedure name. Once you know the sp name - the rest of the code is the same, so no need for repetitive if statements. The only real problem is - how do you map tab object / tab index to a stored procedure name? Using Tag property is one way; having an array of stored procedure names where array index corresponds to tab index is another. You could also map tab name to stored proc name with a dictionary. There are many ways to skin this cat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T22:38:44.093",
"Id": "42379",
"Score": "0",
"body": "Hello, thanks for the reply. Please refer to the edit for the changes that I made in trying to make this more extensible (please let me know if this is the right track). I felt it would have been too ambitious to state what I really wanted to do without really knowing how close to the right track I was so please check the edit for further info."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T23:23:36.343",
"Id": "42381",
"Score": "0",
"body": "Sounds like you want your UI to be completely SQL-driven. The app would know how to log in to the database, and the UI will be built after some interrogation of the table contents. And if the SQL connection fails, then the UI will be almost blank. The advantage of putting it all in SQL is that you do not have to hard-code some data in the db and some data in the UI. Things I do not like are: 1) Do not rely on stored procedure names. I would list them explicitly in a separate table. Also, are tabs the answer? If tabs look very much alike, then differentiate between sources using a combo box?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T00:37:46.447",
"Id": "42382",
"Score": "0",
"body": "@Leonid this is as much as anything just an exercise in practice. I'm not tied or married to any particular design, just trying to learn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T17:57:12.967",
"Id": "42459",
"Score": "0",
"body": "ok ... why not aim high? If you want to succeed as a programmer, you need to be very good - good at writing and refactoring code, good at making and refactoring GUI, good at writing clear documentation ... It also helps to work on real problems. You can get the computer do just about anything for you. It is important to work on something that somebody would need because you learn about tradeoffs that you are often forced to make. Anyhow, if you share the screenshot of what your GUI looks like, I can offer some GUI refactoring advice."
}
] |
[
{
"body": "<p>Leonid's comments cover structure nicely, so I will tackle stylistic points (working off your streamlined edit).</p>\n\n<p><strong>Naming</strong></p>\n\n<p>Avoid shortened form variable names. Extra characters on a variable's name are free, and work wonders for a maintenance programmer down the line.</p>\n\n<p>e.g.</p>\n\n<pre><code>SqlDataReader rdr = cmd.ExecuteReader();\n</code></pre>\n\n<p>would better be:</p>\n\n<pre><code>SqlDataReader reader = command.ExecuteReader();\n</code></pre>\n\n<p><strong>Var</strong></p>\n\n<p>Use the <code>var</code> keyword when defining local variables where the right hand side of the definition makes the type obvious. This looks cleaner and saves time when it comes to changing types during refactoring.</p>\n\n<p>e.g.</p>\n\n<pre><code>using (SqlCommand cmd = new SqlCommand(spName, con))\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>using (var cmd = new SqlCommand(spName, con))\n</code></pre>\n\n<p><strong>Magic Strings</strong></p>\n\n<p>It looks like you have a couple of magic strings (e.g. \"gv\" and \"spTest\") in your code that would be better off refactored into constants with descriptive names.</p>\n\n<p><strong>Misc</strong></p>\n\n<p>It looks like you can get rid of the declaration of 'rdr' and simply use:</p>\n\n<pre><code>gv.DataSource = (SqlDataReader)cmd.ExecuteReader();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-15T13:58:17.583",
"Id": "77598",
"ParentId": "27272",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T16:19:43.437",
"Id": "27272",
"Score": "1",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Button clicks to add GridViews inside TabContainer"
}
|
27272
|
<p>I have implemented a <a href="https://buddy.codeplex.com/SourceControl/latest#Buddy/Buddy-.NET-4.5/Buddy/WaitGroup.cs" rel="nofollow">WaitGroup</a> class to simulate WaitGroup in Go lang. Then I've found that I can use <a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k%28System.Threading.Barrier%29;k%28TargetFrameworkMoniker-.NETFramework,Version=v4.5%29;k%28DevLang-csharp%29&rd=true" rel="nofollow">Barrier</a> in a different manner, to achieve the same thing. My WaitGroup has some additional functionality, but in most scenarios Barrier just would do.</p>
<p><strong>Question:</strong> Do you spot any design flaws in this style of using Barrier?</p>
<p><strong>Code:</strong></p>
<p>I have an instance of Barrier:</p>
<pre><code>static Barrier WaitGroupBarrier = new Barrier(0);
</code></pre>
<p>Then I define my tasks (or threads) this way in multiple places - so I have not the actual number of tasks/threads:</p>
<pre><code>for (int i = 0; i < 1000; i++) // in multiple places
{
var t = new Task(() =>
{
try
{
WaitGroupBarrier.AddParticipant();
// body
}
finally
{
WaitGroupBarrier.RemoveParticipant();
}
});
t.Start();
}
</code></pre>
<p>And I wait for them to complete, this way:</p>
<pre><code>if (WaitGroupBarrier.ParticipantsRemaining > 0)
{
Console.WriteLine("waiting...");
WaitGroupBarrier.SignalAndWait();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T09:30:11.233",
"Id": "42354",
"Score": "0",
"body": "The question is about C#; not Go. I am \"simulating\" this feature of Go, in C#. It's not a comparison. BTW I like Go."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:28:29.483",
"Id": "42355",
"Score": "0",
"body": "@svick How can I move this question there? Should I repeat it there or somebody would migrate it? Please guide me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T15:38:55.663",
"Id": "42356",
"Score": "0",
"body": "Probably the fastest way for you is to ask the question there again and then delete it here. Another option would be to flag it and ask for it to be moved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T15:52:10.153",
"Id": "42357",
"Score": "0",
"body": "OP, if you do this, let a link here in comment so that we can follow the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T10:49:28.603",
"Id": "42417",
"Score": "0",
"body": "Yes, I'd like to see the answer to this... My C# skills are a few (read many) years old, and I'd like to see the solution!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:33:28.973",
"Id": "42430",
"Score": "0",
"body": "@Intermernet This is a solution. The question is: is it a proper solution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T01:21:28.837",
"Id": "42485",
"Score": "0",
"body": "@KavehShahbazian, yes, sorry, ambiguous comment :-)"
}
] |
[
{
"body": "<pre><code>if (WaitGroupBarrier.ParticipantsRemaining > 0) {\n WaitGroupBarrier.SignalAndWait();\n}\n</code></pre>\n\n<p>The above is a non-atomic operation. Thus if the if branch gets evaluated and there is one remaining, but finishes before SignalAndWait, then this will throw an exception.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T20:45:37.817",
"Id": "29244",
"ParentId": "27274",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29244",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T09:27:04.083",
"Id": "27274",
"Score": "1",
"Tags": [
"c#",
"multithreading",
"go",
"task-parallel-library"
],
"Title": "Using Barrier to Implement Go's Wait Group"
}
|
27274
|
<p>OK, this question may seem a little strange at first; however I'd like to have your comments on it.</p>
<p>Background: I do Java. A lot. Java is a statically typed language, it has means to restrict visibility of instance variables, etc. And as such the builder pattern (see <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="nofollow">here</a>) is quite adapted to it.</p>
<p>I took this pattern a step further. The builder pattern is a one-step process: once you <code>.build()</code>, you obtain an instance, preferrably immutable; but once you have the instance, there is no going back. The freeze/thaw pattern is a "reversible builder".</p>
<p>I implemented it in Java and this gives the following interfaces, which I use quite a lot in my own projects (one-sided discussion about this pattern <a href="https://github.com/fge/btf/wiki/The-freeze-thaw-pattern" rel="nofollow">here</a>):</p>
<pre><code>// Frozen
@Immutable
public interface Frozen<T extends Thawed<? extends Frozen<T>>>
{
/**
* Return a thawed representation of this frozen object.
*
* @return a thawed object
*/
T thaw();
}
// Thawed
@NotThreadSafe
public interface Thawed<F extends Frozen<? extends Thawed<F>>>
{
/**
* Obtain a frozen representation of this thawed object
*
* @return a frozen, immutable object
*/
F freeze();
}
</code></pre>
<p>This pattern means that if you have a frozen instance <code>f</code>, you can obtained a thawed instance of that instance by calling <code>.thaw()</code>, modify it (since <code>.thaw()</code> returns a builder) and freeze it again:</p>
<pre><code>// In java, again
final F newFrozen = frozen.thaw().setX().setY().etc().freeze();
</code></pre>
<p>I view this pattern as beneficial for several reasons:</p>
<ul>
<li>thawing an instance gives you a builder with that instance's full state (and you can thaw as many times as you want, in a thread safe manner since frozen instances are immutable by contract);</li>
<li>you get all the power of builders on the thawed side.</li>
</ul>
<p>I use this pattern a lot; I find it useful. Do you? What would be your gripes against it?</p>
<p>Sample implementation of a simple pair:</p>
<pre><code>public final class MyClass
implements Frozen<Builder>
{
final int value;
private MyClass(final Builder builder)
{
value = builder.value;
}
public static Builder newBuilder()
{
return new Builder();
}
public int getValue()
{
return value;
}
@Override
public Builder thaw()
{
return new Builder(this);
}
public static final class Builder
implements Thawed<MyClass>
{
private int value;
private Builder()
{
}
private Builder(final MyClass myClass)
{
value = myClass.value;
}
public Builder withValue(final int value)
{
this.value = value;
}
@Override
public MyClass freeze()
{
return new MyClass(this);
}
}
}
</code></pre>
<p>For more complex cases, I generally create both classes in the same package and make instance variables for both package visible (this leaves of course the responsibility on me that what I inject into the frozen part is actually immutable, but I deal with it ;)</p>
<p><strong>EDIT</strong> Right now the methods are called <code>.thaw()</code> and <code>.freeze()</code>, to reflect the pattern's intents; do you think of better names?</p>
<p><strong>EDIT 2</strong> Objections from @bowmore: the SRP (Single Responsibility Principle) is violated; this is true: the frozen instance has the added responsibility that it must generate a pre-filled thawed instance. The suggestion here is to create an additional constructor/static factory method/method (pick your poison) on the builder class so that it be able to "swallow" the contents of the frozen instance. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T20:48:55.950",
"Id": "42370",
"Score": "1",
"body": "Very cool, if you pardon the pun. The names thaw and freeze might be more precisely labelled as `mutable` and `immutable`, or `makeMutable` and `makeImmutable` to avoid any keyword issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T20:49:24.783",
"Id": "42371",
"Score": "0",
"body": "Is the interface actually used anywhere? For example, would you ever have a variable of type `Fronzen<T>`? If not, wouldn't just having the two methods (without the interfaces) work the same?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T21:40:04.597",
"Id": "42373",
"Score": "0",
"body": "@svick in my own projects, certainly: two examples are [here](https://github.com/fge/json-schema-validator/blob/master/src/main/java/com/github/fge/jsonschema/cfg/ValidationConfiguration.java) (frozen part) and [here](https://github.com/fge/json-schema-validator/blob/master/src/main/java/com/github/fge/jsonschema/cfg/ValidationConfigurationBuilder.java) (thawed part). Right now, customization of my API relies on this pattern. I have been very recently investigating dependency injection (using Guice), so parts of this code may change in the near future depending on my findings in the matter..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T21:44:24.243",
"Id": "42374",
"Score": "0",
"body": "@DaveJarvis do you believe that `thaw` and `freeze` may be reserved? I admit that I chose these names because, well, they sounded cool, pardon the pun ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T21:52:47.580",
"Id": "42375",
"Score": "0",
"body": "@fge: I meant \"immutable\" could become a keyword. Also, if you have an application that involves food or chemistry, you might want to call `object.freeze()` to change its state of matter (rather than its state of mutability), which could be conflicting and confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T22:07:41.697",
"Id": "42376",
"Score": "0",
"body": "@DaveJarvis uhm, OK, but then even `.build()` could become a matter of conflict if you were to pilot a real, \"material\" factory... In fact, those are the two best names I could come up with... `makeMutable()` and `makeImmutable()` do mean what they mean, but personally I think `.thaw()` and `.freeze()` sound... Well... Better! But optimal? Maybe not... Editing the question to reflect that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T22:33:07.713",
"Id": "42378",
"Score": "3",
"body": "Wouldn't a `copy()` method on the builder be simpler, more intuitive, and less of a generics puzzle? e.g. `MyObject.newBuilder().copy(previouslyBuiltInstance).setParam1(newValue).build();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T22:48:46.437",
"Id": "42380",
"Score": "0",
"body": "@bowmore not sure about \"less of a generics puzzle\". As to intuitivity, I prefer to `.thaw()` instead of having to \"manually instantiate\" a new builder and `.copy()`, since this is a single call on the frozen object ;)"
}
] |
[
{
"body": "<p>Pattern pros and cons :</p>\n\n<p>Pros :</p>\n\n<ul>\n<li>easy to use</li>\n<li>readable (provided you are familiar with the pattern)</li>\n</ul>\n\n<p>Cons :</p>\n\n<ul>\n<li>forces a cyclic dependency between builder and the class being built (we're probably not crossing package boundaries, though)</li>\n<li>moves part of the responsibility of the builder to the class being built, in addition to the responsibility that class already had (violating the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a>)</li>\n</ul>\n\n<p>General remarks :</p>\n\n<ul>\n<li>I see no potential clients for the interfaces, i.e. they are little more than marker interfaces.</li>\n</ul>\n\n<p>Conclusion :</p>\n\n<p>In my opinion the pattern adds too little value for what it trades off.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:35:25.167",
"Id": "42441",
"Score": "0",
"body": "I fail to understand your second objection? The frozen part's only responsibility is to \"pre-fill\" the builder with its internal state"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:36:28.813",
"Id": "42442",
"Score": "0",
"body": "yes : it has the added responsibility of \"building a builder\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:38:11.710",
"Id": "42443",
"Score": "0",
"body": "Well, that is the whole point! I fail to see an SRP violation at all here!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:40:00.590",
"Id": "42444",
"Score": "0",
"body": "I assume the Frozen implementor has responsibilities other than building a builder. Otherwise, I fail to see the use of a class, that without this pattern would have no responsibilities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:44:10.017",
"Id": "42445",
"Score": "0",
"body": "Well yes, but that is not the point: if a class chooses to implement this pattern, it will of course bear this responsibility. However this does not prevent the class from fulfilling its \"real\" duty. SRP is like every principle, it has its limits ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:52:09.107",
"Id": "42448",
"Score": "0",
"body": "Yet it's not the classes that choose, it's the programmer :) And of course principles must be used pragmatically, that's why in my conclusion I consider the total trade off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:54:29.037",
"Id": "42449",
"Score": "0",
"body": "OK, fair enough ;) As all my classes are immutable, I am ready to pay the price :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T17:02:23.820",
"Id": "42451",
"Score": "0",
"body": "However you made me have second thoughts... Indeed a builder could have a `.copyOf()` method to \"swallow\" a frozen instance; then SRP wouldn't be violated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T17:03:57.183",
"Id": "42452",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9214/discussion-between-bowmore-and-fge)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:28:57.643",
"Id": "27312",
"ParentId": "27276",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T18:50:20.590",
"Id": "27276",
"Score": "7",
"Tags": [
"java",
"design-patterns"
],
"Title": "Design pattern review: freeze/thaw (aka, \"reversible builder\" pattern)"
}
|
27276
|
<p>I'm converting some C# code to F#. Basically it is some geometry classes that can have properties tuned by a numerical solver. I start with a discriminated union of type <code>parameter</code> that can be fixed or free ( tunable ) and then build tunable geometry objects out of them.</p>
<p>I create a discriminated union called <code>shape</code> with Line, Circle, Point as sub types. The code is below.</p>
<pre><code>module SketchSolveFS.Solver
type parameter =
| Fixed of double
| Free of double ref
let free v = Free (ref v)
let fix v = Fixed v
type point = {x: parameter; y:parameter}
type line = {p0: point; p1:point}
type circle = {center: point; radius:parameter}
type shape =
| Parameter of parameter
| Point of point
| Line of line
| Circle of circle
let rec freeVars v = seq {
match v with
| Parameter p ->
match p with
| Free v -> yield v
| _ -> ()
| Point p ->
yield! Parameter p.x |> freeVars
yield! Parameter p.y |> freeVars
| Line line ->
yield! Point line.p0 |> freeVars
yield! Point line.p1 |> freeVars
| Circle c ->
yield! Point c.center |> freeVars
yield! Parameter c.radius |> freeVars
}
</code></pre>
<p>I have a function called freeVars that return me a sequence of
tunable parameters in a list of geometry objects. The code works
and passes my tests but the implementation leaves me uncomfortable.</p>
<p>Here is why. I keep feeling the need to write my discriminated
union this way</p>
<pre><code>type shape =
Parameter of parameter
Point of Parameter * Parameter
Line of Point * Point
</code></pre>
<p>instead of having to create concrete types before hand. Then my
function <code>freeVars</code> would look like this.</p>
<pre><code>let rec freeVars v = seq {
match v with
| Parameter p ->
match p with
| Free v -> yield v
| _ -> ()
| Point p ->
yield! p.x |> freeVars
yield! p.y |> freeVars
| Line line ->
yield! line.p0 |> freeVars
yield! line.p1 |> freeVars
| Circle c ->
yield! c.center |> freeVars
yield! c.radius |> freeVars
}
</code></pre>
<p>where I don't have to wrap the concrete classes back in the discriminated
union wrappers each time I extract and recursively process. Now obviously
the F# compiler doesn't like this or I wouldn't be asking the question.</p>
<p>Is there a better way to frame the working code. Are discriminated unions
not appropriate for this code perhaps? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T19:12:13.337",
"Id": "42365",
"Score": "0",
"body": "There are a lot of things for the compiler not to like. Do some basic clean-up (correct caps, supply correct parameter types, etc) and re-post with a specific question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T19:17:38.563",
"Id": "42366",
"Score": "0",
"body": "I think you missed the point. The first bit of code compiles fine. It just doesn't seem quite right. The second bit of code is rubbish but tries to indicate that I want to write a recursive discriminated union that refers to specific subtypes but it is not allowed. I can't quite figure out why it should not be allowed or if there is a better way to achieve the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T19:23:48.510",
"Id": "42367",
"Score": "0",
"body": "The code compiles fine in tryfsharp.org http://www.tryfsharp.org/create/bradgonesurfing/freevars.fsx"
}
] |
[
{
"body": "<p>A few suggestions on the first code fragment:</p>\n\n<ul>\n<li>Change type names to upper case</li>\n<li>Change record field names to upper case</li>\n<li>Change fields of <code>line</code> to <code>Begin</code> and <code>End</code> to be descriptive</li>\n<li>Use pattern matching on records instead of <code>.</code> access</li>\n</ul>\n\n<p>The updated code fragment is as follows:</p>\n\n<pre><code>type Parameter =\n | Fixed of double\n | Free of double ref\n\nlet free v = Free (ref v) \nlet fix v = Fixed v\n\ntype Point = { X: Parameter; Y: Parameter }\ntype Line = { Begin: Point; End: Point }\ntype Circle = { Center: Point; Radius: Parameter }\n\ntype Shape =\n | Parameter of Parameter\n | Point of Point\n | Line of Line\n | Circle of Circle\n\nlet rec freeVars v = seq { \n match v with\n | Parameter p -> \n match p with\n | Free v -> yield v\n | _ -> ()\n | Point {X = x; Y = y} ->\n yield! Parameter x |> freeVars\n yield! Parameter y |> freeVars\n | Line {Begin = p0; End = p1} -> \n yield! Point p0 |> freeVars\n yield! Point p1 |> freeVars\n | Circle {Center = c; Radius = r} ->\n yield! Point c |> freeVars\n yield! Parameter r |> freeVars\n }\n</code></pre>\n\n<p>And here are comments on the second code fragment.</p>\n\n<p>You mistakenly assume that <code>Line</code>, <code>Circle</code>, <code>Point</code>, etc as sub types of <code>shape</code>. They are just union cases, so your type definition doesn't make sense. </p>\n\n<p>You can change <code>shape</code> to be recursive:</p>\n\n<pre><code>type shape =\n | Parameter of parameter\n | Point of shape * shape\n | Line of shape * shape\n</code></pre>\n\n<p>but it allows more cases than it should.</p>\n\n<p>You can use tuples instead of records:</p>\n\n<pre><code>type shape =\n | Parameter of parameter\n | Point of parameter * parameter\n | Line of (parameter * parameter) * (parameter * parameter)\n | Circle of (parameter * parameter) * parameter\n</code></pre>\n\n<p>but it is less desirable since <code>Point</code>, <code>Line</code> and <code>Circle</code> deserve to be types on their own rights.</p>\n\n<blockquote>\n <p>Are discriminated unions not appropriate for this code perhaps?</p>\n</blockquote>\n\n<p>It depends. If you have fixed number of cases, then DUs and pattern matching are great to use. Otherwise, you have to fall back to class hierarchy which is much more painful to deal with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T20:56:09.550",
"Id": "42372",
"Score": "0",
"body": "I wonder if it would make sense to go with real class hierarchy and active pattern for the matching."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T07:44:40.150",
"Id": "42393",
"Score": "0",
"body": "If he is more likely to add cases than to add functions processing existing cases, class hierarchy + active patterns is the way to go."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T19:56:35.473",
"Id": "27278",
"ParentId": "27277",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T19:04:21.670",
"Id": "27277",
"Score": "2",
"Tags": [
"f#"
],
"Title": "Improve this numeric solver for properties of geometric objects"
}
|
27277
|
<p>I need to concatenate two content_tag and it works but it seems a little messy to me. Any thoughts on how may I refactor this?</p>
<pre><code>def format_price(money)
mny = get_price_string(money).to_money
str = content_tag(:span, @visitor.currency.symbol.html_safe, class: 'pounds')
str << mny.format(no_cents: true, symbol: '')
str << content_tag(:span, mny.format[-3, 3], class: 'pence') unless condition?
end
</code></pre>
|
[] |
[
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><p>Before refactoring, let's identify what makes this code feel \"messy\". IMO there are two problems: the in-place method <code><<</code> and the inline statement <code>unless</code>. As usual, I'll try to make the case for functional programming (as opposed to imperative programming, not opposed to OOP). I guess you are not familiar with <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">FP in Ruby</a> but somehow you felt something was wrong. A quick intro: when you update variables in-place, the <code>=</code> symbol loses a lot of its glamour :-) In maths <code>x = \"hello\"</code> means that, in this scope, <code>x</code> is always equal to 'hello'. Period. In imperative programming it means \"for now <code>x</code> is equal to 'hello', but I reserve the right to change it whenever I feel like it, in this scope or any other. Good luck debugging!\". I don't know about you, but I prefer <code>=</code> to mean the first one :-) Yes, even for a such simple and short code.</p></li>\n<li><p>I don't understand: <code>m.format</code>, where is <code>m</code>? is it <code>mny</code>?</p></li>\n<li><p><code>ebeach?</code>. What is <code>ebeach?</code>?</p></li>\n<li><p><code>m.format[-3, 3]</code>. Do you want the last 3 chars of a string? In Rails: <code>m.last(3)</code>.</p></li>\n<li><p><code>@visitor</code>: Using an instance variable in a helper is a no-no. Pass it as an argument.</p></li>\n</ul>\n\n<p>So let's rewrite the snippet in functional style. There are at least two ways, 1) use different variable names for the different values and concat the strings, or 2) use an array+compact+join. The first:</p>\n\n<pre><code>def format_price(money_value, visitor)\n money = get_price_string(money_value).to_money\n symbol = content_tag(:span, visitor.currency.symbol.html_safe, class: 'pounds')\n value = money.format(no_cents: true, symbol: '')\n currency = ebeach? ? \"\" : content_tag(:span, money.format.last(3), class: 'pence')\n symbol + value + currency\nend\n</code></pre>\n\n<p>Note how pure functions in FP follow a simple pattern: create intermediate variables (if needed, to make the method more readable and declarative) and use them in the last expression of the method. Don't \"do things\", declare \"what things are\".</p>\n\n<p>Second approach:</p>\n\n<pre><code>def format_price(money_value, visitor)\n money = get_price_string(money_value).to_money\n [\n content_tag(:span, visitor.currency.symbol.html_safe, class: 'pounds'),\n money.format(no_cents: true, symbol: ''),\n *(content_tag(:span, money.format.last(3), class: 'pence') if condition?),\n ].join\nend\n</code></pre>\n\n<p>Of course an alternative approach would have been to create a partial view instead of rendering from a helper.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T20:44:34.500",
"Id": "42467",
"Score": "0",
"body": "First, thanks for answering. I am totally aware of the advantages of immutability and functional approach. The main problem with that... is me, since it's still unfamiliar to me. So let's give it a try.\n**1** yes, I've just updated the question **2** some conditional helper **3** is it better? **4** yes you're right\nIt still seems very procedural to me though, even if assigning everything to a new variable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T21:14:59.530",
"Id": "42472",
"Score": "0",
"body": "\"it still seems very procedural\". There is this misunderstanding with FP on this regard, as if it had to avoid intermediate variables, everything being chains of expressions (the more point-free, the better). But that's not the case (even though it's idiomatic to do this kind of things in FP languages, for example Haskell). The key aspect of FP is -as you say- immutability. I'll add the second solution to see how to do without so many variables. But none of these two are procedural (where the key point is do calculations by changing the state)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T21:34:24.487",
"Id": "42557",
"Score": "0",
"body": "It's ok to me, will you just explain to me the * before the conditional content tag?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:04:10.337",
"Id": "42559",
"Score": "0",
"body": "It's the shortest (and probably most idiomatic) way of flattening the array (here, remove the `nil`, equivalent to `[]` when flattening). I am not a big fan of this syntax (I usually use `compact`, with `flatten(1)` when needed). Do some tests in a console and you'll see."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T12:54:25.027",
"Id": "27304",
"ParentId": "27279",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27304",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T21:26:22.530",
"Id": "27279",
"Score": "1",
"Tags": [
"ruby",
"html",
"ruby-on-rails"
],
"Title": "content_tag concatenation clean up"
}
|
27279
|
<p>I'm working on a school assignment, and it's working fine, but I have a feeling I'm over-using pointers, and I just can't think of a way to not pass a triple pointer to the function <code>readFile</code>.</p>
<p>I'd be more than grateful for your suggestions, and if you have any other suggestions on how to improve my code I'd be glad to hear those too!</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#define handle_error(message) \
do { perror(message); exit(EXIT_FAILURE); } while(0)
int readFile(char ***names, FILE *file, int *size);
void *_realloc(void *ptr, size_t size);
int main(void) {
char **names;
int names_size;
FILE *file;
int chars_read;
int i;
names = NULL;
file = NULL;
names_size = 0;
chars_read = 0;
file = fopen("names", "r");
readFile(&names, file, &names_size);
printf("%s\n", names[0]);
fclose(file);
return EXIT_SUCCESS;
}
int readFile(char ***names_p, FILE *file, int *size) {
int chars_read;
int line;
int chunk_size;
int name_size;
int name_length;
char cur_char;
char **names;
char *name;
name = NULL;
names = NULL;
line = 0;
name_length = 0;
name_size = 0;
chunk_size = 2;
chars_read = 0;
while((cur_char = fgetc(file)) != EOF && cur_char != '\r'){
if(cur_char == '\n') {
if(name_size > 0) {
names = _realloc(names, sizeof(char*) * (line+1));
names[line] = _realloc(name, name_length + 1);
names[line][name_length] = '\0';
name_size = 0;
name_length = 0;
name = NULL;
line++;
}
} else {
if(name_size < name_length + 1) {
name = _realloc(name,
sizeof(char) * (name_size =
(name_size + 1) * chunk_size));
}
name[name_length] = cur_char;
name_length++;
}
chars_read++;
}
*names_p = names;
*size = line;
return chars_read;
}
void *_realloc(void *ptr, size_t size) {
void *temp = realloc(ptr, size);
if(temp == NULL) {
int error = errno;
if(error == ENOMEM) printf("size: %d\n", error);
handle_error("realloc");
}
return temp;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:40:57.087",
"Id": "42431",
"Score": "0",
"body": "Your tripple pointer is indeed unnecessary - just return the `char**` from `readFile`"
}
] |
[
{
"body": "<h3>1. Introduction</h3>\n\n<p>You'll see that I made a lot of comments below, but if you're just starting to learn C, then your code is not at all bad. C is a tough language to write robust code in: it provides many many ways to go wrong, and even the most expert and experienced programmers don't always succeed in avoiding the traps and pitfalls.</p>\n\n<p>I like your attention to error handling, that you check the result of <code>realloc</code>, that you remember to close your file handle, and that you use the symbols <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> to make it clear what you mean.</p>\n\n<h3>2. Bugs</h3>\n\n<ol>\n<li><p>You don't check whether there were in fact any names in the file before printing the first of them. If the file was empty then this would result in undefined behaviour:</p>\n\n<pre><code>$ clang cr27281.c\n$ cat /dev/null > names\n$ ./a.out\nSegmentation fault: 11\n</code></pre></li>\n<li><p>You don't check the result of <code>fopen</code>. If this call failed then you'd end up trying to read from the file handle <code>NULL</code>:</p>\n\n<pre><code>$ rm names\n$ ./a.out\nSegmentation fault: 11\n</code></pre></li>\n</ol>\n\n<h3>3. Other comments on your code</h3>\n\n<ol>\n<li><p>If you need to return multiple values from a function, then why not use a structure? You could declare a structure like this:</p>\n\n<pre><code>typedef struct name_array_s {\n char **names; /* Array of names, allocated with malloc. */\n size_t count; /* Count of names in the 'name' array. */\n} *name_array_t;\n</code></pre>\n\n<p>and then <code>readFile</code> could take a <code>name_array_t</code> as its first argument.</p></li>\n<li><p>There's no comment or documentation explaining the interface to <code>readFile</code>. What is this function supposed to do and how are you supposed to call it? Imagine coming back to this code in a couple of years' time when you have forgotten all about it. Do you really want to have to reverse-engineer it to figure out what it does?</p></li>\n<li><p>The variable <code>names_size</code> is an <code>int</code>, but it counts the number of entries in the <code>names</code> array and it can never legitimately be negative. And there are common platforms where <code>INT_MAX</code> is 2147483647, but where you have enough memory to store many more objects than that. So why not make <code>names_size</code> a <code>size_t</code>?</p></li>\n<li><p>Similarly for the result of the function <code>readFile</code>.</p></li>\n<li><p>Consider using <code>abort()</code> in your error handler instead of <code>exit(EXIT_FAILURE)</code>. When running under the debugger, <code>abort()</code> drops you straight into the debugger prompt with a good chance of being able to find useful information in the backtrace, but <code>exit()</code> just quits the program, leaving you none the wiser.</p></li>\n<li><p>It's a bit restrictive that the file has to be named <code>names</code>. Why not take the name on the command line in <code>argv[1]</code>?</p></li>\n<li><p>This line:</p>\n\n<pre><code>if(error == ENOMEM) printf(\"size: %d\\n\", error);\n</code></pre>\n\n<p>has four problems! First, error messages should go to standard error, not (as here) standard output, so you need <code>fprintf(stderr, ...)</code>. Second, you want <code>size</code> instead of <code>error</code> in the call to <code>printf</code>. Third, <code>size</code> is a <code>size_t</code> but you are using a <code>%d</code> format specifier which takes an <code>int</code>, so this results in undefined behaviour. Fourth, by putting the <code>if</code> and the <code>printf</code> on the same line, you've made it impossible (in most debuggers) to set a breakpoint on the <code>printf</code>. I would write:</p>\n\n<pre><code>if(error == ENOMEM)\n fprintf(stderr, \"size: %lu\\n\", (unsigned long)size);\n</code></pre></li>\n<li><p>The C language allows you to combine the declaration of a variable and its initialization, so instead of writing the repetitive</p>\n\n<pre><code>char **names;\nint names_size;\nFILE *file;\nint chars_read;\nint i;\n\nnames = NULL;\nfile = NULL;\nnames_size = 0;\nchars_read = 0;\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>char **names = NULL;\nint names_size = 0;\nFILE *file = NULL;\nint chars_read = 0;\nint i;\n</code></pre></li>\n<li><p>After making the change above, it becomes obvious that the variable <code>i</code> is unused. But shouldn't your compiler have complained about that? When writing a new program it's well worth turning on as many error-detecting features as you can, for example if you're using GCC it's a good idea to use a comprehensive set of flags like <code>-ansi -pedantic -std=c99 -Wall -Werror</code>.</p></li>\n<li><p>The variable <code>chars_read</code> is also unused.</p></li>\n<li><p>Having an assignment buried inside an expression seems error-prone and hard to understand (especially when broken across lines like this):</p>\n\n<pre><code>name = _realloc(name, \n sizeof(char) * (name_size = \n (name_size + 1) * chunk_size));\n</code></pre>\n\n<p>I prefer to keep the code simple:</p>\n\n<pre><code>name_size = (name_size + 1) * chunk_size;\nname = _realloc(name, sizeof(char) * name_size));\n</code></pre></li>\n<li><p><code>sizeof(char)</code> is defined to be 1 by the <a href=\"http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf\" rel=\"nofollow\">C standard</a>, so you don't need it here (it doesn't do any harm, though).</p>\n\n<blockquote>\n <p>§6.5.3.4.3 When [<code>sizeof</code> is] applied to an operand that has type <code>char</code>, <code>unsigned char</code>, or <code>signed char</code>, (or a qualified version thereof) the result is 1.</p>\n</blockquote></li>\n<li><p><code>chunk_size</code> is poorly named: it's not a size, it's an exponent that controls the exponential growth of the <code>name</code> buffer.</p></li>\n</ol>\n\n<h3>4. Performance</h3>\n\n<p>Your algorithm for allocation involves reallocating the <code>names</code> array each time a new line is reached in the file. This is wasteful, because each time this array is reallocated, the contents may have to be copied across to the new region of memory, potentially making it O(<em>n</em><sup>2</sup>).</p>\n\n<p>If your files are short then you may prefer not to worry about this, but after I did a simple rewrite of your <code>readFile</code> function to do less reallocation, I was able to get a speedup of more than 3× in test cases with many lines, like this one:</p>\n\n<pre><code>$ yes '' | head -10000000 | nl -ba > names\n$ time ./names-old > /dev/null\nreal 0m4.136s\nuser 0m3.777s\nsys 0m0.333s\n$ time ./names-new > /dev/null\nreal 0m1.248s\nuser 0m0.946s\nsys 0m0.287s\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T12:48:51.437",
"Id": "27403",
"ParentId": "27281",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27403",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T22:54:10.130",
"Id": "27281",
"Score": "3",
"Tags": [
"c",
"file",
"pointers"
],
"Title": "Use of pointers with file-reading program"
}
|
27281
|
<p>I've began to read the book <em>Clean Code</em> by Robert Martin, I had a strong desire to learn how to write code that's easy for others to understand. Please criticize my code.</p>
<p><strong>PuzzlesView.java</strong></p>
<pre><code>// Using of PuzzlesView:
// dimension = new Dimension(rows, columns)
// puzzlesView.set(bitmap, dimension);
// after the setting the puzzlesView will scale the bitmap to its size,
// divide the scaled bitmap by puzzles and show mixed puzzles.
// if you want to mix the puzzles again, then use the call mix()
// puzzlesView.mix();
public class PuzzlesView extends View {
private final int LATTICE_WIDTH = 2;
private final float ALLOWABLE_ERROR = 0.4f;
private Dimension dim;
private Bitmap fullImage;
private Matrix<Bitmap> puzzles;
private Mixer mixer = new Mixer();
private Collection<OnGameFinishedListener> onGameFinishedListeners =
new ArrayList<OnGameFinishedListener>();
private GameArbitrator arbitrator;
private Size puzzleSize;
private Point lastTouchedPoint;
private Point draggedLeftUpper;
private Matrix.Position draggedPosition;
private Matrix.Position nearestPosition;
private Canvas canvas;
public PuzzlesView(Context context) {
super(context);
}
public PuzzlesView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PuzzlesView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void addOnGameFinishedListener(OnGameFinishedListener listener) {
onGameFinishedListeners.add(listener);
}
public void set(Bitmap bitmap, Dimension dim) {
if (imageWasSet()) {
releasePreviousImageResources();
}
setDimension(dim);
setBitmap(bitmap);
}
private boolean imageWasSet() {
return (fullImage != null);
}
private void releasePreviousImageResources() {
fullImage.recycle();
puzzles.forEach(new Matrix.OnEachHandler<Bitmap>() {
@Override
public void handle(Matrix<Bitmap> matrix, Position pos) {
Bitmap bitmap = matrix.get(pos);
bitmap.recycle();
matrix.set(pos, null);
}
});
}
private void setDimension(Dimension dim) {
this.dim = dim;
puzzles = new Matrix<Bitmap>(dim);
}
private void setBitmap(Bitmap bitmap) {
draggingStopped();
calculatePuzzleSize();
fullImage = scaledToFullSize(bitmap);
cutIntoPuzzles();
arbitrator = new GameArbitrator(puzzles);
mix();
}
private void draggingStopped() {
draggedPosition = null;
}
private void calculatePuzzleSize() {
int width = getWidth() - LATTICE_WIDTH * (dim.columns - 1);
int height = getHeight() - LATTICE_WIDTH * (dim.rows - 1);
puzzleSize = new Size(width / dim.columns, height / dim.rows);
}
private Bitmap scaledToFullSize(Bitmap bitmap) {
int fullImageWidth = puzzleSize.width * dim.columns;
int fullImageHeight = puzzleSize.height * dim.rows;
return Bitmap.createScaledBitmap(bitmap, fullImageWidth, fullImageHeight, true);
}
private void cutIntoPuzzles() {
puzzles.forEach(new Matrix.OnEachHandler<Bitmap>() {
@Override
public void handle(Matrix<Bitmap> matrix, Position pos) {
matrix.set(pos, puzzleByPosition(pos));
}
});
}
private Bitmap puzzleByPosition(Matrix.Position pos) {
int x = pos.column * puzzleSize.width;
int y = pos.row * puzzleSize.height;
return Bitmap.createBitmap(fullImage, x, y, puzzleSize.width, puzzleSize.height);
}
public void mix() {
mixer.mix(puzzles);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (imageWasSet()) {
this.canvas = canvas;
drawLattice();
drawPuzzles();
}
}
private void drawLattice() {
Point rightDownPoint = puzzlesRightDownPoint();
Paint latticePaint = preparePaintForLattice();
drawVerticalLatticeLines(rightDownPoint, latticePaint);
drawHorizontalLatticeLines(rightDownPoint, latticePaint);
}
private Point puzzlesRightDownPoint() {
Point point = leftUpperOfPuzzle(new Matrix.Position(dim.rows, dim.columns));
return new Point(point.x - LATTICE_WIDTH, point.y - LATTICE_WIDTH);
}
private Point leftUpperOfPuzzle(Matrix.Position pos) {
int x = (puzzleSize.width + LATTICE_WIDTH) * pos.column;
int y = (puzzleSize.height + LATTICE_WIDTH) * pos.row;
return new Point(x, y);
}
private Paint preparePaintForLattice() {
Paint paint = new Paint();
paint.setColor(ResourceReader.colorById(R.color.lattice_color));
paint.setStrokeWidth(LATTICE_WIDTH);
return paint;
}
private void drawVerticalLatticeLines(Point rightDownPoint, Paint latticePaint) {
for (int column = 1; column < dim.columns; ++column) {
Point startPoint = latticeLineStartPoint(0, column);
canvas.drawLine(startPoint.x, 0, startPoint.x, rightDownPoint.y, latticePaint);
}
}
private void drawHorizontalLatticeLines(Point rightDownPoint, Paint latticePaint) {
for (int row = 1; row < dim.rows; ++row) {
Point startPoint = latticeLineStartPoint(row, 0);
canvas.drawLine(0, startPoint.y, rightDownPoint.x, startPoint.y, latticePaint);
}
}
private Point latticeLineStartPoint(int row, int column) {
Point point = leftUpperOfPuzzle(new Position(row, column));
return new Point(point.x - 1, point.y - 1);
}
private void drawPuzzles() {
puzzles.forEach(new Matrix.OnEachHandler<Bitmap>() {
@Override
public void handle(Matrix<Bitmap> matrix, Position pos) {
if (!existDraggedPuzzle() || !pos.equals(draggedPosition)) {
Point leftUpper = leftUpperOfPuzzle(pos);
Paint paint = paintForPosition(pos);
Bitmap puzzle = puzzles.get(pos);
canvas.drawBitmap(puzzle, leftUpper.x, leftUpper.y, paint);
}
}
});
if (existDraggedPuzzle()) {
Bitmap draggedPuzzle = puzzles.get(draggedPosition);
canvas.drawBitmap(draggedPuzzle, draggedLeftUpper.x, draggedLeftUpper.y, null);
}
}
private boolean existDraggedPuzzle() {
return draggedPosition != null;
}
private Paint paintForPosition(Position pos) {
return positionOfCommutablePuzzle(pos)
? commutablePuzzlePaint()
: null;
}
private boolean positionOfCommutablePuzzle(Position pos) {
return draggedAndNearestCanBeSwapped() && pos.equals(nearestPosition);
}
private boolean draggedAndNearestCanBeSwapped() {
if (nearestPosition == null) {
return false;
}
Point nearestLeftUpper = leftUpperOfPuzzle(nearestPosition);
int dx = Math.abs(nearestLeftUpper.x - draggedLeftUpper.x);
int dy = Math.abs(nearestLeftUpper.y - draggedLeftUpper.y);
return allowableOffset(dx, dy);
}
private boolean allowableOffset(int dx, int dy) {
boolean dxAllowable = (dx <= ALLOWABLE_ERROR * puzzleSize.width);
boolean dyAllowable = (dy <= ALLOWABLE_ERROR * puzzleSize.height);
return dxAllowable && dyAllowable;
}
private Paint commutablePuzzlePaint() {
Paint paint = new Paint();
int color = ResourceReader.colorById(R.color.commutable_puzzle_color);
ColorFilter filter = new LightingColorFilter(color, 1);
paint.setColorFilter(filter);
return paint;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!imageWasSet()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onDownTouch(eventPoint(event));
break;
case MotionEvent.ACTION_MOVE:
onMoveTouch(eventPoint(event));
break;
case MotionEvent.ACTION_UP:
onUpTouch(eventPoint(event));
break;
}
return true;
}
private Point eventPoint(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
return new Point(x, y);
}
private void onDownTouch(Point pt) {
Matrix.Position pos = positionByPoint(pt);
if (insideGameBoard(pos) && insidePuzzle(pt)) {
lastTouchedPoint = pt;
draggedPosition = pos;
draggedLeftUpper = leftUpperOfPuzzle(pos);
}
}
private Matrix.Position positionByPoint(Point pt) {
int column = pt.x / (puzzleSize.width + LATTICE_WIDTH);
int row = pt.y / (puzzleSize.height + LATTICE_WIDTH);
return new Matrix.Position(row, column);
}
private boolean insideGameBoard(Position pos) {
return pos.row >= 0 && pos.row < dim.rows &&
pos.column >= 0 && pos.column < dim.columns;
}
private boolean insidePuzzle(Point pt) {
return ((pt.x % (puzzleSize.width + LATTICE_WIDTH)) < puzzleSize.width) &&
((pt.y % (puzzleSize.height + LATTICE_WIDTH)) < puzzleSize.height);
}
private void onMoveTouch(Point pt) {
if (existDraggedPuzzle()) {
int dx = pt.x - lastTouchedPoint.x;
int dy = pt.y - lastTouchedPoint.y;
draggedLeftUpper = new Point(draggedLeftUpper.x + dx, draggedLeftUpper.y + dy);
lastTouchedPoint = pt;
calculateNearestForDragged();
invalidate();
}
}
private void calculateNearestForDragged() {
if (draggedLeftUpper.x >= 0 && draggedLeftUpper.y >= 0) {
Matrix.Position pos1 = positionByPoint(draggedLeftUpper);
Matrix.Position pos2 = new Matrix.Position(pos1.row, pos1.column + 1);
Matrix.Position pos3 = new Matrix.Position(pos1.row + 1, pos1.column);
Matrix.Position pos4 = new Matrix.Position(pos1.row + 1, pos1.column + 1);
calculateNearestForDragged(pos1, pos2, pos3, pos4);
}
}
private void calculateNearestForDragged(Matrix.Position... positions) {
for (Matrix.Position each : positions) {
if (insideGameBoard(each)) {
checkCloseness(each);
}
}
}
private void checkCloseness(Position pos) {
if (nearestPosition == null || !insideGameBoard(nearestPosition)) {
nearestPosition = pos;
} else if (distanceFromDraggedTo(pos) < distanceFromDraggedTo(nearestPosition)) {
nearestPosition = pos;
}
}
private int distanceFromDraggedTo(Position pos) {
Point leftUpper = leftUpperOfPuzzle(pos);
int dx = leftUpper.x - draggedLeftUpper.x;
int dy = leftUpper.y - draggedLeftUpper.y;
return dx * dx + dy * dy;
}
private void onUpTouch(Point pt) {
if (!existDraggedPuzzle()) {
return;
}
if (draggedAndNearestCanBeSwapped()) {
puzzles.swap(nearestPosition, draggedPosition);
}
nearestPosition = null;
draggingStopped();
invalidate();
if (arbitrator.gameFinished(puzzles)) {
notifyThatGameFinished();
}
}
private void notifyThatGameFinished() {
for (OnGameFinishedListener each : onGameFinishedListeners) {
each.onGameFinished();
}
}
}
</code></pre>
<p><strong>ResourceReader.java</strong></p>
<pre><code>public class ResourceReader {
private static Resources resources;
public static void init(Resources res) {
resources = res;
}
public static int colorById(int id) {
return resources.getColor(id);
}
}
</code></pre>
<p><strong>Mixer.java</strong></p>
<pre><code>public class Mixer {
private Random random;
public void mix(Matrix<Bitmap> puzzles) {
random = new Random(System.nanoTime());
int numberOfSwaps = numberOfSwaps(puzzles);
for (int i = 0; i < numberOfSwaps; ++i) {
puzzles.swap(generateRandomPosition(puzzles), generateRandomPosition(puzzles));
}
}
private int numberOfSwaps(Matrix<Bitmap> puzzles) {
return puzzles.rows * puzzles.columns * 2;
}
private Position generateRandomPosition(Matrix<Bitmap> puzzles) {
int row = random.nextInt(puzzles.rows);
int column = random.nextInt(puzzles.columns);
return new Position(row, column);
}
}
</code></pre>
<p><strong>GameArbitrator.java</strong></p>
<pre><code>public class GameArbitrator {
private Matrix<Bitmap> startPuzzles;
public GameArbitrator(Matrix<Bitmap> puzzles) {
startPuzzles = new Matrix<Bitmap>(puzzles);
}
public boolean gameFinished(Matrix<Bitmap> puzzles) {
for (int row = 0; row < puzzles.rows; ++row) {
for (int column = 0; column < puzzles.columns; ++column) {
if (startPuzzles.get(row, column) != puzzles.get(row, column)) {
return false;
}
}
}
return true;
}
}
</code></pre>
<p><strong>Dimension.java</strong></p>
<pre><code>public class Dimension {
public final int rows;
public final int columns;
public Dimension(int rows, int columns) {
if (rows <= 0 || columns <= 0) {
throw new IllegalArgumentException(
"Dimension constructor: rows and columns must be positive");
}
this.rows = rows;
this.columns = columns;
}
}
</code></pre>
<p><strong>TestDimension.java</strong></p>
<pre><code>public class TestDimesion {
@Test
public void testCreation() {
final int rows = 1;
final int columns = 2;
Dimension dim = new Dimension(rows, columns);
assertEquals(rows, dim.rows);
assertEquals(columns, dim.columns);
}
@Test(expected=IllegalArgumentException.class)
public void testRowsIsZero() {
new Dimension(0, 1);
}
@Test(expected=IllegalArgumentException.class)
public void testRowsIsNegative() {
new Dimension(-1, 1);
}
@Test(expected=IllegalArgumentException.class)
public void testColumnsIsZero() {
new Dimension(1, 0);
}
@Test(expected=IllegalArgumentException.class)
public void testColumnsIsNegative() {
new Dimension(1, -1);
}
}
</code></pre>
<p><strong>Size.java</strong></p>
<pre><code>public class Size {
public final int width;
public final int height;
public Size(int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException();
}
this.width = width;
this.height = height;
}
}
</code></pre>
<p><strong>TestSize.java</strong></p>
<pre><code>public class TestSize {
@Test
public void testCreation() {
Size size = new Size(1, 2);
assertEquals(1, size.width);
assertEquals(2, size.height);
}
@Test(expected=IllegalArgumentException.class)
public void testIllegalSize() {
new Size(1, -2);
}
}
</code></pre>
<p><strong>Matrix.java</strong></p>
<pre><code>public class Matrix<T> {
public interface OnEachHandler<T> {
void handle(Matrix<T> matrix, Position pos);
}
public static class Position {
public final int row;
public final int column;
public Position(int row, int column) {
if (row < 0 || column < 0) {
throw new IllegalArgumentException();
}
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || !(obj instanceof Matrix.Position)) {
return false;
}
Matrix.Position other = (Matrix.Position) obj;
return (this.row == other.row) && (this.column == other.column);
}
}
public final int rows;
public final int columns;
private T[] values;
@SuppressWarnings("unchecked")
public Matrix(int rows, int columns) {
if (rows <= 0 || columns <= 0) {
throw new IllegalArgumentException();
}
this.rows = rows;
this.columns = columns;
values = (T[]) new Object[rows * columns];
}
public Matrix(Dimension dim) {
this(dim.rows, dim.columns);
}
public Matrix(Matrix<T> other) {
this(other.rows, other.columns);
other.forEach(new OnEachHandler<T>() {
@Override
public void handle(Matrix<T> matrix, Position pos) {
Matrix.this.set(pos, matrix.get(pos));
}
});
}
public void set(Position pos, T value) {
set(pos.row, pos.column, value);
}
public void set(int row, int column, T value) {
checkIndexes(row, column);
values[index(row, column)] = value;
}
private void checkIndexes(int row, int column) {
if (row < 0 || column < 0) {
throw new IllegalArgumentException();
}
if (row >= rows || column >= columns) {
throw new IndexOutOfBoundsException();
}
}
private int index(int row, int column) {
return row * columns + column;
}
public T get(Position pos) {
return get(pos.row, pos.column);
}
public T get(int row, int column) {
checkIndexes(row, column);
return values[index(row, column)];
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Matrix<?>)) {
return false;
}
@SuppressWarnings("unchecked")
Matrix<T> other = (Matrix<T>) obj;
if (other.rows != rows || other.columns != columns) {
return false;
}
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
T elementOfThis = get(row, column);
T elementOfOther = other.get(row, column);
if (!elementOfThis.equals(elementOfOther)) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashCode1 = get(0, 0).hashCode();
int hashCode2 = get(rows - 1, columns - 1).hashCode();
int hashCode = hashCode1 * hashCode2;
hashCode += Math.max(hashCode1, hashCode2) / Math.min(hashCode1, hashCode2);
return hashCode;
}
public void swap(Position pos1, Position pos2) {
T temp = get(pos1);
set(pos1, get(pos2));
set(pos2, temp);
}
public void forEach(OnEachHandler<T> onEachHandler) {
for (int row = 0; row < this.rows; ++row) {
for (int column = 0; column < this.columns; ++column) {
onEachHandler.handle(this, new Position(row, column));
}
}
}
}
</code></pre>
<p><strong>TestMatrix.java</strong></p>
<pre><code>public class TestMatrix {
private static final Integer VALUE = 5;
private static final int ROWS = 10;
private static final int COLUMNS = 20;
private Matrix<Integer> matrix;
@Before
public void setUp() {
this.matrix = new Matrix<Integer>(ROWS, COLUMNS);
}
@Test
public void testMatrix() {
fillMatrix(matrix);
matrix.forEach(new Matrix.OnEachHandler<Integer>() {
@Override
public void handle(Matrix<Integer> matrix, Matrix.Position pos) {
assertEquals(elementForPosition(pos), matrix.get(pos));
}
});
}
private void fillMatrix(Matrix<Integer> matrix) {
matrix.forEach(new Matrix.OnEachHandler<Integer>() {
@Override
public void handle(Matrix<Integer> matrix, Matrix.Position pos) {
matrix.set(pos, elementForPosition(pos));
}
});
}
private Integer elementForPosition(Matrix.Position pos) {
return pos.row * pos.column;
}
@Test
public void testMatrixCopyConstructor() {
fillMatrix(matrix);
Matrix<Integer> copy = new Matrix<Integer>(matrix);
assertEquals(matrix.rows, copy.rows);
assertEquals(matrix.columns, copy.columns);
copy.forEach(new Matrix.OnEachHandler<Integer>() {
@Override
public void handle(Matrix<Integer> matrix, Matrix.Position pos) {
Integer expected = TestMatrix.this.matrix.get(pos);
assertEquals(expected, matrix.get(pos));
}
});
}
@Test
public void testInitValueIsNull() {
assertNull(matrix.get(0, 0));
}
@Test
public void testDimensionOfMatrix() {
assertEquals(ROWS, matrix.rows);
assertEquals(COLUMNS, matrix.columns);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructorIllegalArguments() {
new Matrix<Integer>(1, -1);
}
@Test(expected=IllegalArgumentException.class)
public void testSetIllegalArguments() {
matrix.set(1, -1, VALUE);
}
@Test(expected=IndexOutOfBoundsException.class)
public void testSetOutOfBoundsArguments() {
matrix.set(0, COLUMNS + 1, VALUE);
}
@Test(expected=IllegalArgumentException.class)
public void testGetIllegalArguments() {
matrix.get(1, -1);
}
@Test(expected=IndexOutOfBoundsException.class)
public void testGetOutOfBoundsArguments() {
matrix.get(ROWS + 1, 3);
}
@Test
public void testSwap() {
Matrix<Integer> matrix = new Matrix<Integer>(2, 2);
Matrix.Position pos1 = new Matrix.Position(0, 0);
Matrix.Position pos2 = new Matrix.Position(1, 1);
Integer val1 = 1;
Integer val2 = 2;
matrix.set(pos1, val2);
matrix.set(pos2, val1);
matrix.swap(pos1, pos2);
assertEquals(val2, matrix.get(pos2));
assertEquals(val1, matrix.get(pos1));
}
@Test(expected=IllegalArgumentException.class)
public void testSwapIllegalArguments() {
Matrix.Position pos1 = new Matrix.Position(0, 0);
Matrix.Position pos2 = new Matrix.Position(0, -1);
matrix.swap(pos1, pos2);
}
@Test(expected=IndexOutOfBoundsException.class)
public void testSwapPositionOutOfBounds() {
Matrix.Position pos1 = new Matrix.Position(0, COLUMNS + 1);
Matrix.Position pos2 = new Matrix.Position(0, 0);
matrix.swap(pos1, pos2);
}
@Test
public void testEquals() {
Matrix<Integer> matrix1 = new Matrix<Integer>(1, 2);
matrix1.set(0, 0, VALUE);
matrix1.set(0, 1, VALUE);
Matrix<Integer> matrix2 = new Matrix<Integer>(1, 2);
matrix2.set(0, 0, VALUE);
matrix2.set(0, 1, VALUE);
assertTrue(matrix1.equals(matrix2));
matrix2.set(0, 0, VALUE + 1);
assertFalse(matrix1.equals(matrix2));
}
@Test
public void testForEach() {
Matrix<Integer> counts = new Matrix<Integer>(matrix.rows, matrix.columns);
for (int row = 0; row < counts.rows; ++row) {
for (int column = 0; column < counts.columns; ++column) {
counts.set(row, column, 0);
}
}
counts.forEach(new Matrix.OnEachHandler<Integer>() {
@Override
public void handle(Matrix<Integer> matrix, Matrix.Position pos) {
matrix.set(pos, matrix.get(pos) + 1);
}
});
for (int row = 0; row < counts.rows; ++row) {
for (int column = 0; column < counts.columns; ++column) {
assertTrue(counts.get(row, column) == 1);
}
}
}
@Test
public void testForEachOrder_LeftToRight_UpToDown() {
Matrix<Boolean> flags = new Matrix<Boolean>(5, 7);
flags.forEach(new Matrix.OnEachHandler<Boolean>() {
@Override
public void handle(Matrix<Boolean> matrix, Position pos) {
matrix.set(pos, false);
}
});
flags.forEach(new Matrix.OnEachHandler<Boolean>() {
@Override
public void handle(Matrix<Boolean> matrix, Position pos) {
assertPreviousElementByPassed(matrix, pos);
assertNextElementNotByPassed(matrix, pos);
matrix.set(pos, true);
}
});
}
private void assertPreviousElementByPassed(Matrix<Boolean> matrix, Position pos) {
if (!pos.equals(new Matrix.Position(0, 0))) {
Matrix.Position positionBefore = positionBefore(matrix.rows, matrix.columns, pos);
assertTrue(matrix.get(positionBefore));
}
}
private void assertNextElementNotByPassed(Matrix<Boolean> matrix, Position pos) {
Matrix.Position lastPos = new Matrix.Position(matrix.rows - 1, matrix.columns - 1);
if (!pos.equals(lastPos)) {
Matrix.Position positionAfter = positionAfter(matrix.rows, matrix.columns, pos);
assertFalse(matrix.get(positionAfter));
}
}
private Matrix.Position positionBefore(int rows, int columns, Position pos) {
if (pos.column - 1 < 0) {
return new Matrix.Position(pos.row - 1, columns - 1);
} else {
return new Matrix.Position(pos.row, pos.column - 1);
}
}
private Position positionAfter(int rows, int columns, Position pos) {
if (pos.column + 1 >= columns) {
return new Matrix.Position(pos.row + 1, 0);
} else {
return new Matrix.Position(pos.row, pos.column + 1);
}
}
}
</code></pre>
<p><strong>Test_Matrix_Position.java</strong></p>
<pre><code>public class Test_Matrix_Position {
@Test
public void testCreation() {
Matrix.Position pos = new Matrix.Position(1, 2);
assertEquals(1, pos.row);
assertEquals(2, pos.column);
}
@Test(expected=IllegalArgumentException.class)
public void testIllegalArguments() {
new Matrix.Position(1, -2);
}
@Test
public void testEquals() {
assertTrue(new Matrix.Position(1, 2).equals(new Matrix.Position(1, 2)));
assertFalse(new Matrix.Position(1, 2).equals(new Matrix.Position(0, 0)));
assertFalse(new Matrix.Position(1, 2).equals(null));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Excellent coding. I don't claim to understand all your code, but your writing style made it easier for me to review.</p>\n\n<p>I have three suggestions. I've found these suggestions to be helpful to me with large Java code bases.</p>\n\n<p>1) Define your class variables in alphabetical order by class. This helps you find a particular variable quickly in a long list of class variables.</p>\n\n<p>Here's what I mean from your <code>PuzzlesView</code> class.</p>\n\n<pre><code>private Bitmap fullImage;\n\nprivate Canvas canvas;\n\nprivate Collection<OnGameFinishedListener> onGameFinishedListeners;\n\nprivate Dimension dim;\n\nprivate GameArbitrator arbitrator;\n\nprivate Matrix<Bitmap> puzzles;\n\nprivate Matrix.Position draggedPosition;\nprivate Matrix.Position nearestPosition;\n\nprivate Mixer mixer;\n\nprivate Point lastTouchedPoint;\nprivate Point draggedLeftUpper;\n\nprivate Size puzzleSize;\n</code></pre>\n\n<p>2) Related to the first point, initialize class fields in the constructor, not the field definition. Initialize static fields in the field definition.</p>\n\n<pre><code>public PuzzlesView(Context context) {\n super(context);\n this.onGameFinishedListeners =\n new ArrayList<OnGameFinishedListener>();\n this.mixer = new Mixer();\n}\n</code></pre>\n\n<p>3) Java already has a <code>Dimension</code> class. Call your class something like <code>PuzzleDimension</code>. You have a similar problem with the <code>Size</code> class. Every <code>Collections</code> class has a <code>size</code> method. Call your class something like <code>PuzzleSize</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:48:34.530",
"Id": "42446",
"Score": "1",
"body": "Very few remarks indeed. `gameFinished()` is too deeply nested, as is `Matrix`' `equals()`. Other than that readability may be helped by using named inner classes instead of anonymous ones, but that is already nitpicking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T06:05:47.113",
"Id": "42679",
"Score": "0",
"body": "To: Gilbert Le Blanc, bowmore. Thank you very much!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T15:05:01.310",
"Id": "27309",
"ParentId": "27292",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T07:41:18.763",
"Id": "27292",
"Score": "0",
"Tags": [
"java",
"android"
],
"Title": "Review my PuzzlesView Android component"
}
|
27292
|
<p>Could you please help me to review my first function (modified from an example) in terms of best practice, coding style suggestions and any obvious language mistake/improvements?</p>
<pre><code>unsigned int edit_distance(const vector<string> &s1, const vector<string> &s2)
{
const size_t len1 = s1.size(), len2 = s2.size();
vector<vector<unsigned int>> d(len1 + 1, vector<unsigned int>(len2 + 1));
d[0][0] = 0;
for(unsigned int i = 1; i <= len1; ++i) d[i][0] = i;
for(unsigned int i = 1; i <= len2; ++i) d[0][i] = i;
for(unsigned int i = 1; i <= len1; ++i)
for(unsigned int j = 1; j <= len2; ++j)
{
unsigned int a = d[i - 1][j] + 1;
unsigned int b = d[i][j - 1] + 1;
unsigned int c = d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1);
d[i][j] = std::min( std::min(a,b), c);
}
return d[len1][len2];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:59:59.420",
"Id": "42432",
"Score": "3",
"body": "For starters you need a function comment, explain what its doing, use readable variable names. You don't get any performance improvement from minified code."
}
] |
[
{
"body": "<p>Do you want <code>unsigned int</code> or do you want <code>std::size_t</code>?</p>\n\n<pre><code>unsigned int edit_distance(const vector<string> &s1, const vector<string> &s2)\n</code></pre>\n\n<p>It comes down to what you are trying to convey.<br>\nThe use of <code>string</code> and <code>vector</code> suggests you are doing <code>using namespace std;</code> try <a href=\"https://stackoverflow.com/q/1452721/14065\">not to do this</a>. Prefer to qualify your types: <code>std::string</code> and <code>std::vector</code>.</p>\n\n<p>Personally, I prefer <code>const</code> on the right. But it's only a preference thing.</p>\n\n<p>Only declare one variable per line:</p>\n\n<pre><code> const size_t len1 = s1.size(), len2 = s2.size();\n</code></pre>\n\n<p>Come up with better names. <code>d</code> is not very descriptive.</p>\n\n<pre><code> vector<vector<unsigned int>> d(len1 + 1, vector<unsigned int>(len2 + 1));\n</code></pre>\n\n<p>I would prefer <code>std::size_t</code> here:</p>\n\n<pre><code> for(unsigned int i = 1; i <= len1; ++i) d[i][0] = i;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T14:12:24.390",
"Id": "27306",
"ParentId": "27294",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27306",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T09:20:47.007",
"Id": "27294",
"Score": "2",
"Tags": [
"c++",
"edit-distance"
],
"Title": "Edit distance function"
}
|
27294
|
<p>I have crated the following small script. I just need to improve this complicated code if possible.</p>
<pre><code>def convUnixTime(t):
expr_date = int(t) * 86400
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.date.today().strftime('%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.fromtimestamp(int(expr_date)).strftime('%Y-%m-%d %H:%M:%S')
d1 = datetime.datetime.strptime(d1, fmt)
d2 = datetime.datetime.strptime(d2, fmt)
return (d2-d1).days
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T09:54:00.197",
"Id": "42410",
"Score": "1",
"body": "What is your reason to do `strftime` followed by `strptime`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T09:56:05.450",
"Id": "42411",
"Score": "0",
"body": "new to python.. don't know much.. just created from googling.. :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T18:41:27.767",
"Id": "42460",
"Score": "1",
"body": "What does this function even do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T02:20:50.683",
"Id": "42488",
"Score": "0",
"body": "On *nix Server it's required to Convert Unix timestamp to Readable Date/time, I used this function to check User account expiry date.."
}
] |
[
{
"body": "<p>I think the main issue here is that you are trying to reuse snippets from Google without trying to understand what is doing what.</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>This might be purely personal but I find <code>60*60*24</code> much easier to understand than <code>86400</code>.</p>\n\n<p><strong>Do not repeat yourself</strong></p>\n\n<p>What is the point of having <code>fmt = '%Y-%m-%d %H:%M:%S'</code> if later on you rewrite <code>strftime('%Y-%m-%d %H:%M:%S')</code> ? You could write it : <code>d1 = datetime.date.today().strftime(fmt)</code> making obvious to everyone that the same format is used.</p>\n\n<p><strong>Useless conversion between strings and dates</strong></p>\n\n<p>You are converting dates to string and string to date in a convoluted and probably not required way.</p>\n\n<p><strong>Usess conversion to int</strong></p>\n\n<p>You are using <code>int(expr_date))</code> but <code>expr_date</code> is defined as <code>int(t) * 86400</code> which is an integer anyway. Also, I am not sure you would need the conversion of <code>t</code> as an int.</p>\n\n<p>Taking into account the different comments, my resulting not-tested code looks like :</p>\n\n<pre><code>def convUnixTime(t):\n return (datetime.datetime.fromtimestamp(t*60*60*24)\n - datetime.datetime.today()).days\n</code></pre>\n\n<p><strong>Edit</strong> : I was using <code>datetime.date.today()</code> instead of <code>datetime.datetime.today()</code>. Also fixed the sign issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:03:17.097",
"Id": "42421",
"Score": "0",
"body": "I have tested it is giving error: `TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T14:02:01.677",
"Id": "42433",
"Score": "0",
"body": "Arg! I'll try and think about a proper working solution then :-P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T22:08:33.287",
"Id": "42479",
"Score": "0",
"body": "If `t` is already in seconds, then that is what `datetime.datetime.fromtimestamp` is expecting, you don't want to do any arithmetic with it. Also, the returned `datetime.datetime` object has no `days` member. If you meant the `day` member, it is the day of the month, not the number of days."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T22:19:55.283",
"Id": "42480",
"Score": "0",
"body": "I've fixed the code and it seems to be behaving just like yours (not sure if good thing or bad thing)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T02:27:49.713",
"Id": "42489",
"Score": "0",
"body": "Thanks Josay for your help.. I saw.. my lazyness in small mistakes.. I will not repeat that again.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T02:50:55.810",
"Id": "42490",
"Score": "0",
"body": "not it's working but, it -1 one day, why ? means today date is 13 Jun and act will expr on 15 Jun , so days should be 2 but it's showing 1, why ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T07:44:27.520",
"Id": "42495",
"Score": "0",
"body": "What value of t are you testing with?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T12:50:40.963",
"Id": "27303",
"ParentId": "27295",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27303",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T09:49:25.310",
"Id": "27295",
"Score": "1",
"Tags": [
"python",
"beginner",
"datetime"
],
"Title": "Converting UNIX time"
}
|
27295
|
<p>Is this the correct implementation of a singleton using enum?</p>
<pre><code>public class Item3 {
public static void main(String[] args) {
Singleton s=Singleton.Single.INSTANCE.getInstance();
Singleton s2=Singleton.Single.INSTANCE.getInstance();
System.out.printf("%b",s==s2);
}
}
class Singleton {
enum Single{
INSTANCE;
Singleton s=new Singleton();
public Singleton getInstance(){
if(s==null)
return new Singleton();
else return s;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>No, it is simpler to code than that:</p>\n\n<pre><code>enum Singleton\n{\n INSTANCE;\n\n // instance vars, constructor\n private final Connection connection;\n\n Singleton()\n {\n // Initialize the connection\n connection = DB.getConnection();\n }\n\n // Static getter\n public static Singleton getInstance()\n {\n return INSTANCE;\n }\n\n public Connection getConnection()\n {\n return connection;\n }\n}\n</code></pre>\n\n<p>Then you use can use <code>final Singleton s = Singleton.getInstance()</code>. Note however that since this is an enum you can always access this via <code>Singleton.INSTANCE</code>.</p>\n\n<p>And NEVER do that:</p>\n\n<pre><code>public Singleton getInstance(){\n if(s==null)\n return new Singleton();\n else return s;\n}\n</code></pre>\n\n<p>this is not thread safe! What is more, the <code>new Singleton()</code> value is never assigned to <code>s</code>... (thanks @DaveJarvis for noticing this!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T10:30:57.633",
"Id": "42412",
"Score": "0",
"body": "thanks. if I need to obtain a Database connection using singleton in this fashion then I would write `enum Singleton{\n INSTANCE;\n Connection c=DB.getConnection(); \n}` and use `Connection con = Singleton.INSTANCE.c` in client code? Please correct me if my understanding is not correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T10:37:02.060",
"Id": "42413",
"Score": "0",
"body": "See my edit. While you _could_ make the connection available as you say, it is something I would not recommend personally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-12T15:39:59.757",
"Id": "156347",
"Score": "0",
"body": "@fge I know that this will help avoiding multiple objects creation from reflection and deserialization and cloning but will it also avoid creating multiple instances from threading?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-14T20:55:36.090",
"Id": "197330",
"Score": "0",
"body": "What if you're initialization throws an exception?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-15T06:30:50.180",
"Id": "197461",
"Score": "0",
"body": "@Mario then `try { ... } catch (Whatever e) { throw new ExceptionInInitializererror(e) }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:33:40.503",
"Id": "508021",
"Score": "0",
"body": "How to pass `connectionString` to Enum"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T10:06:36.103",
"Id": "27298",
"ParentId": "27296",
"Score": "27"
}
},
{
"body": "<p>Your response and other samples in <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">Singleton_pattern</a> </p>\n\n<pre><code>public enum Singleton {\n INSTANCE;\n public void execute (String arg) {\n //... perform operation here ...\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T14:26:39.980",
"Id": "27307",
"ParentId": "27296",
"Score": "0"
}
},
{
"body": "<pre><code>public enum Singleton{\n INSTANCE;\n}\n</code></pre>\n\n<p>This is enough; you can directly use <code>Singleton.INSTANCE</code> to get the instance of the class. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T05:39:33.270",
"Id": "27499",
"ParentId": "27296",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "27298",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T09:56:55.700",
"Id": "27296",
"Score": "18",
"Tags": [
"java",
"singleton",
"enum"
],
"Title": "Singleton using enum"
}
|
27296
|
<p>I want a good design to implement a master-slave protocol. The protocol is proprietary and similar to <a href="http://www.cctalk.org/" rel="nofollow">cctalk</a>.
We have:</p>
<p>Master: <code>HEADER [ DATA ] CHECKSUM</code><br>
Slave: <code>HEADER [ DATA ] CHECKSUM</code></p>
<p>My choice was to have concrete base classes for request and for response:</p>
<pre><code>class PacketReq {
public:
typedef std::vector<uint8_t> container;
typedef container::const_iterator const_iterator;
PacketCommand command() const
{
return static_cast< PacketCommand >( mBuffer[ 2 ] );
};
const container& data() const
{
return mBuffer;
}
const_iterator begin() const
{
return mBuffer.begin();
}
const_iterator end() const
{
return mBuffer.end();
}
protected:
container mBuffer;
};
class PacketOut1 : public PacketReq {
public:
PacketOut1()
{
mBuffer.reserve( PacketHeaderHelper::HEADER_SIZE );
mBuffer.push_back( /* something. */ );
mBuffer.push_back( /* something. */ );
mBuffer.push_back( /* something. */ );
mBuffer.push_back( /* something. */ );
}
};
</code></pre>
<p>The response can be a good response or a NACK (an error). My Implentation is:</p>
<pre><code>class PacketRes {
public:
PacketRes(const std::vector<uint8_t>& buffer)
{
if (!checkChecksum( buffer ))
{
throw Error("invalid checksum");
}
PacketHeaderHelper header( buffer );
mCommand = header.command();
if (header.len() > PacketHeaderHelper::HEADER_SIZE)
{
const size_t bodySize = header.len() - PacketHeaderHelper::HEADER_SIZE;
mData.reserve( bodySize );
mData.insert(
mData.end(),
buffer.begin() + PacketHeaderHelper::HEADER_SIZE - 1,
buffer.end() - 1
);
}
}
virtual ~PacketReq() {}
PacketCommand command() const
{
return mCommand;
}
const std::vector<uint8_t>& body() const
{
return mData;
}
private:
bool checkChecksum(const std::vector<uint8_t>& buffer) const
{
/* calc checksum. */
}
private:
std::vector<uint8_t> mData;
PacketCommand mCommand;
};
class PacketInAck : public PacketReq {
public:
PacketInAck(const std::vector<uint8_t>& buffer) : PacketReq( buffer )
{
}
};
</code></pre>
<p>So if I want make a request the sequence is:</p>
<pre><code>lock_guard
send( const PacketOut& p )
std::unique_ptr< PacketRes > read();
</code></pre>
<p>But I don't like this design, but it works.</p>
<p>Is there some other way to implement this?</p>
|
[] |
[
{
"body": "<p>A possible altenrative implementation can be the following:</p>\n\n<p>All the packet have no inheritance, nor recieved packet nor sent packet</p>\n\n<p><code>PacketOutA</code>, <code>PacketOutB</code>, <code>PacketOutC</code> are all classes with a common interface, they have just two method: <code>begin()</code> and <code>end()</code> to access internal data;</p>\n\n<p>The recieved class are <code>PacketInA</code>, <code>PacketInB</code> and so on.</p>\n\n<p>The class <code>Communication</code> is used to allow me to send and recieve data to the communication port.</p>\n\n<p>The <code>ReaderAndValidator</code> class allow me to get and validate the body of the recieved packet.</p>\n\n<p>The <code>Dispatcher</code> class allow me to obtain a packet from a recieved one ( sorry for my english... look the example... )</p>\n\n<p>The <code>Device</code> class instead is needed to rappresent, in a domain context, our connected device.</p>\n\n<pre><code>/** abstract the communication mechanism. */\nclass Communication {\npublic:\n\n Communication ();\n\n template < typename Iterator >\n void send( Iterator first, Iterator last ) const\n {\n // send from first to last to \n }\n\n template< typename Iterator >\n std::vector< char > read( Iterator first, Iterator last ) const\n {\n // read from first to last to \n }\n\nprivate:\n // internal stuff\n};\n\n/** Validate an input packet and get the body */\nclass ReaderAndValidator {\npublic:\n\n ReaderAndValidator ( const Communication& comm )\n : mComm( comm )\n {\n }\n\n std::vector< char > read()\n {\n // read data\n return mComm.read( /* params */ );\n }\n\nprivate:\n const Communication& mComm;\n}\n\n/** Given the PacketOut obtain the corrisponding PacketIn. */\ntemplate < typename PacketOut >\nclass Dispatcher {\n Dispatcher()\n {\n static_assert( false, \"unable to instantiate Controller\" );\n }\n};\n\ntemplate <>\nclass Dispatcher< PacketOutA > {\npublic:\n Dispatcher( const Communication& comm )\n : mComm( comm )\n {\n }\n\n PacketInA send( const PacketOutA & packet ) const\n {\n mComm.send( std::begin( packet ), std::end( packet ) );\n\n ReaderAndValidator reader( mComm );\n auto body = reader.read();\n\n // RVO\n PacketInA result( std::begin( body ), std::end( body ) );\n return result;\n }\n\nprivate:\n const Communication& mComm;\n};\n\n// same thing for Controller< PacketOutB >, Controller< PacketOutC > and so on\n\n\nclass Device : private boost::noncopyable {\npublic:\n\n Device ()\n {\n // init communication\n }\n\n void doPacketOutA( int param )\n {\n PacketOutA packet( param );\n recieve( packet );\n }\n\n PacketInB doPacketB()\n {\n PacketOutB packet();\n return recieve( packet );\n }\n\nprivate:\n\n template < typename PacketOutKind >\n auto recieve( const PacketOutKind& p ) -> decltype( std::declval< Dispatcher< PacketOutKind > >().send( p ) ) )\n {\n Dispatcher< PacketOutKind > disp( mCommunication );\n return controller.send( p );\n }\n\nprivate:\n\n Communication mCommunication;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T14:22:39.350",
"Id": "27404",
"ParentId": "27297",
"Score": "3"
}
},
{
"body": "<h2>Preliminaries</h2>\n\n<p>I would decouple the <a href=\"http://www.objectmentor.com/resources/articles/srp.pdf\" rel=\"nofollow\">data transmission + message encoding/decoding from the data connection</a> problem. The linked Uncle Bob article also shows how to distinguish connection management differences for master and slave. You probably want this to work with any reasonable networking implementation. Since you already use <code>boost::noncopyable</code>, I take that as a hint that you are willing to use Boost in general.</p>\n\n<p>My recommendation would be for you to study, and then modify, the simple <a href=\"http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/examples.html\" rel=\"nofollow\">chat_message/chat_client/chat_server</a> example from the <a href=\"http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio.html\" rel=\"nofollow\">Boost.Asio</a> documentation. That library -or a modified version of it- is likely to become the official networking component in a future version of the Standard Library. So it's a good investment to learn about it.</p>\n\n<h2>Message Interface</h2>\n\n<p>Compared to the simple <code>chat_message</code> example, your question is a little more involved. I assume that the header information is used to identify which type of message is going to follow. I would recommend to factor all the common message stuff <code>HEADER|BODY|CHECKSUM</code> into an abstract base class <code>IMessage</code></p>\n\n<pre><code>class IMessage\n{\npubic:\n virtual ~IMessage() {} // virtual destructor\n\n // virtual functions that can be overriden for concrete message types \n\n static std::string header(std::string const& input)\n {\n return input.substr(0, HeaderLength);\n }\n\n static std::string body(std::string const& input)\n {\n return input.substr(HeaderLength, HeaderLength + BodyLength);\n }\n\n enum { \n HeaderLength = /* bla */,\n BodyLength = /* bla */,\n ChecksumLength = /* bla */\n };\n};\n</code></pre>\n\n<h2>Message Implementations</h2>\n\n<p>You could then define a bunch of different concrete messages that inherit the general message interface <code>IMessage</code>, and add some stuff of their own:</p>\n\n<pre><code>class Request: public IMessage \n{\n Request(std::string const& body) { /* decode the buffer */ }\n\n static std::unique_ptr<IMessage> create(std::string body const&) \n { \n return std::make_unique<Request>(body); \n }\n\n // Request specific overrides of virtual functions\n // Request unique functions\n};\n\nclass Acknowledge: public IMessage\n{\n Acknowledge(std::string const& body) { /* decode the buffer */ }\n\n static std::unique_ptr<IMessage> create(std::string const& body) \n { \n return std::make_unique<Acknowledge>(body); \n }\n\n // Acknowledge specific overrides of virtual functions\n // Acknowledge unique functions\n};\n</code></pre>\n\n<p>You might find it puzzling that I have written both a constructor and a <code>create()</code> function. That is explained in the next section. But for now, note that the declared return type is <code>std::unqiue_ptr<IMessage></code> but the function body return a unique pointer to the concrete message types. This legal C++ feature is known as <strong>covariant return types</strong>, and makes it possible to have polymorphic object construction.</p>\n\n<p>Note that <code>std::make_unique</code> is not yet officially availabe but you can get <a href=\"http://isocpp.org/files/papers/N3656.txt\" rel=\"nofollow\">a working version</a> that has been accepted for the upcoming C++14 Standard.</p>\n\n<h2>Reading messages</h2>\n\n<p>If you look at the Boost.Asio example, the <code>chat_client</code> and <code>chat_server</code> read from a character buffer that is being filled from a socket. So you need to decode the header in order to distinguish which message has to be created. </p>\n\n<p>Especially since you tagged this question with <code>design-patterns</code>, I would recommend to write a small <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow\">Factory class</a> that keeps a registry of function pointers. At startup, you fill the factory's registry with function pointers to the static member functions <code>create()</code> of all the message types in your application. In this case the registry would be e.g. of type</p>\n\n<pre><code>typedef std::map<std::string, std::function<std::unique_ptr<IMessage>(std::string const&)> Registry;\n</code></pre>\n\n<p>What this says is that every unique header (encoded in a <code>std::string</code>) stores a pointer to a function taking a <code>std::string</code> and returning a <code>std::unique_ptr<IMessage></code>. Those type of function pointers are preciesly the <code>create()</code> functions of your messages.</p>\n\n<p>Given a buffer that has been read from the socket, and converted to a <code>std::string</code>, your factory would do something like:</p>\n\n<pre><code> std::unique_ptr<IMessage> Factory::create(std::string const& input) const\n {\n auto const fun = registry_.find(IMessage::header(input));\n // here you can also do your CHECKSUM validation\n return fun? (fun)(IMessage::body(input)) : nullptr;\n }\n</code></pre>\n\n<p>What this does is to split the message into a header and body. These functions are static functions of the message interface, so that they can be called before we have a concrete message object. Then the header is looked up in the registry. </p>\n\n<p>If it is found, we simply call the corresponding <code>create()</code> message that was stored, taking the <code>body</code> as argument. This will call the constructor (now you see why we had both a constructor and a creator, because constructors cannot be stored in a factory registry). The constructor will finally create a <code>std::unique_ptr</code> to the concrete message type that was encoded in the header. </p>\n\n<p>If we didn't find a registered message type, we return a <code>nullptr</code>. The caller of the factory creator would then have to check this before being able to safely use the returned pointer.</p>\n\n<h2>Final thoughts</h2>\n\n<p>The above explained how to decode messages from a stream of tokens that you get from a socket. Writing is of course much easier because then you already know the message type. I think that the data transmission and connection management part, and the semantic part of how to respond to each message type is beyond the scope of this Q&A. The Boost.Asio example does not need too much modification to allow reading your message structures from a socket.</p>\n\n<p>For the above message parsing machinery, I have implemented a heavily templated version of <a href=\"http://www.mesander.nl/damexchange/edxplg2.htm\" rel=\"nofollow\">similar protocol called DamExchange</a> (used for letting checkers/draughts engines over a network). You can follow the header trail on a <a href=\"https://bitbucket.org/rhalbersma/dctl/src/9abc0c0d35f962297ebaf1a9676cd06f8b846289/test/test/dxp/parser.cpp?at=default\" rel=\"nofollow\">simple use case</a> in my BitBucket repo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T01:12:43.303",
"Id": "42647",
"Score": "0",
"body": "I've thought along to the solution, but I prefer my solution. I know that I've to study better so I'll try your implementation too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T18:24:52.303",
"Id": "42857",
"Score": "0",
"body": "@elvis.dukaj Which parts in your answer do you prefer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:58:17.870",
"Id": "42875",
"Score": "0",
"body": "well, not always request and response has something common, I've a low coupling and high cohesion. No need to derive request packet so I've no need to cast from request to derived. No need for a factory class, no need for a register (sometimes we need some more data to know response ) and because it's very easy to implement and to use. And also is very easy to extend"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:56:07.780",
"Id": "27414",
"ParentId": "27297",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27404",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T10:02:07.120",
"Id": "27297",
"Score": "6",
"Tags": [
"c++",
"design-patterns"
],
"Title": "Design for a protocol based software in C++"
}
|
27297
|
<p>Any time I'm testing a Ruby class that calls a Kernel method such as <code>sleep</code> or <code>exit</code>, i define a singleton method on the class instance and test that it has been invoked:</p>
<pre><code>it "must throttle requests" do
sleep_was_called = false
subject.define_singleton_method(:sleep) { |seconds|
sleep_was_called = true
}
subject.request query
subject.request query
sleep_was_called.must_equal true
end
</code></pre>
<p>I have seen far more sophisticated method stub testing in RSpec, but it there a more fancy and less verbose way to do this using MiniTest?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T12:02:56.263",
"Id": "42610",
"Score": "1",
"body": "This seems like more of an SO type question."
}
] |
[
{
"body": "<p>I know MiniTest has an expectations framework, but I'm not familiar with it. I use rspec-expectations to accomplish this, like so:</p>\n\n<pre><code>describe ClassName do\n let(:subject) { described_class.new }\n\n describe '#method' do\n it 'should sleep 3 times and output hello world' do\n expect(subject).to receive(:sleep).exactly(3).times\n expect(subject).to receive(:puts).with('Hello world!').exactly(3).times\n\n subject.method\n end\n end\nend\n</code></pre>\n\n<p>I know this doesn't directly answer your question, but my hope is it leads you in the right direction.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T14:30:55.150",
"Id": "92259",
"Score": "0",
"body": "However, it's not a great idea to do this much. It's normally better to test behavior, not implementation, except in a few special cases."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T18:01:42.530",
"Id": "49091",
"ParentId": "27299",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T11:16:36.687",
"Id": "27299",
"Score": "0",
"Tags": [
"ruby"
],
"Title": "Am I correctly testing that methods from Kernel have been called?"
}
|
27299
|
<p>I need to find the flaws in this design. So far the only ones i can think of are:</p>
<ul>
<li>No use of generics</li>
<li>the class Concept uses a parametrized constructor, which means every sub class would need to pass a parameter. The setter method could be used instead. </li>
</ul>
<p>Can you think of anymore flaws? </p>
<p>Concept.Java </p>
<pre><code>public abstract class Concept
{
private String id;
protected Concept( String anId )
{
if ( anId == null )
{
throw new NullPointerException( "id must not be null" );
}
id = anId;
}
public String getId()
{
return id;
}
public void setId( final String id ) //changed
{
this.id = id;
}
public boolean equals( Object other )
{
return other != null && other.getClass().equals( getClass() ) && id.equals( ( (Concept) other ).id );
}
public String toString()
{ return "Concept(" + id + ")";
}
}
</code></pre>
<p>ConceptA.java</p>
<pre><code>public class ConceptA extends Concept
{
private final Concept parent;
public ConceptA( String anId, Concept aParent )
{
super( anId );
parent = aParent;
}
public Concept getParent()
{
return parent;
}
public String toString()
{
return "ConceptA{" + getId() + ", parent=" + parent + '}';
}
}
</code></pre>
<p>ConceptB.java</p>
<pre><code>import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class ConceptB extends ConceptA
{
private final Set children;
public ConceptB( final String anId, final Concept aParent )
{
super( anId, aParent );
children = new HashSet();
}
public int getCount()
{
return children.size();
}
public void addChild( Concept aChild )
{
children.add( aChild );
}
public void removeChild( Concept aChild )
{
children.remove( aChild );
}
public Iterator getChildren()
{
return children.iterator();
}
public int getFamilySize()
{
int count = children.size();
for ( Iterator iter = getChildren(); iter.hasNext(); )
{
count += ( (ConceptB) iter.next() ).getFamilySize();
}
return count;
}
public int getAncestorCount()
{
int count = 0;
Concept ancestor = getParent();
while ( ancestor != null )
{
count++;
if ( ancestor instanceof ConceptA )
{
ancestor = ( (ConceptA) ancestor ).getParent();
}
else
{
ancestor = null;
}
}
return count;
}
public String toString()
{
return "ConceptB{" + getId() + ", parent=" + getParent() + ", children=" + children.size() + "}";
}
}
</code></pre>
<p>ConceptC.java</p>
<pre><code> package com.result.exam.a;
public class ConceptC extends ConceptA
{
private static int nextSerialNo = 0;
public static int getNextSerialNo()
{
return nextSerialNo++;
}
private final int serialNo;
public ConceptC( String anId )
{
super( anId, null );
serialNo = getNextSerialNo();
}
public int getSerialNo()
{
return serialNo;
}
public String toString()
{
return "ConceptC(" + getId() + ", " + serialNo + ")";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T11:55:42.023",
"Id": "42418",
"Score": "1",
"body": "Finding flaws, OK, but you need to tell us what you want to do with these classes first ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T11:58:54.787",
"Id": "42419",
"Score": "0",
"body": "lol, its a test, nothing needs to be done. Also I was thinking in ConceptB.java in the getFamilySize() is that downcasting ? Can you cast from Concept to ConceptB ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:13:34.600",
"Id": "42424",
"Score": "0",
"body": "You have also to test 'null' parameter : *public void setId(final String id) { if(null != id && id.length > 0) this.id = id; }* - see also my comment about *.equal()* in Marco's answer."
}
] |
[
{
"body": "<p>i would rewrite your equals method a bit (just for readability)</p>\n\n<pre><code>public boolean equals(Object other) {\n if(this == other) {\n return true;\n }\n\n if(!(other instanceof Concept)) {\n return false; \n }\n\n Concept otherConcept = (Concept) other;\n\n return id.equals(otherConcept.id);\n }\n</code></pre>\n\n<p>And concerning your parameterized constructor I don't see anything the speaks against this. It is part of the contract of you model and if you don't intend to use this class in any framework that requires a parameterless constructor to work i think we are fine</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:11:31.420",
"Id": "42423",
"Score": "1",
"body": "if (false == other instanceof Concept) {return false;} // test other == null . Cf: JLS, 15.19.2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:21:14.243",
"Id": "42427",
"Score": "0",
"body": "okay now i see. when did that change? i remember getting a NPE from instance of in earlier versions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:22:18.070",
"Id": "42428",
"Score": "0",
"body": "It is now (java7) in http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T14:04:49.250",
"Id": "42434",
"Score": "0",
"body": "Uhm, you don't check for null!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T14:05:42.973",
"Id": "42435",
"Score": "0",
"body": "i did. but then cl-r pointed out that this is unneccessary. Try yourself `Object x = null; System.out.println(x instanceof Object);`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T12:17:51.037",
"Id": "27302",
"ParentId": "27301",
"Score": "1"
}
},
{
"body": "<p>The casting in <code>getFamilySize()</code> is very dangerous. Notice that </p>\n\n<pre><code>public void addChild( Concept aChild )\n</code></pre>\n\n<p>means you can add any sub-class of <code>Concept</code> as a child, and therefore <code>getChildren()</code> returns an iterator to <strong>any</strong> sub-class of <code>Concept</code>.</p>\n\n<p>Furthermore, you're only finding the size two levels down (the current <code>Concept</code>'s children and their children). I suspect you want to find the size of the entire sub-tree.</p>\n\n<p>A safer and more correct way to implement the method would be:</p>\n\n<pre><code>public Set getChildren()\n{\n return Collections.unmodifiableSet(children);\n}\n\npublic int getFamilySize()\n{\n int count = 0;\n\n Queue<Concept> queue = new LinkedList<Concept>();\n\n queue.addAll(this.getChildren());\n\n while (!queue.empty())\n {\n Concept concept = queue.poll();\n // count the Concept we just pulled off the queue\n count++;\n\n if (concept instanceof ConceptB)\n {\n // we need his children too\n queue.addAll(((ConceptB) concept).getChildren());\n }\n }\n\n return count;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T19:48:06.217",
"Id": "27318",
"ParentId": "27301",
"Score": "0"
}
},
{
"body": "<p>Others have pointed out some potential problem with it, but I'll try to compile them and add my own. </p>\n\n<p><strong>Concept</strong></p>\n\n<ul>\n<li>Readability of <strong>equal</strong> method (<a href=\"https://codereview.stackexchange.com/a/27302/26120\">Marco</a>)</li>\n<li>Not checking for null in the <strong>setId</strong> method</li>\n</ul>\n\n<p><strong>ConceptB</strong></p>\n\n<ul>\n<li>I would rename <strong>getCount</strong> to <strong>getNumberOfChildren</strong> or getChildrenCount just to make it more readable</li>\n<li><p>Question you want to consider is what kind of children can ConceptB have? If it's only ConceptB, you may want to consider addChild only takes in ConceptB and specifying which type of data the set hold to avoid casting. And as <a href=\"https://codereview.stackexchange.com/a/27318/26120\">kuporific</a> said, downcasting without checking is dangerous. I would rewrite it something like this: </p>\n\n<pre><code>public int getFamilySize() {\nint count = children.size();\n\nfor (Iterator iter = getChildren(); iter.hasNext(); ) {\n Concept child = (Concept) iter.next();\n if (child instanceof ConceptB){\n count += ((ConceptB) child).getFamilySize();\n }\n}\n\nreturn count;\n</code></pre>\n\n<p>}</p></li>\n</ul>\n\n<p><strong>ConceptC</strong></p>\n\n<ul>\n<li>Since ConceptC doesn't use a parent and the only thing that ConceptA adds to Concept is a parent, it might be better for ConceptC to extend Concept instead of ConceptA. </li>\n</ul>\n\n<p>Last thing, for all subclass of Concept, there is no equal method. So for example, if I have two classes with the same id, but different parent, they are still equal. This may or may not be what you want. But I think it's something to take note of.</p>\n\n<pre><code>Concept parent = new ConceptC(\"parent c\"); \nConcept concept1 = new ConceptA(\"a\", null);\nConcept concept2 = new ConceptA(\"a\", parent);\n\nSystem.out.println(concept1.equals(concept2));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:50:42.797",
"Id": "27356",
"ParentId": "27301",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T11:47:12.113",
"Id": "27301",
"Score": "-1",
"Tags": [
"java",
"object-oriented",
"inheritance"
],
"Title": "Design of Concept Class"
}
|
27301
|
<p>I'm new to Elixir, and in order to learn the syntax, I'm doing a roman numeral kata which converts a decimal number into roman numeral. I would appreciate any feedback you have.</p>
<pre><code>defmodule RomanNumeral do
@decimal_roman_numerals [[5, 'V'], [4, 'IV'], [1, 'I']]
def converts(number) do
converts(number, [], @decimal_roman_numerals)
end
def converts(number, roman_value, _) when number < 1 do
roman_value
end
def converts(number, roman_value, [[decimal, roman] | numerals]) when number >= decimal do
converts(number - decimal, roman_value ++ roman, [[decimal, roman] | numerals])
end
def converts(number, roman_value, [_ | numerals]) do
converts(number, roman_value, numerals)
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T13:58:13.873",
"Id": "66300",
"Score": "0",
"body": "That is a very Prolog solution, which is good because Erlang is prolog inspired.]"
}
] |
[
{
"body": "<p>Your code looks very nice indeed, I only have some minor observations you code use to improve this code:</p>\n\n<p><strong>Naming</strong><br>\nUse the imperative form of the verb (<code>convert</code> instead of <code>converts</code>)</p>\n\n<p><strong>Implementation Hiding</strong><br>\nUse <code>defp</code> for methods which are not intended for external use. You might consider also renaming them to start with underscore <code>_</code> to further differentiate them as internal.</p>\n\n<p><strong>Multiple assignment in method signature</strong><br>\nTo make you code more succinct, you can use multiple assignment - meaning that instead of:</p>\n\n<pre><code>def converts(number, roman_value, [[decimal, roman] | numerals]) when number >= decimal do\n converts(number - decimal, roman_value ++ roman, [[decimal, roman] | numerals])\nend\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>def converts(number, roman_value, [[decimal, roman] | _] = numerals) \n when number >= decimal do\n converts(number - decimal, roman_value ++ roman, numerals)\nend\n</code></pre>\n\n<p>to the same effect. This form assigns the first item in the list to <code>[decimal, roman]</code>, as well as assigning the <em>whole</em> list (including the first element) to <code>numerals</code>, so you don't have to re-build it inside the method body.</p>\n\n<hr>\n\n<p>Implementing the above suggestions, your code will look like this:</p>\n\n<pre><code>defmodule RomanNumeral do\n\n @decimal_roman_numerals [[5, 'V'], [4, 'IV'], [1, 'I']]\n\n def convert(number) do\n _convert(number, [], @decimal_roman_numerals)\n end\n\n defp _convert(number, roman_value, _) when number < 1 do\n roman_value\n end\n\n defp _convert(number, roman_value, [[decimal, roman] | _] = numerals) \n when number >= decimal do\n _convert(number - decimal, roman_value ++ roman, numerals)\n end\n\n defp _convert(number, roman_value, [_ | numerals]) do\n _convert(number, roman_value, numerals)\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-17T08:12:24.640",
"Id": "60279",
"ParentId": "27310",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "60279",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T15:20:06.603",
"Id": "27310",
"Score": "10",
"Tags": [
"beginner",
"roman-numerals",
"elixir"
],
"Title": "Roman numeral kata in Elixir"
}
|
27310
|
<p>I am working on a Java program which creates a map using Voronoi. I am using a <a href="http://sourceforge.net/projects/simplevoronoi/" rel="nofollow">Java library which generates Voronoi</a> and it is very fast.</p>
<p>The problem I am facing is that, then, I have to scan every Voronoi edge to know what point is on the left and on the right of the edge to create the polygon which contains each point.</p>
<p>This is the class which contains every Voronoi edge:</p>
<pre><code>public class GraphEdge
{
public double x1, y1, x2, y2;
public int site1;
public int site2;
}
</code></pre>
<p>The coordinates <code>x1, y1, x2, y2</code> are the edge start and end coordinates and <code>site1</code> and <code>site2</code> are the indexes of the points which are on the left and on the right of the edge. So, to create the polygon which contains every point I do this:</p>
<pre><code>for(int n = 0; n < xValues.length; ++n){
polygonsList.add(new GPolygon());
for(GraphEdge mGraphEdge : edgesList){
if( (xValues[mGraphEdge.site1] == xValues[n] || xValues[mGraphEdge.site2] == xValues[n])
&& (yValues[mGraphEdge.site1] == yValues[n] || yValues[mGraphEdge.site2] == yValues[n]) ){
polygonsList.get(n).addPoint((int)mGraphEdge.x1, (int)mGraphEdge.y1);
polygonsList.get(n).addPoint((int)mGraphEdge.x2, (int)mGraphEdge.y2);
}
}
}
</code></pre>
<p>Where <code>xValues</code> and <code>yValues</code> are the points coordinates from which I generate the Voronoi diagram and <code>GPolygon</code> is a Polygon class I created which extends from <code>java.awt.Polygon</code>.</p>
<p>These are the times I measured:</p>
<ul>
<li><strong>Voronoi Time:</strong> 283 ms (time to generate Voronoi diagram)</li>
<li><strong>Polygon Search Time:</strong> 34589 ms (time to complete the for loop which generates the polygons)</li>
<li><strong>Polygon Fill Time:</strong> 390 ms (time to fill the polygons and save to image, which is optional)</li>
<li><strong>Points quantity:</strong> 26527 (number of points from which Voronoi is generated)</li>
<li><strong>Map Generation Finished</strong></li>
<li><strong>Polygon quantity:</strong> 26527 (number of polygons, one for each point)</li>
</ul>
<p>As you can see, the time is really significant compared to the others. How can I speed up the <code>for</code> loop? What other alternatives do I have?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T21:37:09.737",
"Id": "42476",
"Score": "0",
"body": "I ALMOST solved it here http://stackoverflow.com/questions/17072832/how-to-optimize-this-loop/17072926?noredirect=1#17072926 HashMap answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:40:39.860",
"Id": "216431",
"Score": "0",
"body": "The solved it on [this](http://stackoverflow.com/questions/17072832/how-to-optimize-this-loop/17073495?noredirect=1#17073495 \"this\") way using a HashMap."
}
] |
[
{
"body": "<p>To improve the speed of your code, you'd really have to profile it, and know what the bottleneck is (use a profiler, and find out in what methods most of the time is spent).</p>\n\n<p>Here's what I would have a look at <em>(no promise it will yield significant improvements)</em>.</p>\n\n<ul>\n<li><code>polygonsList.get(n)</code> is evaluated twice per iteration.</li>\n<li>The polygon class you're using (I assume <code>java.awt.Polygon</code>) takes <code>int</code>s as coordinates, while the library calculates them in <code>double</code>s. Yo may want to consider writing a custom Polygon class that takes doubles, in order to avoid the casts.</li>\n<li>if you only need the Polygon class for drawing, you may even forego that entirely and make a class that can draw a line given a <code>GraphEdge</code>. This will avoid creating <code>Polygon</code> objects, and you can reuse the same drawing instance.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T05:20:48.460",
"Id": "27333",
"ParentId": "27314",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T18:41:13.163",
"Id": "27314",
"Score": "2",
"Tags": [
"java",
"performance",
"coordinate-system"
],
"Title": "Constructing polygons from the edges in a Voronoi diagram"
}
|
27314
|
<p>This is DFS/BFS C++ code for Cormen pseudo code. Please comment on this.</p>
<pre><code>#include "iostream"
#include "vector"
#include "list"
enum color{
WHITE,
GREY,
BLACK
};
struct edge{
int destination_vertex;
edge(int ver){
destination_vertex = ver;
}
};
struct vertex{
int id;
color visited;
std::list<edge> list;
vertex(int _id){
id = _id;
}
};
class graph
{
private:
std::vector<vertex> vertexes;
void dfs_visits(vertex& source);
int next;
public:
graph(void){
next = 0;
}
~graph(void){}
void dfs();
void bfs();
};
void graph::dfs(void)
{
for(std::vector<vertex>::iterator iter =vertexes.begin();iter < vertexes.end();iter++ ){
iter->visited = WHITE;
}
for(std::vector<vertex>::iterator iter =vertexes.begin();iter < vertexes.end();iter++ ){
if(iter->visited == WHITE){
dfs_visits(*iter);
}
}
}
void graph::dfs_visits(vertex& source){
source.visited = GREY;
for(std::list<edge>::iterator iter = source.list.begin();iter != source.list.end();iter++){
if(vertexes[iter->destination_vertex].visited == WHITE){
dfs_visits(vertexes[iter->destination_vertex]);
}
}
source.visited = BLACK;
std::cout<< source.id <<std::endl;
}
void graph::bfs(){
for(std::vector<vertex>::iterator iter=vertexes.begin();iter != vertexes.end();iter++){
iter->visited = WHITE;
}
std::queue<vertex*> bsf_q;
bsf_q.push(&vertexes[0]);
while(!bsf_q.empty()){
vertex * v = bsf_q.front();
bsf_q.pop();
for(std::list<edge>::iterator iter = v->list.begin() ;iter != v->list.end();iter++ ){
if(vertexes[iter->destination_vertex].visited == WHITE){
vertexes[iter->destination_vertex].visited = GREY;
bsf_q.push(& vertexes[iter->destination_vertex]);
}
}
v->visited = BLACK;
std::cout << v->id <<std::endl;
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Preliminaries</h2>\n\n<p>It's conventional to include system headers <a href=\"https://stackoverflow.com/a/3162067/819272\">with brackets instead of quotes</a> and <a href=\"https://stackoverflow.com/a/471461/819272\">prefer <code>std::vector</code> over <code>std::list</code></a> unless proven wrong by a benchmark (note that the use of the word \"list\" in CLRS is not used in the same sense as <code>std::list</code>).</p>\n\n<pre><code>#include <vector>\n#include <limits>\n</code></pre>\n\n<h2>Data structures</h2>\n\n<p><a href=\"https://stackoverflow.com/a/11948413/819272\">Separate your algorithms and data structures</a> and use a common naming convention where types have capitalized initial letters</p>\n\n<pre><code>enum { \n INFINITY = std::numeric_limits<int>::max() \n};\n\nenum Color {\n WHITE,\n GREY,\n BLACK\n};\n\nstruct Vertex {\n int id;\n\n // BFS properties\n Color color;\n int discovery;\n Vertex* parent;\n\n // DFS properties\n int finish;\n};\n\n// adjacenty list representation (Figure 22.1 (b) of CLRS 3rd ed.)\nstruct Graph {\n std::vector<Vertex> vertices;\n std::vector< std::vector<Vertex*> > adjacent;\n}; \n</code></pre>\n\n<p>Several things can be said about my choice of data structures. <em>For the purpose of illustrating BFS and DFS</em> I wouldn't make them full-fledged classes with data hiding. You also need to set up some scaffolding code to initialize a <code>Graph</code> object, and make sure that the <code>Vertex*</code> inside <code>adjacent</code> are actually only pointing to <code>Vertex</code> objects inside <code>vertices</code> of the same <code>Graph</code> object (so that in fact <code>adjacent</code> only holds non-owning pointers). Real-world code would encapsulate the enforcement of such invariants inside the constructor and modifying member functions. For brevity this is not being show.</p>\n\n<p>I also would remove the <code>Edge</code> class because it is implicitly represented as an <code>Vertex*</code> in the adjacency list graph representation. Finally, because the <code>id</code> in <code>Vertex</code> is an <code>int</code>, you get away with using a <code>std::vector</code> as a container. For <code>std::string</code> vertex labels, one would need to use a <code>std::map<std::string, std::vector<Vertex*>></code> for the <code>adjacent</code> data inside <code>Graph</code>.</p>\n\n<p>Note that the properties of BFS and DFS are put inside <code>Vertex</code>. This is to accomodate the style of notation of CLRS. They write on p592 that you can put that information in separate data structures as well (e.g. a <code>std::map<Vertex*, SearchProperties></code>). Boost.Graph (the closest thing in C++ to a standardized graph implementation) uses such <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/graph/doc/using_property_maps.html\" rel=\"nofollow noreferrer\">property maps</a> to achieve the same effect more elegantly.</p>\n\n<h2>Breadth-first search</h2>\n\n<p>Document your algorithms pre- and post-conditions, as well as the runtime complexity as a function of the input size (look it up in CLRS!). I would give the function <code>breadth_first_search</code> the same signature as in CLRS, except that they are not very careful about whether they pass by value, reference or pointer.</p>\n\n<pre><code>#include <queue>\n\n// pre-condition: graph of vertices with unitialized BFS properties\nvoid breadth_first_search(Graph& g, Vertex* s)\n{ \n for (auto& v: g.vertices)\n if (v.id == s->id) continue;\n v.color = WHITE;\n v.discovery = INFINITY;\n v.parent = nullptr;\n }\n s->color = GRAY;\n s->discovery = 0;\n s->parent = nullptr; \n std::queue<Vertex*> q;\n q.push(s); \n while (!q.empty()) {\n auto u = q.front();\n q.pop(); \n for (auto v: G.adjacent[u->id])) {\n if (v->color == WHITE) {\n v->color = GRAY;\n v->discovery = u->discovery + 1;\n v->parent = u;\n q.push(v);\n }\n }\n u->color = BLACK;\n }\n}\n// post-condition: graph with initialized vertex color and discovery times\n</code></pre>\n\n<p>Notice that I would strongly recommend to use the C++11 features <a href=\"https://stackoverflow.com/q/8542873/819272\"><code>auto</code></a> type deduction and <a href=\"https://stackoverflow.com/q/6963894/819272\">ranged for-loop</a>. These enormously improve the readability of your code: the code above is in almost exactly the same notation as the listing of BFS(G,s) on p595 of CLRS (except that I use <code>color</code>, <code>discovery</code> and <code>parent</code> instead of the terser <code>c</code>, <code>d</code> and <code>pi</code>.</p>\n\n<p>Except for debugging purposes, I would eliminate the <code>std::cout</code> calls from the BFS algorithm. Because the algorithm also keeps track of the <code>parent</code> information, you can completely retrace the algorithms steps after it finishes, should you want to, and print whatever information necessary.</p>\n\n<h2>Depth-first search</h2>\n\n<p>For the depth-first search, I again would follow the CLRS conventions as much as possible:</p>\n\n<pre><code>void depth_first_search(Graph& g)\n{\n for (auto& u: g.vertices) {\n u.color = WHITE;\n u.parent = nullptr;\n }\n\n for (auto& u: g.vertices) {\n if (u.color == WHITE)\n depth_first_search_visit(g, &u, 1)\n }\n}\n\nvoid depth_first_search_visit(Graph& g, Vertex* u, int time)\n{\n u->color = GRAY;\n u->discovery = time;\n for (auto v: g.adjacent[u->id]) {\n if (v->color == WHITE) {\n v->parent = u;\n depth_first_search_visit(G, u, time + 1)\n }\n }\n u->color = BLACK;\n u->finish = time + 1; \n}\n</code></pre>\n\n<p>Note that I would pass the <code>time</code> variable by value along the recursive calls to <code>depth_first_search_visit</code>, which makes it slightly clearer to reason about the algorithm (and also avoids a few explicit increments here and there). Again note that the code above is in almost exactly the same notation as the listing of DFS(G) on p604 of CLRS.</p>\n\n<p><strong>Extra:</strong> note that BFS is written as a single function with an init phase + infinite loop over a <code>std::queue</code>, and DFS as an init function + a recursive fuction. It is a nice exercise to rewrite DFS as a single function with an init phase + infinite loop over a <code>std::stack</code> (instead of the implicit stack used by the recursion).</p>\n\n<h2>Further reading</h2>\n\n<p>If you want to know how the pros are doing it: familiarize yourself with <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/graph/doc/index.html\" rel=\"nofollow noreferrer\">Boost.Graph</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T20:55:54.237",
"Id": "42552",
"Score": "0",
"body": "@bapusethi glad to have been of help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:56:39.210",
"Id": "27372",
"ParentId": "27316",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27372",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T18:50:40.463",
"Id": "27316",
"Score": "5",
"Tags": [
"c++",
"graph",
"breadth-first-search",
"depth-first-search"
],
"Title": "DFS/BFS implementation of Cormen's pseudo code"
}
|
27316
|
<p>I hate having almost two identical blocks do almost the exact same thing.</p>
<p><strong>I am working with Entity Framework 4.4.0.0<br />
Asp.Net MVC</strong></p>
<p>Right now if the user is a "manager" I want to show them the entire list, if they are a normal user or a Team Lead. I only want to show them their specific department. The only different from both <code>model</code> is that one add's a where and the other does not.</p>
<pre><code>public ActionResult Index()
{
AD_CurrentUserProfile currentUP = new ActiveDirectory().GetUserProfile(User.Identity.Name.Split("\\".ToCharArray())[1].ToString());
IQueryable<IPACS_DT_MasterList> model;
if (currentUP.currentUser.isManager)
{
model = (from d in db.IPACS_Department
join f in db.IPACS_Function on d.departmentID equals f.departmentID
join pg in db.IPACS_Process on f.functionID equals pg.functionID
join sop in db.IPACS_Procedure on pg.processID equals sop.processID
select new IPACS_DT_MasterList
{
departmentID = d.departmentID,
functionID = f.functionID,
processID = pg.processID,
procedureID = sop.procedureID,
departmentName = d.name,
functionName = f.name,
processName = pg.name,
procedureName = sop.name,
owner = sop.owner
});
}
else
{
model = (from d in db.IPACS_Department
where d.name == currentUP.currentUser.department // only change
join f in db.IPACS_Function on d.departmentID equals f.departmentID
join pg in db.IPACS_Process on f.functionID equals pg.functionID
join sop in db.IPACS_Procedure on pg.processID equals sop.processID
select new IPACS_DT_MasterList
{
departmentID = d.departmentID,
functionID = f.functionID,
processID = pg.processID,
procedureID = sop.procedureID,
departmentName = d.name,
functionName = f.name,
processName = pg.name,
procedureName = sop.name,
owner = sop.owner
});
}
return View(model);
}
</code></pre>
|
[] |
[
{
"body": "<p>Merge your if statement into the <code>where</code> clause.</p>\n\n<pre><code>public ActionResult Index()\n{\n AD_CurrentUserProfile currentUP = new ActiveDirectory().GetUserProfile(User.Identity.Name.Split(\"\\\\\".ToCharArray())[1].ToString());\n\n IQueryable<IPACS_DT_MasterList> model =\n (from d in db.IPACS_Department\n where (currentUP.currentUser.isManager || d.name == currentUP.currentUser.department)\n join f in db.IPACS_Function on d.departmentID equals f.departmentID\n join pg in db.IPACS_Process on f.functionID equals pg.functionID\n join sop in db.IPACS_Procedure on pg.processID equals sop.processID\n select new IPACS_DT_MasterList\n {\n departmentID = d.departmentID,\n functionID = f.functionID,\n processID = pg.processID,\n procedureID = sop.procedureID,\n departmentName = d.name,\n functionName = f.name,\n processName = pg.name,\n procedureName = sop.name,\n owner = sop.owner\n });\n\n return View(model);\n}\n</code></pre>\n\n<p>If the current user is a manager, the first condition will return true and cause the <code>where</code> statement to short-circuit; otherwise it will compare the department name to the user's department.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-21T16:48:43.777",
"Id": "97604",
"ParentId": "27317",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "97604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T18:52:56.043",
"Id": "27317",
"Score": "2",
"Tags": [
"c#",
"linq",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Restricting search to a user's own department, if the user is not a manager"
}
|
27317
|
<p>Basically, the code converts a large select list with optgroups into a more user-friendly tabbed Twitter-bootstrap component.</p>
<p>I'm not sure how much into detail I need to get but on GitHub I uploaded a <a href="https://github.com/alphacss/bootstrap-tabbed-select" rel="nofollow noreferrer">working example</a>. This is the first time I write a jquery plugin and any advise is welcome.</p>
<pre><code>(function($) {
$.fn.bootstrapSelect = function(options) {
//Extend default options with those provided.
var opts = $.extend({}, $.fn.bootstrapSelect.defaults, options);
var topLevel='';
var subLevel='';
var selectedValue ='';
var sectionActive = false;
var selected = '';
// Rewrite the info in the select box
$('optgroup',this).each(function(x) { //for each optgroup
//get section label
var sectionLabel = $(this).attr('label');
//get section content
var sectionContent = '';
$('option',this).each(function(x) {
/*Check if an option is selected, and set section active*/
if ($(this).attr('selected')) {
selectedValue = $(this).attr('value');
sectionActive = true;
}
sectionContent += '<a ';
$(this).attr('selected') ? sectionContent += 'class="bsactive" ' : '';
sectionContent += 'value="' + $(this).attr('value') + '">' + $(this).text() + '</a>\n';
});
sectionActive ? selected = true : false;
topLevel += '<li';
sectionActive ? topLevel += ' class="active"' : '';
topLevel += '><a href="#optgroup' + x + '" data-toggle="tab">' + sectionLabel + '</a></li>\n';
subLevel += '<div id="optgroup' + x + '" class="tab-pane';
sectionActive ? subLevel += ' active' : '';
subLevel += '">\n' + sectionContent + '</div>\n';
sectionActive = false;
});
//Replacement tabbed select
var tabbedselect = '<div class="tabbable '+opts.position+'">\n';
if ( opts.position != "tabs-below") tabbedselect += '<ul class="nav nav-tabs">\n'+topLevel+'</ul>\n';
tabbedselect += '<div class="tab-content">\n'+subLevel+'</div>\n'
if ( opts.position == "tabs-below") tabbedselect += '<ul class="nav nav-tabs">\n'+topLevel+'</ul>\n';
tabbedselect += '</div>\n';
// Replace the select with the tabbed menu
this.replaceWith(tabbedselect);
// Add hidden input field with the selected value
$("form").append('<input type="hidden" name="'+opts.inputId+'" id="'+opts.inputId+'" value="'+selectedValue+'" />');
//set first tab and content area active if nothing is selected
if (selected == false) {
$("div.tab-content div:first-child").addClass("active");
$("ul.nav-tabs li:first-child").addClass("active");
}
// set input field value on click
$(".tab-content a").click(function () {
$("*").removeClass("bsactive");
$(this).addClass("bsactive");
$('input#'+opts.inputId).attr('value', $(this).attr('value'));
})
};
//default settings
$.fn.bootstrapSelect.defaults = {
'position' : 'tabs-left',
'inputId' : 'bootstrap-select'
};
})(jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T21:13:13.450",
"Id": "42470",
"Score": "0",
"body": "I set up a working example at http://tinker.io/fce06, would you please take a look an make sure that it looks and works as you would expect? It looks good to me."
}
] |
[
{
"body": "<p>In order to be able to use this plugin on a page with multiple forms, I would recommend identifying the specific form that you are operating on. I can see that you are aware of the issue because you have been using the context parameter in most of the selectors, but since the <code><form></code> is an ancestor of <code>this</code>, it would need to be selected differently:</p>\n\n<pre><code>$(\"form\").append(...\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>$(this).ancestor('form').append(...\n</code></pre>\n\n<p>Also, I just wanted to mention a personal preference when working with HTML snippets generated by jQuery. Instead of having HTML in JS strings, like</p>\n\n<pre><code>$(this).ancestor(\"form\").append(\n '<input type=\"hidden\" name=\"'+opts.inputId+'\" id=\"'+opts.inputId+'\" value=\"'+selectedValue+'\" />'\n);\n</code></pre>\n\n<p>I like to make hidden template elements, and then clone them, remove the <code>.template</code> class, set the attributes and inner html, and insert the clone into the document. For example:</p>\n\n<pre><code>// stylesheet:\n.template { display: none; }\n\n// html, near the end of the <body>:\n<input type=\"hidden\" id=\"hiddenInputTemplate\" class=\"template\"/>\n\n// js:\n$(this).ancestor('form').append(\n $('#hiddenInputTemplate')\n .clone()\n .removeClass('template')\n .attr('name', opts.inputId)\n .attr('id', opts.inputId)\n .val(selectedValue)\n);\n</code></pre>\n\n<p>For a short example like this, it might not be worth the extra verbosity, but I do have reasons for doing it this way:</p>\n\n<ul>\n<li>My editor can't highlight HTML code, and especially syntax errors, inside of JS strings.</li>\n<li>I can read and understand this style a little faster, and I will read it more often than I will write it. Like I said, it's just personal preference.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T20:34:52.910",
"Id": "42549",
"Score": "0",
"body": "Thanks for the review. I tried using \"ancestor\" but it didn't work, so I tried to see the documentation for it but didn't find it. I found \"parents\" which I believe does what was intended, the problem is that doesn't work either.\nI believe it is because I do a \"replaceWith\" right before, so the object doesn't exist anymore. As a workaround I added the input field to the tabbedselect variable.\nI also made other changes to support multiple instances."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:59:26.267",
"Id": "42564",
"Score": "0",
"body": "Would it work to select the form and keep the selection in a variable, before doing the `replaceWith`? You would still be doing `form.append(...` after `replaceWith`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T21:43:27.007",
"Id": "27324",
"ParentId": "27321",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27324",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T19:57:59.973",
"Id": "27321",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"twitter-bootstrap"
],
"Title": "Twitter-bootstrap add-on"
}
|
27321
|
<p>So I have a <code>DataTable</code> that returns results within a month to month range when available. However, when I format the return, I need to still show skipped months as blanks.</p>
<p>I have a working solution, but it's a little verbose and I think it can be done cleaner.</p>
<p><strong>Here's a setup to the problem</strong></p>
<pre class="lang-vb prettyprint-override"><code>Dim startMonth As Date = #5/1/2011#
Dim endMonth As Date = #6/1/2012#
Dim dr As DataRow
Dim dtData As New DataTable
With dtData.Columns
.Add("MonthDate", GetType(Date))
.Add("OtherInfo", GetType(String))
'other columns...
End With
With dtData.Rows
.Add(#6/1/2011#, "Info")
.Add(#7/1/2011#, "Info")
.Add(#7/1/2011#, "Info")
.Add(#1/1/2012#, "Info")
End With
</code></pre>
<p><strong>This part will loop through the date ranges and generate a <code>DataTable</code> with one blank row per possible date</strong></p>
<pre class="lang-vb prettyprint-override"><code>'get all dates
Dim dtAllTimes As DataTable = dtData.Clone()
Do While startMonth <= endMonth
dr = dtAllTimes.NewRow()
dr("MonthDate") = startMonth
dtAllTimes.Rows.Add(dr)
startMonth = startMonth.AddMonths(1)
Loop
</code></pre>
<p><strong>This part will create a blank <code>DataTable</code> with one date per found value</strong></p>
<pre class="lang-vb prettyprint-override"><code>'get used dates
Dim dtUsedTimes As DataTable = dtData.Clone()
For Each usedDate As Date In
From row As DataRow In dtData.AsEnumerable Select CDate(row("MonthDate")) Distinct
dr = dtUsedTimes.NewRow()
dr("MonthDate") = usedDate
dtUsedTimes.Rows.Add(dr)
Next
</code></pre>
<p><strong>Finally I combine those two tables to get the unused dates and add them onto the original data</strong></p>
<pre class="lang-vb prettyprint-override"><code>'subtract used dates from all dates
Dim unusedDates As IEnumerable(Of DataRow)
unusedDates = dtAllTimes.AsEnumerable.Except(dtUsedTimes.AsEnumerable(), DataRowComparer.Default)
'add subtraction back into all
dtData = dtData.AsEnumerable.Union(unusedDates).CopyToDataTable()
</code></pre>
<p>Any suggestions would be great.</p>
<h2>Update...</h2>
<p>Implementing my own custom comparison class helps to shave off a couple lines of code and processing time by not having to compare every column in the entire row against every other column and also helps skip the step of finding used rows since that was only done to put them into a DataTable that could be used with the Default <code>DataRowComparer</code>.</p>
<p><strong>Here's the custom DataRowComparer</strong></p>
<pre class="lang-vb prettyprint-override"><code>Public Class DataRowDateComparer : Implements IEqualityComparer(Of DataRow)
Public Function Equals(x As DataRow, y As DataRow) As Boolean _
Implements IEqualityComparer(Of DataRow).Equals
Return x("MonthDate") = y("MonthDate")
End Function
Public Function GetHashCode(obj As DataRow) As Integer _
Implements IEqualityComparer(Of DataRow).GetHashCode
Return obj.ToString.GetHashCode
End Function
End Class
</code></pre>
<p><strong>Here's the code after creating a DataTable with every date</strong></p>
<pre class="lang-vb prettyprint-override"><code>'only add rows that aren't already in datatable
dtData = dtData.AsEnumerable _
.Union(dtAllTimes.AsEnumerable, New DataRowDateComparer) _
.CopyToDataTable()
</code></pre>
<p>Also, sorting by MonthDate in a <code>DataView</code> can help view the results more easily
</p>
<pre><code>Dim dv As New DataView(dtData)
dv.Sort = "MonthDate"
</code></pre>
|
[] |
[
{
"body": "<p>You can have fewer lines of code by creating a the list of missing dates in a single Linq query.</p>\n\n<p>The idea is:</p>\n\n<ul>\n<li>Get the list of all dates in the given time period) </li>\n<li>Left-Outer-Join this list with the list of given dates </li>\n<li>Add the missing dates to the original <code>DataTable</code> </li>\n</ul>\n\n<hr>\n\n<pre><code>Dim missingDates = From a in Enumerable.Range(0, Int32.Maxvalue)\n Let c = startMonth.AddMonths(a)\n Take While c <= endMonth 'create list of all dates'\n Group Join d in dtData On c Equals d(\"MonthDate\") Into g = Group\n Where Not g.Any() 'take only the missing ones'\n Select c\n\nFor Each d in missingDates 'and add them to the DataTable'\n dtData.Rows.Add(d, Nothing)\nNext\n</code></pre>\n\n<hr>\n\n<p>Using <code>Union</code> is also fine IMHO, but then the <code>GetHashCode</code> method of your comparer should return the hash code of the value you actually want to compare:</p>\n\n<pre><code>Public Function GetHashCode(obj As DataRow) As Integer _\n Implements IEqualityComparer(Of DataRow).GetHashCode\n Return obj(\"MonthDate\").GetHashCode\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:42:07.327",
"Id": "45495",
"Score": "0",
"body": "That is some cool lookin' linq!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:45:20.130",
"Id": "45496",
"Score": "1",
"body": "@KyleMit That's because the linq query syntax in VB.Net is quite powerfull (more than in C#), supporting `Take` and `Skip` :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:48:14.067",
"Id": "45498",
"Score": "1",
"body": "@KyleMit Also, instead of `a`, `c` and `d` you could also use some proper variable names (e.g. `counter`, `month` and `row`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T09:09:56.767",
"Id": "28916",
"ParentId": "27322",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28916",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T21:07:37.730",
"Id": "27322",
"Score": "1",
"Tags": [
"vb.net",
".net-datatable"
],
"Title": "Adding blank rows for every skipped value in a DataTable"
}
|
27322
|
<p>Ok, So first I must say that everything I know about coding I have learned on my own in my spare time so bear with me if my code is primitive, but please, I am open to any comments to make me better...</p>
<p>Anyway, as for my question. I have an application I am building in C# for .NET Compact Framework (for an HP iPaq) the program's purpose is to act similarly to a Restaurant POS terminal to "ring up" food orders. it has gotten to the point where some of my code is the same line copied god even knows how many times with only a numerical difference between them. here is an example:</p>
<pre><code> private void button9_Click(object sender, EventArgs e)
{
AddItem(buttonNames[0], prices[0]);
}
private void button14_Click(object sender, EventArgs e)
{
AddItem(buttonNames[1], prices[1]);
}
private void button5_Click(object sender, EventArgs e)
{
AddItem(buttonNames[2], prices[2]);
}
private void button10_Click(object sender, EventArgs e)
{
AddItem(buttonNames[3], prices[3]);
}
private void button13_Click(object sender, EventArgs e)
{
AddItem(buttonNames[4], prices[4]);
}
private void button4_Click(object sender, EventArgs e)
{
AddItem(buttonNames[5], prices[5]);
}
</code></pre>
<p>or</p>
<pre><code> button9.Text = buttonNames[0];
button14.Text = buttonNames[1];
button5.Text = buttonNames[2];
button10.Text = buttonNames[3];
button13.Text = buttonNames[4];
button4.Text = buttonNames[5];
button11.Text = buttonNames[6];
button15.Text = buttonNames[7];
button7.Text = buttonNames[8];
button12.Text = buttonNames[9];
button16.Text = buttonNames[10];
button8.Text = buttonNames[11];
</code></pre>
<p>I KNOW there are easier ways to do a lot of the code I have written, I just don't know how to do it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T21:28:03.277",
"Id": "42556",
"Score": "0",
"body": "You could organize the buttons by keeping them in an array or list and then create a generic click event. If you have certain data associated with the buttons, such as prices and names, you could create a class which has properties that could store this information instead of keeping it separate. `Buttons[0].name`, `Buttons[0].price`, `Buttons[0].buttonControl`, etc."
}
] |
[
{
"body": "<h2>Clear your namings</h2>\n\n<p><code>button9.Text = buttonNames[0];</code> should be <code>button0.Text = buttonNames[0];</code>\nThis is also applies to your prices array.</p>\n\n<h2>One event handler method</h2>\n\n<p>Create one event handler which is subscribed on every buttons' <code>OnClick</code> and this method should parse the sender name and look for the button's index. If you can read the index number (from the above example the 0) then you can say:</p>\n\n<pre><code>AddItem(buttonNames[parsedIndex], prices[parsedIndex]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:13:49.240",
"Id": "42529",
"Score": "0",
"body": "Yes, I agree about the buttons being named better, however, I keep moving the buttons on the form (using visual studio) and it is (currently) easier to get the basics worked out in terms of having it work, then when it is finally the way I want it then fixing that up and doing a \"re-write\" that is easier to follow."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T07:30:21.327",
"Id": "27337",
"ParentId": "27335",
"Score": "6"
}
},
{
"body": "<p>Even though the difference is minimal, there IS a difference. So you'll need to make a minimal distinction, depending on the button that was pressed. </p>\n\n<p>What you could do is create a general event for all the buttons and in that event you'll determine the index to be passed to the <code>AddItem()</code> method. The code might look like this:</p>\n\n<pre><code>private void ButtonClick(object sender, EventArgs e)\n{\n Button b = (Button)sender;\n\n switch(b.Name)\n {\n case \"button9\" : AddItem(buttonNames[0], prices[0]); break;\n case \"button14\" : AddItem(buttonNames[1], prices[1]); break;\n case \"button5\" : AddItem(buttonNames[2], prices[2]); break;\n //other buttons...\n }\n}\n</code></pre>\n\n<p>Another solution is to pre-assign the index to the Tag property of your button:</p>\n\n<pre><code>button9.Text = buttonNames[0];\nbutton9.Tag = 0;\n//Same for other buttons\n</code></pre>\n\n<p>This way you can also use a general method like before and use the tag to call the <code>AddItem()</code> method. Like this:</p>\n\n<pre><code>private void ButtonClick(object sender, EventArgs e)\n{\n Button b = (Button)sender;\n int index = Convert.ToInt32(b.Tag);\n AddItem(buttonNames[index], prices[index]);\n}\n</code></pre>\n\n<p>Lastly, if you name your buttons in a different way, it will become even more easy to do this. Place the index to be used in the name of the button and get it from the name in the general event. Example:</p>\n\n<pre><code>//Assignment of the buttons:\nbutton0.Text = buttonNames[0];\nbutton1.Text = buttonNames[1];\nbutton2.Text = buttonNames[2];\n\n//Event:\nprivate void ButtonClick(object sender, EventArgs e)\n{\n Button b = (Button)sender;\n int index = Convert.ToInt32(b.Name.Replace(\"button\", \"\"));\n AddItem(buttonNames[index], prices[index]);\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:22:06.360",
"Id": "42531",
"Score": "0",
"body": "Thanks for this answer! this has many options for me to work with, but now I have another question. another thing I am doing is re-using the same buttons to \"page\" so say clicking one button will swap EVERYTHING about the button, for example on the when I page from one page to the next, the text on the button must change to the text from a different position in buttonNames, and (currently) the handler needs to change to accept that the new index needs to change... is there a way to simplify that?\nThanks again for the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:28:52.050",
"Id": "42534",
"Score": "0",
"body": "and one more thing i should mention is the fact that the reason I am changing handlers (currently) as opposed to something like `AddItem(butonNames[(index+(page*12)), prices[(index+(page*12))]);`\nis because some buttons DO need completely different handlers. or should I just overload AddItems() so that it can somehow accept the different parameters?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T07:39:37.353",
"Id": "27338",
"ParentId": "27335",
"Score": "14"
}
},
{
"body": "<p>If you can, I think the best solution would be to create those buttons from code behind (which is BTW much easier to do in WPF thanks to panels, binding and templates). Something like:</p>\n\n<pre><code>for (int i = 0; i < 6; i++)\n{\n var button = new Button();\n // set the position of the button based on i here\n int iCopy = i; // to make closure work correctly\n button.Click += (s, e) => AddItem(buttonNames[iCopy], prices[iCopy]);\n this.Controls.Add(button); // assumes this is a Form\n}\n</code></pre>\n\n<p>Also, having two arrays with synchronized indexes is a code smell. You should probably have just one array which contains objects with properties <code>ButtonName</code> and <code>Price</code>. Then you could do just <code>AddItem(items[iCopy])</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:40:48.920",
"Id": "42535",
"Score": "0",
"body": "adding the buttons via code is not something I am particularly good at right now, but yes I realize that this is a possible easier solution. I have tried to add some buttons via code and the problems I encountered were 1) These buttons are located on a user control which is on a form. and my buttons always end up in the wrong place! and 2) I don't know (until the array is populated) how many buttons will be used, although never more than 36. the best way that i know how to have 12 buttons and swap the handlers. although if you know of a trick that i could use I am ALWAYS open to learn. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:41:06.543",
"Id": "42538",
"Score": "0",
"body": "@Michael Can't you just create the buttons after the array is populated?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:57:55.193",
"Id": "42541",
"Score": "0",
"body": "Yes, which solves half of the issue, for example: I would have to have it create the first 12 buttons then stop. then if the user pages to the next one over it needs to then remove the old buttons and replace them with buttons using the info from the middle 12 indexes, and then if they page back it needs to start at the beginning again. and the HP Ipaq is easily slowed, so wont having to redraw the buttons after every click basically slow it down immensely?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:14:07.140",
"Id": "42544",
"Score": "0",
"body": "Oh, I guess I didnt mention that only 12 buttons fit per page... guess thats important"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:51:12.687",
"Id": "27357",
"ParentId": "27335",
"Score": "3"
}
},
{
"body": "<p>Here's how you'd do it by using a map. This has several advantage including the ability to support additional buttons and items in a single line of code. The only seemingly repeating code is where you specify the map. </p>\n\n<p>Here we use an object to represent a food item instead of 2 arrays</p>\n\n<pre><code>public class FoodItem\n{\n public String Name { get; set; }\n public double Price { get; set; }\n public override string ToString()\n {\n return Name + \"@\" + Price;\n }\n}\n</code></pre>\n\n<p>Then we use the fooditem in a map with buttons</p>\n\n<pre><code> //Some setup in order to get our buttons all situated. \n private void Form1_Load(object sender, EventArgs e)\n {\n FillButtonMap(); //First load the button map\n SetupButtons(); //Then register the click events to the proper additem call\n }\n\n public Dictionary<Button, FoodItem> ButtonMap = new Dictionary<Button, FoodItem>();\n //Here is where you add more buttons.\n void FillButtonMap()\n {\n ButtonMap.Add(button1, new FoodItem() { Name = \"Taco\", Price = 1.0 });\n ButtonMap.Add(button2, new FoodItem() { Name = \"Burrito\", Price = 2.0 });\n ButtonMap.Add(button3, new FoodItem() { Name = \"Tostada\", Price = 3.5 });\n }\n\n //This part sets the button text properly and registers the click event \n //of the button to add the item \n void SetupButtons()\n {\n foreach (var button in ButtonMap.Keys)\n {\n button.Text = ButtonMap[button].Name; //Set the button text\n var mappedFoodItem = ButtonMap[button]; //get the food item for the button \n button.Click += (s, o) => { AddItem(mappedFoodItem); }; //Set the click event\n }\n }\n\n //Change AddItem to accept a FoodItem instead of String,Number\n void AddItem(FoodItem item)\n { // Your Code Here... }\n</code></pre>\n\n<p>To add Salsa you simply add this line in FillButtonMap...</p>\n\n<pre><code> ButtonMap.Add(button4, new FoodItem() { Name = \"Salsa\", Price = 0.25 });\n</code></pre>\n\n<p>To make this more flexible you'd actually move the FillButtonMap into an external file without having to statically connect them to buttons so you could add more menu items simply by adding them to the text file (or XML, or JSON, or whatever format you want) but that's another topic as well. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T04:31:08.393",
"Id": "42577",
"Score": "0",
"body": "I REALLY want to do this via XML. I feel it would potentially be a ton easier after the initial setup. BUT it seems that the HP Ipaq using .NET CF is a tad bit slow at processing XML files and performance seems to drop significantly when using them... any tips on XML for .NET CF that might help performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T13:43:36.537",
"Id": "42614",
"Score": "0",
"body": "Just load the xml once during load of your application then keep the data in memory. The associations you have will likely take up very little memory. I assume we're talking <100 menu items which likely means <10kb."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T14:32:56.037",
"Id": "42617",
"Score": "0",
"body": "Yeah, I guess if loading it at the start a little delay isn't too bad... Will have to toy with it :)\nThanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T21:05:29.960",
"Id": "27374",
"ParentId": "27335",
"Score": "2"
}
},
{
"body": "<p>All good answers. I'd like to add my two cents to @deepee1's answer.\nIf you keep the FoodItem class he provides (with a constructor), you can create a list of food items and then create everything else with completely DRY code. You can even easily move the definitions out of the code. Not to mention creating n different UI's with the same \"logic\".</p>\n\n<p>Here's what I'd do:\n(Forgive any mistakes, long time since WinForms :) )</p>\n\n<pre><code>private List<FoodItem> foods = new[] {\n new FoodItem(\"Taco\", 1.0),\n new FoodItem(\"Burrito\", 2.0),\n new FoodItem(\"Fajita\", 1.5)\n};\nprivate const int buttonMargin = 5;\n\nprotected void Form_Load(...)\n{\n CreateButtons();\n}\n\nprivate void CreateButtons()\n{\n for(var i = 0; i<foods.Length; i++)\n AddButton(foods[i], i);\n}\n\nprivate void AddButton(FoodItem food, int index)\n{\n var btn = new Button();\n btn.Id = \"Button_\" + i;\n btn.Tag = food;\n btn.Click += FoodClicked;\n btn.Top = btn.Height*index + buttonMargin*index;\n // Whatever initialization code you have\n Controls.Add(btn);\n}\n\nprivate void FoodClicked(object sender, EventArgs e)\n{\n var button = (Button)sender;\n var food = (food)button.Tag;\n // Do whatever with the food..\n}\n</code></pre>\n\n<p>I just re-read some comments and realize you need paging too. Add a private int page, and a private int pagesize, then add the multiplication of those to foods[i] in CreateButtons, and swap foods.Length with pagesize. You can have as big an array as you want then.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:31:29.993",
"Id": "27606",
"ParentId": "27335",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27338",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T06:50:45.957",
"Id": "27335",
"Score": "11",
"Tags": [
"c#",
".net",
"array"
],
"Title": "Repetitive code driving me crazy!"
}
|
27335
|
<p>I'm trying to reduce consecutive elements of array to one, but not for all values like:</p>
<pre><code>{3,0,0,0,3,3,3,0,0,0} => {3,0,3,0}
</code></pre>
<p>but for specific one, in my example 0:</p>
<pre><code>{3,0,0,0,3,3,3,0,0,0} => {3,0,3,3,3,0}
</code></pre>
<p>so only zeros (the threes are intact) are reduced.</p>
<p>I have Java String working code I wrote:</p>
<pre><code>public static String removeConsecutive(String str, char remove) {
char[] chars = str.toCharArray();
int current = 0;
int result = current;
while (current < chars.length) {
if (chars[current] == remove) {
// keep the first occurrence
chars[result++] = chars[current++];
// ignore the others
while (current < chars.length && chars[current] == remove) {
++current;
}
} else {
chars[result++] = chars[current++];
}
}
return new String(chars, 0, result);
}
</code></pre>
<p>and it does the trick:</p>
<pre><code>public static void main(String[] args) {
System.out.println(removeConsecutive("000300300030303330000", '0'));
}
</code></pre>
<p>outputs: <code>0303030303330</code></p>
<p>Can anyone suggest any improvements, since it think the code is not perfect. It's doesn't have to be String in use, but with any other array.</p>
|
[] |
[
{
"body": "<p>You can have the same output with <em>regex</em> , using <code>Arrays.toString(char[])</code>:</p>\n\n<pre><code>System.out.println(\"000300300030303330000\".replaceAll(\"[0]+\", \"0\"));\n</code></pre>\n\n<p>or, with a parameter :</p>\n\n<pre><code>char charToRemove = '0' ;\nSystem.out.println(\"000300300030303330000\".replaceAll(\"[\" + charToRemove + \"]{1,}\", charToRemove + \"\"));\n</code></pre>\n\n<p>or change <code>charToRemove + \"\"</code> in <code>Character.toString(charToRemove)</code> more academic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T09:35:30.063",
"Id": "42496",
"Score": "0",
"body": "`{1,}` is just `+` ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T09:38:35.120",
"Id": "42497",
"Score": "0",
"body": "@fge changed, both works"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T10:20:21.700",
"Id": "42498",
"Score": "0",
"body": "Hi @cl-r, tnx for your answer, but I'm trying to avoid regex and replace / replaceAll methods when removing only one char, since it inefficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T10:33:45.830",
"Id": "42499",
"Score": "0",
"body": "@robosoul It is more efficient to declare `static field Pattern.compile(regex);` and use them as needed ; powerful with complex matches. It would be intresting to compare *regex* and *StringBuilder* response time with many arrays to test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T12:23:05.460",
"Id": "42501",
"Score": "0",
"body": "Nit: When matching a single character `0+` does the same job as `[0]+`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T12:44:59.837",
"Id": "42503",
"Score": "0",
"body": "@l0b0 You are right, but I keep the `[0]+`, more understandable for me when I have to read old regex (perhaps an habit I have to leave)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T09:27:40.343",
"Id": "27340",
"ParentId": "27339",
"Score": "4"
}
},
{
"body": "<p>Another apporach to the <code>removeConsecutive</code> method, using a <code>StringBuilder</code> and <code>String.charAt()</code>:</p>\n\n<pre><code>public static String removeConsecutive(String str, char remove) {\n final StringBuilder sb = new StringBuilder(str.length());\n int i = 0;\n\n while(i < str.length()) {\n if(i == 0 || str.charAt(i) != remove || str.charAt(i) != str.charAt(i-1)) \n sb.append(str.charAt(i));\n i++;\n }\n\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T09:38:31.197",
"Id": "27341",
"ParentId": "27339",
"Score": "3"
}
},
{
"body": "<p>This is another solution:</p>\n\n<pre><code>public static String removeConsecutive(String str, char remove)\n{\n final StringBuilder sb = new StringBuilder(str.length());\n boolean seen = false;\n\n for (final char c: str.toCharArray()) {\n if (c == remove) {\n if (!seen) {\n sb.append(c);\n seen = true;\n }\n continue;\n }\n seen = false;\n sb.append(c);\n }\n\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T09:42:30.630",
"Id": "27342",
"ParentId": "27339",
"Score": "1"
}
},
{
"body": "<p>Here's the same <a href=\"https://stackoverflow.com/a/17078236/45914\">answer</a> that I gave on you Stack Overflow:</p>\n\n<p>Think this is clearer, and does the job:</p>\n\n<pre><code>public static String removeConsecutive(String str, char remove) {\n StringBuilder sb = new StringBuilder();\n for(char c : str.toCharArray()) {\n int length = sb.length();\n if(c != remove || length == 0 || sb.charAt(length - 1) != c) {\n sb.append(c);\n }\n }\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T11:27:34.997",
"Id": "27345",
"ParentId": "27339",
"Score": "1"
}
},
{
"body": "<p>This may be not the most efficient solution but works fine</p>\n\n<pre><code>public static String removeConsecutive(String str, char remove) {\n String result = str;\n String removeAsString = String.valueOf(remove);\n String searchText = removeAsString + removeAsString;\n\n while(result.indexOf(searchText) > -1) {\n result = result.replace(searchtext, removeAsString);\n }\n\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T11:54:22.983",
"Id": "27346",
"ParentId": "27339",
"Score": "1"
}
},
{
"body": "<p>This one came from my friend, sticking to the original char array idea:</p>\n\n<pre><code>private static String removeConsecutive(final String str, final char remove) {\n final char[] chars = str.toCharArray();\n\n char current;\n char previous = 0;\n\n int i = 0, result = 0;\n while (i < chars.length) {\n current = chars[i];\n\n if (current != previous || current != remove) {\n chars[result++] = current;\n }\n\n previous = current;\n ++i;\n }\n\n return new String(chars, 0, result);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T01:26:19.680",
"Id": "27381",
"ParentId": "27339",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27345",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T09:16:07.590",
"Id": "27339",
"Score": "2",
"Tags": [
"java",
"algorithm",
"strings",
"array"
],
"Title": "Remove specific consecutive element in array"
}
|
27339
|
<p>This algorithm is intended to determine the epsilon of a given double precision number. As numbers increase in value, their accuracy decreases. This algorithm will return the smallest increment / decrement possible at any given value.</p>
<p>Given the way floating point numbers are structured, is there logically any situation where this algorithm won't work? It has worked fine for whatever numbers I've thrown at it.</p>
<pre><code>public enum EZeroDirection { TowardsZero, AwayFromZero };
[StructLayout(LayoutKind.Explicit)]
private struct DL
{
[FieldOffset(0)]
internal double D;
[FieldOffset(0)]
internal long L;
}
/// <summary>
/// Returns the dynamic epsilon of this Double. If the value is NaN or ±Inf, or the initial result overflows, the result will be null.
/// </summary>
/// <remarks>See (http://bit.ly/10KS2wo)</remarks>
/// <param name="dir">Determines if the epsilon is calculated from the delta of its next value towards zero or away from zero. Choose the direction
/// the value moves in. Note: EZeroDirection.TowardsZero allows proper processing of Double.MaxValue and Double.MinValue.</param>
/// <returns>Double?</returns>
public static Double? DynamicEpsilon(this Double a, EZeroDirection dir = EZeroDirection.TowardsZero)
{
if (!double.IsNaN(a) && a != double.NegativeInfinity && a != double.PositiveInfinity)
{
DL dl = new DL();
dl.D = a;
dl.L -= ((dir == EZeroDirection.TowardsZero) ? 1 : -1);
if (!double.IsNaN(dl.D))
{
return Math.Abs(a - dl.D);
}
}
return null;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T13:24:13.297",
"Id": "42504",
"Score": "0",
"body": "Can you add an explanation or a link to explain what this is supposed to do? And/or sample input. I get 0 no matter what I pass in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:05:01.697",
"Id": "42508",
"Score": "1",
"body": "How are you inspecting what you get back? try pass in something like 1E+100, which will give you back a large number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:05:46.997",
"Id": "42509",
"Score": "0",
"body": "I ported and adapted this from C, so I don't have a link to how it works (although the remark shows the source of where it came from, which has an extended discussion on the topic)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:37:46.393",
"Id": "42512",
"Score": "0",
"body": "Ah, I'd broken it in adding it to LINQpad. I'm getting results now, although I don't know what they mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:54:00.997",
"Id": "42521",
"Score": "0",
"body": "Why do you need to do this? In most cases, the exact precision of `double` shouldn't matter to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:10:54.997",
"Id": "42524",
"Score": "0",
"body": "In most cases, yes. I have specialized bucketing functions and range processing that requires this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:13:21.643",
"Id": "42525",
"Score": "0",
"body": "This is the C# version of C++'s union, which isn't directly supported by C#. The `FieldOffset` attributes cause `D` and `L` to refer to the same memory location. It seems to work by using the `long` representation to add/subtract one starting from the least significant bit. Maybe you knew all this already. It *seems* like this should always work, but I'm not an IEEE754 expert."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:24:18.127",
"Id": "42527",
"Score": "0",
"body": "@recursive yes, this is what I know. Unfortunately, I'm not an IEEE754 expert either."
}
] |
[
{
"body": "<pre><code>a != double.NegativeInfinity && a != double.PositiveInfinity\n</code></pre>\n\n<p>This could be simplified to just <code>double.IsInfinity(a)</code>. Though as far as I know, it is correct. I was worried that there may be more values representing infinity, like there are for <code>NaN</code>, but that doesn't seem to be the case.</p>\n\n<hr>\n\n<p>Otherwise, your method seems to work to me in all edge cases, including +/-0, <code>double.MaxValue</code> and <code>double.Epsilon</code> (though you should write unit tests for these just in case). In the case of +/-0 and <code>TowardsZero</code>, <code>D</code> will become <code>NaN</code>, so your method returns <code>null</code>, which I think is correct behavior.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T06:40:19.287",
"Id": "42586",
"Score": "0",
"body": "Thanks @svick. I did test all edge cases (except -0, which I don't know how to generate). Thanks for the IsInfinity tip."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T06:58:04.187",
"Id": "42587",
"Score": "0",
"body": "Per this article (http://en.wikipedia.org/wiki/Endianness) one may \"safely assume\" that the endiansess is the same for integers and FP numbers, so I *think* this code should work on both platforms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T09:59:07.090",
"Id": "42604",
"Score": "0",
"body": "@IanC I assumed that IEEE 754 did specify endianness. I removed that part from my answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:26:12.957",
"Id": "27359",
"ParentId": "27344",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27359",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T11:14:03.923",
"Id": "27344",
"Score": "1",
"Tags": [
"c#",
"algorithm",
"mathematics"
],
"Title": "Is this routine for determining the epsilon of a Double 100% valid?"
}
|
27344
|
<p>I am basically looking for Critique on the following code as i know its not the best and i am trying to find a set way of building javascript objects.</p>
<p>Be brutal as you way its a learning tool for me, basically i am pulling in a twitter feed via json and adding it to the dom.</p>
<pre><code>var TwitterTimeline = {
twitterFeed: function (data) {
$.ajax({
url: 'http://example.com/api/twitter/timeline/name/' + data.name,
dataType: 'json',
crossDomain: true,
cache: false,
success: function (items) {
var tweets = "<ul>";
$.each(items, function (i, tweet) {
var parser = new TwitterTimeline.Parser(tweet.text);
parser.linkifyURLs();
parser.linkifyHashTags();
tweets += "<li><h6><a href=''>" + tweet.user.name + "</a></h6>" + parser.getHTML() + "</li>";
if(i === (data.limit - 1)) {
return false;
}
});
tweets += "</ul>";
$(data.id).html(tweets);
}
});
},
Parser: function (text) {
var html = text;
var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
var hashTagRegex = /#([^ ]+)/gi;
this.linkifyURLs = function () {
html = html.replace(urlRegex, '<a href="$1">$1</a>');
};
this.linkifyHashTags = function () {
html = html.replace(hashTagRegex, '<a href="http://twitter.com/#!/search?q=%23$1">#$1</a>');
};
this.getHTML = function () {
return html;
};
}
}
TwitterTimeline.twitterFeed({
id: "#twitter-feed",
name: 'testaccount',
limit: 2
});
</code></pre>
<p>And my html</p>
<pre><code><div id="twitter-feed" class="twitter-feed"></div>
</code></pre>
<p>Any issues or bad practise which i bet there is a lot please let me know. So many different way to do things with javascript i always feel like i am hacking things together without any structure.</p>
<p>Thanks</p>
|
[] |
[
{
"body": "<pre><code> //Let's wrap this module in a closure so we can have a private scope for our\n //module. That way, we don't expose too many globals as well as place too\n //many things in our namespace\n;\n(function (exports) {\n\n //Let's pull out these guys since they are static, and we don't want them\n //get recreated everytime a parse is required.\n var urlRegex = /((ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?)/gi;\n var hashTagRegex = /#([^ ]+)/gi;\n\n //I suggest you use a templating system. In this example, I am using\n //Mustache. As you can see, it's easily readable, where you have an\n //array of tweets, each printing the contained section.\n var feedTemplate = '<ul>{{#tweets}}<li><h6><a href=\"\">{{user.name}}</a></h6>{{parsedHTML}}{{/tweets}}</ul>';\n\n //Now our parser doesn't need to be an object. It could only be a function\n //that returns parsed data. Also, unless parse is required to be public, it\n //should remain inside the scope that requires it. That way, we don't\n //expose too much to our namespace.\n\n function parse(html) {\n return html.replace(urlRegex, '<a href=\"$1\">$1</a>')\n .replace(hashTagRegex,'<a href=\"http://twitter.com/#!/search?q=%23$1\">#$1</a>');\n }\n\n //We move out this function to separate it from the AJAX call. That way,\n //it's not jumbled up with the AJAX code.\n\n function format(data, config) {\n\n //We have an array of twets that we will use later with the templating.\n var tweets = [];\n\n $.each(data, function (i, tweet) {\n //Now, for each tweet retrieved, we parse the text, and reattach it to\n //the tweet object as parsedHTML, which will be used in the template.\n tweet.parsedHTML = parse(tweet.text);\n\n //We then collect the tweets into the array defined earlier.\n tweets.push(tweet);\n\n //We needed that array, so that we won't feed the original array into\n //the template. So here's the break when the limit is reached.\n if(i === config.limit) return false;\n });\n\n //Now, with the template, and our tweet array, we render. The return is\n //an HTML string, which we can then use jQuery to build the elements.\n var html = Mustache.render(feedTemplate, {\n tweets: tweets\n });\n\n $(data.id).html(html);\n }\n\n //We expose our twitterFeed function to our namespace\n exports.twitterFeed = function (config) {\n $.ajax({\n url: 'http://example.com/api/twitter/timeline/name/' + data.name,\n dataType: 'json',\n crossDomain: true,\n cache: false,\n success: function (data) {\n format(data, config);\n }\n });\n }\n\n}(this.TwitterTimeline = this.TwitterTimeline || {}));\n</code></pre>\n\n<p>Minus the comments, this is how it looks:</p>\n\n<pre><code>;(function (exports) {\n var urlRegex = /((ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?)/gi;\n var hashTagRegex = /#([^ ]+)/gi;\n var feedTemplate = '<ul>{{#tweets}}<li><h6><a href=\"\">{{user.name}}</a></h6>{{parsedHTML}}{{/tweets}}</ul>';\n\n function parse(html) {\n return html.replace(urlRegex, '<a href=\"$1\">$1</a>')\n .replace(hashTagRegex,'<a href=\"http://twitter.com/#!/search?q=%23$1\">#$1</a>')\n }\n\n function format(data, config) {\n var tweets = [];\n $.each(data, function (i, tweet) {\n tweet.parsedHTML = parse(tweet.text);\n tweets.push(tweet);\n if(i === config.limit) return false\n });\n var html = Mustache.render(feedTemplate, {\n tweets: tweets\n });\n $(data.id).html(html)\n }\n\n exports.twitterFeed = function (config) {\n $.ajax({\n url: 'http://example.com/api/twitter/timeline/name/' + data.name,\n dataType: 'json',\n crossDomain: true,\n cache: false,\n success: function (data) {\n format(data, config)\n }\n })\n }\n\n}(this.TwitterTimeline = this.TwitterTimeline || {}));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:56:07.997",
"Id": "42514",
"Score": "0",
"body": "I would probably have the model pull the view from the HTML (for example from a <template> tag, or a `<script type='template/Mustache`>`) rather than store it as a string template. Other than that, I think this solution is very nice and solves most of the problems OP's code has. That `$.each` could have been a `$.map`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:12:10.890",
"Id": "42515",
"Score": "0",
"body": "@BenjaminGruenbaum Nice point. But I used a string instead to represent the fact that it is a string. One can easily use `.html()` to pull it out from the HTML, or use AJAX if the template is from another file later on. Also, I think `$.each()` would be better since `return false` will break the loop. In `$.map()`, you can return `null` to remove the item, but the loop will still run through the entire collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:16:11.520",
"Id": "42517",
"Score": "2",
"body": "I've always viewed the fact you can break an `each` by returning false as a bug in the implementation. It was considered, and rejected in the spec when building [native `.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). If you're filtering and then mapping, consider using `.filter` and then `.map`. I think it represents the actual action done much better. Also, `feedTemplate` is _not_ just a string, it's an HTML string. Storing HTML strings in code means not separating your view from your view model, which can get really sucky as you scale."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:49:48.037",
"Id": "42520",
"Score": "0",
"body": "@BenjaminGruenbaum Point taken on the HTML string and code semantics. However, on the performance department, filter+map is slower due to the fact that it equates to running 2 nonbreaking loops, generating at least 2 more objects as seen in [this test](http://jsperf.com/jquery-each-push-vs-filter-map) (Firefox24 and Chromium25 seem to agree)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:54:12.020",
"Id": "42522",
"Score": "1",
"body": "Are we really having a discussion on which is faster? Performance would be meaningless in this case (Or do you intend to run over 30K arrays with 100 elements through it every second?). If you're worried about performance, all three options are _very_ slow compared to a native loop [by at least a factor of 10](http://jsperf.com/jquery-each-push-vs-filter-map/2)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:23:14.750",
"Id": "27353",
"ParentId": "27350",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27353",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T13:53:25.647",
"Id": "27350",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Best practice javascript objects"
}
|
27350
|
<p>Just checking that this shuffling algorithm is suitable. Or maybe there could be improvements?</p>
<pre><code>public static void shuffleArray(Object[] arr, Random rnd){
int lastIndex = arr.length - 1;
for (int i=0; i<=lastIndex; i++){
int k = nextInt(i,lastIndex+1, rnd);
Object a = arr[i];
Object b = arr[k];
arr[i] = b;
arr[k] = a;
}
}
//Returns an integer between start(inclusive) and end(exclusive) [start..end)
public static int nextInt ( int start, int end, Random rnd);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:33:34.260",
"Id": "42511",
"Score": "1",
"body": "Those +1 and -1 hurt my eyes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T15:20:49.220",
"Id": "42519",
"Score": "1",
"body": "Hmm, there is `Collections.shuffle()`, any reason why you don't use that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:05:27.557",
"Id": "42523",
"Score": "0",
"body": "I wish to shuffle an array of `byte`(s). And I believe it will be tedious todo type conversions, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:55:53.343",
"Id": "42528",
"Score": "0",
"body": "http://stackoverflow.com/a/1520212/59087"
}
] |
[
{
"body": "<p>One small thing is during the last iteration of the loop, the last element is swapped with itself.</p>\n\n<p>Why not just use the <code>Collections.shuffle</code> as a guide?</p>\n\n<pre><code>public static void shuffle(List<?> list, Random rnd) {\n int size = list.size();\n if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {\n for (int i=size; i>1; i--)\n swap(list, i-1, rnd.nextInt(i));\n } else {\n Object arr[] = list.toArray();\n\n // Shuffle array\n for (int i=size; i>1; i--)\n swap(arr, i-1, rnd.nextInt(i));\n\n // Dump array back into list\n ListIterator it = list.listIterator();\n for (int i=0; i<arr.length; i++) {\n it.next();\n it.set(arr[i]);\n }\n }\n}\n\nprivate static void swap(Object[] arr, int i, int j) {\n Object tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n</code></pre>\n\n<p>This could be altered to:</p>\n\n<pre><code>public static void shuffleArray(Object[] arr, Random rnd) {\n for (int i=arr.length; i>1; i--) {\n int j = rnd.nextInt(i);\n Object tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:25:51.697",
"Id": "42533",
"Score": "0",
"body": "This is very helpful, I spotted the last element self-swap too. However,`j` in your example is being restricted in a similar way to `k`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:15:41.997",
"Id": "42536",
"Score": "0",
"body": "@Kurent Ah, you're right about `j`, I didn't see that. Nice catch, I'll edit my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:42:51.250",
"Id": "27360",
"ParentId": "27351",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:15:02.733",
"Id": "27351",
"Score": "2",
"Tags": [
"java",
"algorithm",
"random"
],
"Title": "Shuffling algorithm suitable?"
}
|
27351
|
<p><strong>Edit:</strong> Disclaimer: I am new to templates and traits.
I apologize in advance if this is a bad question.</p>
<p>I am refactoring two similar classes with small differences strewn all over them into one template class (or I am trying to anyway).
This is something I just wrote. (I hope I didn't make any mistakes renaming everything.)</p>
<pre><code>// declaration - empty
template <typename SETTINGS>
struct SettingsTraits;
// specialization for type CFoo
template <>
struct SettingsTraits<CFoo>
{
typedef CFooRelated RelatedType;
typedef CAttribute<CFooRelated > & (CDataSource::*AttrGetter)();
static CAttribute<CFooRelated > & (CDataSource::*GetAttr)();
};
SettingsTraits<CFoo>::AttrGetter SettingsTraits<CFoo>::GetAttr = &CDataSource::GetFooAttr;
// specialization for type CBar
template <>
struct SettingsTraits<CBar>
{
typedef CBarRelated RelatedType;
typedef CAttribute<CBarRelated> & (CDataSource::*AttrGetter)();
static CAttribute<CBarRelated> & (CDataSource::*GetAttr)();
};
SettingsTraits<CBar>::AttrGetter SettingsTraits<CBar>::GetAttr = &CDataSource::GetBarAttr;
</code></pre>
<p>So that I can write something like this</p>
<pre><code>CAttribute<SettingsTraits<SETTINGS>::RelatedType> attr = (datasource.*SettingsTraits<SETTINGS>::GetAttr)();
</code></pre>
<p>But now I am wondering if I shouldn't just have created two different structs and passed those as template parameters instead.</p>
<p>I imagine the calling code would end up looking like this:</p>
<pre><code>CAttribute<FooTraits::RelatedType> attr = FooTraits::GetAttr(datasource);
</code></pre>
<p>So probably somewhat cleaner but I haven't tried it so I don't know if it will actually work.
(I should probably replace the function pointer with a simple one line function that calls the appropriate function for each type in any case.)</p>
<p>Which alternative should I chose? What are the benefits/drawbacks of each?</p>
<p>Does it even make sense to have functions in traits? Should I maybe just use free template functions instead?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T22:34:52.283",
"Id": "42707",
"Score": "1",
"body": "Do you think you could prepare a [Short, Self Contained, Correct Example (SSCCE)](http://sscce.org/) (at minimum, something that can be compiled with an [on-line compiler](http://isocpp.org/blog/2013/01/online-c-compilers))? This way it may become easier to compare and illustrate the trade-offs involved in your choices."
}
] |
[
{
"body": "<p>Yes, the <code>std</code> way of doing things in C++ would be to provide static member functions of your traits type. Consider:</p>\n\n<pre><code>// declaration - empty\ntemplate <typename SETTINGS>\nstruct SettingsTraits;\n\n// specialization for type CFoo\ntemplate <>\nstruct SettingsTraits<CFoo>\n{\n typedef CFooRelated RelatedType;\n static CAttribute<RelatedType>& GetAttrFrom(CDataSource& ds) { return ds.GetFooAttr(); }\n};\n\n// specialization for type CBar \ntemplate <>\nstruct SettingsTraits<CBar>\n{\n typedef CBarRelated RelatedType;\n static CAttribute<RelatedType>& GetAttrFrom(CDataSource& ds) { return ds.GetBarAttr(); }\n};\n\ntypedef SettingsTraits<SETTINGS> TRAITS;\nCAttribute<TRAITS::RelatedType> attr = TRAITS::GetAttrFrom(datasource);\n</code></pre>\n\n<p>Notice that this way of doing things doesn't involve global <em>objects</em> or <em>values</em> at all; it's all done entirely within the type system. The compiler can look at the line <code>TRAITS::GetAttrFrom(datasource)</code> and statically know that it's equivalent to <code>datasource.GetFooAttr()</code>, which means the whole thing compiles down to a single <code>call</code> instruction. Your old code would have required a trip to memory in order to load the value of the pointer <code>SettingsTraits<CFoo>::GetAttr</code>.</p>\n\n<p>Rule of thumb: you should never need to <em>construct</em> a type-traits object at all. If you do, you're probably doing it wrong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:54:11.250",
"Id": "37998",
"ParentId": "27361",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:48:22.927",
"Id": "27361",
"Score": "3",
"Tags": [
"c++",
"template",
"template-meta-programming"
],
"Title": "Should I use an object or type as trait?"
}
|
27361
|
<p>I am attempting to write a function to calculate a user's Chinese zodiac sign based on his or her birthday for Drupal.</p>
<p>I originally had a function for calculating based on the Gregorian calendar (1924 = Rat, 1925 = Ox). This was easy to write, but several of my users have complained that the Chinese zodiac is actually based on the lunar calendar, and <a href="https://en.wikipedia.org/wiki/Chinese_zodiac" rel="nofollow">a list of relevant start and end dates can be found here</a>.</p>
<p>I started writing the code as follows. The big problem is that I have an <code>if</code>, <code>else if</code>, and <code>else</code> per year, and at this rate I will have to manually code 100 years worth of birthdays. On the other hand, I'm unsure of how to use a loop to iterate over this, because the day the lunar year starts and ends each year is different. Any insight on how to make this more efficient would be highly appreciated.</p>
<pre><code>function mymodule_calculate_chinese_zodiac($birthdate) {
// Drupal MySQL data looks like this: 1981-07-30 00:00:00
$year = substr($birthdate, 0, 4);
$month = substr($birthdate, 5, 2);
$day = substr($birthdate, 8, 2);
if ($year == 1924) {
if ($month > 2) {
// Rat
$sign = "1";
}
else if (($month == 2) && ($day > 4) {
$sign = "1";
}
else {
// Pig
$sign = "12";
}
}
else if ($year == 1925) {
if ($month > 1) {
// Ox
$sign = "2";
}
else if (($month == 1) && ($day > 23)) {
$sign = "2";
}
else {
$sign = "1";
}
}
else if ($year == 1926) {
if ($month > 2) {
// Tiger
$sign = "3";
}
else if ($month == 2) && ($day > 12) {
$sign = "3";
}
else {
$sign = "2";
}
}
//All years until 2020
return $sign;
}
</code></pre>
|
[] |
[
{
"body": "<p>My PHP is a bit rusty, but I think you could use two-dimensional arrays, maybe a structure like this:</p>\n\n<pre><code>$dates = array( \"1924\" => array( \"month\" => 2, \"day\" => 4),\n \"1925\" => array( \"month\" => 2, \"day\" => 23),\n ... );\n\n$signs = array( \"1924\" => array ( \"beforeSign\" => \"2\", \"afterSign\" => \"1\"),\n ...);\n\nif (($month == $dates[$year][\"month\"] && $day < $dates[$year][\"day\"]) \n || ($month < $dates[$year][\"month\"]))\n{\n $sign = $signs[\"beforeSign\"];\n}\nelse\n{\n $sign = $signs[\"afterSign\"];\n}\n</code></pre>\n\n<p>An ideal solution would not have any arrays with dates; the start and end date of the Chinese new year would be calculated on the fly. As I have not had a chance to look into how to do those calculations, I am showing a simple solution with look-up lists in arrays.</p>\n\n<p>It's possible that the place you found the list of dates might also have the formulae necessary for doing on-the-fly calculations...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:37:44.907",
"Id": "42537",
"Score": "0",
"body": "This means that they would have to maintain a large array of years, months and dates"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:43:01.657",
"Id": "42539",
"Score": "2",
"body": "@jsanc623: Yes, your `sexagenaryToGregorian` is good, but you did not handle the problem of the Chinese year beginning on a date that is not January 1st, which is what the OP was original asking for. There is probably a way to calculate this so that lookup tables aren't needed at all, I just haven't had time to research that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:00:58.583",
"Id": "42542",
"Score": "0",
"body": "Agreed - my code only works for numerical year and doesn't take into account months / dates."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:05:44.947",
"Id": "27365",
"ParentId": "27362",
"Score": "2"
}
},
{
"body": "<p>There's a few ways this could be improved:</p>\n\n<ol>\n<li>Use <code>DateTime</code>'s rather than fiddling with individual date parts.</li>\n<li>Use an array to store the edges between each Chinese year.</li>\n<li>Search through the array until you find a match then return the index of that element mod 12. (plus 1 since you want values ranging from 1 - 12).</li>\n</ol>\n\n<p>I'd recommend something like this:</p>\n\n<pre><code>$target = new DateTime($birthdate);\n\n$dates = array (\n new DateTime('2024-02-05'),\n new DateTime('2025-01-24'),\n new DateTime('2026-02-13'),\n new DateTime('2027-02-02'),\n // all years until 2020\n);\n\nforeach ($array as $i => $value) {\n $diff = $target->diff($value);\n if ($diff->invert == 0) {\n return (string)(($i % 12) + 1);\n }\n}\n</code></pre>\n\n<p>According to the <a href=\"http://www.php.net/manual/en/datetime.diff.php\" rel=\"nofollow\">documentation</a>, as of PHP 5.2.2 you can do this:</p>\n\n<pre><code>foreach ($array as $i => $value) {\n if ($target > diff) {\n return (string)(($i % 12) + 1);\n }\n}\n</code></pre>\n\n<p>You can also use a <a href=\"http://en.wikipedia.org/wiki/Binary_search_algorithm\" rel=\"nofollow\">binary search</a> (since this data is sorted) to speed up the search. My PHP is a bit rusty, so some one else might be able to improve this further, but I think it would look like this:</p>\n\n<pre><code>$min = 0;\n$max = count($dates) - 1;\nwhile ($max >= $min) {\n $mid = (int)(($max + $min) / 2);\n $value = $dates[$mid];\n if ($target < $value) {\n $max = $mid - 1;\n }\n else if ($target > $value) {\n $min = $mid + 1;\n }\n else {\n break;\n }\n}\n\nif ($target > $value) {\n $mid++;\n}\n\nreturn (string)(($mid % 12) + 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T00:44:48.610",
"Id": "42569",
"Score": "0",
"body": "Awesome answer. I chose this one because it required by far the least amount of work to reformat the dates."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:11:05.703",
"Id": "27366",
"ParentId": "27362",
"Score": "2"
}
},
{
"body": "<p>To start, lets look for something that we can loop through. From your link to relevant dates, we can see that the associated animals loop through 12 animals, in order:</p>\n\n<pre><code>Rat\nOx\nTiger\nRabbit\nDragon\nSnake\nHorse\nGoat\nMonkey\nRooster\nDog\nPig\n</code></pre>\n\n<p>After <code>[Pig]</code>, it restarts again with <code>[Rat]</code>. So let's put these into an associative array, with the associated element:</p>\n\n<pre><code>$assocs = array(\n \"Rat\" => \"Yang Wood\", \n \"Ox\" => \"Yin Wood\", \n \"Tiger\" => \"Yang Fire\",\n \"Rabbit\" => \"Yin Fire\", \n \"Dragon\" => \"Yang Earth\", \n \"Snake\" => \"Yin Earth\", \n \"Horse\" => \"Yang Metal\", \n \"Goat\" => \"Yin Metal\", \n \"Monkey\" => \"Yang Water\", \n \"Rooster\" => \"Yin Water\", \n \"Dog\" => \"Yang Wood\", \n \"Pig\" => \"Yin Wood\" )\n);\n</code></pre>\n\n<p>Now, to determine the sexagenary cycle of a gregorian year, the algorightm is as follows:</p>\n\n<pre><code>sCycle = (grego - 3) - (60 X ([(grego - 3)] / 60))\n</code></pre>\n\n<p>So, let's translate that to a PHP function:</p>\n\n<pre><code>function sexagenaryToGregorian($gYear){\n return ($gYear - 3) - (60 * (floor(( $gYear - 3) / 60)));\n}\n</code></pre>\n\n<p>Now, we know that the Sexagenary cycle consists of 60 periods, thus, to determine what animal and element a certain year matches:</p>\n\n<pre><code>$bdayYear = 1989;\n$sYear = sexagenaryToGregorian($bdayYear);\n// $sYear == 6\n</code></pre>\n\n<p>For birth year 1989, sYear should be period 6. Now, let's generate a function that will hold the animal-element array above ($assoc) and contain two loops. The outer loop will decrement through the ceiling of the sexagenarian cycle divided by 12, and the inner loop is a foreach() over the animal-element array. This method is accurate all the way back to 4AD. </p>\n\n<pre><code>function generateAnimal($sexaCycle){\n $assocs = array(\n \"Rat\" => \"Yang Wood\", \n \"Ox\" => \"Yin Wood\", \n \"Tiger\" => \"Yang Fire\",\n \"Rabbit\" => \"Yin Fire\", \n \"Dragon\" => \"Yang Earth\", \n \"Snake\" => \"Yin Earth\", \n \"Horse\" => \"Yang Metal\", \n \"Goat\" => \"Yin Metal\", \n \"Monkey\" => \"Yang Water\", \n \"Rooster\" => \"Yin Water\", \n \"Dog\" => \"Yang Wood\", \n \"Pig\" => \"Yin Wood\"\n );\n\n $i = 1;\n while(ceil($sexaCycle / 12) > 0){\n foreach($assocs as $animal => $element){\n if($i == $sexaCycle)\n return array($animal => $element);\n $i++;\n }\n }\n}\n</code></pre>\n\n<p>Let's give it a few runs:</p>\n\n<pre><code>// Let's find the result for the year 2041\n$result = generateAnimal(sexagenaryToGregorian(2041));\nprint_r($result); // Array ( [Rooster] => Yin Water )\n\n// Let's find the result for the year 4\n$result = generateAnimal(sexagenaryToGregorian(4));\nprint_r($result); // Array ( [Rat] => Yang Wood )\n\n// Let's find the result for the year 1989\n$result = generateAnimal(sexagenaryToGregorian(1989));\nprint_r($result); // Array ( [Snake] => Yin Earth )\n</code></pre>\n\n<p>Looks good to me! Now, if you want to include the dates, that's when you may want to start thinking about just using a database as a static lookup table.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T00:45:16.330",
"Id": "42570",
"Score": "1",
"body": "Unfortunately, I do need the dates. But this is a really informative answer in general, so +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T13:41:15.333",
"Id": "42613",
"Score": "0",
"body": "@PatrickKenny: No problem :) thanks for the +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-31T03:00:15.947",
"Id": "124905",
"Score": "1",
"body": "There's an error in this code. The animal years are on a twelve year cycle, but the elements are only on a ten year cycle. You can't match from one to the other. You can say that in the first year of a sixty year cycle, they will always have the same pairing. But the first year won't match the thirteenth. So 2041 should be Rooster / Yin Metal (not Water)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-31T03:01:05.020",
"Id": "124906",
"Score": "1",
"body": "@Brythan good catch (and a good reason for why unit tests are important :))"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:35:55.317",
"Id": "27367",
"ParentId": "27362",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27366",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:00:10.360",
"Id": "27362",
"Score": "4",
"Tags": [
"php",
"datetime"
],
"Title": "Calculating Chinese zodiac signs based on birthdays"
}
|
27362
|
<blockquote>
<ol>
<li>Each element of the array is a coordinate <code>(x, y)</code>.</li>
<li>Each coordinate has two labels.</li>
</ol>
<p>Goal:
sum the elements that have the same two labels.</p>
</blockquote>
<p>How can this be made faster?</p>
<pre><code>import numpy
from scipy import ndimage
label1 = numpy.array([0, 0, 1, 1, 2, 2])
kinds_of_label1 = 3
label2 = numpy.array([0, 1, 0, 0, 1, 1])
kinds_of_label2 = 2
data = numpy.array([[1, 2], [3, 8], [4, 5], [2, 9], [1, 3], [7, 2]])
data_T = data.view().T
### processing ####
label1_and_2 = label1 * kinds_of_label2 + label2
result = numpy.empty((kinds_of_label1 * kinds_of_label2, 2))
result_T = result.view().T
result_T[0] = ndimage.measurements.sum(
position.T[0], labels=label1_and_2,
index=range(kinds_of_label1 * kinds_of_label2)
)
result_T[1] = ndimage.measurements.sum(
position.T[1], labels=label1_and_2,
index=range(kinds_of_label1 * kinds_of_label2)
)
### output ###
print(result)
# [[ 3. 4.]
# [ 1. 2.]
# [ 8. 15.]
# [ 0. 0.]
# [ 0. 0.]
# [ 1. 6.]]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-04T19:16:34.037",
"Id": "98764",
"Score": "9",
"body": "In your example code, where does `position` come from?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T17:33:18.897",
"Id": "27364",
"Score": "5",
"Tags": [
"python",
"array",
"mathematics",
"numpy"
],
"Title": "Summing 2D NumPy array by multiple labels"
}
|
27364
|
<p>I just want to know if there room for improvement or something I should redo to be better.</p>
<pre><code>var dataCell = new Array();
dataCell[0] = document.getElementById("data0");
dataCell[1] = document.getElementById("data1");
dataCell[2] = document.getElementById("data2");
dataCell[3] = document.getElementById("data3");
dataCell[4] = document.getElementById("data4");
dataCell[5] = document.getElementById("data5");
dataCell[6] = document.getElementById("data6");
dataCell[7] = document.getElementById("data7");
dataCell[8] = document.getElementById("data8");
dataCell[9] = document.getElementById("data9");
var d = new Date();
var transactionNumber;
var post;
var accountId = new Array();
var account = new Array();
var credit = new Array();
var debit = new Array();
function newEntry() {
post = 0;
requestHighTransactionNumber();
dataCell[0].innerHTML = "<td id='date'><div id='year' contenteditable='true'>"+d.getFullYear()+"</div>-<div id='month' contenteditable='true'>"+parseInt(d.getMonth()+1)+"</div>-<div id='day' contenteditable='true'>"+d.getDate()+"</div></td><td id='source' contenteditable='true'></td><td id='account'><div class='accountId' id='accountId0' contenteditable='true'></div>&nbsp;&nbsp;&nbsp;&nbsp;<div class='accountName' id='accountName0' contenteditable='true'></div></td><td class='debit' id='debit0' contenteditable='true'>0.00</td><td class='credit' id='credit0' contenteditable='true' onkeypress='addRow(1);'>0.00</td><div id='transactionNumber' style='visibility:hidden;position: absolute;'>"+transactionNumber+"</div>";
dataCell[1].innerHTML = "";
dataCell[2].innerHTML = "";
dataCell[3].innerHTML = "";
dataCell[4].innerHTML = "";
dataCell[5].innerHTML = "";
dataCell[6].innerHTML = "";
dataCell[7].innerHTML = "";
dataCell[8].innerHTML = "";
dataCell[9].innerHTML = "";
}
function addRow(offset) {
var i = offset;
dataCell[i].innerHTML = "<td></td><td></td><td id='account'><div class='accountId' id='accountId"+i+"' contenteditable='true'></div>&nbsp;&nbsp;&nbsp;&nbsp;<div class='accountName' id='accountName"+i+"' contenteditable='true'></div></td><td class='debit' id='debit"+i+"' contenteditable='true'>0.00</td><td class='credit' id='credit"+i+"' contenteditable='true' onkeydown='addRow("+parseInt(i+1)+");'>0.00</td><div id='transactionNumber' style='visibility:hidden;position: absolute;'>"+transactionNumber+"</div>";
post = i;
}
function genPost() {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var i = 0;
while (i <= post) {
if(document.getElementById("accountName"+i) != null) {
if(document.getElementById("accountId"+i) != null) {
var month = document.getElementById("month").innerHTML;
var day = document.getElementById("day").innerHTML;
if(month < 10) {month = 0+month};
if(day < 10) {day = 0+day};
date = document.getElementById("year").innerHTML+"-"+month+"-"+day;
dateFind = document.getElementById("year").innerHTML+month+day;
account[i] = document.getElementById("accountName"+i).innerHTML;
accountId[i] = document.getElementById("accountId"+i).innerHTML;
source = document.getElementById("source").innerHTML;
debit[i] = document.getElementById("debit"+i).innerHTML;
credit[i] = document.getElementById("credit"+i).innerHTML;
}
}
if (account[i] != "") {
ajaxRequest.open("GET", "post1.php?date="+date+"&accountId="+accountId[i]+"&account="+account[i]+"&source="+source+"&dateFind="+dateFind+"&debit="+debit[i]+"&credit="+credit[i]+"&transactionNumber="+transactionNumber, false);
}
ajaxRequest.send();
i++;
}
}
//Init function for post number.
requestHighTransactionNumber();
function requestHighTransactionNumber() {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
transactionNumber = parseInt(ajaxRequest.responseText)+1;
}
}
ajaxRequest.open("GET", "transactionNumber.php", true);
ajaxRequest.send(null);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:53:02.870",
"Id": "42540",
"Score": "0",
"body": "No, it does not. Sorry, but it looks pretty bad. You're using ids like arrays, editing HTML as strings and so on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:07:16.993",
"Id": "42543",
"Score": "0",
"body": "Figured. How should I do it? I won't lie. I am basically a very *old* rookie who never done much. You know, hobby."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:15:55.010",
"Id": "42545",
"Score": "0",
"body": "JQuery has a lot to offer for an example like this. DOM manipulation and iteration, AJAX abstractions, and browser abstraction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:34:45.683",
"Id": "42546",
"Score": "0",
"body": "I haven't cared for JQuery much, but should I start using that over JS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:38:49.827",
"Id": "42548",
"Score": "0",
"body": "Nothing wrong with using plain JS in my opinion, especially if you don't plan to make very large projects or have to share code with others using jQuery"
}
] |
[
{
"body": "<ol>\n<li><p>Where you have a load of html elements with similar functions it's useful to either include them in one containing element or give them all the same <code>class</code>. Then you can access them in the JavaScript using:</p>\n\n<pre><code>var dataCell = document.getElementsByClassName('dataCells');\n</code></pre>\n\n<p>or </p>\n\n<pre><code>var dataCell = document.getElementById('dataContainer').children;\n</code></pre></li>\n<li><p>You could use <code>for</code> loops to avoid repetition:</p>\n\n<pre><code>for (var i = 1; i < 9; i++) {\n dataCell[i] = '';\n}\n</code></pre></li>\n<li><p>You use a <code>while</code> loop (<code>while (i <= post)</code>) where one would normally use <code>for</code>:</p>\n\n<pre><code>for (var i = 0; i < post; i++) {...\n</code></pre></li>\n<li><p>You could use an Ajax function to avoid repetition of that bit of code:</p>\n\n<pre><code>function getAjaxRequest() {\n var ajaxRequest;\n try {\n // ...\n return ajaxRequest;\n}\n</code></pre>\n\n<p>If you extend your code you will ultimately want a more capable function for controlling ajax requests, in which case look at <a href=\"https://stackoverflow.com/a/16825593/567595\">this Stack Overflow answer</a>. Not using synchronous requests is probably good advice. Also, I think the usual way of dealing with IE is <a href=\"https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started\" rel=\"nofollow noreferrer\">as shown here</a>.</p></li>\n<li><p>It is better to build HTML using <code>createElement</code> and <code>appendChild</code> rather than setting the <code>innerHTML</code>. In particular, using <code>innerHTML</code> to set event handlers will get confusing and unreadable very quickly for code of any complexity. Better to do something like...</p>\n\n<pre><code>var creditTd = document.createElement('td');\ncreditTd.className = 'credit';\ncreditTd.id = 'credit0';\ncreditTd.addEventListener('keypress', function() {\n addRow(1);\n});\ncreditTd.contentEditable = \"true\";\ndataCell[0].appendChild(creditTd);\n</code></pre>\n\n<p>... even though this admittedly takes up a lot more lines. But you can then set up functions to remove any repetitive parts of this code. </p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T00:41:00.817",
"Id": "42568",
"Score": "0",
"body": "Could you explain the first part with how children works? I believe I know how it works, but I just want to verify. I have never used it before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:15:32.377",
"Id": "42629",
"Score": "1",
"body": "`x.children` just gets all the elements contained within an element `x`. It returns them in whatever order they appear in the HTML. Have a look at this http://jsfiddle.net/nBanC/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T07:55:03.140",
"Id": "42728",
"Score": "0",
"body": "Thanks. So it doesn't need an ID or anything? It returns all of them as the first element it detects to the last? In order, not by anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T22:59:00.437",
"Id": "42780",
"Score": "0",
"body": "yep. when you have multiple elements all performing the same function it's better not to give them all individual ids but to find some other way to distinguish them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T06:26:08.637",
"Id": "43150",
"Score": "0",
"body": "Okay thank you. Now I know for future reference. I knew there was a better way, just didn't know what. So if I changed that and a few others things, my code would look better?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:22:22.900",
"Id": "27370",
"ParentId": "27368",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27370",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T18:41:29.517",
"Id": "27368",
"Score": "4",
"Tags": [
"javascript",
"ajax",
"finance"
],
"Title": "Managing debit/credit accounts"
}
|
27368
|
<p>While solving a problem on an online judge, I tried with these two implementations.</p>
<p>These two implementations do the same thing. Task is to report duplicate entry for a given set of data.</p>
<p>Implementation #1 : Converts input data to a <code>String</code> and adds to a <code>HashSet</code>. After all the input is read, appropriate message is displayed.</p>
<pre><code>class Databse2 {
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());//number of test cases
int N=0,R=0,C=1;
while(t-->0){ //while there are more test cases
HashSet<String> set=new HashSet<String>();
StringTokenizer st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
N=Integer.parseInt(st.nextToken());
R=Integer.parseInt(st.nextToken());//Number of Rows of data
}
int ID=0,SC=0;boolean haha=true;
for(int i=0;i<R;i++){ //for number of rows read each record in the row
st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
ID=Integer.parseInt(st.nextToken());
SC=Integer.parseInt(st.nextToken());
}
String key=ID+""+SC;//convert to string,this combo is used to check for duplicates
haha=haha && set.add(key);
}
if(haha)
System.out.println("Scenario #"+C+": possible");
else System.out.println("Scenario #"+C+": impossible");
C++;
}
}
}
</code></pre>
<p><code>Running time = 3.41 sec (for N number of test cases)</code></p>
<p>Implementation #2: Same task is accomplished as in Implementation #1 but in a different way. An object is created based on input type and added to <code>HashSet</code>.</p>
<pre><code>class Database {
private int ID;
private int SC;
public Database(int ID,int SC){
this.ID=ID;
this.SC=SC;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Database) ? ID==((Database)obj).ID:SC==((Database)obj).SC;
}
@Override
public int hashCode() {
return 31*(ID+SC);
}
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
int N=0,R=0,C=1;
while(t-->0){
HashSet<Database> set=new HashSet<Database>();
StringTokenizer st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
N=Integer.parseInt(st.nextToken());
R=Integer.parseInt(st.nextToken());
}
int ID=0,SC=0;boolean haha=true;
for(int i=0;i<R;i++){
st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
ID=Integer.parseInt(st.nextToken());
SC=Integer.parseInt(st.nextToken());
}
haha=haha?set.add(new Database(ID, SC)):false;
}
String str=haha?"Scenario #"+C+": possible":"Scenario #"+C+": impossible";
System.out.println(str);
C++;
}
}
}
</code></pre>
<p><code>Running Time #2 = 2.74 sec (for N number of test cases)</code></p>
<p>What causes implementation #2 to be faster? Is it the <code>hashCode</code> method? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:38:49.123",
"Id": "42547",
"Score": "3",
"body": "I'd say it's the string concatenation in version 1. Not sure though. You may want to give a try at caliper for being sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T23:16:07.710",
"Id": "42565",
"Score": "1",
"body": "Did you do multiple runs of each? If not, i would do that then compare the mean times to each."
}
] |
[
{
"body": "<ol>\n<li><code>String.equals()</code> compare their <code>char[]</code> inside, which is slower than simply compare two <code>int</code>s.</li>\n<li><code>String</code> concatenation is slower than creating a <code>Database</code>.</li>\n<li><code>String.hashcode()</code> is just like its <code>equals</code>.</li>\n</ol>\n\n<p>Note that your implementation of <code>Database.equals</code> is incorrect, though you're lucky this time.</p>\n\n<pre><code>@Override\npublic boolean equals(Object obj) {\n return (obj instanceof Database) && ID == ((Database)obj).ID &&\n SC == ((Database)obj).SC;\n}\n</code></pre>\n\n<p>The <code>hashcode</code> implementation is only a suggestion.</p>\n\n<pre><code>@Override\npublic int hashCode() {\n return 31 * (31 * 17 + ID) + SC;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T06:08:02.543",
"Id": "42583",
"Score": "1",
"body": "`String.hashCode()` uses a precalculated `hashCode` so this is not any slower that comparing integers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T08:01:37.973",
"Id": "42595",
"Score": "0",
"body": "@UwePlonus But it still calculate it once, and because `hashcode` cache the result, I put it at the third cause."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T15:56:13.247",
"Id": "42620",
"Score": "0",
"body": "@johnchen902 thanks for pointing out incorrect `equals` implementation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T03:41:11.403",
"Id": "27389",
"ParentId": "27371",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27389",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T19:28:32.317",
"Id": "27371",
"Score": "1",
"Tags": [
"java",
"performance",
"comparative-review"
],
"Title": "Reporting duplicate entry for a given set of data"
}
|
27371
|
<p>I am working on a way to parse data using xml. </p>
<p>The file that I am given contains lines that look like this:</p>
<pre><code>George | Washington | Carver
</code></pre>
<p>or someone else can send me someting like this</p>
<pre><code>Carver | Washington | George
</code></pre>
<p>And so on...</p>
<p>No matter what the format is, whoever sends me the file will also send me rules on how to parse the file. In the first example, it's First Name | Middle Name | Last Name. And in the second example, it's Last Name | Middle Name | First Name</p>
<p>Instead of writing a special case for each possibility, I created an XML file to describe the meta data.</p>
<pre><code><file>
<first>0</first>
<middle>1</middle>
<last>2</last>
</file>
</code></pre>
<p>For instance, in this case. The tag <code>first</code> corresponds to <code>0</code> indicating that first name occurs at the 0th position.</p>
<p>Intuitively, I thought about creating a dictionary, with the key set to be the tag, and the value to be the text. Like such...</p>
<pre><code> public static IDictionary<string, string> GetLookupTable(string xmlContents)
{
XElement xmlElement = XElement.Parse(xmlContents);
IDictionary<string, string> table = new Dictionary<string, string>();
foreach (var element in xmlElement.Elements())
{
table.Add(element.Name.LocalName, element.Value);
}
return table;
}
</code></pre>
<p>However, I'm not really familiar with .NET implementation of things, which led me to question some stuff. </p>
<ol>
<li><p>Would it be better to just traverse <code>XElement</code> instead of creating a dictionary? I don't think this is a good idea since I believe that <code>XElement</code> traversal may invovle an unordered tree traversal to get what I need. Doing this for each property (I have more than just 3) would be very inefficient. I am just speculating here...</p></li>
<li><p>Is retrieval from <code>dictionary</code> constant time? I know that in Java <code>HashMap</code> has constant get. If that was the case for c# as well, then this would seem like a better route to go as I would just traverse once, and then be able to retrieve whatever I need in constant time. </p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T21:14:17.483",
"Id": "42553",
"Score": "1",
"body": "If you're not going to need to configure anything else, then I think XML is an overkill. A simple text file containing `0 1 2` would suffice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T21:23:11.463",
"Id": "42555",
"Score": "0",
"body": "As an entirely different route, you might want to look at this [FlatFileParser](http://flatfileparser.codeplex.com/) project. It can read the `|`-separated data in directly, with appropriate column names, and stick it into a `DataTable`."
}
] |
[
{
"body": "<p>You can use the order of XML nodes as field order:</p>\n\n<pre><code><importformat>\n <firstname/>\n <middlename/>\n <lastname/>\n</importformat>\n</code></pre>\n\n<p>and parse it like that:</p>\n\n<pre><code>public static string[] GetFieldsOrder(string xmlContents)\n{\n return XElement.Parse(xmlContents)\n .Elements()\n .Select(element => element.Name.LocalName)\n .ToArray();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T09:01:34.217",
"Id": "27399",
"ParentId": "27373",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27399",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T20:20:45.517",
"Id": "27373",
"Score": "1",
"Tags": [
"c#",
"xml"
],
"Title": "Parsing XML in C# .NET"
}
|
27373
|
<p>I'm working on a CMS, currently on being able to create static pages, manage menus etc.
so.. I have This function that reads from the DB and finds all the static pages, and their position in the menu.
I want to know what Do you think. </p>
<pre><code>function update_menu(&$pdo, $filepath){
$qry = "SELECT * FROM pages WHERE top = 1";
$exec = $pdo->query($qry);
$string = "<ul>";
while($row=$exec->fetch(PDO::FETCH_ASSOC)){
$string.= "<li><a href='?page=".$row['id']."'>".$row['title']."</a>";
$qry = "SELECT * FROM pages WHERE parent = ?";
$child_ex = $pdo->prepare($qry);
$child_ex->bindValue(1, $row['id'], PDO::PARAM_INT);
if($child_ex->execute()){
$i=0;
while($child=$child_ex->fetch(PDO::FETCH_ASSOC)){
if($i==0){
$string.="<ul>";
}
$string.="<li><a href='?page=".$child['id']."'>".$child['title']."</a>";
$i++;
}
if($i != 0)
$string.="</ul>";
}
$string.="</li>";
}
$string.="</ul>";
file_put_contents($filepath, $string);
</code></pre>
<p>};</p>
<p>Output html: </p>
<pre><code><ul><li><a href='?page=1'>Page1</a><ul><li><a href='?page=4'>append1</a><li><a href='?page=5'>append2</a></ul></li><li><a href='?page=2'>page2</a><ul><li><a href='?page=6'>append1b</a></ul></li><li><a href='?page=3'>page3</a></li></ul>
</code></pre>
<p><img src="https://i.stack.imgur.com/7ebIS.jpg" alt="SampleOutput"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:14:59.047",
"Id": "42561",
"Score": "0",
"body": "See: http://codereview.stackexchange.com/a/26810/20611"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:25:54.810",
"Id": "42562",
"Score": "1",
"body": "What is the purpose of this CMS? After all, there is a lot of PHP based CMS'es already, so why reinvent another?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:40:00.257",
"Id": "42563",
"Score": "1",
"body": "there's not propose, I like to do my own stuff plus its a good way of learning and gaining experience (Im a Cs student)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T15:40:40.390",
"Id": "66670",
"Score": "0",
"body": "@CarlosArturoAlaniz A quote a wise man once told me \"Why are building your own framework?! Let me guess what you do is too special for one that already exists? No it not, why would you put yourself through what has already been done for you. What ever you build is not special\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:10:12.310",
"Id": "72362",
"Score": "0",
"body": "@SaggingRufus you guys miss some reflexion. Further pushing your point, why do you even speak since what you've just said has already been said so much times, and so much better then you did?"
}
] |
[
{
"body": "<p>I think it overall is good, but there's some minor changes that could still quicken this script, namely using <code>fetchAll</code> and <code>foreach</code> instead of <code>fetch</code> and <code>while</code></p>\n\n<p>using fetchAll will get the values quicker then fetch on every single row. also foreach will prevent you from having to check if you have results, it just won't run if there are not.</p>\n\n<p>also, you prepare the statement multiple times in the huge loop, instead of preparing it outside of the loop and <strong>execute()</strong> it multiple times</p>\n\n<pre><code>function update_menu(&$pdo, $filepath){\n $qry = \"SELECT * FROM pages WHERE top = 1\";\n $exec = $pdo->query($qry)->fetchAll(PDO::FETCH_ASSOC);\n $qryChild = $pdo->prepare(\"SELECT * FROM pages WHERE parent = ?\");\n $string = '<ul>' . \"\\n\";\n foreach($exec as $row)){\n $string.= \"<li><a href='?page=\".$row['id'].\"'>\".$row['title'].'</a>' . \"\\n\";\n $qryChild->execute($row['id']);\n $childs = $qryChild->fetchAll(PDO::FETCH_ASSOC);\n $i=0;\n foreach($childs as $child){\n if($i==0){\n $string.='<ul>' . \"\\n\";\n }\n $string.=\"<li><a href='?page=\".$child['id'].\"'>\".$child['title'].'</a>' . \"\\n\";\n $i++;\n }\n if($i != 0) $string.='</ul>' . \"\\n\";\n $string.='</li>' . \"\\n\";\n }\n$string.='</ul>' . \"\\n\";\nfile_put_contents($filepath, $string);\n</code></pre>\n\n<p>also, adding some <code>\"\\n\"</code> will give some better readability to you html code</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T20:25:37.170",
"Id": "42003",
"ParentId": "27375",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T22:05:58.410",
"Id": "27375",
"Score": "1",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Pages system PHP/SQL"
}
|
27375
|
<p>Previous review of this project:</p>
<p><a href="https://codereview.stackexchange.com/questions/27154/am-i-following-any-bad-practices-in-my-updated-card-and-deck-classes">Card Deck class for a Poker game - version 2</a></p>
<p>This time, I considered combining both classes into one header file so that I can reduce my use of <code>#include</code> and to keep them together. I also did this so that I can define my <code>const std::string</code> variables only once for both classes. However, I decided to try using a <code>namespace</code> for these variables for easier access. It makes more sense (to me) to keep them with <code>Card</code> and let <code>Deck</code> refer to them during the latter's construction, but I'm not sure how to do that.</p>
<p>Is this the proper thing to do, or could something be done differently? Is there a need for <code>extern</code> somewhere? The code below doesn't include class implementations, but I've kept them intact from the linked code.</p>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <iostream>
#include <string>
#include <array>
namespace rs
{
const std::string RANKS = "A23456789TJQK";
const std::string SUITS = "HDCS";
}
class Card
{
private:
unsigned rankValue;
char rank;
char suit;
public:
Card();
Card(char r, char s);
bool operator<(const Card &rhs) const {return (rankValue < rhs.rankValue);}
bool operator>(const Card &rhs) const {return (rankValue > rhs.rankValue);}
bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
friend std::ostream& operator<<(std::ostream &out, const Card &aCard)
{return out << '[' << aCard.rank << aCard.suit << ']';}
};
class Deck
{
private:
static const unsigned MAX_SIZE = 52;
std::array<Card, MAX_SIZE> cards;
int topCardPos;
public:
Deck();
void shuffle();
Card deal();
unsigned size() const {return topCardPos+1;}
bool empty() const {return topCardPos == -1;}
friend std::ostream& operator<<(std::ostream &out, const Deck &aDeck);
};
#endif
</code></pre>
|
[] |
[
{
"body": "<p>Okay, I'm liking this better than <code>namespace</code> and <code>extern</code>. No more global access. I've instead moved the variables into <code>Deck</code> while declaring <code>Card</code> as a <code>friend</code>. These variables are still accessible to <code>Card</code>'s implementation, and <code>main()</code> can no longer see them.</p>\n\n<p><strong>Deck.h</strong></p>\n\n<pre><code>// class Card...\n\n// class Deck:\nfriend class Card;\nprivate:\n static const std::string RANKS;\n static const std::string SUITS;\n</code></pre>\n\n<p><strong>Deck.cpp</strong></p>\n\n<pre><code>const std::string RANKS = \"A23456789TJQK\";\nconst std::string SUITS = \"HDCS\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T02:29:52.457",
"Id": "42571",
"Score": "1",
"body": "`friend` should be a last resort: it really breaks encapsulation badly. In this case, it's not needed. Anything that is `static const` can safely be made `public`, or if you really want, simply make some public static functions to get ranks/suits: `static const std::string& ranks() { return RANKS; }`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T02:43:21.030",
"Id": "42572",
"Score": "0",
"body": "Really? Interesting. I thought member variables shouldn't be made `public`, period. I'll try them both and see which one I like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T02:57:41.437",
"Id": "42573",
"Score": "0",
"body": "Ah yes! This makes sense to me now. I started thinking about `std::string::npos` and, after reading its documentation again, I found out that it too is `static const`. I'm still uncomfortable with data members declared under `public`, so I'm using the public static functions instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T02:04:12.163",
"Id": "27382",
"ParentId": "27379",
"Score": "1"
}
},
{
"body": "<p>Here's my newest solution using Yuushi's advice from my other answer's comments:</p>\n\n<blockquote>\n <p><code>friend</code> should be a last resort: it really breaks encapsulation badly. In this case, it's not needed. Anything that is <code>static const</code> can safely be made <code>public</code>, or if you really want, simply make some public static functions to get ranks/suits: <code>static const std::string& ranks() { return RANKS; }</code>.</p>\n</blockquote>\n\n<p><strong>Deck.h</strong></p>\n\n<pre><code>// class Card:\n\nprivate:\n static const std::string RANKS;\n static const std::string SUITS;\n\npublic:\n static const std::string& ranks() {return RANKS;}\n static const std::string& suits() {return SUITS;}\n\n// class Deck...\n</code></pre>\n\n<p><strong>Card.cpp</strong></p>\n\n<pre><code>const std::string Card::RANKS = \"A23456789TJQK\";\nconst std::string Card::SUITS = \"HDCS\";\n// everything else...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T03:05:36.860",
"Id": "27385",
"ParentId": "27379",
"Score": "3"
}
},
{
"body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Consider using an <code>enum class</code></h2>\n\n<p>Instead of using constructs such as <code>char suit</code>, use the superior safety of an <code>enum class</code>. You can read <a href=\"https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum\">this question</a> for an overview of when to use one, but I think this would be a better way to do things for this case:</p>\n\n<pre><code>enum class suits : char {HEART = 'H', DIAMOND = 'D', CLUB = 'C', SPADE = 'S'};\nenum class ranks : char {ACE=1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, \n EIGHT, NINE, TEN, JACK, QUEEN, KING };\n</code></pre>\n\n<p>This allows the small storage size of a <code>char</code>, the convenience of an <code>enum</code> and the type-safety of a <code>class</code>.</p>\n\n<h2>Force only valid cards to be created</h2>\n\n<p>With the existing default constructor, and with the constructor that takes arguments, any enforcement on validity of initialized values becomes part of the detail of the constructor rather than part of the interface. By using the <code>enum class</code> types mentioned above, we can make it very clear from the interface that it's not going to be possible to create invalid cards:</p>\n\n<pre><code>Card(ranks r, suits s);\n</code></pre>\n\n<h2>Delete unhelpful autogenerated operators</h2>\n\n<p>Duplicating cards will get you kicked out of most casinos. It's probably better to avoid such trouble before it begins by making it a little harder to do:</p>\n\n<pre><code>Card() = delete;\nCard(Card&) = delete;\n</code></pre>\n\n<h2>Wrap all of your objects inside a name</h2>\n\n<p>Rather than putting just the constants in a namespace, put your whole interface into a namespace. In some future use in which your code is used within an electronic poker game cruise ship simulator, your <code>Card</code> could then be distinguished from a circuit <code>Card</code> that might be part of the electronic game classes, and your <code>Deck</code> could be distinguished from the <code>Deck</code>s of a cruise ship.</p>\n\n<h2>Reconsider your class design</h2>\n\n<p>The <code>Deck</code> class is really just a collection of <code>Card</code> objects. While you may have ideas on how to use your <code>Deck</code> class, it's very likely that you're going to want to have many other kinds of <code>Card</code> collections such as <code>Hand</code> or <code>DiscardPile</code> or <code>Shoe</code> (if you're simulating casino blackjack). In addition, even the notion of <code>Deck</code> can change if you're using it for, say, Pinochle which uses a 48-card deck rather than a 52-card deck. For that reason, it may be better to define a generic <code>Card</code> collection and then specialize that for the various uses. </p>\n\n<h2>Reconsider your comparison operators</h2>\n\n<p>The comparison operators for the <code>Card</code> class may well be valid for your particular use, in which case, you should certainly use them, but comparisons and relative valuations tend to change by the particular rules of each card game. In some games the Ace is low, and in others high. In some, such as blackjack, it can take on the values of 1 or 11. For that reason, it is likely that the comparison operators are likely to need to be changed. This suggests that they could be made virtual so that derived <code>Card</code> classes can override them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-09T00:59:48.520",
"Id": "104183",
"ParentId": "27379",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "104183",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T00:08:25.313",
"Id": "27379",
"Score": "6",
"Tags": [
"c++",
"classes",
"playing-cards"
],
"Title": "Deck and Card classes and member-accessing with one header"
}
|
27379
|
<p>I have these two functions and I was just wondering if there is any way to shorten the line of code with the many && statements. Shortening of the rest of the code would be cool too, but it's not necessary. I'm trying to learn if there is a better way to accomplish this though. </p>
<pre><code># Accepts two stroks and determines if they overlap with one another
def overlap? stroke1, stroke2
min_x = 0
max_x = 1
min_y = 2
max_y = 3
bounds1 = get_bounds stroke1
bounds2 = get_bounds stroke2
return true if (bounds1[max_x] >= bounds2[min_x]) && (bounds1[max_y] >= bounds2[min_y]) && (bounds2[max_x] >= bounds1[min_x]) && (bounds2[max_y] >= bounds1[min_y])
return false
end
# Returns an array of bounds [x_min, x_max, y_min, y_max] for the stroke
def get_bounds stroke
# Arrays for storing x and y values for the stroke currently being inspected
xvals = Array.new
yvals = Array.new
stroke.each_slice(3) do |point|
xvals.push(point[0])
yvals.push(point[1])
end
# A temporary array that stores the min/max x/y for the stroke being inspected
bounds = Array.new
bounds << xvals.min << xvals.max << yvals.min << yvals.max
return bounds
end
</code></pre>
<p>I actually did not write this code, but I offered to clean it up and I came upon this and thought that there was probably a better way.</p>
|
[] |
[
{
"body": "<p>The code in the if is duplicate, so we can extract it to a method that I will call gte (greater than or equal). The maxs and mins values are used at this comparison, so they will be moved to the new method too:</p>\n\n<pre><code>def gte(bounds1, bounds2)\n min_x, max_x, min_y, max_y = 0, 1, 2, 3\n\n bounds1[max_x] >= bounds2[min_x] && bounds1[max_y] >= bounds2[min_y]\nend\n</code></pre>\n\n<p>The content in the if expression changes to:</p>\n\n<pre><code>gte(bounds1, bounds2) && gte(bounds2, bounds1)\n</code></pre>\n\n<p>But the <code>if</code> is not necessary because this expression already returns a boolean value, then we will return it directly. The keyword <code>return</code> is not required, then the method <code>overlap?</code> code looks like this:</p>\n\n<pre><code>def overlap?(stroke1, stroke2)\n bounds1 = get_bounds stroke1\n bounds2 = get_bounds stroke2\n\n gte(bounds1, bounds2) && gte(bounds2, bounds1)\nend\n</code></pre>\n\n<p>Maybe you have a better name than gte, but remember that it must have a meaningful name!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T04:55:07.323",
"Id": "42579",
"Score": "1",
"body": "I would avoid using the `and` operator because it has [different precedence](http://blog.jayfields.com/2007/08/ruby-operator-precedence-of-and-which.html) than `&&` and can behave unpredictably."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T05:23:18.953",
"Id": "42581",
"Score": "0",
"body": "Ah I thought about switching the bounds, but I didn't think about doing both bounds comparisons in one and then switching the bounds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T13:35:30.310",
"Id": "42612",
"Score": "0",
"body": "You're right @nickcoxdotme, thanks for the correction!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T03:18:53.747",
"Id": "27387",
"ParentId": "27383",
"Score": "1"
}
},
{
"body": "<p>I would echo @Juliano's answer. Also, when you're assigning variables like you are in the first method, it helps to use parallel assignment. It also helps to use parentheses for method arguments when using a predicate method. That is the style you see in the <a href=\"https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods/dirty.rb#L87\" rel=\"nofollow\">Rails source</a>. Thus:</p>\n\n<pre><code>def overlap?(stroke1, stroke2)\n min_x, max_x, min_y, max_y = 0, 1, 2, 3\n\n ...\nend \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T04:58:37.257",
"Id": "27390",
"ParentId": "27383",
"Score": "0"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li>Use 2 spaces for indentation.</li>\n<li>Don't write explicit <code>return</code>.</li>\n<li>You <em>may</em> omit parenthesis, but while that's (sometimes) idiomatic in calls, almost nobody does it in signatures (they are harder to read).</li>\n<li><code>overlap?</code> uses constants as indexes, note this is a low-level way (C and alike) of doing things. De-structure the value instead.</li>\n<li><code>return true if condition</code> + <code>return false</code> -> <code>condition</code>. In any case, try not to write with this imperative style, think in terms of expressions.</li>\n<li><code>get_bounds</code> is <em>very</em> convoluted, definitely not the way you do it in Ruby, with a bit of <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming</a> practice you'll see that all this method can be simply written <code>stroke.transpose.map(&:minmax)</code>.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def overlap?(stroke1, stroke2)\n (min_x1, max_x1), (min_y1, max_y1) = get_bounds(stroke1)\n (min_x2, max_x2), (min_y2, max_y2) = get_bounds(stroke2)\n max_x1 >= min_x2 && max_y1 >= min_y2 && max_x2 >= min_x1 && max_y2 >= min_y1\nend \n\ndef get_bounds(stroke)\n stroke.transpose.map(&:minmax)\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T00:19:01.380",
"Id": "43709",
"Score": "0",
"body": "can you explain the `stroke.transpose.map(&:minmax)` line? I really don't understand what is happening there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T12:12:26.800",
"Id": "43734",
"Score": "0",
"body": "@snowe2010: I'll try, but it's a lot easier if you create an example \"stroke\" in irb and run each part of the expression. \"transpose\" makes [[1, 2], [3, 4], [5, 6]] -> [[1, 3, 5], [2, 4, 6]] so now all coordinates of the same axis are together. Now, for each of those arrays, we want the minimum and maximum to get the bounding box, so we map with the \"minmax\" method (which returns pair [min, max]). That returns: [[1, 5], [2, 6]], which is the bounding box you wanted. I know it seems cryptic, but it's the standard mathematical way to do it, nothing fancy."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T16:51:59.487",
"Id": "27406",
"ParentId": "27383",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T02:04:57.593",
"Id": "27383",
"Score": "1",
"Tags": [
"ruby",
"collision"
],
"Title": "Checking whether two strokes overlap"
}
|
27383
|
<p>I wrote a function to find a specific fibonacci number, which runs in <code>O(lg n)</code>. Then I modified it with a template. Though it works, I'm new to template and want to know if I used template correctly. Moreover, I wonder whether someone who has a <code>BigNumber</code> class
can use my function without modify my source code.</p>
<pre><code>#include <iomanip>
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <cstring>
using namespace std;
const int initFibo[5] = {5,3,2,1,1};
template <class U, class V>
void fastFibo(U n, V *tuple) {
assert(n >= 4);
if(n <= 5) {
for(int i = 0; i < 4; i++)
tuple[i] = initFibo[i + (5 - n)];
return;
}
V tmp[4];
fastFibo<U, V>(n / 2 + 1, tmp);
if(n % 2 == 0) { // even
tuple[0] = tmp[0] * tmp[1] + tmp[1] * tmp[2];
tuple[1] = tmp[1] * tmp[1] + tmp[2] * tmp[2];
tuple[2] = tmp[1] * tmp[2] + tmp[2] * tmp[3];
tuple[3] = tmp[2] * tmp[2] + tmp[3] * tmp[3];
} else {
tuple[0] = tmp[0] * tmp[0] + tmp[1] * tmp[1];
tuple[1] = tmp[0] * tmp[1] + tmp[1] * tmp[2];
tuple[2] = tmp[1] * tmp[1] + tmp[2] * tmp[2];
tuple[3] = tmp[1] * tmp[2] + tmp[2] * tmp[3];
}
}
int main(){
unsigned long long tuple[4];
for(int i = 4; i <= 93; i++){
fastFibo<int, unsigned long long >(i, tuple);
cout << "Fibo(" << setw(2) << i << ")=" << setw(20) << tuple[0] << endl;
}
system("pause");
return 0;
}
</code></pre>
<hr>
<p>@Yuushi:</p>
<p><em>"Why does n have to be >= 4?... passing a size and a pointer..."</em> Required by my algorithm, <code>n</code> must be <code>>= 4</code> and <code>tuple</code> is always an array of size 4 (not <code>n</code>) (After invocation <code>tuple</code> will contains 4 fibonacci numbers: the <code>n</code>th, <code>n-1</code>th, <code>n-2</code>th and <code>n-3</code>th). I thought up an idea to create a method like this:</p>
<pre><code>V fastFibo2(U n){
if( n < 4 )
return initFibo[5 - n];
else{
V buf[4];
fastFibo(n, buf)
return buf[0];
}
}
</code></pre>
<p>However if I create it I don't want user to access the ordinary <code>fastFibo</code>. Is it possible or is there a better solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T04:28:28.497",
"Id": "42576",
"Score": "0",
"body": "`using namespace std` is not good to use. [Read this](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) for more information.`system(\"PAUSE\")` is not good, either. Instead, try `std::cin.get()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T15:05:41.700",
"Id": "42618",
"Score": "0",
"body": "@Jamal: Rather than add any command to pause the code. 1) run it in the command line (there it does not matter). 2) Set up your IDE to pause and not shut down the window when the application exits. There should be no reason to add manual pause."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T17:04:01.240",
"Id": "42623",
"Score": "0",
"body": "@LokiAstari: Oh yeah, I forgot to mention that. I also never figured out how to do it with my own IDE (Visual C++ 2010), but I'll find out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T02:14:48.717",
"Id": "423450",
"Score": "0",
"body": "If you don't mind some precision loss, you can use the formula $$F_n = \\frac{\\phi^n - \\hat{\\phi}{}^n}{\\sqrt{5}}.$$"
}
] |
[
{
"body": "<p>As always, <code>using namespace std;</code> is dangerous. In fact, there is a <code>tuple</code> class in C++11, <code>std::tuple</code>. You could very easily have a naming collision here thanks to that.</p>\n\n<p>Why bother using a template for the size if you compare it to an <code>int</code> anyway? It's overkill here. If you do decide to keep it, you should give your template parameters more descriptive names here. <code>T</code> is used when there really is no information about what the possible type could be, as in container classes. However, the value here is going to have to be some kind of integral constant - so call it as such. </p>\n\n<pre><code>template <class IntegralValue, class IntegralValue2> \nvoid fastFibo(IntegralValue n, IntegralValue *tuple)\n</code></pre>\n\n<p>Why does <code>n</code> have to be <code>>= 4</code>? What happens if the user wants the value at 1? This shouldn't throw up an error (or in this case, call <code>abort</code>). This violates the principle of least surprise. </p>\n\n<p>Finally, passing a size and a pointer as parameters is the <code>C</code> way of doing things. In C++, prefer to use the concept of <code>Iterators</code>:</p>\n\n<pre><code>template <typename Iterator>\nvoid fastFibo(Iterator begin, Iterator end)\n</code></pre>\n\n<p>This makes the code below a little bit messier, but doesn't force the user to utilize an array. They could use a <code>std::vector</code> (preferable), or even a <code>list</code>, <code>set</code>, or their own custom data structure to store the results. You can get the distance between two iterators using <code>std::distance</code>.</p>\n\n<p>Edit: There are a couple of solutions to your problem. Using another function which forwards to <code>fastFibo</code> is a reasonable solution here, as it hides the user from some of the implementation details. With templates, it's a bit trickier to hide things (since they need to be in header files). One way is using a namespace like <code>detail</code> (which generally indicates that the things inside it are internal and shouldn't be used directly). Another possibility is to use a <code>class</code> or <code>struct</code> with static member functions: the call then looks very much like using a namespace, but you can utilize access protection modifiers. For example:</p>\n\n<pre><code>struct fib\n{\nprivate:\n const static int initFibo[5] = {5,3,2,1,1};\n\n template <class U, class V> \n static void fastFibo_impl(U n, V *tuple) {\n assert(n >= 4);\n if(n <= 5) {\n for(int i = 0; i < 4; i++)\n tuple[i] = initFibo[i + (5 - n)];\n return;\n }\n V tmp[4];\n fastFibo_impl<U, V>(n / 2 + 1, tmp);\n if(n % 2 == 0) { // even\n tuple[0] = tmp[0] * tmp[1] + tmp[1] * tmp[2];\n tuple[1] = tmp[1] * tmp[1] + tmp[2] * tmp[2];\n tuple[2] = tmp[1] * tmp[2] + tmp[2] * tmp[3];\n tuple[3] = tmp[2] * tmp[2] + tmp[3] * tmp[3];\n } else {\n tuple[0] = tmp[0] * tmp[0] + tmp[1] * tmp[1];\n tuple[1] = tmp[0] * tmp[1] + tmp[1] * tmp[2];\n tuple[2] = tmp[1] * tmp[1] + tmp[2] * tmp[2];\n tuple[3] = tmp[1] * tmp[2] + tmp[2] * tmp[3];\n }\n }\n\npublic:\n\n template <typename U, typename V>\n static V fastFibo(U n){\n if( n < 4 )\n return initFibo[5 - n];\n else {\n V buf[4];\n fastFibo_impl<U, V>(n, buf)\n return buf[0];\n }\n }\n};\n</code></pre>\n\n<p>which is then called by <code>fib::fastFibo<...>(...)</code>.</p>\n\n<p>I also noticed I didn't answer one of your questions. If someone wishes to use this with their own <code>BigNumber</code> class, then their class would need to support <code>operator*</code>, <code>operator+</code>, and <code>operator=</code> (and have those functions perform integer multiplication, integer addition, and integer assignment). This falls under the idea of <code>Concepts</code>, which were slated for inclusion into <code>C++11</code>, but were dropped due to not being ready. Suffice to say, as long as the user has a <code>BigNumber</code> class that \"acts like\" an integer with respect to <code>*</code>, <code>+</code> and <code>=</code>, is <code>DefaultConstructable</code> (since you call the default constructor for <code>V</code> in <code>V buf[4]</code>), and has an overload of <code>operator+</code> taking a <code>BigNumber</code> and an <code>int</code>, they could use it in your template without having to touch anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T07:59:36.010",
"Id": "42594",
"Score": "0",
"body": "Can you take a look at my update? I put everything I want to speak there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T08:35:54.307",
"Id": "42597",
"Score": "0",
"body": "@johnchen902 See my edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T05:33:23.283",
"Id": "27394",
"ParentId": "27388",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27394",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T03:21:45.697",
"Id": "27388",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"template"
],
"Title": "O(lg n) algorithm for a fibonacci number with c++ template"
}
|
27388
|
<p>Normally I do this:</p>
<pre><code>if (Animal is Dog)
{
Doc d = (Dog)Animal;
// d. etc..
}
else if (Animal is Cat)
{
Cat c = (Cat)Animal;
// c. ....
}
</code></pre>
<p>Is this a good way or are there better ways to implement this code above (performance, ...) ?</p>
<p>Should it be like this?:</p>
<pre><code>Dog d = Animal as Dog;
if (d != null;)
{
// d. etc..
}
else if (Animal is Cat)
{
Cat c = (Cat)Animal;
// c. ....
}
</code></pre>
<p>Or maybe like this?:</p>
<pre><code>Dog d = Animal as Dog;
Cat c;
if (d != null;)
{
// d. etc..
}
else if ((c = Animal as Cat) != null)
{
// c. ....
}
</code></pre>
<p>Or maybe something else?</p>
|
[] |
[
{
"body": "<p>This question is better suited for <a href=\"https://softwareengineering.stackexchange.com/\">Programmers Stack Exchange</a> than Code Review...</p>\n\n<p>To answer your question - if you do evaluations like that it means that most likely you have a design issue at the first place. In most cases you should not branch your logic based on specific type you're working with, since it breaks <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow noreferrer\">Open/Closed principle</a> and <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov substitution principle</a>. \nEither your class should be a generic class accepting type of the animal to work with, or there must be a virtual method on <code>Animal</code> that should be overridden in <code>Cat</code> and <code>Dog</code>, or something else, depending on specifics of your case.</p>\n\n<p>In most cases the <code>is</code>/<code>as</code> checks are used to check whether a certain object supports an interface or well-known behaviour like:</p>\n\n<pre><code>object message = ....;\nif (message is IEnumerable) //now we know that we can iterate on it\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int Count(this IEnumerable source) //\"simplified\" version of LINQ's extension method\n{\n ICollection collection = source as ICollection;\n if (collection != null)\n return collection.Count;\n\n int count = 0;\n foreach (var element in source)\n count++;\n\n return count;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T09:07:49.903",
"Id": "42600",
"Score": "0",
"body": "asked the question also on Programmers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T08:25:59.977",
"Id": "27397",
"ParentId": "27395",
"Score": "5"
}
},
{
"body": "<p>I agree with almaz' answer that this is likely an architectural problem. But assuming it's not, I would do something like this.</p>\n\n<pre><code>Dog dog = animal as Dog;\nif(dog != null)\n{\n DoDogStuff(dog);\n return;\n}\n\nCat cat = animal as Cat;\nif(cat != null)\n{\n DoCatStuff(cat);\n return;\n}\n</code></pre>\n\n<p>The is keyword casts the object to the type you're checking against in order to do the check, then you have to cast it again. The as keyword does the cast only once, then you have to do a null check which is slightly faster. However if you're optimizing for performance this is probably the wrong place to start. These are very small optimizations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T03:46:10.417",
"Id": "27424",
"ParentId": "27395",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27397",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T07:32:23.417",
"Id": "27395",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Best way to check for specific types"
}
|
27395
|
<p>Lets say I build functions.php and I have 3 functions inside of it that I use. Lets say that I build a 4th function, but what I really want to do is simply put the instructions of function 4 into function 1 for example. Is there anything wrong with this?</p>
<p>Consider my example here, where I have included a function inside of a function. I am aware that the variables inside of a function are local, and that you cannot call a variable inside a function outside of it, however I have tested this with a simple echo test and it seems to work. Is there anything wrong with doing this? If so, can you explain how you might go about doing this generally? You do not have to be specific. </p>
<p>functions.php</p>
<pre><code>function validate_registration($password, $confirmpassword, $email) {
if ((empty($email)) || (empty($password)) || (empty($confirmpassword))) {
registration_form();
echo "Please enter the required information:";
}
elseif ((filter_var($email, FILTER_VALIDATE_EMAIL)) && ($password == $confirmpassword)) {
input_registration($email, $password);
}
elseif ((filter_var($email, FILTER_VALIDATE_EMAIL)) && ($password !== $confirmpassword)) {
registration_form();
echo "Your password does not match!";
}
else {
registration_form();
echo "You have not entered a valid email address!";
}
</code></pre>
<p>}</p>
<p>the input_registration function:</p>
<pre><code>function input_registration ($email, $password) {
$email_clean = htmlspecialchars($email);
$password_clean = htmlspecialchars($password);
$hash = md5($password_clean);
$db = new PDO("mysql:host=localhost;dbname=users", "root", "")
$statement = $db->prepare("INSERT into userinfo(email, hash) VALUES (:email, :hash)")
//continue with inputting info into database
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T07:48:12.963",
"Id": "42593",
"Score": "1",
"body": "Off-topic, but an important sidenote: don't use MD5 for password hashing. Use Bcrypt, Scrypt, or PBKDF2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T08:06:30.370",
"Id": "42596",
"Score": "0",
"body": "Show this simple echo test please"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T22:24:23.630",
"Id": "42641",
"Score": "0",
"body": "When I say simple echo test, I mean to say that if everything else is working properly and the logic works its way out correctly then the end result is just an command like echo \"Looks good\" instead of continuing with an SQL command I haven't written yet."
}
] |
[
{
"body": "<p>It is absolutely ok to call functions from other functions. There is nothing wrong with that. However, there's room for improvements in your code.</p>\n\n<p><strong>function.php</strong>:</p>\n\n<ol>\n<li>There is no need to put simple expressions within parenthesis in your conditions.</li>\n<li><p>The order of your conditions is irritating (negative, positive, negative, negative). Group them properly. That also helps to simplify the conditions.</p>\n\n<pre><code>function validate_registration($password, $confirmpassword, $email)\n{\n if (empty($email) || empty($password) || empty($confirmpassword)) {\n registration_form();\n echo \"Please enter the required information:\";\n } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {\n registration_form();\n echo \"You have not entered a valid email address!\";\n } elseif ($password !== $confirmpassword) {\n registration_form();\n echo \"Your password does not match!\";\n } else {\n input_registration($email, $password);\n }\n}\n</code></pre></li>\n</ol>\n\n<p><strong>input_registration</strong>:</p>\n\n<ol>\n<li>Escape values on <strong>output</strong> using the right escaping function. Since you use prepared statements, no extra escaping is needed for the database.</li>\n<li><p>Create the database connection in central place, so you don't have to change several files and functions, if the database (or your password) changes.</p>\n\n<pre><code>function input_registration($db, $email, $password)\n{\n $hash = md5($password); // Consider using a better hash algorithm\n $statement = $db->prepare(\"INSERT INTO userinfo(email, hash) VALUES (:email, :hash)\");\n\n // Continue with inputting info into database\n}\n</code></pre></li>\n</ol>\n\n<p>Of course you have to change <code>validate_registration</code> to support the injection of the database dependency.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T21:39:59.157",
"Id": "42640",
"Score": "0",
"body": "Thanks, I did not know you could use the negative logic for a filter, putting ! in front of a filter. The reason for my poor logic was because I did not know that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T17:15:55.250",
"Id": "27407",
"ParentId": "27396",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27407",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T07:43:25.813",
"Id": "27396",
"Score": "1",
"Tags": [
"php"
],
"Title": "Building functions.php"
}
|
27396
|
<p>I had already <a href="https://codereview.stackexchange.com/questions/26143/email-report-generation-from-database">posted a question</a> about the one I am asking right now.</p>
<p>To quickly revisit the scenarios:</p>
<p>I am trying to generate reports which involve fetching data from a DB, writing data to a CSV file, and sending email. I am pulling data for all the reports in the same format since I wanted to keep the DAO layer and CSV-writing independent of a particular report. The problem I am facing now is that most of the logic is the same for all reports. I still have different classes for different reports. Of course, there are some customizations there, but in different services.</p>
<p><strong><code>ReportInterface</code> where I have two methods:</strong></p>
<pre><code>/**
* This interface should be implemented by the report programs.
*/
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import com.aig.dtc.report.batch.exception.SystemException;
public interface ReportsInterface {
public String[] execute(String startDate,String endDate,String reportType) throws IOException,SQLException,Exception;
/**
* called after execute.
*/
public String getMailContent(boolean singleDate,String startDate,String endDate) throws SystemException, ParseException;
}
</code></pre>
<p><strong>RequestCallReport</strong></p>
<pre><code>import java.io.IOException;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Map;
import java.util.TreeMap;
public class RequestCallReport implements ReportsInterface {
private static final String STILD = "~";
private Map<Integer, TreeMap<String,String>> callMeReportData =null;
String dateTimeStamp;
public String[] execute(String startDate, String endDate,String reportType) throws IOException,SQLException,Exception{
String[] details= new String[5];
ReportDao reportDao = new ReportDao();
Object[] reportDetails = reportDao.getDataForRepot(startDate,
endDate,reportType);
callMeReportData = (Map<Integer, TreeMap<String,String>>) reportDetails[0];
CsvWriter csvWriter = new CsvWriter();
setCallMeReportData(callMeReportData);
String[] fileName=csvWriter.writeDetailsToFile(reportType, callMeReportData,startDate,endDate);
for (int i = 0; i < fileName.length; i++) {
details[i]=fileName[i];
}
details[3]=(String)reportDetails[1];
details[4]=(String)reportDetails[2];
dateTimeStamp=fileName[2];
return details;
}
public String getMailContent(boolean singleDate,String startDate,String endDate) throws SystemException, ParseException{
// only this method has some diiferent logic in few reports
}
public Map<Integer, TreeMap<String, String>> getCallMeReportData() {
return callMeReportData;
}
public void setCallMeReportData(
Map<Integer, TreeMap<String, String>> callMeReportData) {
this.callMeReportData = callMeReportData;
}
}
</code></pre>
<p><strong><code>RequestLeadReport</code></strong></p>
<pre><code>import java.io.IOException;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Map;
import java.util.TreeMap;
public class RequestLeadReport implements ReportsInterface {
private static final String STILD = "~";
private Map<Integer, TreeMap<String,String>> callMeReportData =null;
String dateTimeStamp;
public String[] execute(String startDate, String endDate,String reportType) throws IOException,SQLException,Exception{
String[] details= new String[5];
ReportDao reportDao = new ReportDao();
Object[] reportDetails = reportDao.getDataForRepot(startDate,
endDate,reportType);
callMeReportData = (Map<Integer, TreeMap<String,String>>) reportDetails[0];
CsvWriter csvWriter = new CsvWriter();
setCallMeReportData(callMeReportData);
String[] fileName=csvWriter.writeDetailsToFile(reportType, callMeReportData,startDate,endDate);
for (int i = 0; i < fileName.length; i++) {
details[i]=fileName[i];
}
details[3]=(String)reportDetails[1];
details[4]=(String)reportDetails[2];
dateTimeStamp=fileName[2];
return details;
}
public String getMailContent(boolean singleDate,String startDate,String endDate) throws SystemException, ParseException{
// only this method has some diiferent logic in few reports
}
public Map<Integer, TreeMap<String, String>> getCallMeReportData() {
return callMeReportData;
}
public void setCallMeReportData(
Map<Integer, TreeMap<String, String>> callMeReportData) {
this.callMeReportData = callMeReportData;
}
}
</code></pre>
<p>I have at least 6 such reports. As of now, only <code>getMailContent</code> has changes but execution remains the same.</p>
<p>I have this code to fetch data from a DB. I am using the same code for all the reports.</p>
<p><strong><code>ReportDao</code></strong></p>
<pre><code>import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class ReportDao {
public RConnection connection = new RConnection();
public enum ReportType{CALLME_REPORT,LEADGEN_REPORT};
public final static int NO_OF_RECORDS=6;
public Object[] getDataForRepot(String startDate, String endDate,String reportType) throws Exception {
BatchJLogger.logMessage(" Started Execution of method getDataForRepot " );
ResultSet rs = null;
Statement stmt = null;
CallableStatement cstmt = null;
Object[] details = new Object[3];
try {
stmt = connection.getDBConnection().createStatement();
Object[] reportDetails = getReportRecords(cstmt,startDate,endDate,reportType);
rs = (ResultSet)reportDetails[0];
Map<Integer, TreeMap<String,String>> values= getFormattedData(rs);
details[0]=values;
details[1]=reportDetails[1];
details[2]=reportDetails[2];
BatchJLogger.logMessage(" No of records fetched "+values.size() );
BatchJLogger.logMessage(" End Execution of method getDataForRepot " );
return details;
} finally {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
/*if(cstmt!=null){
cstmt.close();
}*/
connection.close();
BatchJLogger.logMessage(" End Execution of method getDataForRepot " );
}
}
public Object[] getReportRecords(CallableStatement cstmt,String startDate, String endDate,String reportType)
throws SQLException,Exception {
Object[] queryValues = new Object[3];
ResultSet rs = null;
try{
BatchJLogger.logMessage(" Started Execution of method getReportRecords ");
String procedure = "{call GET_DAILY_RPT_REC (?,?,?,?,?,?)}";
cstmt = connection.createCallableStatement(procedure);
int procId=7;
switch (ReportType.valueOf(reportType)) {
case REPORTCALL_REPORT:
cstmt.setInt(1, 7);
break;
case REPORTLEAD_REPORT:
cstmt.setInt(1, 8);
break;
default:
break;
}
if(startDate!=null){
cstmt.setTimestamp(2, BatchJUtil.convertToTimeStamp(startDate,true));
cstmt.setTimestamp(3, BatchJUtil.convertToTimeStamp(endDate,false));
}else{
cstmt.setTimestamp(2, null);
cstmt.setTimestamp(3, null);
}
cstmt.registerOutParameter(4,
getOracleParamReturnType("CURSOR"));
cstmt.registerOutParameter(5,
java.sql.Types.VARCHAR);
cstmt.registerOutParameter(6,
java.sql.Types.VARCHAR);
cstmt.execute();
rs = connection.getResultSet(cstmt, 4);
System.out.println(" out params form proc");
System.out.println(cstmt.getString(5));
System.out.println(cstmt.getString(6));
Timestamp cronJobStDate=cstmt.getTimestamp(6);
String formattedDate=null;
if(cronJobStDate!=null){
formattedDate=cronJobStDate.toString();
formattedDate=BatchJUtil.convertformat(formattedDate);
}
String changeInStDate=cstmt.getString(5);
queryValues[0]=rs;
queryValues[1]=changeInStDate;
queryValues[2]=cstmt.getString(6);
BatchJLogger.logMessage(" End Execution of method getReportRecords ");
return queryValues;
}catch (Exception e) {
e.printStackTrace();
connection.close();
}
return queryValues;
}
public static int getOracleParamReturnType(String paramName) {
if (paramName == null)
return -1;
Field cursorField;
try {
Class c = Class.forName("oracle.jdbc.driver.OracleTypes");
cursorField = c.getField(paramName);
return cursorField.getInt(c);
} catch (Throwable th) {
th.printStackTrace();
return -1;
}
}
public Map<Integer, TreeMap<String,String>> getFormattedData(ResultSet rs ) throws SQLException, ParseException{
Map<Integer, TreeMap<String,String>> data = new TreeMap<Integer, TreeMap<String,String>>();
List<String> coulmnNames = new ArrayList<String>();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i < columnCount + 1; i++ ) {
coulmnNames.add(rsmd.getColumnName(i)) ;
}
int noOfRecords =0 ;
while (rs.next()) {
TreeMap<String,String> values = new TreeMap<String, String>();
for (String name : coulmnNames) {
if(name.equalsIgnoreCase("Submitted On")){
if(rs.getString(name)!=null){
String submittedOn =rs.getString(name);
values.put(name, submittedOn);
}else{
values.put(name, null);
}
}else{
values.put(name, rs.getString(name));
}
}
data.put(++noOfRecords, values);
}
return data;
}
public void deleteBatchJobRecord(String reportName) throws SQLException{
try {
String deleteRecord = "delete from TBATCH_RUN_LOG where SYSTEM_ID=? and RUN_ID=(Select MAX(RUN_ID) "
+ "from TBATCH_RUN_LOG where SYSTEM_ID=?)";
PreparedStatement pstmt = connection.getDBConnection()
.prepareStatement(deleteRecord);
switch (ReportType.valueOf(reportName)) {
case REPORTCALL_REPORT:
pstmt.setInt(1, 7);
pstmt.setInt(2, 7);
break;
case REPORTLEAD_REPORT:
pstmt.setInt(1, 8);
pstmt.setInt(2, 8);
break;
default:
break;
}
int result = pstmt.executeUpdate();
System.out.println(" record deleted " + result);
} finally {
connection.close();
}
}
}
</code></pre>
<p><strong><code>CsvWriter</code></strong></p>
<pre><code>import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
public class CsvWriter {
private static Map<String,ArrayList<String>> headers = new HashMap<String, ArrayList<String>>();
static{
ArrayList<String> callMe = new ArrayList<String>();
callMe.add("Mobile Phone");
callMe.add("Call Time");
callMe.add("Submitted On");
callMe.add("First Name");
callMe.add("Last Name");
callMe.add("Email");
ArrayList<String> leadGen = new ArrayList<String>();
leadGen.add("Title");
leadGen.add("First Name");
leadGen.add("Last Name");
leadGen.add("Mobile Phone");
leadGen.add("Product Interested");
leadGen.add("Submitted On");
headers.put("CALLME_REPORT", callMe);
headers.put("LEADGEN_REPORT", leadGen);
}
private FileWriter fileWriter = null;
private String folderName = null;
public enum ReportType{CALLME_REPORT,LEADGEN_REPORT};
public FileWriter getFileWriter() {
return fileWriter;
}
public void setFileWriter(FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
final ResourceBundle BUNDLE = ResourceBundle
.getBundle(AppConstants.CONFIG_PATH);
public CsvWriter() {
folderName = BUNDLE.getString("FOLDER_PATH");
}
public String[] writeDetailsToFile(String reportType,Map<Integer, TreeMap<String,String>> values,String startDate,String endDate) throws IOException,Exception {
String filePath=null;
String fileName =null;
String[] details=null;
try{
//BatchJLogger.logMessage(" Started Execution of method writeDetailsToFile " );
BatchJLogger.logMessage(" Started Execution of method openXls " );
details = createFileName(reportType, startDate, endDate);
fileName=details[0];
filePath = folderName + File.separator + fileName;
fileWriter = new FileWriter(filePath);
File f = new File(filePath);
BatchJLogger.logMessage(" file created "+f.exists() );
fileWriter.write("Report Name");
fileWriter.write(",");
switch (ReportType.valueOf(reportType)) {
case CALLME_REPORT:
fileWriter.write("Call Me");
break;
case LEADGEN_REPORT:
fileWriter.write("Lead Gen");
break;
default:
break;
}
fileWriter.write(",");
fileWriter.write("Date ");
fileWriter.write(",");
fileWriter.write(CsvWriter.getCurrentDate());
fileWriter.write("\n");
fileWriter.write("\n");
ArrayList<String> cloumnNames = headers.get(reportType);
int fileHeader = 0;
for (String columnName : cloumnNames) {
fileWriter.write(columnName);
if(fileHeader < cloumnNames.size()){
fileWriter.write(",");
}
fileHeader++;
}
fileWriter.write("\n");
Set<Integer> recordSet = values.keySet();
for (Integer record : recordSet) {
TreeMap<String, String> data = values.get(record);
int columnCount = 0;
for (String columnName : cloumnNames) {
String columnData=data.get(columnName);
if((columnName.equalsIgnoreCase("Mobile Phone")||columnName.equalsIgnoreCase("Submitted On")) && columnData!=null ){
fileWriter.write("'");
}
fileWriter.write(BatchJUtil.checknull(columnData));
if(columnCount < cloumnNames.size()){
fileWriter.write(",");
}
columnCount++;
}
fileWriter.write("\n");
}
}
finally{
fileWriter.flush();
fileWriter.close();
return new String[]{filePath,fileName,details[1]};
}
//BatchJLogger.logMessage(" end of Execution of method writeDetailsToFile " );
}
public String[] createFileName(String reportType,String startDate,String endDate) throws ParseException{
String[] data =null;
String fileName=null;
String toDaysDate=null;
if(startDate!=null && startDate.length()!=0){
startDate=BatchJUtil.convertformat(startDate);
endDate=BatchJUtil.convertformat(endDate);
toDaysDate=startDate+"_To_"+endDate;
}else{
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
String date = dateFormat.format(cal.getTime());
String[] parsedDate = date.split("-");
int numDay = Integer.parseInt(parsedDate[0]);
String month = parsedDate[1];
int numYear = Integer.parseInt(parsedDate[2]);
toDaysDate = BatchJUtil.checkNumber(numDay) + "-"+month+ "-" + BatchJUtil.checkNumber(numYear);
}
switch (ReportType.valueOf(reportType)) {
case CALLME_REPORT:
fileName="reprot_call_"+toDaysDate+".csv";
break;
case LEADGEN_REPORT:
fileName="reprot_lead_"+toDaysDate+".csv";
break;
default:
break;
}
data=new String[]{fileName,toDaysDate};
return data;
}
public static String getCurrentDate(){
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
//cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
public static String getPreviousDate(){
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T09:01:30.520",
"Id": "42599",
"Score": "0",
"body": "Why are your start and end date strings? Java has `Date`... Joda Time has even better (`DateTime`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T09:50:27.067",
"Id": "42602",
"Score": "0",
"body": "they are passed as Strings arguments"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T09:55:30.820",
"Id": "42603",
"Score": "0",
"body": "Yes, but the question is why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T11:19:52.440",
"Id": "42606",
"Score": "0",
"body": "it is passsed form command prompt,later i am converting to date format if there is better way let me know"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T14:22:33.117",
"Id": "42616",
"Score": "0",
"body": "Please, split your code in blocks. It's impossible to read as it's now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T16:21:13.160",
"Id": "42622",
"Score": "0",
"body": "Don't reinvent the wheel: http://opencsv.sourceforge.net/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-04T23:32:30.493",
"Id": "181556",
"Score": "1",
"body": "The title of your post should be the function/purpose of your code."
}
] |
[
{
"body": "<p>This code needs some refactoring. Here are my suggestions:</p>\n\n<p>1) since you have some kinds of reports, which seem to share some common behaviour, you could use a base class and some classical inheritance. So you have to write the execution logic once for all cases, where no change is needed and override in your subclass, where changes are needed. And your interface would be obsolete.</p>\n\n<p>\"startDate\", \"endDate\" and \"reportType\" would be member variables of the class.\nAnd at best start/endDate of some date-type and reportType as an enum.</p>\n\n<p>2) it is bad to gereate new objects in objects. That leads to code, that is hard to test. Instead of </p>\n\n<pre><code>ReportDao reportDao = new ReportDao();\n</code></pre>\n\n<p>you could \"inject\" a Dao via <a href=\"http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/\" rel=\"nofollow\">\"constructor injection\"</a>. If you take step (1) you will have to split your concerns: a) you need an object to represent the report itself and b) you need an object, which creates different kinds of reports. There will be the right place to inject your DAO.</p>\n\n<p>3) What are these details about?</p>\n\n<pre><code>String[] details= new String[5];\n</code></pre>\n\n<p>Will anybody know? Okay, I admit, at least you know. But think of a freshman, new to your code: it will take (too much) time, to get his head around the code.</p>\n\n<p>4) Shorten your methods.</p>\n\n<pre><code>public Object[] getReportRecords(CallableStatement cstmt,String startDate, String endDate,String reportType)\n throws SQLException,Exception {\n Object[] queryValues = new Object[3];\n ResultSet rs = null;\n try{\n BatchJLogger.logMessage(\" Started Execution of method getReportRecords \");\n\n String procedure = \"{call GET_DAILY_RPT_REC (?,?,?,?,?,?)}\";\n cstmt = connection.createCallableStatement(procedure);\n int procId=7;\n switch (ReportType.valueOf(reportType)) {\n case REPORTCALL_REPORT:\n cstmt.setInt(1, 7);\n break;\n case REPORTLEAD_REPORT:\n cstmt.setInt(1, 8);\n break;\n default:\n break;\n }\n if(startDate!=null){\n cstmt.setTimestamp(2, BatchJUtil.convertToTimeStamp(startDate,true));\n cstmt.setTimestamp(3, BatchJUtil.convertToTimeStamp(endDate,false));\n }else{\n cstmt.setTimestamp(2, null);\n cstmt.setTimestamp(3, null);\n }\n cstmt.registerOutParameter(4,\n getOracleParamReturnType(\"CURSOR\"));\n cstmt.registerOutParameter(5,\n java.sql.Types.VARCHAR);\n cstmt.registerOutParameter(6,\n java.sql.Types.VARCHAR);\n cstmt.execute();\n rs = connection.getResultSet(cstmt, 4);\n System.out.println(\" out params form proc\");\n System.out.println(cstmt.getString(5));\n System.out.println(cstmt.getString(6));\n Timestamp cronJobStDate=cstmt.getTimestamp(6);\n String formattedDate=null;\n if(cronJobStDate!=null){\n formattedDate=cronJobStDate.toString();\n formattedDate=BatchJUtil.convertformat(formattedDate);\n }\n String changeInStDate=cstmt.getString(5);\n queryValues[0]=rs;\n queryValues[1]=changeInStDate;\n queryValues[2]=cstmt.getString(6);\n\n BatchJLogger.logMessage(\" End Execution of method getReportRecords \");\n return queryValues;\n }catch (Exception e) {\n e.printStackTrace();\n connection.close();\n }\n\n return queryValues;\n\n\n } \n</code></pre>\n\n<p>That is hard to read.</p>\n\n<p>And unless your app is a console app:</p>\n\n<pre><code>System.out.println(\" out params form proc\");\nSystem.out.println(cstmt.getString(5));\nSystem.out.println(cstmt.getString(6));\n</code></pre>\n\n<p>there should be no reference to a console at all.</p>\n\n<p>5) Perhaps it makes sense to outsource the writing of a report to a report writing class. There you have a <em>List</em> of <em>Writer</em> which take a <em>Report</em> as an input and produce the wanted output. </p>\n\n<pre><code>public class ReportWriter{\n public List<ReportOuptput> = new ArrayList<ReportOuptput>();\n // ...\n public void addOutputChannel(ReportOutput ... channels);\n // ...\n public void writeReport(Report report);\n}\n</code></pre>\n\n<p>6) Use better naming: It is hard to understand, what something like</p>\n\n<pre><code>Map<Integer, TreeMap<String, String>>\n</code></pre>\n\n<p>is. Okay: A mapping of integer values to a treemap, which maps one string to another. Let's have a look deeper in the code:</p>\n\n<pre><code>public Map<Integer, TreeMap<String,String>> getFormattedData(ResultSet rs ) throws SQLException, ParseException{\n Map<Integer, TreeMap<String,String>> data = new TreeMap<Integer, TreeMap<String,String>>();\n</code></pre>\n\n<p>It is \"data\"... And</p>\n\n<pre><code>TreeMap<String,String> values = new TreeMap<String, String>();\n</code></pre>\n\n<p>That are values.\nUp to this point, one has no idea, what this code is about. If you are dealing with books, you have a book, which consists of pages, which have lines, which have characters. So that would be the way to go.</p>\n\n<p>7) What does the following code do?</p>\n\n<pre><code>for (String name : coulmnNames) {\n if(name.equalsIgnoreCase(\"Submitted On\")){\n if(rs.getString(name)!=null){\n String submittedOn =rs.getString(name);\n values.put(name, submittedOn); \n }else{\n values.put(name, null);\n }\n\n }else{\n values.put(name, rs.getString(name)); \n }\n\n}\n</code></pre>\n\n<p>Effectively:</p>\n\n<pre><code>String submittedOn =rs.getString(name);\nvalues.put(name, submittedOn);\n\nvalues.put(name, null);\n</code></pre>\n\n<p>In case of \"null\", it puts \"null\" in there.\nAnd at least:</p>\n\n<pre><code>values.put(name, rs.getString(name));\n</code></pre>\n\n<p>So if I am getting it right: it puts, what it finds in values.</p>\n\n<p>I think, you have a lot of work to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T06:54:02.127",
"Id": "42726",
"Score": "0",
"body": "Thank you, thats the kind of review i needed, SInce i have same format for all the Reports still do i have to maintain different writers for each, can you also let me know if my data structure Map<Integer, TreeMap<String, String>> is this fine is there a better way"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T11:04:28.420",
"Id": "42735",
"Score": "0",
"body": "With all respect: I do not have a clue, what this structure expresses. (6) deals with that. As far as I got skimming your code was: a mapping of integer indices to column names and their values - which resembles something like a data grid. But that is only a guess. Your domain language is not clear about that. If I am guessing right, a List<Lines> or something would be more clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T11:33:45.207",
"Id": "42737",
"Score": "0",
"body": "YOur right TreeMap<String, String> is mapping of column name and its value Map<Ineteger> is used to store rownumber so that i can presever order. so that i can iterate in ordererd manner and diplsay valuesn"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:31:25.430",
"Id": "42829",
"Score": "0",
"body": "I have one more question regarding u said it is bad to gereate new objects in objects does it apply only to dao , any objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:35:20.847",
"Id": "42830",
"Score": "0",
"body": "No. It is a general principle. The following metaphor makes it clear: When building a car, no car takes care of building its engine. An engine is built into the car (from the outside so to say). So the car is flexible which engine could be used, as long one is implemented."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T23:26:32.287",
"Id": "27422",
"ParentId": "27398",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T08:40:35.027",
"Id": "27398",
"Score": "-1",
"Tags": [
"java",
"design-patterns"
],
"Title": "Generating reports from a database"
}
|
27398
|
<p>I have an email contact form that is PHP and very basic. I am concerned, however, that injections might be possible through it. So I was wondering if anyone with far superior PHP skills than myself would be willing to take a look and see if I have any gaps or vulnerabilities in my code that could be exploited. I very much appreciate any help with this.</p>
<p>PHP</p>
<pre><code><?php
$field_name = isset( $_POST['cf_name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['cf_name'] ) : "";
$field_email = isset( $_POST['cf_email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/" , "", $_POST['cf_email'] ) : "";
$field_message = isset( $_POST['cf_message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['cf_message'] ) : "";
$mail_to = 'admin@mywebsite.com';
$subject = 'New Contact for My Website from '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
?>
</code></pre>
<p>For the brief moment I had this on Stack Overflow (before I was told that it should be here) the comment was made that I shouldn't be stripping characters out of emails. So... what should I do then? Is there a simple method to achieve the goal that I am missing? I am very new to this and just want to be as secure as possible. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:17:39.430",
"Id": "42630",
"Score": "0",
"body": "Sanitizing input isn't really what you need (to some extent), what is more important is to properly escape your output. Take a look at the answers here: http://stackoverflow.com/questions/17103318/correct-way-to-sanitize-input-in-mysql-using-pdo/17103381#17103381"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T13:54:58.570",
"Id": "42657",
"Score": "0",
"body": "Michael, thank you so much for the link. I think I understand what is happening with the htmlspecialchars and how it is protecting my contact form. However, I am a little unsure as to where I would put it in my code. Would I want to eliminate the sanitizing script and just use htmlspecialchars or do I want to sanitize and then cancel the output? Thank you so much for your direction so far! I am new to the php side of things and especially to the security part (one of the most important parts) Thanks again!"
}
] |
[
{
"body": "<h2>Validate, but don't change user input</h2>\n\n<p>Don't change the value of a user input. Either accept or reject it, but don't try to guess what might be ment. Some examples:</p>\n\n<p>The name could be <code>Søren Kierkegård</code>, which in many evironments will become <code>Sren Kierkegrd</code> due to your 'sanitation'.</p>\n\n<p>An email address can be much more complicated than your test suggests. How about parenthesis, exclamation or question marks? <a href=\"http://www.regular-expressions.info/email.html\" rel=\"nofollow\">Read this for other thoughts about email validation with regular expressions</a>.</p>\n\n<p>The message still could contain 'Bcc:' or 'Cc:'. Making the expression case insensitive will lead to the next problem: The sequence \"People I met in Toronto: A, B, and C.\" would become \"People I met in Toron A, B, and C.\" </p>\n\n<h2>Escape your output instead</h2>\n\n<p>Header fields are restricted to a single line (each). So is the name of a person. In these cases, all whitespaces are equivalent (at least for non-malicious input), so replacing newlines and tabs with spaces does not alter the (meaning of the) content.</p>\n\n<pre><code>$name = isset($_POST['cf_name']) ? $_POST['cf_name'] : '';\n$email = isset($_POST['cf_email']) ? $_POST['cf_email'] : '';\n$message = isset($_POST['cf_message']) ? $_POST['cf_message'] : '';\n\n$mail_status = sendMail($name, $email, $message);\n\nfunction sendMail($name, $email, $message)\n{\n // Whitespace pattern, icluding different masking methods\n $whitespace = '~(<CR>|<LF>|0x0A|%0A|0x0D|%0D|\\\\n|\\\\r|\\s)+~i';\n\n $name = trim(preg_replace($whitespace, '', $name));\n if (empty($name)) {\n return false;\n }\n\n $email = trim(preg_replace($whitespace, ' ', $email));\n if (empty($email)) {\n return false;\n }\n\n $mail_to = 'admin@mywebsite.com';\n $subject = 'New Contact for My Website from ' . $name;\n\n $body = \"From: $name\\n\";\n $body .= \"E-mail: $email\\n\";\n $body .= \"Message: $message\";\n\n $headers = \"From: $email\\r\\n\";\n $headers .= \"Reply-To: '$email\\r\\n\";\n\n return mail($mail_to, $subject, $body, $headers);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:19:24.780",
"Id": "42825",
"Score": "0",
"body": "nibra, thank you so much for the response and what you are explaining makes sense. Far too much potential to strip content that you don't necessarily want to strip. On the basis of what you have written here, it appears that you are just taking any malicious content and replacing it with whitespace, which in turn, escapes the output. So if I use this script (making the appropriate edits to the email and subject header) it should work correct? At least it appears that it should..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:51:05.613",
"Id": "42849",
"Score": "0",
"body": "I think so, and I'd also use it without fear. But you never know for sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T14:01:00.327",
"Id": "42920",
"Score": "0",
"body": "nibra, thanks again for your help. I implemented the script and I am not getting the messages delivered to the address that is entered. Let me give you the code that I have posting the information entered to the php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T14:03:09.960",
"Id": "42921",
"Score": "0",
"body": "`<form id=\"myForm\" action=\"send_form_email.php\" method=\"post\">\n NAME<span>*</span><br>\n <input name=\"cf_name\" type=\"text\" size=\"32\"><br>\n EMAIL<span>*</span><br>\n <input name=\"cf_email\" type=\"text\" size=\"32\"><br>\n MESSAGE<span>*</span><br>\n <textarea name=\"cf_message\" maxlength=\"1000\" cols=\"30\" rows=\"6\" style=\"resize:none;\"></textarea><br>\n <input type=\"submit\" value=\"Send\">\n <input type=\"reset\" value=\"Clear\">\n</form>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T14:05:38.873",
"Id": "42922",
"Score": "0",
"body": "Also to note, I have a jQuery script that is validating the information to ensure that the fields are completed properly, but I don't think that should be interfering with the script since it isn't posting any data, but checking the data and popping up an alert."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T02:09:19.783",
"Id": "42964",
"Score": "0",
"body": "What's in `$mail_status`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:41:16.160",
"Id": "43040",
"Score": "0",
"body": "Exactly as you scripted it `$mail_status = sendMail($name, $email, $message);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T03:15:51.953",
"Id": "43052",
"Score": "0",
"body": "So what's in `$mail_status`? Hint: `var_dump($mail_status);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T15:32:31.317",
"Id": "43270",
"Score": "0",
"body": "nibra, I tracked it down. :) the preg_replace of the $name variable was missing a second parentheses to close out the trim. It seems to be working just fine now. Thank you so much for your help."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T23:06:42.753",
"Id": "27442",
"ParentId": "27408",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27442",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T18:10:42.333",
"Id": "27408",
"Score": "1",
"Tags": [
"php"
],
"Title": "Is my script secure to prevent email injection?"
}
|
27408
|
<p>I'm looking at a class diagram and it shows a method like this:</p>
<pre><code>SavePrintOptions(bool,bool,bool,bool,bool,bool,bool,bool,bool);
</code></pre>
<p>where each of the parameters match up with save options (checkboxes) in the UI. How could I refactor this signature to reduce the number of parameters? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:22:22.123",
"Id": "42631",
"Score": "5",
"body": "As the answer to [this question](http://codereview.stackexchange.com/questions/8737/too-many-parameters-too-few-methods?rq=1) suggests, collect all of the parameters into a class, and change the method to accept an object of that class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T21:05:52.887",
"Id": "42639",
"Score": "0",
"body": "It's also possible that a large number of parameters to a method indicates the code is smelling. Extract and refactor to more methods, possibly even more classes, to embody SRP (Single Responsibility Principle)."
}
] |
[
{
"body": "<p>That is a real code smell and should be refactored.\nHow should any mortal soul unterstand, what this code does?</p>\n\n<p>Why not using a simple object?</p>\n\n<pre><code>public class{\n\n public bool Whateveryouwant { get; set; }\n public bool Whateveryouwantelse { get; set; }\n}\n</code></pre>\n\n<p>The advantage:</p>\n\n<p>1) your parameter shrunk to just one</p>\n\n<p>2) if you name the properties (better than above) anybody else knows, what options were chosen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T09:53:00.827",
"Id": "42651",
"Score": "1",
"body": "You may also wish to use enumerations rather than boolean values. An enum with 2 possibilities is a lot clearer and easier to understand than simply \"true/false\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T10:01:51.030",
"Id": "42652",
"Score": "1",
"body": "Or http://blog.barvinograd.com/2012/06/working-with-bitfields-in-c/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T22:04:08.230",
"Id": "27420",
"ParentId": "27409",
"Score": "6"
}
},
{
"body": "<p>I would create additional PrintOptions class with immutable fields having meaningful names, it could be easily serialized, passed as method parameter etc.</p>\n\n<p>You also can have several different option sets so it easy to manipulate with several options at once not just one by one if it's required, for example you can have DefaultOptions instance.</p>\n\n<pre><code>public class PrintOptions {\n public readonly bool option1;\n public readonly bool option2;\n public readonly bool optionN;\n\n public PrintOptions(bool option1, bool option2, bool optionN) {\n this.option1 = option1;\n this.option2 = option2;\n this.optionN = optionN;\n }\n}\n\npublic class SomeClass {\n\n public SomeClass(PrintOptions printOptions) {\n PrintOptions = printOptions;\n }\n\n public PrintOptions PrintOptions {get; set;}\n\n public void Print() {\n Print(this.PrintOptions);\n }\n\n public void Print(PrintOptions printOptions) {\n Print(printOptions);\n }\n}\n</code></pre>\n\n<p>So print options is decoupled from class that do some work using this options.\nPrintOptions could be considered as dependency or passed as an argument to Print method, depending on your requirements </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T20:07:15.897",
"Id": "27456",
"ParentId": "27409",
"Score": "1"
}
},
{
"body": "<p>Looks like there are a lot of hidden work is going inside class that is not responsible for saving print options.</p>\n\n<p>It might be even possible that this method doesn't use all of the parameters. I also saw code, where private instance fields were passed into method instead of using them inside calling method:</p>\n\n<pre><code>public Work()\n{\n ...\n SaveOptions(_instanceField, whatever)\n}\nprivate void SaveOptions(bool option, string parameter)\n</code></pre>\n\n<p>I'd rather move this parameters as fields into separate class. Then give meaningfull names and provide default values for fields. \nAfter all you will have class with single responsibility and method without ANY parameters</p>\n\n<pre><code>var printOptions = new PrintOptions(bool, bool);\nprintOptions.Orientation = Orientation.Vertical;\nprintOptions.BlackAndWhite = true;\n\nprintOptions.Save();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T10:17:32.260",
"Id": "27842",
"ParentId": "27409",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:14:50.807",
"Id": "27409",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Reduce number of parameters of the same type"
}
|
27409
|
<p>I have a string of four bits which represent true/false values. There are only seven valid options:</p>
<pre><code>1010
1110
0000
1101
1001
1000
0101
</code></pre>
<p>There are three options which could potentially be selected which are not valid and that I want to check for before I proceed with some other code. These are:</p>
<pre><code>0110
0100
0010
</code></pre>
<p>I want to do this with as little code as possible thus having one regex to test all three conditions. My question is if this is a correct regex to accomplish this test. It seems to work, but I am not a regex expert, and have to be sure in this case.</p>
<pre><code> if (!/0(10|01|11)0/.test(precode)) {
//do some code
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T07:05:15.477",
"Id": "42650",
"Score": "0",
"body": "What about 1111?"
}
] |
[
{
"body": "<p>Why not simply test the valids?</p>\n\n<pre><code>if((/0110|0100|0010/).test(precode))\n</code></pre>\n\n<p>Seems more readable to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T00:21:33.863",
"Id": "42643",
"Score": "0",
"body": "Yeah that is true, I guess I was just trying to be minimalistic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T21:55:27.560",
"Id": "27419",
"ParentId": "27410",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27419",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:20:24.723",
"Id": "27410",
"Score": "2",
"Tags": [
"javascript",
"regex"
],
"Title": "Regular Expression in Javascript to test a string of 1s and 0s"
}
|
27410
|
<p>I've been programming for about 5 years now, mostly in C++ and Java, while continuing my college education in Computer Science. As an adult student, I'm always looking for opinions and ways to improve from professionals in the field. Aside from reading from numerous text books, I've read these forums for tips and good programming practices to improve.</p>
<p>I'm posting a binary search tree in java to hear any and all feedback to continue with this trend of learning; any positive and negative criticism would be helpful to improve. Thanks in advance.</p>
<pre><code>public class NewBinaryTree {
Node root; // top most node of tree
public void addNode(int key, String name) { // adds node to tree
Node newNode = new Node(key, name);
if(root == null) {
root = newNode;
}
else {
Node focusNode = root;
Node parent;
while(true) {
parent = focusNode;
if(key < focusNode.key){ // checks if the key is less than, then inserts left
focusNode = focusNode.leftChild;
if(focusNode == null) {
parent.leftChild = newNode;
return;
}
}
else { // key is greater than, so inserts on right
focusNode = focusNode.rightChild;
if(focusNode == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
public void inOrderTraverseTree(Node focusNode) { // in order tree traversal using recursion
if(focusNode != null) { // checks if something is in there
inOrderTraverseTree(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraverseTree(focusNode.rightChild);
}
} // end in order tree traversal
public void preOrderTraverseTree(Node focusNode) { // preorder tree traversal using recursion
if(focusNode != null) { // checks if something is in there
System.out.println(focusNode);
preOrderTraverseTree(focusNode.leftChild);
preOrderTraverseTree(focusNode.rightChild);
}
} // end preorder tree traversal
public void postOrderTraverseTree(Node focusNode) { // post order tree traversal using recursion
if(focusNode != null) { // checks if something is in there
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
}
} // end post order tree traversal
public Node findNode(int key) { // searches tree by key value
Node focusNode = root;
while(focusNode.key != key) {
if(key < focusNode.key) {
focusNode = focusNode.leftChild;
}
else {
focusNode = focusNode.rightChild;
}
if(focusNode == null)
return null;
}
return focusNode;
} // end tree search by key
public boolean remove(int key) {
Node focusNode = root;
Node parent = root;
boolean isItAleftChild = true;
while(focusNode.key != key) {
parent = focusNode;
if(key < focusNode.key) {
isItAleftChild = true;
focusNode = focusNode.leftChild;
} else {
isItAleftChild = false;
focusNode = focusNode.rightChild;
}
if(focusNode == null)
return false;
}
if(focusNode.leftChild == null && focusNode.rightChild == null) {
if(focusNode == root) {
root = null;
} else if(isItAleftChild) {
parent.leftChild = null;
} else {
parent.rightChild = null;
}
}
else if(focusNode.rightChild == null) {
if(focusNode == root)
root = focusNode.leftChild;
else if(isItAleftChild)
parent.leftChild = focusNode.leftChild;
else parent.rightChild = focusNode.leftChild;
}
else if(focusNode.leftChild == null) {
if(focusNode == root)
root = focusNode.rightChild;
else if(isItAleftChild)
parent.leftChild = focusNode.rightChild;
else
parent.rightChild = focusNode.leftChild;
}
else {
Node replacement = getRePlacementNode(focusNode);
if(focusNode == root)
root = replacement;
else if(isItAleftChild)
parent.leftChild = replacement;
else parent.rightChild = replacement;
replacement.leftChild = focusNode.leftChild;
}
return true;
}
public Node getRePlacementNode(Node replacedNode) {
Node replacementParent = replacedNode;
Node replacement = replacedNode;
Node focusNode = replacedNode.rightChild;
while(focusNode != null) {
replacementParent = replacement;
replacement = focusNode;
focusNode = focusNode.leftChild;
}
if(replacement != replacedNode.rightChild) {
replacementParent.leftChild = replacement.rightChild;
replacement.rightChild = replacedNode.rightChild;
}
return replacement;
}
public static void main(String[] args) {
NewBinaryTree theTree = new NewBinaryTree();
// insert testing code
}
}
class Node { // Node class
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name) { // node constructor
this.key = key;
this.name = name;
}
public String toString() { // prints out contents of Nodes
return name + " has a key " + key;
}
} // end node class
</code></pre>
|
[] |
[
{
"body": "<p>Many of your comments are superfluous. If you flood your reader with useless comments, they might skip some important ones:</p>\n\n<p><code>// adds node to tree</code> - this is already clear from method name - <code>addNode</code>.</p>\n\n<p><code>// end in order tree traversal</code> - markers such as this are unnecessary, if you are using modern IDE. In most editors there are much better ways to easily navigate through your code.</p>\n\n<p><code>getRePlacementNode</code> should be private. It doesn't look it would be useful to users of your class. This way you will be able to change it without breaking backwards compatibility.</p>\n\n<p><code>remove(int)</code> is really long. It looks like it could be split up into smaller methods. You should re-use <code>findNode(int)</code> instead of copying it.</p>\n\n<p>I'm not sure if your program works as intended, try:</p>\n\n<pre><code>theTree.addNode(0, \"a\");\ntheTree.addNode(1, \"b\");\ntheTree.addNode(2, \"c\");\ntheTree.remove(1);\ntheTree.inOrderTraverseTree(theTree.root);\n</code></pre>\n\n<p>should both 1 and 2 be removed? It's a good idea to add unit tests to your classes. This way, if there is a test checking this behavior, it probably is intended. If not, it's probably a bug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T23:25:27.913",
"Id": "27443",
"ParentId": "27412",
"Score": "4"
}
},
{
"body": "<p>Many of these methods would be simplified by moving them to <code>Node</code>. The biggest clue is how you have to keep passing <code>Node</code>s around between the various <code>Tree</code> methods and recursively. This makes <code>Node</code> responsible for managing its key, name, and children while leaving <code>Tree</code> free to worry solely about the root.</p>\n\n<pre><code>// Tree\npublic Node findNode(int key) {\n return root == null ? null : root.find(key);\n}\n\n// Node\npublic Node find(int key) {\n if (key == this.key) {\n return this;\n }\n else if (key < this.key) {\n return leftChild == null ? null : leftChild.find(key);\n }\n else {\n return rightChild == null ? null : rightChild.find(key);\n }\n}\n</code></pre>\n\n<p>Combining this with the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern#Java\" rel=\"nofollow\">Null Object</a> pattern would simplify others even further. Instead of storing <code>null</code> in the root, left, or right child when there is no key stored there, store a shared instance of <code>NullNode</code> which implements most methods by doing nothing or returning <code>null</code>. Since it doesn't store any data, it can be a static member of <code>Tree</code> shared by all trees.</p>\n\n<pre><code>private static final NullNode NULL = new NullNode();\n\n// Tree\npublic void preOrderTraverse() {\n root.preOrderTraverse();\n}\n\n// Node\npublic void preOrderTraverse() {\n System.out.println(this);\n leftChild.preOrderTraverse();\n rightChild.preOrderTraverse();\n}\n\n// NullNode\npublic void preOrderTraverse() {\n // nothing to do\n}\n</code></pre>\n\n<p>This eliminates much of the <code>null</code>-checking that complicates code and makes it harder to read and follow and is a common source of bugs.</p>\n\n<pre><code>// Tree\npublic Node findNode(int key) {\n return root.find(key);\n}\n\n// Node\npublic Node find(int key) {\n if (key == this.key) {\n return this;\n }\n else if (key < this.key) {\n return leftChild.find(key);\n }\n else {\n return rightChild.find(key);\n }\n}\n\n// NullNode\npublic Node find(int key) {\n return null;\n}\n</code></pre>\n\n<p>Using this technique can complicate some logic, for example <code>insert</code> which now must check to see if the node is a real one or not. One trick around this is to have the node return a <code>boolean</code> stating whether it was able to insert the new node or not. If not, overwrite it.</p>\n\n<pre><code>// Tree\npublic void addNode(int key, String name) {\n Node node = new Node(key, name);\n if (!root.add(node)) {\n root = node;\n }\n\n// Node\npublic boolean add(Node node) {\n if (node.key == this.key) {\n // Your code doesn't handle a key clash. What should we do?\n throw new IllegalArgumentException(\"Key clash\");\n }\n else if (node.key < this.key) {\n if (!leftChild.add(node)) {\n leftChild = node;\n }\n }\n else {\n if (!rightChild.add(node)) {\n rightChild = node;\n }\n }\n return true;\n}\n\n// NullNode\npublic boolean add(Node node) {\n return false;\n}\n</code></pre>\n\n<p>One thing I definitely don't like is leaking <code>Node</code> outside of <code>Tree</code>. I think <code>findNode</code> should return the node's name instead of the node itself. <code>Node</code> should be a static inner class of <code>Tree</code> and entirely an implementation detail.</p>\n\n<p>Finally, as Banthar said, you need to look again at the case of removing a node with two children. It's hard to tell from the code, but it looks like you drop the right subtree instead of assigning it to the replacement. As well, you should be promoting the right-most (largest) node from the left subtree, yet I see you moving left in <code>getRePlacementNode</code>. A better name for this method might be <code>removeLargestNode</code> since it should be removed from the left subtree.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T09:17:28.877",
"Id": "27447",
"ParentId": "27412",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:39:11.513",
"Id": "27412",
"Score": "3",
"Tags": [
"java",
"recursion",
"tree"
],
"Title": "Binary Tree Operations"
}
|
27412
|
<p>I have a need to express something like this:</p>
<pre><code>while(bytesToWrite > 0)
{
// get the NEXT location to write from a Key/Value collection of locations
// read a packet from a file at the specified location
// write some bytes to the packet
bytesToWrite -= bytesWritten
}
</code></pre>
<p>This was my first attempt:</p>
<pre><code>var dictionary = new Dictionary<long, long>() { .. }
...
while(bytesToWrite > 0)
{
var pin = dictionary.Take(1).First();
Debug.Print(pin.Key.ToString() + ", " + pin.Value.ToString());
// Write the bytes using Key and Value for location information.
dictionary = dictionary.Skip(1)
bytesToWrite -= bytesWritten;
}
</code></pre>
<p>But it doesn't look terribly efficient to me. It looks like I'm making a new collection each time through the loop, just to peel off a single item, and the <code>Take(1).First()</code> and <code>dictionary = dictionary.Skip(1)</code> syntax is a bit awkward.</p>
<p>If I put my original collection in a <code>LinkedList</code>, I can do this:</p>
<pre><code>var map = new LinkedList<KeyValuePair<long, long>>(dictionary);
...
var pin = map.First;
while (pin != null && bytesToWrite > 0)
{
// Value.Key and Value.Value??
Debug.Print(pin.Value.Key.ToString() + ", " + pin.Value.Value.ToString());
// Write the bytes
pin = pin.Next;
bytesToWrite -= bytesWritten;
}
</code></pre>
<p>Eww. <code>Value.Key</code> and <code>Value.Value</code> is not exactly intuitive.</p>
<p>I can write a couple of wrapper classes, like so:</p>
<pre><code>public class StateList<T>
{
LinkedList<T> list;
LinkedListNode<T> currentNode;
public StateList(IEnumerable<T> source)
{
list = new LinkedList<T>(source);
}
public StateList<T> Create<T>(IEnumerable<T> source)
{
return new StateList<T>(source);
}
public T First
{
get
{
var node = list.First;
return Value(node);
}
}
public T Last
{
get
{
var node = list.Last;
return Value(node);
}
}
public T Next
{
get
{
var node = currentNode.Next;
return Value(node);
}
}
public T Previous
{
get
{
var node = currentNode.Previous;
return Value(node);
}
}
public T Value(LinkedListNode<T> node)
{
if (node != null)
{
var value = node.Value;
currentNode = node;
return value;
}
return default(T);
}
}
public static class StateList
{
public static StateList<T> Create<T>(IEnumerable<T> source)
{
return new StateList<T>(source);
}
}
</code></pre>
<p>and get the code look like this:</p>
<pre><code>var map = StateList.Create(dictionary);
...
var pin = map.First;
while (bytesToWrite > 0)
{
// Ah, that's better.
Debug.Print(pin.Key.ToString() + ", " + pin.Value.ToString());
// Write the bytes
// Pin is taken from the map, not from the previous pin.
pin = map.Next;
bytesToWrite -= bytesWritten;
}
</code></pre>
<p>Ah, that's much better. The question is, is all that ceremony really worth it? I feel like I'm missing something simple and obvious. </p>
<p>I'd also like comments on the relative merit of the StateList class, whether it is a satisfactory approach from a good practices viewpoint, or a terrible abomination.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:37:16.217",
"Id": "42634",
"Score": "0",
"body": "Why can't you simply use a `foreach` over the `Dictionary`? If you need to end the loop early due to `bytesToWrite`, you could just use `break`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:39:33.430",
"Id": "42636",
"Score": "0",
"body": "@svick: I admit that the example is somewhat contrived (although it is based on real-world code). This is more of a language syntax exercise, using a simple state machine. I tried doing it with `yield` `return`, but got wrapped around the axle over the generic definitions, and it still returns a collection anyway, rather than the next element in the sequence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:56:31.993",
"Id": "42637",
"Score": "0",
"body": "You might have misunderstood me. I'm not proposing doing anything complicated like `yield return`. Just use `foreach (var pin in dictionary)` and it should do exactly what you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:57:08.173",
"Id": "42638",
"Score": "0",
"body": "@svick: I refactored my existing code using your suggestion, and it turned out cleaner than any of my other tries, so it appears that the state machine approach is not going to be worth it. If you post an answer with one of my code samples above so modified, I'll upvote and accept."
}
] |
[
{
"body": "<p>It sounds like what you want is a <code>foreach</code> over the <code>Dictionary</code>, combined with a <code>break</code> for the <code>bytesToWrite</code> condition.</p>\n\n<pre><code>foreach (var pin in dictionary)\n{\n if (bytesToWrite <= 0)\n break;\n\n Debug.Print(pin.Key + \", \" + pin.Value);\n\n // Write the bytes using Key and Value for location information.\n\n bytesToWrite -= bytesWritten;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:59:19.537",
"Id": "27418",
"ParentId": "27413",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27418",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T19:49:09.057",
"Id": "27413",
"Score": "2",
"Tags": [
"c#"
],
"Title": "The quest for a succint, readable expression of Next in a sequence"
}
|
27413
|
<p>So I'm using the <a href="https://github.com/mbleigh/acts-as-taggable-on" rel="nofollow">acts_as_taggable_on</a> gem to tag 3 different models: <code>Question</code>, <code>Blog</code>, and <code>Video</code></p>
<p>Each one has a <code>site_id</code> to distinguish which site they show up on (SaaS-ish).</p>
<p>I wanted to get all tags for a specific site without saving <code>site_id</code> right on a <code>Tag</code> or <code>Tagging</code>.</p>
<p>I came up with the following, but I feel like there might be something more efficient I could do.</p>
<pre><code>ActsAsTaggableOn::Tag.class_eval do
extend FriendlyId
friendly_id :name, use: :slugged
def self.find_by_site site, limit=0
klasses = [Blog, Question, Video]
sql = []
site_ids = []
klasses.each do |k|
sql << "
SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
FROM tags
LEFT JOIN taggings
ON (taggings.tag_id = tags.id)
LEFT JOIN #{k.table_name}
ON (#{k.table_name}.id = taggings.taggable_id)
WHERE taggings.taggable_type = '#{k.name}'
AND #{k.table_name}.site_id = ?
"
end
sql = sql.join(" UNION ")
sql += " GROUP BY id "
sql += " ORDER BY COUNT DESC "
sql += "LIMIT #{limit}" if limit > 0
klasses.count.times { site_ids << site.id }
find_by_sql([sql, *site_ids])
end
end
</code></pre>
<p>Here is the current functionality with timing:</p>
<pre><code>irb(main):011:0> ActsAsTaggableOn::Tag.find_by_site Site.find(3); nil
Site Load (0.4ms) SELECT `sites`.* FROM `sites` WHERE `sites`.`id` = 3 LIMIT 1
ActsAsTaggableOn::Tag Load (0.5ms)
SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
FROM tags
LEFT JOIN taggings
ON (taggings.tag_id = tags.id)
LEFT JOIN blogs
ON (blogs.id = taggings.taggable_id)
WHERE taggings.taggable_type = 'Blog'
AND blogs.site_id = 3
UNION
SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
FROM tags
LEFT JOIN taggings
ON (taggings.tag_id = tags.id)
LEFT JOIN questions
ON (questions.id = taggings.taggable_id)
WHERE taggings.taggable_type = 'Question'
AND questions.site_id = 3
UNION
SELECT tags.*, (SELECT COUNT(*) FROM taggings t WHERE t.tag_id = tags.id) AS `count`
FROM tags
LEFT JOIN taggings
ON (taggings.tag_id = tags.id)
LEFT JOIN videos
ON (videos.id = taggings.taggable_id)
WHERE taggings.taggable_type = 'Video'
AND videos.site_id = 3
GROUP BY id ORDER BY COUNT DESC
</code></pre>
|
[] |
[
{
"body": "<p>Assuming these are all AR models with appropriate associations, I'd create a method on Site that iterates over a site instance's Blogs, Questions and Videos and collects their tags. Something like this maybe:</p>\n\n<pre><code>def get_site_tags\n tags = []\n self.blogs.each do |blog|\n (tags << blog.tags)\n end\n self.questions.each do |question|\n (tags << question.tags)\n end\n self.videos.each do |video|\n (tags << video.tags)\n end\n tags.flatten!\nend\n</code></pre>\n\n<p>Would this work for you or am I missing something?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T23:08:39.810",
"Id": "42671",
"Score": "0",
"body": "The one I have now works, it just feels like it could be done with better performance. Your solution is very AR friendly, but has many trips to the database (each time `instance.tags` is called)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T16:48:08.357",
"Id": "43018",
"Score": "1",
"body": "this should be a `map` instead of `each`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T16:03:09.683",
"Id": "27433",
"ParentId": "27415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:04:11.563",
"Id": "27415",
"Score": "1",
"Tags": [
"ruby",
"mysql",
"ruby-on-rails"
],
"Title": "Review my ruby for performance"
}
|
27415
|
<p>I just wrote this, and cleaned it up as much as I could. A couple things worry me:</p>
<ul>
<li>I change the scope of <code>$(this)</code> twice (and apparently don't know how to use <code>=></code>)</li>
<li>The big <code>if if/else</code> statement. Is there a better way to write that?</li>
</ul>
<p>Also, it's an IIFE, and the big identing makes the <code>)()</code> at the end look out of place.</p>
<pre><code> emptyTagFieldsOnDeletion = (->
$('form.simple_form').submit ->
$form = $(this)
$form.find('.fake-input').each ->
$fakeInput = $(this)
$ulId = $fakeInput.closest('ul').attr('id')
if $fakeInput.children('li').length is 1
$fakeInput.children().remove()
if $ulId is 'primary_diagnosis_select'
$fakeInput.append emptyListArrayHTML('primary_icd9_codes')
else if $ulId is 'secondary_diagnosis_select'
$fakeInput.append emptyListArrayHTML('secondary_icd9_codes')
else
$fakeInput.append emptyListArrayHTML('med_names')
)()
</code></pre>
<p>For reference, the <code>emptyListArrayHTML</code> method looks like this:</p>
<pre><code>emptyListArrayHTML = (list_type)->
"<input type='text' name='#{nameWithListType(list_type)}' value=''>"
</code></pre>
|
[] |
[
{
"body": "<p>You mention the changes in scope as though they're a problem. But you actually want them here, since that's how jQuery operates, and using <code>=></code> would be counterproductive. Anyway here are some notes</p>\n\n<ol>\n<li><p>CoffeeScript has a <code>do</code> keyword for IIFEs. So <code>do -> ...</code> is equivalent to <code>(-> ...)()</code> without the need for all those parentheses</p></li>\n<li><p>It seems your IIFE isn't returning something you'll need later; it's just encapsulating some code. In that case, don't bother giving it a name. Just invoke it.</p></li>\n<li><p>You don't need to cache <code>$form</code> - you only use it once</p></li>\n<li><p>Don't call the UL id <code>$ulId</code> - that is, don't use a <code>$</code> in the name. It's not a jQuery object, it's just a string</p></li>\n<li><p>You can use a <code>switch</code> statement instead of the <code>if... else</code>, which helps a bit (but read on for a better solution)</p></li>\n</ol>\n\n<p>Here's the code with these tweaks:</p>\n\n<pre><code>do ->\n $('form.simple_form').submit ->\n $(this).find('.fake-input').each -> # don't bother caching $form\n $fakeInput = $ this\n return unless $fakeInput.children().length is 1 # return early instead of a big if-block\n\n $fakeInput.empty()\n\n switch $fakeInput.closest('ul').attr('id')\n when 'primary_diagnosis_select'\n $fakeInput.append emptyListArrayHTML('primary_icd9_codes')\n when 'secondary_diagnosis_select'\n $fakeInput.append emptyListArrayHTML('secondary_icd9_codes')\n else\n $fakeInput.append emptyListArrayHTML('med_names')\n</code></pre>\n\n<p>However, I'd make the relationships explicit in the markup. For instance, give the UL element a <code>data-codes</code> attribute or something:</p>\n\n<pre><code><ul id=\"primary_diagnosis_select\" data-codes=\"primary_icd9_codes\">\n...\n<ul id=\"secondary_diagnosis_select\" data-codes=\"secondary_icd9_codes\">\n...\n<ul id=\"something_else\"> <!-- no data-codes for this one; defaults to \"med_names\" in the CoffeeScript code -->\n</code></pre>\n\n<p>Then you can shorten the code like so:</p>\n\n<pre><code>do ->\n $('form.simple_form').submit ->\n $(this).find('.fake-input').each ->\n $fakeInput = $ this\n return unless $fakeInput.children().length is 1\n $fakeInput.empty()\n codes = $fakeInput.closest('ul').data(\"codes\") or \"med_names\"\n $fakeInput.append emptyListArrayHTML(codes)\n</code></pre>\n\n<p>Now the CoffeeScript handles only logic while the data and relationships are declared in the markup. You can add the single line from <code>emptyListArrayHTML</code> back into the function with complicating things too much, though.</p>\n\n<p>p.s. CoffeeScript also has a triple-quote Python-like heredoc syntax, if you want to use double quotes in a string without escaping them. So your <code>emptyListArrayHTML</code> function could be written as</p>\n\n<pre><code>emptyListArrayHTML = (list_type) ->\n \"\"\"<input type=\"text\" name=\"#{nameWithListType list_type}\" value=\"\">\"\"\"\n</code></pre>\n\n<p>It looks a little strange at first (and the syntax highlighting is messed up here), but I like to use it, because I prefer to always use double quotes for HTML attributes (just personal preference).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:51:21.080",
"Id": "42884",
"Score": "0",
"body": "Yep. All great suggestions. Just what I was looking for! Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T12:04:58.210",
"Id": "27448",
"ParentId": "27416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27448",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:17:33.813",
"Id": "27416",
"Score": "1",
"Tags": [
"form",
"coffeescript"
],
"Title": "Conditionally replacing an input field when submitting a form"
}
|
27416
|
<p>This is just a simple script for testing sprite sheet animations. I'm trying to improve my code style, so I'm curious about suggestions anyone might have about best practices or readability.</p>
<pre><code><html>
<head>
<script>
//just a shim to provide requestAnimationFrame support in different browsers
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 17 /*~ 1000/60*/);
});
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = (window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame ||
window.clearTimeout);
}
//loads when the body element has loaded.
var init = function() {
//the actual event loop. Runs inside of the init() closure.
var animate = function() {
(function animloop(){
//clear the canvas
canvas.width = canvas.width;
//increment the tick variable.
tick++;
//if it's greater than five, reset to zero and go to the next tile
if (tick > 5) {
tick = 0;
//check to see if currently viewing the last tile in the sequence. If so, reset to the first, otherwise go the the net one.
if (currentTile > tiles - 2) {
currentTile = 0;
} else {
currentTile++
}
}
//pull the current tile out of the sprite sheet and draw it to the canvas.
ctx.drawImage(img, currentTile * tileWidth, 0, tileWidth, tileHeight, 0, 0, tileWidth, tileHeight);
//let the browser decide when to call the event loop again
window.requestAnimationFrame(animloop);
})();
};
//get a reference to the canvas element
var canvas = document.getElementById('canvas');
//same for the canvas context
var ctx = canvas.getContext('2d');
//and index that refers to the tile currently selected
var currentTile = 0;
//used in the event loop to slow down the animation
var tick = 0;
//*************************************
//change this next value depending on the number of tiles in the animation
var tiles = 5;
//used to select the tile currently being drawn from sprite sheet
var tileWidth = null;
//same
var tileHeight = null;
//new image object
img = new Image();
//called when the image loads
img.onload = function() {
//the sprite sheet should be composed of tiles of equal length and the animation should be centered on each tile.
tileWidth = img.width / tiles;
//the script only handles sprite sheets that are one dimensional.
//ie, the animation should only run along the x axis, so the animation will always be the same height as the image itself.
tileHeight = img.height;
//call the event loop
animate();
};
//*********************************
//this is the name of the file you want to test. Make sure it's in the
//the same directory as the script
//load the specified sprite sheet
img.src = 'zombieChase3.png';
};
</script>
</head>
//run init when body is loaded
<body onload="init()">
//just a canvas element
<canvas id="canvas" width="500" height="500">
You need a browser that supports the canvas element.
</canvas>
</body>
</html>
</code></pre>
<p>Thanks guys!</p>
|
[] |
[
{
"body": "<pre><code>//I suggest you use this polyfill for the rAF and cAF\n//https://gist.github.com/paulirish/1579671\n\n\n//Enclosing the module in a closure to avoid pollution of the global scope\n(function (exports) {\n\n //Let's make each sprite an object, so that we have a reusable constructor\n function Sprite(config) {\n\n //A typical convention to not lose the context is to store it in another variable\n var self = this;\n\n //Setting a few configs for this object\n this.canvas = document.getElementById(config.canvas);\n this.context = this.canvas.getContext('2d');\n this.path = config.path;\n this.tiles = config.tiles;\n\n //We can add properties to the Sprite instance, like states and counters\n this.paused = false;\n this.tick = 0;\n\n //Let's load up the image when creating an instance\n var image = this.image = new Image();\n image.onload = function () {\n\n //When loaded, get the info\n self.width = image.width;\n self.height = image.height;\n\n //Start the animation via the instance's start method\n self.animate();\n\n }\n image.src = this.path;\n }\n\n //Let's extend the constructor to have methods\n\n //Unpauses the instance and runs animate\n Sprite.prototype.play = function () {\n this.paused = false;\n this.animate();\n }\n\n //Our animation loop function\n Sprite.prototype.animate = function () {\n\n //If say the state is paused, don't request the next frame\n //Otherwise, schedule the next frame\n if(this.paused) return;\n requestAnimationFrame(animate);\n\n //clear and draw\n this.canvas.width = this.canvas.width;\n this.context.drawImage(this.image, this.tick * this.width, 0, this.width, this.height, 0, 0, this.width, this.height);\n\n //reset it tiles reached\n if(++this.tick > this.tiles) this.tiles = 0;\n\n }\n\n //This one stops the animation\n Sprite.prototype.stop() {\n this.paused = true;\n }\n\n exports.load = function (config) {\n return new Sprite(config)\n }\n\n}(this.Sprite = this.Sprite || {}));\n\n//Extensibility. Don't limit yourself to a fixed set of configurations.\n//Make your code reusable.\nvar sprite = Sprite.load({\n canvasId: 'canvas',\n path: 'zombieChase3.png',\n tiles: '5'\n});\n\n//you can control the sprite\nsprite.play();\nsprite.stop();\n\n//Additionally, you can add something like play, pause, unload etc. which I just did\n//Also, sprite sheets are usually big sheets containing more than one sequence per image\n//you should consider that. If you Google \"sprite sheets\", you'll see.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T03:10:44.930",
"Id": "58241",
"Score": "0",
"body": "+1 but only because the review is in the comments. I would be an even better post if you elaborated a little bit in plain text."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T05:19:02.710",
"Id": "27427",
"ParentId": "27417",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27427",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T20:21:12.193",
"Id": "27417",
"Score": "2",
"Tags": [
"javascript",
"canvas"
],
"Title": "Review a simple sprite sheet animation script"
}
|
27417
|
<p>Is this a good implementation for <code>Equals</code> and <code>GetHashCode</code> for a base class in C#? If it's not good enough, can you suggest improvements for it, please?</p>
<pre><code>public abstract class Entity<TKey> //TKey = Type of the Key
{
private string FullClassName;
private bool KeyIsNullable;
private Type BaseClassType;
private bool KeyIsComplex;
public abstract TKey Key { get; } //Key of the object, which determine it's uniqueness
public Entity()
{
FullClassName = GetType().FullName + "#";
KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable));
BaseClassType = typeof(Entity<TKey>);
KeyIsComplex= !typeof(TKey).IsPrimitive;
}
public override bool Equals(object obj)
{
bool result = BaseClassType.IsAssignableFrom(obj.GetType());
result
= result
&& (
(
(
!KeyIsNullable
||
(Key != null && ((Entity<TKey>)obj).Key != null
)
)
&&
Key.Equals(((Entity<TKey>)obj).Key )
) // The key is not nullable, or (it's nullable but) both aren't null, and also equal
||
(
KeyIsNullable
&&
Key == null
&&
((Entity<TKey>)obj).Key == null
)
); // Or the key is nullable, and both are null
return result;
}
public override int GetHashCode()
{
if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey))))
{
return base.GetHashCode();
}
string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString());
return stringRepresentation.GetHashCode();
}
}
</code></pre>
<p>Example of a derived class:</p>
<pre><code>public class Foo : Entity<int>
{
public virtual int FooId { set; get; }
public virtual string FooDescription { set; get; }
public override int Key { get { return FooId; } }
}
</code></pre>
<p>Specific and special details to the proposal:</p>
<ol>
<li>Any instance of a derived class is considered equal to a instance of the base class if they have the same key.</li>
<li>The key could be <code>null</code>.</li>
<li>If the key of the current class and the key of the comparing object are both <code>null</code>, the two objects are considered equal. This is because I am planning to handle just one new object at a time, and if the key is nullable, it will be <code>null</code> for the new object. So if I have two instances with a <code>null</code> key, I will consider them as the same entity.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T00:03:41.087",
"Id": "42642",
"Score": "1",
"body": "When you're having to indent your parenthesis, then it should be obvious that you should rewrite your code instead. Having everything in a single huge expression is not a good thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T06:21:13.443",
"Id": "42648",
"Score": "0",
"body": "Hehehe, you are right. It's kind of a nested if-else, but without the if-else."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T16:24:28.370",
"Id": "42689",
"Score": "0",
"body": "I would not override equality at all for entities. I'd define an `IEqualityComparer<T>` that compares by `Id`, but I'd avoid making it the default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T19:48:00.927",
"Id": "42698",
"Score": "0",
"body": "“Any instance of a derived class is considered equal to a instance of the base class if they have the same key.” Does that mean that `new Foo { FooId = 42 }.Equals(new Bar { BarId = 42 })` should return `true`? That would be very weird."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T22:43:18.837",
"Id": "42709",
"Score": "0",
"body": "It's because it is a base class for NHibernate entities, and sometimes I work with stub objects and NHibernate proxies at the same time. For example, sometimes I create a new stub, and need to replace the object with the same key in a list of proxies."
}
] |
[
{
"body": "<pre><code>//TKey = Type of the Key\n//Key of the object, which determine it's uniqueness\n</code></pre>\n\n<p>If you're going to use comments like these, it's useful to use XML documentation comments instead, so that you can see them in IntelliSense.</p>\n\n<p>Also, you should try to keep your comments grammatically correct, though I understand that's not always easy, especially if you're not a native speaker.</p>\n\n<pre><code>public Entity()\n{\n FullClassName = GetType().FullName + \"#\";\n KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable));\n BaseClassType = typeof(Entity<TKey>);\n KeyIsComplex = !typeof(TKey).IsPrimitive;\n}\n</code></pre>\n\n<p>I think it doesn't make much sense to store these in each instance. If your profiling shows that retrieving these values on each call slows down your code, store at least the last three values in <code>static</code> fields (you could initialize them from a <code>static</code> constructor).</p>\n\n<p>Also, <code>KeyIsNullable</code> will be always <code>false</code>, because <code>Nullable</code> is a static class that's distinct from <code>Nullable<T></code>. (But it doesn't matter anyway, see below.)</p>\n\n<pre><code>bool result = BaseClassType.IsAssignableFrom(obj.GetType());\n</code></pre>\n\n<p>According to ReSharper, you could instead use <code>BaseClassType.IsInstanceOfType(obj)</code>. (I had no idea such method existed.)</p>\n\n<p>But this check means that for example two different types deriving from <code>Entity<int></code> with the same key will compare as equal. I don't think that's what you want, you should compare the type against <code>GetType()</code> and you should make sure that the types are exactly equal. This is especially true since in such case, the two objects will compare as equal, but will have different hash codes, which makes your code wrong.</p>\n\n<p>Also, your code will throw an exception when <code>obj</code> is <code>null</code>, you should add a check against that.</p>\n\n<pre><code>result\n = result\n && ( …\n</code></pre>\n\n<p>This monstrous expression doesn't make much sense to me (and that's not just because it's hard to understand). For nullable value types, <code>Equals()</code> works fine, you don't need all this gymnastics.</p>\n\n<pre><code>if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey))))\n{\n return base.GetHashCode();\n}\n</code></pre>\n\n<p>This code indicates that if the <code>Key</code> has its default value, you want to use reference equality. But there is no indication of that in your <code>Equals()</code>. You have to decide what exactly does <em>equal</em> mean for your type and keep that definition consistent across <code>Equals()</code> and <code>GetHashCode()</code>.</p>\n\n<p>Also, again, you don't need special code for nullable value types.</p>\n\n<pre><code>string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString());\nreturn stringRepresentation.GetHashCode();\n</code></pre>\n\n<p>I haven't seen hash code include the type before. It could make sense if you're using hash-based collections that can contain different types with the same key values, though doing that is not very common, I think.</p>\n\n<p>Though if you want to do that, I would use the hash code of <code>GetType()</code> instead of dealing with type name.</p>\n\n<p>Also, there is no reason to use <code>string</code>s here, simply combining the hash codes (e.g. using XOR) is enough.</p>\n\n<hr>\n\n<p>With all these changes, your code will look like this:</p>\n\n<pre><code>/// <typeparam name=\"TKey\">Type of the Key</typeparam>\npublic abstract class Entity<TKey>\n{\n /// <summary>\n /// Key of the object, which determines its uniqueness\n /// </summary>\n public abstract TKey Key { get; }\n\n public override bool Equals(object obj)\n {\n if (obj == null)\n return false;\n\n if (obj.GetType() != GetType())\n return false;\n\n bool sameKey = Key.Equals(((Entity<TKey>)obj).Key);\n\n if (sameKey && Key.Equals(default(TKey)))\n return ReferenceEquals(this, obj);\n\n return sameKey;\n }\n\n public override int GetHashCode()\n {\n if (Key.Equals(default(TKey)))\n return base.GetHashCode();\n\n return GetType().GetHashCode() ^ Key.GetHashCode();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T03:07:18.753",
"Id": "42678",
"Score": "0",
"body": "Many thanks @svick. It's a very detailed explanation. I will take all your valuable advices into account. I added more details to the question, regarding to the inheritance and key nullability, sorry because I didn't mentioned them before. PD: You are right, english it's not my native language, I had to translate my code, hehehe..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:26:52.160",
"Id": "42871",
"Score": "0",
"body": "One question: why using XOR? I have seen a couple of examples using it to generate a new hash code, but I didn't get why. Thanks in advance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:42:05.717",
"Id": "42882",
"Score": "0",
"body": "@guillegr123 Because it's a simple and reasonable way to combine two unrelated hashcodes. [XOR has its issues](http://stackoverflow.com/a/263416/41071), so in general it's better to combine them using prime numbers and multiplication. But I think that in this specific case, XOR is okay."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T12:26:52.453",
"Id": "27429",
"ParentId": "27421",
"Score": "3"
}
},
{
"body": "<p>I think you are overcomplicating things you can say simple this:</p>\n\n<pre><code> public abstract class Entity<TKey> where TKey : struct \n {\n public abstract TKey Key { get; }\n\n protected bool Equals(Entity<TKey> other)\n {\n return Key.Equals(other.Key);\n }\n\n public override bool Equals(object obj)\n {\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n var asThis = obj as Entity<TKey>;\n return asThis != null && Equals(asThis);\n }\n\n public override int GetHashCode()\n {\n return Key.GetHashCode();\n }\n }\n</code></pre>\n\n<p>No need the type magic\nA key cannot be null and it should be a ValueType\nAn Equals and GetHashCode implementation should be symmetric and fast (your solution is slow and i'm not sure it is symmetric or not)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T03:00:54.557",
"Id": "42677",
"Score": "0",
"body": "Thanks @Peter Kiss, I like the Hash Code based on the Keys HashCode. Also, I haven't considered the symmetric implementation between Equals and GetHashCode, I will review that. There is a caveat, though: the key can be null."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T14:34:30.657",
"Id": "27430",
"ParentId": "27421",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27429",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T23:14:59.533",
"Id": "27421",
"Score": "3",
"Tags": [
"c#",
"inheritance",
"null"
],
"Title": "Implementation of Equals and GetHashCode for base class"
}
|
27421
|
<p>I have that $db, that I will use again and again to connect to the database. How do I put this in a central location so if I change my db I will not have to rewrite a bunch of lines of code? Everything I've tried so far just gives me an error concerning variable scope, the variable is not declared in my functions, so I am forced to simply connect and use the $db object everytime I need to access the database.</p>
<p>TLDR: How do I create the $db object once, and then use it again and again. Just looking for a general idea here. </p>
<pre><code>function input_registration ($email, $password) {
$email_clean = htmlspecialchars($email);
$password_clean = htmlspecialchars($password);
$hash = md5($password_clean);
$db = new PDO("mysql:host=localhost;dbname=users", "root", "");
try {
$statement = $db->prepare("INSERT into userinfo(email, hash) VALUES (:email, :hash)");
$array_parameters = array(
'email' => $email_clean,
'hash' => $hash
);
$statement->execute($array_parameters);
}
catch (Exception $error) {
echo "Database error: ". $error->getMessage();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T00:31:38.467",
"Id": "42645",
"Score": "0",
"body": "The second. Sorry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T00:32:47.487",
"Id": "42646",
"Score": "0",
"body": "Ah, alright. Have reverted it back to the original formatting except with the markdown fixed a little bit. I suspect someone's review will contain a \"use more standard indenting\" item, so I wanted to make sure it didn't get silently fixed."
}
] |
[
{
"body": "<p>You can't find the correct answer until your code is just a bunch simple PHP scripts. The ultimate solution would be is to use a dependency injection container and resolver where sou can say for example a PDO instance to keep in use until the request ends (in PHP this would be a singleton behavior).</p>\n\n<p>If you can't rewrite your whole system to have an object oriented design to have the ability to use a DI container then the only thing you could do is to create a class loader in your bootstrap section to load a factory.</p>\n\n<p>A Factory is a simple class which can build object instances like a DatabaseFactory::CreateNewConnection would return a new PDO instance. You can create a static factory but that would be as flexible as the pig-iron. A recommend you to have a static DatabaseBuilder class there you can register a DatabaseFactory class instance as the default database factory and your factory can hold a database class instance until the request ends. Here is the skeleton:</p>\n\n<pre><code><?php\n\nclass DatabaseFactoryBuilder {\n\n private function __construct() {}\n\n public static function SetFactory(IDatabaseFactory $factory) {\n $this->_factory = $factory;\n }\n\n public static function GetFactory() {\n return $this->_factory;\n }\n\n}\n\ninterface IDatabaseFactory {\n function GetDatabase();\n}\n\nclass DatabaseFactory implements IDatabaseFactory {\n\n /* ... */\n\n private $_db;\n\n public function __construct($dbServer, $dbName, $dbUser, $dbPassword) {\n /* ... */\n }\n\n public function GetDatabase() {\n if ($this->_db == NULL) {\n $this->_db = new PDO(/* ... */);\n }\n\n return $this->_db;\n }\n\n}\n</code></pre>\n\n<p>Ofcourse as you can se you have to create a decent way to set the connection properties for your database.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T15:41:18.010",
"Id": "27432",
"ParentId": "27423",
"Score": "1"
}
},
{
"body": "<p>I'll keep the procedural style, you use; otherwise I'd prefer object oriented code.</p>\n\n<p>You need a function that creates the database connection on the first call and returns that connection on every call.</p>\n\n<pre><code>function getDbConnection()\n{\n static $db = null;\n\n if (is_null($db)) {\n $db = new PDO(\"mysql:host=localhost;dbname=users\", \"root\", \"\");\n }\n return $db;\n}\n</code></pre>\n\n<p>The <code>static</code> keyword makes the variable keep its value after leaving the function.</p>\n\n<p>Now the functions with database access only have to know the <code>getDbConnection()</code> function, but no details about the connection.</p>\n\n<pre><code>function input_registration($email, $password)\n{\n try {\n $db = getDbConnection();\n $statement = $db->prepare(\"INSERT INTO userinfo(email, hash) VALUES (:email, :hash)\");\n $array_parameters = array(\n 'email' => $email,\n 'hash' => md5($password)\n );\n $statement->execute($array_parameters);\n } catch (Exception $error) {\n echo \"Database error: \". $error->getMessage();\n }\n}\n</code></pre>\n\n<p>It is better design though, if any function that needs the database connection, gets it through its arguments.</p>\n\n<pre><code>function input_registration(PDO $db, $email, $password)\n{\n try {\n $statement = $db->prepare(\"INSERT INTO userinfo(email, hash) VALUES (:email, :hash)\");\n $array_parameters = array(\n 'email' => $email,\n 'hash' => md5($password)\n );\n $statement->execute($array_parameters);\n } catch (Exception $error) {\n echo \"Database error: \". $error->getMessage();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T21:37:54.783",
"Id": "27440",
"ParentId": "27423",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T23:39:08.543",
"Id": "27423",
"Score": "1",
"Tags": [
"php",
"pdo"
],
"Title": "How do I put $db in a central location, but maintain variable scope"
}
|
27423
|
<p>I have inherited an application that has code to save and populate values in an ASP.NET checkboxlist control. The existing code is very lengthy and does not appear to be efficient to me. I plan on rewriting this application and have complete control over the database design.</p>
<p>All of the checkboxlist items are stored in an SQL table as bit fields. Each row of checkboxlist values are assigned to a user ID. Once again, my goal is to find a more efficient way to save and populate selected checkboxlist items with less code. I'm open to changing the table design, using Linq or lambda if it helps. I'm new to ASP.NET but there must be a better way of doing this.</p>
<pre><code>Current table design
UserID AA BC AC
1 1 1 0
2 0 1 1
3 1 1 0
4 1 1 1
'Code to populate selected checkboxlist items(there are a total of 22 bit values)
Dim CodeData as datarow
CodeData = CodeDataTable.Rows(0)
For Each li As ListItem In Me.cblCodes.Items
If li.Text = "AA" Then
If Not CodeData.IsOneNull Then
If CodeData.One = True Then
li.Selected = True
End If
End If
End If
If li.Text = "BC" Then
If Not CodeData.IsTwoNull Then
If CodeData.Two = True Then
li.Selected = True
End If
End If
End If
If li.Text = "AC" Then
If Not CodeData.IsTwoNull Then
If CodeData.Two = True Then
li.Selected = True
End If
End If
End If
......
Next
'Code to save checkboxlist values
Dim AA As Boolean = False
Dim BC As Boolean = False
Dim AC As Boolean = False
Dim AD As Boolean = False
AA = Me.cblCodes.Items.FindByText("AA").Selected()
BC = Me.cblCodes.Items.FindByText("BC").Selected
AC = Me.cblCodes.Items.FindByText("AC").Selected
AD = Me.cblCodes.Items.FindByText("AD").Selected
CodeTableAdapter.UpdateCodes(UserID,AA,BC,AC,AD.......)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T12:20:47.600",
"Id": "42654",
"Score": "0",
"body": "If nought else, you can use [`AndAlso`](http://msdn.microsoft.com/en-us/library/wz3k228a(v=vs.110).aspx) and stop check for `True`: `If li.Text = \"AA\" AndAlso Not CodeData.IsOneNull AndAlso CodeData.One Then li.Selected = True`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T23:57:27.200",
"Id": "42710",
"Score": "0",
"body": "Ok, but is it a better approach for me to change the table structure to just store the value in one column? I would have to use a for loop and delete all items before inserting each time the page is saved. Just not sure about the best approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T00:14:57.900",
"Id": "42713",
"Score": "0",
"body": "If you really need to support nullable bits then I would keep them as separate bit columns. Breaking the repeating code out into a small `Sub` might help with readability and reliability (DRY)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T10:29:33.947",
"Id": "42734",
"Score": "0",
"body": "I think the code was designed this way to prevent the need to loop thru tons of table rows on page load. There could be 20+ selected checkboxes for one user id. They developer thought the bit field approach would be easier on the database(one row for each user)"
}
] |
[
{
"body": "<p>I think it's reasonable to look at whether a single column design is possible - it certainly makes life easier:</p>\n\n<pre><code>For Each DataRow dr in CodeDataTable.Rows\n Dim li as ListItem = Me.cblCodes.Items.FindByText(CType(dr[\"Text\"], String))\n li.Selected = True\nNext\n</code></pre>\n\n<p>You could alternatively do a two column design, with a <code>Text varchar</code> and a <code>Value bit</code>:</p>\n\n<pre><code>For Each DataRow dr in CodeDataTable.Rows\n Dim li as ListItem = Me.cblCodes.Items.FindByText(CType(dr[\"Text\"], String))\n li.Selected = CType(dr[\"Value\"], Boolean)\nNext\n</code></pre>\n\n<p>But even the wide table could be done with less repetitive code by using <code>DataTable.Columns</code> to get the names of the columns:</p>\n\n<pre><code>Dim codeData as DataRow = CodeDataTable.Rows(0)\nFor Each DataColumn dc in CodeDataTable.Columns\n Dim li as ListItem = Me.cblCodes.Items.FindByText(dc.Name)\n If Not codeData.IsNull(dc) AndAlso CType(codeData[dc], Boolean) Then\n li.Selected = True\n End If\nNext\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T03:02:25.703",
"Id": "42788",
"Score": "0",
"body": "Your recommendations are extremely helpful and I've learned a lot from your post. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T02:45:36.730",
"Id": "27492",
"ParentId": "27426",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T04:32:43.017",
"Id": "27426",
"Score": "1",
"Tags": [
"performance",
"asp.net",
"vb.net"
],
"Title": "Populating and saving checkboxlist items to the database"
}
|
27426
|
<p>I have a method that takes a generator, converts it into a tuple to sort it, then into a list. It works perfectly, but being as I am fairly new to the Python world, I keep asking myself if it is worth doing or not...</p>
<pre><code>@property
def tracks(self):
if 'tracks' not in self.cache:
s = Search(Track)
q = {'query': self.name}
if self.artists[0]['name'] != 'Various Artists':
q.update({'artist': self.artists[0]['name']})
_, tracks = s.search(**q)
tracks = sorted(((int(i.track_number), i) for i in tracks))
self.cache['tracks'] = [t for n, t in tracks]
return self.cache['tracks']
</code></pre>
<p>I could care less about <code>track_number</code> as the <code>track[i]</code> already has that information, I'm just using it to sort the track list. <code>s.search(**q)</code> generates a generator of <code>Track</code> instances from a <code>json</code> object, I sort the track list, then I turn it back to a generator for an output.</p>
<p>Is there a better way? Should I just deal with the track number being there?</p>
<pre><code>for _, track for Album.tracks:
# work with track
</code></pre>
<p><strong>Update</strong>:</p>
<p>The way the backend API works it only requires the first artist in the search, on a collaborated album of various artists, it just gives <code>Various Artists</code>, hence the <code>self.artists[0]['name']</code> which is usually the only item in the list anyways.</p>
<p>And I know <code>q['key'] = value</code> is better practice than <code>q.update({key: value})</code>, originally it was taking more than a few items, hence the use of <code>.update()</code>, I just never changed that part.</p>
<p>The method is being called in <code>Album.tracks</code> where <code>s = Search(Track)</code> tells the <code>Search</code> class to use the <code>Track</code> class.</p>
<pre><code>## models.py
class Album:
@property
def tracks(self):
s = Search(Track)
## search.py
class Search(Service):
def __init__(self, model):
self.model = model
</code></pre>
<p>Instead of:</p>
<pre><code>## models.py
class Album:
@property
def tracks(self):
s = Search('track')
## search.py
from models import *
MODELS = {
'album': Album,
'artist': Artist,
'track': Track
}
class Search(Service):
def __init__(self, model):
self.model = MODELS[model]
</code></pre>
<p><code>Search</code> calls a backend api service that returns queries in <code>JSON objects</code> which then generates instances based on what <code>self.model</code> is set to. <code>s = Search(Tracks)</code> tells <code>Search</code> to call the <code>track</code> api and iterate through the results and return <code>Track</code> instances.</p>
<p>The main question here is, the current method that I have, is it doing too much? It generates the <code>Track</code> instances from the <code>Search.search()</code> generator, which is a somewhat abstract method for calling the api service for <code>Album</code>, <code>Artist</code>, and <code>Track</code> so it does nothing but generating instances based on what model it is given. Which is why I then have <code>Album.tracks</code> create a tuple so that I can sort the tracks base on track number, and then return a list of the tracks, nice and sorted.</p>
<p><strong>Main point:</strong> Should I be worried about getting rid of the track numbers and just return the tuple, or is it fine to return the list?</p>
<p><strong>Update 2:</strong></p>
<pre><code>class Album:
@property
def tracks(self):
if 'tracks' not in self.cache:
s = Search(Track)
q = {'query': '', 'album': self.name}
if self.artists[0]['name'] != 'Various Artists':
q['artist'] = self.artists[0]['name']
_, tracks = s.search(**q)
self.cache['tracks'] = sorted(tracks,
key = lambda track: int(track.track_number))
return self.cache['tracks']
class Track(BaseModel):
def __repr__(self):
artist = ', '.join([i['name'].encode('utf-8') for i in self.artists])
track = self.name.encode('utf-8')
return '<Track - {artist}: {track}>'.format(artist=artist, track=track)
</code></pre>
<p>Calling it:</p>
<pre><code>album_meta = Search(Album)
results = album_meta.search('making mirrors', artist='gotye')
for album results:
print album.tracks
''' Output
[<Track - Gotye: Making Mirrors>,
<Track - Gotye: Easy Way Out>,
<Track - Gotye, Kimbra: Somebody That I Used To Know>,
<Track - Gotye: Eyes Wide Open>,
<Track - Gotye: Smoke And Mirrors>,
<Track - Gotye: I Feel Better>,
<Track - Gotye: In Your Light>,
<Track - Gotye: State Of The Art>,
<Track - Gotye: Don’t Worry, We’ll Be Watching You>,
<Track - Gotye: Giving Me A Chance>,
<Track - Gotye: Save Me>,
<Track - Gotye: Bronte>] '''
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T16:40:34.707",
"Id": "42658",
"Score": "0",
"body": "This function would be easier to review if you told us a bit more about the Album class that it is defined on, what is it used for, what the performance considerations are, etc."
}
] |
[
{
"body": "<p>I'm not sure I understand what your question is. You already remove the track numbers from the value you return with:</p>\n\n<pre><code>self.cache['tracks'] = [t for n, t in tracks]\n</code></pre>\n\n<p>Other notes:</p>\n\n<ul>\n<li>I'm a little worried about the line <code>s = Search(Track)</code>. What is it searching? Does the constructor for <code>Search</code> have access to some sort of singleton database? This is a place where dependency injection would probably improve the code.</li>\n<li>Why only <code>self.artists[0]</code>? In what circumstances would there be multiple artists? Why would you ignore results for the other artists? What if an artist participated in multiple albums with the same name but a different set of collaborators?</li>\n<li>The <code>q.update({...})</code> line is a bit odd. I would find it considerably clearer to read <code>q['artist'] = ...</code> instead.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T17:31:35.330",
"Id": "42661",
"Score": "0",
"body": "The question has been updated with the in-depth explanation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T17:02:58.710",
"Id": "27436",
"ParentId": "27431",
"Score": "1"
}
},
{
"body": "<p>You create intermediate list for sorting:</p>\n\n<pre><code>tracks = sorted(((int(i.track_number), i) for i in tracks))\n</code></pre>\n\n<p>and then chose only one column:</p>\n\n<pre><code>self.cache['tracks'] = [t for n, t in tracks]\n</code></pre>\n\n<p>I think this would be better to replace two statements above:</p>\n\n<pre><code>self.cache['tracks'] = sorted(tracks, key = lambda track: int(track.track_number))\n</code></pre>\n\n<p>Also, <code>q.update({'artist': self.artists[0]['name']})</code> doesn't look good. It can easily be replaced with <code>q['artist'] = self.artists[0]['name']</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T17:38:50.060",
"Id": "42662",
"Score": "0",
"body": "This is exactly what I was looking to hear. A way to reduce/combine it all. I felt like it was doing too much repetitive work generating a list to sort, then generate another list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T17:16:31.830",
"Id": "27437",
"ParentId": "27431",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27437",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T15:21:55.950",
"Id": "27431",
"Score": "0",
"Tags": [
"python",
"generator"
],
"Title": "Generator to Tuple to List?"
}
|
27431
|
<p>Sometime ago I saw a code which packed key,value pairs into several GET messages. That code had a bug (that is why it was shown to me: as the example of beautiful code which doesn't do what it should).</p>
<p>Today I decided to write this code out of curiosity and for training.</p>
<p>This is what I have written:</p>
<pre><code>def group(url,D,limit):
if len(D) == 0:
if len(url) <= limit:
yield url
return
else:
raise ValueError("url is longer than limit")
if len(url) > limit - 2:
raise ValueError("url is too long to be able to hold any key-value pairs")
for i,(key,value) in enumerate(D.iteritems()):
if i == 0:
old = url
new = '{url}?{key}={value}'.format(**locals())
continue
new, old = '{new}&{key}={value}'.format(**locals()), new
if len(new) > limit:
if len(old) > limit:
raise ValueError("String '{old}' is longer than GET query limit.".format(**locals()))
yield old
old = url
new = '{url}?{key}={value}'.format(**locals())
if len(new) != len(url):
if len(new) > limit:
raise ValueError("String '{new}' is longer than GET query limit.".format(**locals()))
yield new
</code></pre>
<p>I have <a href="http://ideone.com/VcZzEf" rel="nofollow">written some tests</a> and the code seems to work correctly.</p>
<p>Still, I don't like it.</p>
<p>If we leave alone corner case checking at the beginning, we will only have one working cycle.
Inside that cycle I had to keep two strings: <code>old</code> and <code>new</code>. If <code>new</code> is longer than the limit, I <code>yield</code> the old one, and start a new string with blank url plus key,value pair added which caused the previous new string to grow beyond the limit.</p>
<p>To make it work I had to write the same statements in different places of that loop.</p>
<p>For example, </p>
<pre><code>old = url
new = '{url}?{key}={value}'.format(**locals())
</code></pre>
<p>is written it two places.</p>
<pre><code>raise ValueError("String '{new}' is longer than GET query limit.".format(**locals()))
</code></pre>
<p>is also in two places.</p>
<p>Can it be refactored to have statements to be written only once without duplication?</p>
<p>Are there any other things that I should pay attention to?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T17:12:44.493",
"Id": "42659",
"Score": "0",
"body": "Are you sure that you want to return the url if there are no key-value pairs, instead returning without generating any values? It makes the base case different than cases with key-value pairs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T17:19:15.967",
"Id": "42660",
"Score": "0",
"body": "@ruds I thought about it. And yes, I think it would be more expected behavior. I can implement it this way or that way and describe it in the docstring. But I think if a caller provides empty dictionary, they want just to issue url query with no parameters."
}
] |
[
{
"body": "<pre><code>def group(url,D,limit):\n</code></pre>\n\n<p>D is a bad parameter name because it doesn't follow the python convention: lowercase_with_underscores, and because it a pointless abbreviation.</p>\n\n<pre><code> if len(D) == 0:\n if len(url) <= limit:\n yield url\n return\n else:\n raise ValueError(\"url is longer than limit\")\n\n if len(url) > limit - 2:\n raise ValueError(\"url is too long to be able to hold any key-value pairs\")\n</code></pre>\n\n<p>Is this really a useful check? Two characters is probably not enough to actually hold any of the pairs. You probably don't catch anything here you wouldn't already catch</p>\n\n<pre><code> for i,(key,value) in enumerate(D.iteritems()):\n if i == 0:\n</code></pre>\n\n<p>enumerating for the sole purpose of special casing the first entry is rather gross. </p>\n\n<pre><code> old = url\n new = '{url}?{key}={value}'.format(**locals())\n continue\n</code></pre>\n\n<p>I discourage the use of continue. It's almost always better to put things in an else block</p>\n\n<pre><code> new, old = '{new}&{key}={value}'.format(**locals()), new\n</code></pre>\n\n<p>Use of <code>locals()</code> is discouraged. It encourages sloppy coding and forces python into a slower compatibility mode for that function. </p>\n\n<pre><code> if len(new) > limit:\n if len(old) > limit:\n raise ValueError(\"String '{old}' is longer than GET query limit.\".format(**locals()))\n yield old\n old = url\n new = '{url}?{key}={value}'.format(**locals())\n if len(new) != len(url):\n</code></pre>\n\n<p>In which case would this be false?</p>\n\n<pre><code> if len(new) > limit:\n</code></pre>\n\n<p>Why is this check inside the other check?</p>\n\n<pre><code> raise ValueError(\"String '{new}' is longer than GET query limit.\".format(**locals()))\n yield new\n</code></pre>\n\n<p>Of course, you've already noted the duplicated code here.</p>\n\n<p>Here's my take on reworking it:</p>\n\n<pre><code>def blocked(items, limit, seperator):\n \"\"\"\n items is a list of strings, to be joined with seperator.\n Produces a generator of strings, each with a length <= the limit\n \"\"\"\n current = []\n current_length = 0\n for item in items:\n length = len(item) + len(seperator)\n if length > limit:\n raise ValueError('{} cannot fit'.format(item))\n elif length + current_length > limit:\n yield seperator.join(current)\n current = [item]\n current_length = length\n else:\n current.append(item)\n current_length += length\n yield seperator.join(current)\n\ndef group(url,data,limit):\n if len(url) > limit:\n raise ValueError('{} is longer than the limit of {}'.format(url, limit))\n\n pairs = [\"{}={}\".format(k,v) for k, v in data.iteritems()]\n for block in blocked(pairs, limit - len(url), \"&\"):\n if block:\n yield '{}?{}'.format(url, block)\n else:\n yield url\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T12:37:52.357",
"Id": "42682",
"Score": "0",
"body": "Thank you! You pointed to a lot of things I should pay attention to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T12:39:32.317",
"Id": "42683",
"Score": "0",
"body": "I like your solution where you separated the parameter serialization code into another function `blocked`. This removed code duplication."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T12:41:25.010",
"Id": "42684",
"Score": "0",
"body": "What I would change is `pairs` which can be just generator expression as `blocked` may accept `items` as iterator because it only iterates over these values (no random-access, in-place modifications, etc.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T13:18:58.547",
"Id": "42687",
"Score": "0",
"body": "I have slightly refactored the code. Made it as lazy as possible. Here is the link: http://ideone.com/81NDnK Maybe it will come in handy for somebody searching for ready solution for this problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T16:04:18.390",
"Id": "42688",
"Score": "0",
"body": "@ovgolovin, your pairs generator expression just produces the .iteritems(). You can just pass the return of iteritems into the blocked function. I'm generally suspicious of laziness, as I suspect its usually more expensive if you're going to do the work anyways."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T22:34:14.933",
"Id": "27441",
"ParentId": "27435",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27441",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T16:38:55.233",
"Id": "27435",
"Score": "1",
"Tags": [
"python"
],
"Title": "Group key-value pairs in chunks no longer than specified limit"
}
|
27435
|
<p>Trying to implement <a href="http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at" rel="nofollow">this API</a> in a way that works pre and post jQuery UI 1.9:</p>
<p>I have a subtle feeling that there should be a more elegant way.</p>
<pre><code>/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
return n === 0 ? "" :(( n > 0 ) ? ("+" + n) : ("" + n));
}
var posOpts = {
at: "left top",
of: $target
};
if( isVersionAtLeast($.ui.version, 1, 9) ){
posOpts.my = "left" + offsetString(markerOffsetX) +
" top" + offsetString(markerOffsetY);
} else {
posOpts.my = "left top";
posOpts.offset = "" + markerOffsetX + " " + markerOffsetY;
}
$dropMarker.position(posOpts);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-26T15:12:36.790",
"Id": "110880",
"Score": "0",
"body": "I recommend that you put the relevant information from that link into this post in case the link ever goes dead."
}
] |
[
{
"body": "<p>Interesting question,</p>\n\n<p>have you tried passing <code>+0</code> as an offset, that should work and make your code a little easier to read. </p>\n\n<pre><code>/** Prefix number with '+'/'-' or return empty string for 0. */\nfunction offsetString(n){\n return '' + ( n < 0 ? n : '+' + n );\n}\n</code></pre>\n\n<p>As for the <code>isVersionAtLeast($.ui.version, 1, 9)</code> I would only check this once.</p>\n\n<pre><code>function generateCompatibleOffsetFunction(){\n\n if( isVersionAtLeast($.ui.version, 1, 9) ){\n return function setOffset( options , offsetX , offsetY ){\n options.my = \"left\" + offsetString(offsetX ) + \" top\" + offsetString(offsetY );\n }\n } else {\n return function setOffset( options , offsetX , offsetY ){\n options.my = \"left top\";\n options.offset = \"\" + offsetX + \" \" + offsetY;\n }\n }\n}\n\nvar setOffset = generateCompatibleOffsetFunction();\n\n/** Prefix number with '+'/'-' or return empty string for 0. */\nfunction offsetString(n){\n return '' + ( n < 0 ? n : '+' + n );\n}\n\nvar posOpts = {\n at: \"left top\",\n of: $target\n};\n\nsetOffset( posOpts, markerOffsetX, markerOffsetY );\n\n$dropMarker.position(posOpts);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-15T00:02:33.713",
"Id": "66690",
"ParentId": "27439",
"Score": "2"
}
},
{
"body": "<p>I came up with this approach (barely tested): the idea is to use the new syntax, but convert to the old syntax when a legacy jQuery UI is included (i.e. version <= 1.8).</p>\n\n<p>This could be used like so:</p>\n\n<pre><code>$(\"#source\").position(fixPositionOptions({\n my: \"left+30 center\",\n at: \"center bottom+30\",\n of: $(\"#target\")\n}));\n</code></pre>\n\n<p>(See also this fiddle: <a href=\"http://jsfiddle.net/mar10/6xtu9a4e/\" rel=\"nofollow\">http://jsfiddle.net/mar10/6xtu9a4e/</a>)</p>\n\n<pre><code>var uiVersion = $.ui.version.match(/^(\\d)\\.(\\d+)/);\n\n/** Make jQuery.position() arguments backwards compatible,i.e. if \n * jQuery UI version <= 1.8, convert \n * { my: \"left+3 center\", at: \"left bottom\", of: $target }\n * to\n * { my: \"left center\", at: \"left bottom\", of: $target, offset: \"3 0\" }\n *\n * See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at\n * and http://jsfiddle.net/mar10/6xtu9a4e/\n */\nfunction fixPositionOptions(opts) {\n if( opts.offset || (\"\" + opts.my + opts.at ).indexOf(\"%\") >= 0 ) {\n $.error(\"expected new position syntax (but '%' is not supported)\");\n }\n if( uiVersion[1] < 2 && uiVersion[2] <= 8 ) {\n var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined]\n myParts = /(\\w+)([+-]?\\d+)?\\s+(\\w+)([+-]?\\d+)?/.exec(opts.my),\n atParts = /(\\w+)([+-]?\\d+)?\\s+(\\w+)([+-]?\\d+)?/.exec(opts.at),\n // convert to numbers\n dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0),\n dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0);\n\n opts = $.extend({}, opts, { // make a copy and overwrite\n my: myParts[1] + \" \" + myParts[3],\n at: atParts[1] + \" \" + atParts[3]\n });\n if( dx || dy ) {\n opts.offset = \"\" + dx + \" \" + dy;\n }\n }\n return opts;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-22T20:35:21.863",
"Id": "78358",
"ParentId": "27439",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T20:12:47.243",
"Id": "27439",
"Score": "4",
"Tags": [
"javascript",
"jquery-ui"
],
"Title": "Using jQuery UI .position() in a backwards compatible way"
}
|
27439
|
<p>I wrote this a couple months ago and just wanted to get some feedback on it. In the <code>printBoard()</code> function, you see I commented out the system function. I've read this is considered bad practice. Does anyone know of any alternative to clearing the terminal window? I thought it'd be a nice touch to clear the window instead of just having the updated board appear below the previous.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BOARD_ROWS 6
#define BOARD_COLS 7
void printBoard(char *board);
int takeTurn(char *board, int player, const char*);
int checkWin(char *board);
int checkFour(char *board, int, int, int, int);
int horizontalCheck(char *board);
int verticalCheck(char *board);
int diagonalCheck(char *board);
int main(int argc, char *argv[]){
const char *PIECES = "XO";
char board[BOARD_ROWS * BOARD_COLS];
memset(board, ' ', BOARD_ROWS * BOARD_COLS);
int turn, done = 0;
for(turn = 0; turn < BOARD_ROWS * BOARD_COLS && !done; turn++){
printBoard(board);
while(!takeTurn(board, turn % 2, PIECES)){
printBoard(board);
puts("**Column full!**\n");
}
done = checkWin(board);
}
printBoard(board);
if(turn == BOARD_ROWS * BOARD_COLS && !done){
puts("It's a tie!");
} else {
turn--;
printf("Player %d (%c) wins!\n", turn % 2 + 1, PIECES[turn % 2]);
}
return 0;
}
void printBoard(char *board){
int row, col;
//system("clear");
puts("\n ****Connect Four****\n");
for(row = 0; row < BOARD_ROWS; row++){
for(col = 0; col < BOARD_COLS; col++){
printf("| %c ", board[BOARD_COLS * row + col]);
}
puts("|");
puts("-----------------------------");
}
puts(" 1 2 3 4 5 6 7\n");
}
int takeTurn(char *board, int player, const char *PIECES){
int row, col = 0;
printf("Player %d (%c):\nEnter number coordinate: ", player + 1, PIECES[player]);
while(1){
if(1 != scanf("%d", &col) || col < 1 || col > 7 ){
while(getchar() != '\n');
puts("Number out of bounds! Try again.");
} else {
break;
}
}
col--;
for(row = BOARD_ROWS - 1; row >= 0; row--){
if(board[BOARD_COLS * row + col] == ' '){
board[BOARD_COLS * row + col] = PIECES[player];
return 1;
}
}
return 0;
}
int checkWin(char *board){
return (horizontalCheck(board) || verticalCheck(board) || diagonalCheck(board));
}
int checkFour(char *board, int a, int b, int c, int d){
return (board[a] == board[b] && board[b] == board[c] && board[c] == board[d] && board[a] != ' ');
}
int horizontalCheck(char *board){
int row, col, idx;
const int WIDTH = 1;
for(row = 0; row < BOARD_ROWS; row++){
for(col = 0; col < BOARD_COLS - 3; col++){
idx = BOARD_COLS * row + col;
if(checkFour(board, idx, idx + WIDTH, idx + WIDTH * 2, idx + WIDTH * 3)){
return 1;
}
}
}
return 0;
}
int verticalCheck(char *board){
int row, col, idx;
const int HEIGHT = 7;
for(row = 0; row < BOARD_ROWS - 3; row++){
for(col = 0; col < BOARD_COLS; col++){
idx = BOARD_COLS * row + col;
if(checkFour(board, idx, idx + HEIGHT, idx + HEIGHT * 2, idx + HEIGHT * 3)){
return 1;
}
}
}
return 0;
}
int diagonalCheck(char *board){
int row, col, idx, count = 0;
const int DIAG_RGT = 6, DIAG_LFT = 8;
for(row = 0; row < BOARD_ROWS - 3; row++){
for(col = 0; col < BOARD_COLS; col++){
idx = BOARD_COLS * row + col;
if(count <= 3 && checkFour(board, idx, idx + DIAG_LFT, idx + DIAG_LFT * 2, idx + DIAG_LFT * 3) || count >= 3 && checkFour(board, idx, idx + DIAG_RGT, idx + DIAG_RGT * 2, idx + DIAG_RGT * 3)){
return 1;
}
count++;
}
count = 0;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T08:51:36.860",
"Id": "42681",
"Score": "3",
"body": "To clear the screen in a Linux terminal, use the [ncurses library](http://linux.die.net/man/3/curs_clear). Under windows, see [Microsoft KB 92261](http://support.microsoft.com/kb/99261)."
}
] |
[
{
"body": "<p>Some comments, in no particular order:</p>\n\n<p><strong>1:</strong> For applications like this, I think it is perfectly legitimate to use <code>system()</code>. It's not exactly elegant, but in this particular case I think it's fine. You could do:</p>\n\n<pre><code>void clearScreen() {\n#ifdef WIN32\n system(\"cls\");\n#else\n system(\"clear\");\n#endif // WIN32\n}\n</code></pre>\n\n<p><strong>2:</strong> Consider using the <a href=\"http://en.wikipedia.org/wiki/C99\">C99</a> or <a href=\"http://en.wikipedia.org/wiki/C11_%28C_standard_revision%29\">C11</a> standards. They allow a couple of things that make the code easier to read and maintain. For example, substitute your <code>#define</code>s with <code>const int BOARD_ROWS = 6</code>. This helps debugging (because you see <code>BOARD_ROWS</code> and not <code>6</code> in the compiler and debugger output), adds scope to the variables and generally avoids most of the problems with <code>#define</code>s.</p>\n\n<p>C99 and C11 don't require that variable definitions appear at the beginning of their scope. This means you can keep variables closer to their relevant context. The most useful example for this is <code>for</code> loops. In C99 and C11, you can write</p>\n\n<pre><code> for (int row = 0; row < BOARD_ROWS; ++row)\n</code></pre>\n\n<p>C99 also introduced a <code>bool</code> type (which is actually just a typedef for <code>int</code>). This makes the code more readable. Usage example: <code>bool done = false; while (!done) { ... done = true; }</code>. The bool type is of course available in C11 as well.</p>\n\n<p><strong>3:</strong> What is the value of <code>row</code> after <code>int row, col = 0;</code>? It's unspecified, so <code>row</code> can have any value. If you mean to initialize both variables, which you should, you need to write <code>int row = 0, col = 0;</code>.</p>\n\n<p>(There's a similar gotcha in C. What's the type of p2 in this snippet: <code>int *p1, p2;</code>? It's a plain <code>int</code>, only <code>p1</code> is an <code>int*</code>. To make both variables pointers, write <code>int *p1, *p2</code>.)</p>\n\n<p><strong>4:</strong> Consider using <code>printf</code> consistently instead of <code>puts</code>.</p>\n\n<p><strong>5:</strong> Consider preferring pre-increment operators. <code>row++</code> means \"increment row, then return a copy of what it looked like before incrementing\". <code>++row</code> means \"increment row\", which is what you mean. It's not a big difference in this case, and the compiler can optimize away the extra copy, but I like the habit of writing exactly what you mean. If you ever start writing C++-code with user-defined increment operators, this can actually be important.</p>\n\n<p><strong>6:</strong> Try to always initialize your variables, rather than set their value at a later time. It's faster, cleaner and safer. Note that static and global variables are guaranteed to be zero-initialized when the program starts, but it doesn't hurt to be explicit.</p>\n\n<p><strong>7:</strong> Full variable names are easier to read, and there's no good reason not to type them out. Prefer <code>index</code> over <code>idx</code>, <code>DIAGONAL_RIGHT</code> over <code>DIAG_RGT</code> and so on.</p>\n\n<p><strong>8:</strong> Personally, I prefer <code>for (;;)</code> over <code>while (1)</code>. The former is commonly read out loud as \"forever\".</p>\n\n<p><strong>9:</strong> Consider adding documentation and comments to your code. For example Doxygen comments before each function.</p>\n\n<p><strong>10:</strong> Code that is not self-explanatory should be factored out into separate functions with meaningful names. Consider your <code>while(getchar() != '\\n');</code>. Putting this into a function called either <code>flushInputBuffer()</code> or <code>waitForEnter()</code> conveys intent and what is going on much better than the original code.</p>\n\n<p><strong>11:</strong> Consider changing your whitespace to increase readability. Instead of\n return 0;</p>\n\n<pre><code> }\n int diagonalCheck(char *board){\n</code></pre>\n\n<p>write</p>\n\n<pre><code> return 0;\n }\n\n int diagonalCheck(char *board) {\n</code></pre>\n\n<p>to emphasize that the closing bracket belongs to the topmost function, not the bottom one. Also consider whitespace before brackets, for example. This is a matter of preference, the most important thing is that you're consistent and that the code is readable.</p>\n\n<p><strong>12:</strong> Break up long lines into more, shorter lines. This is a tremendous help for readability, and especially helps when doing source control merges, debugging in a debugger and other cases where your window width is limited. It's common to limit lines to 80-100 characters.</p>\n\n<p><strong>13:</strong> Consider sorting <code>#include</code>s in alphabetical order.</p>\n\n<p><strong>14:</strong> Consider using unit tests.</p>\n\n<p><strong>15:</strong> There are several things you are doing that are <em>good</em>. For example using symbolic rather than literal constants, i.e. <code>const int DIAG_RGT = 6, DIAG_LFT = 8;</code>. Your program is also fairly well divided into functions, and most variable names are reasonably named. Keep doing these things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T20:53:06.713",
"Id": "42702",
"Score": "0",
"body": "Thanks! I don't really have a very profound reason, it's just that I think the \"print\" makes `printf` clearer than `puts`. I like the principle of least astonishment, and my impression is that `printf` is more common. I base that only on code I've read and not on any research, so I may well be biased."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T03:00:11.023",
"Id": "42967",
"Score": "0",
"body": "Thanks for the review. Regarding `puts`, my friend who's a software developer said to use it if you're just printing a string because it doesn't have to analyze the string format that `printf` does. As far as I know, it probably isn't gonna make much difference for speed, other than its 2 letters shorter to type. I've just always had the habit of doing that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T03:04:20.193",
"Id": "42968",
"Score": "1",
"body": "It's very typical of C-programmers to think like that, but I recommend preferring readability over performance except in the critical path :) By the way, if you feel that the answer is satisfactory, feel free to click *accept answer*. If you like another answer better, accept it instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T15:33:09.650",
"Id": "27451",
"ParentId": "27446",
"Score": "5"
}
},
{
"body": "<p>Here are some extra points not covered by the excellent review from @Lstor</p>\n\n<p>You can avoid the need for prototypes by putting <code>main</code> at the end. This\nmight seem odd but it is quite common practice. Also, your functions could\nall be <code>static</code>, as they are used only in this file. For single-file programs\nthis is of no significance, but for large programs it is best practice as it\navoids polluting the namespace and may make optimisation possible.</p>\n\n<hr>\n\n<p>This:</p>\n\n<pre><code>char board[BOARD_ROWS * BOARD_COLS];\nmemset(board, ' ', BOARD_ROWS * BOARD_COLS);\n</code></pre>\n\n<p>is better written with <code>sizeof</code></p>\n\n<pre><code>char board[BOARD_ROWS * BOARD_COLS];\nmemset(board, ' ', sizeof board);\n</code></pre>\n\n<p>This guarantees that the array is cleared even if you were to change the size of <code>board</code> and forgot to change the <code>memset</code> line.</p>\n\n<hr>\n\n<p>As there are only two ways of leaving the for-loop in <code>main</code>, namely when\n<code>(turn >= BOARD_ROWS * BOARD_COL)</code> and when <code>done</code> is set, this line following\nthe loop:</p>\n\n<pre><code>if(turn == BOARD_ROWS * BOARD_COLS && !done){\n</code></pre>\n\n<p>is the same as just testing <code>!done</code></p>\n\n<hr>\n\n<p>Your input loop in <code>takeTurn</code> is unusual. I would usually use <code>fgets</code> rather\nthan <code>scanf</code> (using <code>scanf</code> results in you having to purge the input on false data, as you discovered, because <code>scanf</code> doesn't remove the false data from the input stream. Also your loop doesn't check for the input stream being closed):</p>\n\n<pre><code>int col = 0;\nchar buf[10];\nwhile (fgets(buf, sizeof buf, stdin) != NULL) {\n col = (int) strtol(buf, 0, 0);\n if (col >= 1 && col <= 7 ) {\n break;\n }\n puts(\"Number out of bounds! Try again.\");\n}\nif (col == 0) { // user entered ctrl-d to end input\n exit(1);\n}\n</code></pre>\n\n<hr>\n\n<p>The fact that you <strong>always</strong> call <code>checkBoard</code> with the 4th and 5th parameters\nmultiplied by 2 and 3 respectively implies to me that the function might be\nbetter doing the multiplications.</p>\n\n<hr>\n\n<p>Your long expression:</p>\n\n<pre><code>if(count <= 3 &&\n checkFour(board, idx, idx + DIAG_LFT, idx + DIAG_LFT * 2, idx + DIAG_LFT * 3) ||\n count >= 3 &&\n checkFour(board, idx, idx + DIAG_RGT, idx + DIAG_RGT * 2, idx + DIAG_RGT * 3)){\n return 1;\n}\n</code></pre>\n\n<p>needs some brackets. The compiler gives me this warning:</p>\n\n<pre><code> warning: '&&' within '||' [-Wlogical-op-parentheses]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T00:07:50.640",
"Id": "42712",
"Score": "0",
"body": "+1. Many valid points that I had missed. Regarding using `sizeof` with `memset`: I wholly agree. When doing so, however, it is very important not to do it through a function. Arrays are demoted to pointers when passed to functions, and the size will in that case be the same as `sizeof(char*)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T21:19:48.283",
"Id": "27460",
"ParentId": "27446",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27451",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T08:12:54.713",
"Id": "27446",
"Score": "4",
"Tags": [
"c",
"console",
"connect-four"
],
"Title": "Connect Four game"
}
|
27446
|
<p><a href="http://www.codechef.com/JUNE13/problems/COLLECT" rel="nofollow">Here is the link of the problem</a> for which I need your help. </p>
<p>I came up with solution and it is working fine for all cases, but it takes more time. I need your help in reducing the runtime of code. I unable to optimised it more.</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
long nChoosek( unsigned n, unsigned k )
{
if (k > n)
return 0;
if (k * 2 > n)
k = n-k;
if (k == 0)
return 1;
long result = n, temp;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
int main()
{
int n,q,i,j,left,right;
cin>>n;
int arr[n];
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cin>>q;
string s;
while(q--)
{
int b=0,r,q,re;
long res=1;
cin>>s >>left >>right;
if(s=="change")
{
arr[left-1]=right;
}
else
{
for(i=left-1;i<right;i++)
{
b+=arr[i];
}
r=(right-left+1);
q=(b/r);
re=(b%r);
res*=nChoosek(r,re);
for(i=0;i<re;i++)
{
res*=nChoosek((b-(i*(q+1))),(q+1));
}
i=0;
while((r-re-i) > 1)
{
res*=nChoosek(((r-re-i)*q),q);
i++;
}
res%=3046201;
cout<<res<<endl;
}
}
return 0;
}
</code></pre>
<p>I also tried to replace the function <code>nChoosek</code></p>
<pre><code>long nChoosek( unsigned n, unsigned k )
{
if (k > n)
return 0;
if (k * 2 > n)
k = n-k;
if (k == 0)
return 1;
long result = n, temp;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
</code></pre>
<p>By new recursive function ncr but no change in result:</p>
<pre><code>long ncr(int n,int r)
{
if((r==0)||(n==r))
return 1;
else
return (ncr(n-1,r-1)+ncr(n-1,r));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T12:58:41.670",
"Id": "42685",
"Score": "0",
"body": "Not an optimization but a code style thingie: when testing `s == change`, if it is true, you could just `continue` instead of having `else`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T13:03:23.110",
"Id": "42686",
"Score": "0",
"body": "Okay, Thanks. I will try to use it from now onward.But please tell me something about optimization. Any help will be appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:12:01.397",
"Id": "42740",
"Score": "0",
"body": "One of the reasons they ask you to report the answer mod 3046201 is to prevent overflow errors. When you wait until the last moment to take the modulus, you frustrate that goal. If you had 100000 bushes with 30 berries each (as the problem statement permits), ncr would overflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:17:18.477",
"Id": "42742",
"Score": "0",
"body": "When seeking to write fast code, you should first write clear code using the best algorithm possible. Then, if the code is not fast enough, run the code through a profiler to identify hot spots. Please profile your code (I like to use gperftools https://code.google.com/p/gperftools/). I suspect that ncr is going to be where your code spends most of its time and therefore where you should focus your effort."
}
] |
[
{
"body": "<p>No optimisation so far but a few comments to make your code easier to read/improve :</p>\n\n<p>1 Don't do <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">\"using namespace std;\"</a></p>\n\n<p>2 Give your variables meaningful names.</p>\n\n<p>3 Declare your variables in the smallest possible scope. Also, you should declare and define in the same times when it's possible. That would make things much easier (such as <code>int res = nChoosek(r,re);</code> instead of <code>res*=nChoosek(r,re);</code>).</p>\n\n<p>4 Be consistent. You use <code>for(i=0;i<re;i++) {foo;}</code> and then, a few lines later <code>i=0; while((r-re-i) > 1){foo; i++;}</code>. Using another for loop would have have been a better option : <code>for (i=0; i<r-re-1; i++) {foo;}</code></p>\n\n<p>5 Enable the warnings in your compiler. A few weird things such as the useless statement in <code>for(i-0;i<n;i++)</code> should be detected.</p>\n\n<p>6 Add a comment about the algorithm you've used.</p>\n\n<p>Once this is done, we'll be in better conditions to start thinking about optimisations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T17:11:24.277",
"Id": "42690",
"Score": "0",
"body": "Thanks Josay, Your tips are really awesome. From now onward i will try to implement all your tips in my code. But one question for you : Why should i don't use \"using namespace std;\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T17:13:29.107",
"Id": "42691",
"Score": "0",
"body": "Glad you liked the tips. Please let me know when the next version of the code is to be reviewed and I'll try to have a look. As for the namespace question, my answer contains a link to a relevant SO question with interesting answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T18:07:36.737",
"Id": "42692",
"Score": "0",
"body": "Hey josay, I edited the question according to your answer. The latest code you will find the in the below part of the question. Please let me know if we can optimize it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T18:48:30.320",
"Id": "42695",
"Score": "0",
"body": "There are still a few things I do find weird : `i-0` in the initialisation of the for loop for instance. Also, `string s` and `int berries` can still be defined a bit later in the logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T19:22:06.713",
"Id": "42696",
"Score": "0",
"body": "Okay, i have edited my question according to your last comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T21:29:24.623",
"Id": "42703",
"Score": "0",
"body": "Ok, I still see a fair amount of places where the comments are not taken into account : the `i` variable could be declared in the initialisation of most of the for-loops. Also as said before : `string s` and `int berries` can still be defined a bit later. This being said, if you want to work on performances, my advise would be to extract the computing logic taking the number of berries and the number of persons and put it in the logic on its own. Also provide some unit test for that method and optimisation can begin..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T00:16:25.133",
"Id": "42714",
"Score": "0",
"body": "Okay, Thanks a lot for pointing out my mistakes ( improper way of coding ).Here the link of program of variable declared accordingly. https://gist.github.com/Shravan40/5793959"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T17:04:53.933",
"Id": "27453",
"ParentId": "27449",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T12:38:46.680",
"Id": "27449",
"Score": "2",
"Tags": [
"c++",
"optimization",
"algorithm",
"programming-challenge"
],
"Title": "Collecting magical berries"
}
|
27449
|
<p>I wrote a small particle engine in Java for my Pong clone.</p>
<p>I read that changing a texture is very expensive in OpenGL, so I tried to change the texture as few times as possible. Therefore I change the texture in the render method of the emitter and not in the render method of every particle. Although my framerate drops from about 8000 FPS to 4000 FPS while there are about 60 particles on the screen.</p>
<p>So, is it possible to improve my particle engine when it comes to rendering? I am only asking for the rendering, because when I use the engine, but disable its rendering, nothing changes in the FPS.</p>
<p>This is the render Method of the particle emitter: </p>
<pre><code>public void render() {
//Initialize....
GL11.glMatrixMode(GL11.GL_MODELVIEW);
BloodParticle.PARTICLE_TEXTURE.bind();
for(Integer index : this.getBlockedParticles()){
this.getParticles()[index].render();
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
}
</code></pre>
<p>And this is the code for the particle self: </p>
<pre><code>public void render() {
if(!this.isAlive()){
return;
}
// Store matrix
GL11.glPushMatrix();
// Set to particle's position and scale
GL11.glTranslatef(this.getPosition().getX(), this.getPosition().getY(), 0);
GL11.glScalef(3.5f, 3.5f, 1.0f);
// Set the current alpha.
GL11.glColor4f(1.0f, 1.0f, 1.0f, this.getAlphaFade());
//Draw the texture on a quad.
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
-PARTICLE_TEXTURE.getImageHeight()/2.0f);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
PARTICLE_TEXTURE.getImageHeight()/2.0f);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
PARTICLE_TEXTURE.getImageHeight()/2.0f);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(PARTICLE_TEXTURE.getImageWidth()/2.0f,
-PARTICLE_TEXTURE.getImageHeight()/2.0f);
}
GL11.glEnd();
//Get the matrix again.
GL11.glPopMatrix();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:31:45.847",
"Id": "42746",
"Score": "1",
"body": "you should calculate `PARTICLE_TEXTURE.getImageWidth()/2.0f` and `PARTICLE_TEXTURE.getImageHeight()/2.0f` only once. If `PATICLE_TEXTURE` is a constant (as the name suggests) it might be a good idea to calculate it on initialization and provide accessor-methods like `getHalfImageWidth()` and `getHalfImageHeight()`"
}
] |
[
{
"body": "<p>A few notes:</p>\n\n<pre><code>for(Integer index : this.getBlockedParticles()){\n this.getParticles()[index].render();\n}\n</code></pre>\n\n<p>This should be:</p>\n\n<pre><code>for( Particle particle : getBlockedLivingParticles() ) {\n particle.render();\n}\n</code></pre>\n\n<p>By maintaining a list of living particles, you can eliminate a number unwarranted calls to <code>render</code> and eliminate the following check:</p>\n\n<pre><code>if(!this.isAlive()){\n return;\n}\n</code></pre>\n\n<p>Assuming the width and height cannot change while rendering:</p>\n\n<pre><code> GL11.glTexCoord2f(0, 0);\n GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,\n -PARTICLE_TEXTURE.getImageHeight()/2.0f);\n</code></pre>\n\n<p>As Marco commented, that duplicate code can be refactored:</p>\n\n<pre><code> float width = PARTICLE_TEXTURE.getImageWidth() / 2.0f;\n float height = PARTICLE_TEXTURE.getImageHeight() / 2.0f;\n\n GL11.glTexCoord2f(0, 0);\n GL11.glVertex2f(-width, -height);\n</code></pre>\n\n<p>This will reduce the number of divisions (an expensive operation) from 8 to 2. You'll also note that there's a relationship between <code>glTexCoord2f</code> and the sign of the width/height passed to <code>glVertex2f</code>, which can be abstracted.</p>\n\n<p>Architecturally, I'd be concerned that the Particle can only be rendered using the GL11 API. Use an <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow\">Abstract Factory</a> to decouple the rendering device from the application logic. This will also help determine the slower parts of the code (i.e., you could employ a dummy particle that has no rendering device to quickly and easily tune the other parts of the application).</p>\n\n<p>One other trick to speed things up: if all calculations can be made with integer math, then instead of diving by 2, bit-shift by 1.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T21:08:16.230",
"Id": "35988",
"ParentId": "27450",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35988",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T14:55:22.523",
"Id": "27450",
"Score": "1",
"Tags": [
"java",
"optimization",
"performance",
"opengl"
],
"Title": "Small particle engine"
}
|
27450
|
<p>The following is a code from one of my projects which implements a loading cache with timeout and expiry. The associated tests are <a href="https://raw.github.com/fge/msg-simple/master/src/test/java/com/github/fge/msgsimple/provider/LoadingMessageSourceProviderTest.java" rel="nofollow">here</a> (mixed with a good number of argument sanity checks tests). I seek comments on the thread safety aspects in particular. I think it is, but I may miss something.</p>
<p>Also, do you see ways it could be improved?</p>
<pre><code>/**
* A caching, on-demand loading message source provider with configurable expiry
*
* <p>This class uses a {@link MessageSourceLoader} internally to look up
* message sources. As is the case for {@link StaticMessageSourceProvider}, you
* can also set a default source if the loader fails to grab a source.</p>
*
* <p>Apart from the loader, you can customize two aspects of the provider:</p>
*
* <ul>
* <li>its load timeout (5 seconds by default);</li>
* <li>its expiry time (10 minutes by default).</li>
* </ul>
*
* <p>Note that the expiry time is periodic only, and not per source. The
* loading result (success or failure) is recorded permanently until the expiry
* time kicks in, <b>except</b> when the timeout kicks in; in this case, loading
* will be retried.</p>
*
* <p>You cannot instantiate that class directly; use {@link #newBuilder()} to
* obtain a builder class and set up your provider.</p>
*/
@ThreadSafe
public final class LoadingMessageSourceProvider
implements MessageSourceProvider
{
/*
* Use daemon threads. We don't give control to the user about the
* ExecutorService, and we don't have a reliable way to shut it down (a JVM
* shutdown hook does not get involved on a webapp shutdown, so we cannot
* use that...).
*/
private static final ThreadFactory THREAD_FACTORY = new ThreadFactory()
{
private final ThreadFactory factory = Executors.defaultThreadFactory();
@Override
public Thread newThread(final Runnable r)
{
final Thread ret = factory.newThread(r);
ret.setDaemon(true);
return ret;
}
};
private static final InternalBundle BUNDLE
= InternalBundle.getInstance();
private static final int NTHREADS = 3;
/*
* Executor service for loading tasks
*/
private final ExecutorService service
= Executors.newFixedThreadPool(NTHREADS, THREAD_FACTORY);
/*
* Loader and default source
*/
private final MessageSourceLoader loader;
private final MessageSource defaultSource;
/*
* Timeout
*/
private final long timeoutDuration;
private final TimeUnit timeoutUnit;
/*
* List of sources
*/
private final Map<Locale, FutureTask<MessageSource>> sources
= new HashMap<Locale, FutureTask<MessageSource>>();
private LoadingMessageSourceProvider(final Builder builder)
{
loader = builder.loader;
defaultSource = builder.defaultSource;
timeoutDuration = builder.timeoutDuration;
timeoutUnit = builder.timeoutUnit;
if (builder.expiryDuration > 0L)
setupExpiry(builder.expiryDuration, builder.expiryUnit);
}
/**
* Create a new builder
*
* @return an empty builder
*/
public static Builder newBuilder()
{
return new Builder();
}
@Override
public MessageSource getMessageSource(final Locale locale)
{
FutureTask<MessageSource> task;
/*
* The algorithm is as follows:
*
* - access the sources map in a synchronous manner (the expiry task
* also does this);
* - grab the FutureTask matching the required locale:
* - if no task exists, create it;
* - if it exists but has been cancelled (in the event of a timeout,
* see below), create a new task;
* - always within the synchronized access to sources, submit the task
* for immediate execution to our ExecutorService;
* - to be followed...
*/
synchronized (sources) {
task = sources.get(locale);
if (task == null || task.isCancelled()) {
task = loadingTask(locale);
sources.put(locale, task);
service.execute(task);
}
}
/*
* - try and get the result of the task, with a timeout;
* - if we get a result in time, return it, or the default source (if
* any) if the result is null;
* - in the event of an error, return the default source; in addition,
* if this is a timeout, cancel the task.
*/
try {
final MessageSource source = task.get(timeoutDuration, timeoutUnit);
return source == null ? defaultSource : source;
} catch (InterruptedException ignored) {
return defaultSource;
} catch (ExecutionException ignored) {
return defaultSource;
} catch (TimeoutException ignored) {
task.cancel(true);
return defaultSource;
}
}
private FutureTask<MessageSource> loadingTask(final Locale locale)
{
return new FutureTask<MessageSource>(new Callable<MessageSource>()
{
@Override
public MessageSource call()
throws IOException
{
return loader.load(locale);
}
});
}
private void setupExpiry(final long duration, final TimeUnit unit)
{
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
/*
* We need to walk the list of current tasks and cancel them if
* they are still running.
*/
synchronized (sources) {
/*
* This MUST be done from within this block. If we don't do
* this here, a task can "leak" from getMessageSource(), and
* if the caller .get()s, it will be greeted with a
* CancellationException. Not what we want!
*/
for (final FutureTask<MessageSource> task: sources.values())
task.cancel(true);
sources.clear();
}
}
};
// Overkill?
final ScheduledExecutorService scheduled
= Executors.newScheduledThreadPool(1, THREAD_FACTORY);
final long initialDelay = unit.toMillis(duration);
scheduled.scheduleAtFixedRate(runnable, initialDelay, duration, unit);
}
/**
* Builder class for a {@link LoadingMessageSourceProvider}
*/
public static final class Builder
{
private MessageSourceLoader loader;
private MessageSource defaultSource;
private long timeoutDuration = 5L;
private TimeUnit timeoutUnit = TimeUnit.SECONDS;
private long expiryDuration = 10L;
private TimeUnit expiryUnit = TimeUnit.MINUTES;
private Builder()
{
}
/**
* Set the message source loader
*
* @param loader the loader
* @throws NullPointerException loader is null
* @return this
*/
public Builder setLoader(final MessageSourceLoader loader)
{
BUNDLE.checkNotNull(loader, "cfg.nullLoader");
this.loader = loader;
return this;
}
/**
* Set the default message source if the loader fails to load
*
* @param defaultSource the default source
* @throws NullPointerException source is null
* @return this
*/
public Builder setDefaultSource(final MessageSource defaultSource)
{
BUNDLE.checkNotNull(defaultSource, "cfg.nullDefaultSource");
this.defaultSource = defaultSource;
return this;
}
/**
* Set the load timeout
*
* @param duration number of units
* @param unit the time unit
* @throws IllegalArgumentException {@code duration} is negative or zero
* @throws NullPointerException {@code unit} is null
* @return this
*
* @deprecated use {@link #setLoadTimeout(long, TimeUnit)} instead.
* Will be removed in 0.6.
*/
@Deprecated
public Builder setTimeout(final long duration, final TimeUnit unit)
{
BUNDLE.checkArgument(duration > 0L, "cfg.nonPositiveDuration");
BUNDLE.checkNotNull(unit, "cfg.nullTimeUnit");
timeoutDuration = duration;
timeoutUnit = unit;
return this;
}
/**
* Set the load timeout (5 seconds by default)
*
* <p>If the loader passed as an argument fails to load a message
* source after the specified timeout is elapsed, then the default
* messagesource will be returned (if any).</p>
*
* @param duration number of units
* @param unit the time unit
* @throws IllegalArgumentException {@code duration} is negative or zero
* @throws NullPointerException {@code unit} is null
* @return this
*
* @see {@link #setLoader(MessageSourceLoader)}
* @see {@link #setDefaultSource(MessageSource)}
*/
public Builder setLoadTimeout(final long duration, final TimeUnit unit)
{
BUNDLE.checkArgument(duration > 0L, "cfg.nonPositiveDuration");
BUNDLE.checkNotNull(unit, "cfg.nullTimeUnit");
timeoutDuration = duration;
timeoutUnit = unit;
return this;
}
/**
* Set the source expiry time (10 minutes by default)
*
* <p>Do <b>not</b> use this method if you want no expiry at all; use
* {@link #neverExpires()} instead.</p>
*
* @since 0.5
*
* @param duration number of units
* @param unit the time unit
* @throws IllegalArgumentException {@code duration} is negative or zero
* @throws NullPointerException {@code unit} is null
* @return this
*/
public Builder setExpiryTime(final long duration, final TimeUnit unit)
{
BUNDLE.checkArgument(duration > 0L, "cfg.nonPositiveDuration");
BUNDLE.checkNotNull(unit, "cfg.nullTimeUnit");
expiryDuration = duration;
expiryUnit = unit;
return this;
}
/**
* Set this loading provider so that entries never expire
*
* <p>Note that, as noted in the description, apart from loading
* timeouts, successes and failures are recorded permanently (see
* {@link FutureTask}).</p>
*
* @since 0.5
*
* @return this
*/
public Builder neverExpires()
{
expiryDuration = 0L;
return this;
}
/**
* Build the provider
*
* @return a {@link LoadingMessageSourceProvider}
* @throws IllegalArgumentException no loader has been provided
*/
public MessageSourceProvider build()
{
BUNDLE.checkArgument(loader != null, "cfg.noLoader");
return new LoadingMessageSourceProvider(this);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:05:21.187",
"Id": "42755",
"Score": "1",
"body": "Just 2 comments: (i) Technically (although unlikely), `sources` could be `null` in `setupExpiry` as your constructor has not completed yet. (ii) In case of InterruptedException, you could probably reinterrupt `Thread.currentThread.interrupt()`, as a courtesy to the calling code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:21:29.853",
"Id": "42760",
"Score": "0",
"body": "@assylias (as to sources) really? Uh! How is that possible? (as to interrupting) I am not sure I am following you here? I catch `InterruptedException` here as a possible result of the `FutureTask`'s `.get()` call"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:24:29.400",
"Id": "42761",
"Score": "0",
"body": "It is possible that the scheduled thread starts before your constructor finishes (unlikely but possible). If that happens, `sources` might not be initialised yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:32:43.987",
"Id": "42763",
"Score": "0",
"body": "In \"your code\", you mean the `Callable` in `Future` or the call to `.getMessageSource()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:35:35.520",
"Id": "42764",
"Score": "0",
"body": "You are right, only you have access to the ExecutorService and the tasks so an interruption would come from your class and you can ignore it. My mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:28:11.977",
"Id": "42767",
"Score": "1",
"body": "@assylias You're actually right. The client calling `getMessageSource()` is blocking on the `Future.get()`. If that client is interrupted, the interrupted flag is not set when exiting `getMessageSource()` and the client will not know it got interrupted, and needs to clean up. Proper solution here seems to simply add InterruptedException to the method signature : clients have a right to know they're calling a blocking method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:39:51.227",
"Id": "42769",
"Score": "0",
"body": "@bowmore uh, I'd like to avoid that if I can :/ Is there a way to distinguish between the future raising it or the client actually being interrupted? If I add the exception to the signature, this also means I have to add the exception on _all_ the call chain (given that the library provides log messages, that is rather a pain!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T20:32:47.583",
"Id": "42774",
"Score": "0",
"body": "How would the Future raise it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T20:38:16.993",
"Id": "42775",
"Score": "0",
"body": "@bowmore uh OK, that is a brain fart from my part :/ So, basically, I `Thread.currentThread.interrupt()` before I return the value and that should be OK?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T21:28:17.893",
"Id": "42777",
"Score": "0",
"body": "That would be ok, but it's probably better to let clients know they're calling a blocking method and add InterruptedException to the method sig, and not catch it yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T21:29:42.523",
"Id": "42778",
"Score": "0",
"body": "Well, this is a message provider API, the end user calls `.getMessage()` from another class, not this method. And there are providers which are static and can therefore not throw that exception, except on purpose."
}
] |
[
{
"body": "<p>I think you do have a race condition. The test below should expose it.</p>\n\n<pre><code>@Mock\nprivate MessageSource messageSource;\n\n@Test\npublic void testExpiryDuringLoadingDoesNotInterfereWithGetMessageSourceCallInProgress() throws Exception {\n\n MessageSourceProvider sourceProvider = LoadingMessageSourceProvider.newBuilder().setExpiryTime(20, TimeUnit.MILLISECONDS)\n .setDefaultSource(messageSource).setLoader(new SlowLoader())\n .build();\n MessageSource messageSource = sourceProvider.getMessageSource(Locale.CHINA);\n assertThat(messageSource).isEqualTo(messageSource);\n}\n\nprivate class SlowLoader implements MessageSourceLoader {\n @Override\n public MessageSource load(Locale locale) {\n try {\n Thread.sleep(5000);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return messageSource;\n }\n}\n</code></pre>\n\n<p>While I force the race condition to fail in the test by making the expiry time really short, and the loading time long, that is in itself not a necessary condition.</p>\n\n<p>Here's the code relevant snippet with added comments :</p>\n\n<pre><code>synchronized (sources) { // cannot clean up here\n task = sources.get(locale);\n if (task == null || task.isCancelled()) {\n task = loadingTask(locale);\n sources.put(locale, task);\n service.execute(task);\n }\n}\n // yet here it can : task cancellation may happen during cleanup here\n // expiry may have been imminent just before the resource was requested\ntry {\n final MessageSource source = task.get(timeoutDuration, timeoutUnit); // load may even be short : cancelation could have happened even before this request.\n return source == null ? defaultSource : source;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:05:49.557",
"Id": "42756",
"Score": "0",
"body": "I think you're right... I'll reproduce. This can happen if the load timeout is _more_ than the expiry time, which right now I don't disallow. Duh."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:11:31.960",
"Id": "42758",
"Score": "0",
"body": "By the way, you can use `TimeUnit.SECONDS.sleep(5);` ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:17:46.397",
"Id": "42759",
"Score": "0",
"body": "Spot on! I did reproduce..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:21:26.530",
"Id": "42766",
"Score": "0",
"body": "Added some more clarification to my answer to show that it isn't necessarily tied to load vs expiry times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T20:54:59.290",
"Id": "42776",
"Score": "0",
"body": "Yup, after I analyzed it I figured out it was deeper than what I initially surmised. Thanks a LOT for noticing this one!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T17:55:05.427",
"Id": "27486",
"ParentId": "27452",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27486",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T16:18:49.830",
"Id": "27452",
"Score": "3",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Custom, simple cache with load timeout and expiry; thread safety, tests"
}
|
27452
|
<p>I read <a href="https://stackoverflow.com/questions/8388415/does-the-display-attribute-in-the-model-violate-separation-of-concerns-from-view">this question and answers</a>, about if Display Annotations on model properties violates the separation of concerns between view and model. And my interpretation of their answer was "No, not if you're using a ViewModel for Display Annotations". But additional separation of concerns questions arose as I began implementing.</p>
<p>I have two questions but both are kind of related to each other. In both, I am wondering if I am violating the separation of concerns:</p>
<ol>
<li>I'm using localized strings from my views/resources.resx in my Model for Display Attributes, does this violate the separation of concerns since it's a resource in my views folder intended for views?</li>
<li>Do I need a ViewModel for my Model to keep separation of concerns? And if so, which Annotations need to go on my model's properties, and which need to go on the ViewModel properties?</li>
</ol>
<p>I think I need to keep all the Display Annotations and Validation Annotations (like <code>[required]</code> and <code>[range(x,y)]</code>) that I have in my ViewModel. In my Model I think I need to keep just the Validation Annotations. But, If this is true, then I have two classes to maintain Validation Annotations if I decide to add another property!?</p>
<p>The reason I think that I need Validation Annotations on both classes is so that the Model class can tell EF to put the correct constraints into database when I change schema with DbMigrations. Also, so the ViewModel tells the browser to tell the user when he's putting an invalid value in.</p>
<h2>The ViewModel</h2>
<pre><code>public class RestaurantReviewViewModel
{
public int Id { get; set; }
[Range(1, 10)]
[Required]
public int Rating { get; set; }
[Required]
[StringLength(1024)]
[Display(Name = Resources.Description)]
public string Body { get; set; }
[Display(Name = Resources.UserName)]
[DisplayFormat(NullDisplayText = "[Anonymous]")]
public string ReviewerName { get; set; }
public int RestaurantId { get; set; }
}
</code></pre>
<p>The attributes that I commented out in the next class are the attributes I think i need to remove for the Model.</p>
<h2>The Model</h2>
<pre><code>public class RestaurantReviewModel
{
public int Id { get; set; }
[Range(1, 10)]
[Required]
public int Rating { get; set; }
[Required]
[StringLength(1024)]
//[Display(Name = Resources.Description)]
public string Body { get; set; }
//[Display(Name = Resources.UserName)]
//[DisplayFormat(NullDisplayText = "[Anonymous]")]
public string ReviewerName { get; set; }
public int RestaurantId { get; set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>A solution could be:</p>\n\n<pre><code>public class RestaurantReviewViewModel : RestaurantReviewModel\n{\n [Display(Name = Resources.Description)]\n public override string Body { get; set; }\n\n [Display(Name = Resources.UserName)]\n [DisplayFormat(NullDisplayText = \"[Anonymous]\")]\n public override string ReviewerName { get; set; }\n}\n\npublic class RestaurantReviewModel\n{\n public int Id { get; set; }\n\n [Range(1, 10)]\n [Required]\n public int Rating { get; set; }\n\n [Required]\n [StringLength(1024)]\n public virtual string Body { get; set; }\n\n public virtual string ReviewerName { get; set; }\n\n public int RestaurantId { get; set; }\n}\n</code></pre>\n\n<p>You can derive from the model class without any problem your attributes will get applied in you view model also (not every but for exmple the validation attributes will). I also recmommend to have copy constructors becouse they can help you a lot.</p>\n\n<p>Beside this my opinion is that no need to worry about display/display format attributes in you model classes it doesn't feel an incorrect way and it helps to keep things clear if you have a lot of derived classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T21:53:14.540",
"Id": "42706",
"Score": "1",
"body": "I understand. There's another error now, The compiler doesn't like this line of code: [Display(Name = Resources.UserName)] and it says _\"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type\"_ So I guess I cannot give localized strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T22:38:02.203",
"Id": "42708",
"Score": "2",
"body": "Not so sure I'm keen on this. Making a model property virtual so that a viewmodel can override it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T05:03:15.033",
"Id": "42723",
"Score": "0",
"body": "@Matt: [Display(ResourceType = typeof(Resources), Name = \"UserName\")]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T05:04:49.723",
"Id": "42724",
"Score": "0",
"body": "@dreza, why not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T07:47:32.227",
"Id": "42727",
"Score": "0",
"body": "Well your viewmodel now inherits all your model to start and is now tightly coupled with it. What happens if you want the properties of the model to do something. The viewmodel not even part of the model domain could prevent that. I guess I'm not 100% exactly sure but it just feels wrong about everything I've read about view models. Of course happy to hear thoughts on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T08:50:08.297",
"Id": "42730",
"Score": "0",
"body": "ViewModels can depend on models from your domain (becouse we want to display them somehow) the reverse way would be bad."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T18:08:58.197",
"Id": "27455",
"ParentId": "27454",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>I'm using localized strings from my views/resources.resx in my Model\n for Display Attributes, does this violate the separation of concerns\n since it's a resource in my views folder intended for views?</p>\n</blockquote>\n\n<p>I would probably say yes. You are tying UI concerns in your business models. Why does your model even care about the text that is used to display it? It should be more concerned with buiseness rules and performing buiseness operations I think. Let your UI layer/layers deal with presenting it to the user.</p>\n\n<blockquote>\n <p>Do I need a ViewModel for my Model to keep separation of concerns? And\n if so, which Annotations need to go on my model's properties, and\n which need to go on the ViewModel properties?</p>\n</blockquote>\n\n<p>No I don't think you necessarilly need a viewmodel and there is plenty of debate on this on the internet. However I personally like the viewmodel approach as it provides the flexibility of adding any UI specified fields I would like without the overhead of my view being tied directly to the buiseness model. Of course this means also that you now have to have the rules copied twice like you mentioned. However if you were using jquery validation this would be the case anyway (or so I believe).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T20:19:49.350",
"Id": "42859",
"Score": "0",
"body": "My UI is using `HTML.LabelFor` and `EditorFor` to show names of the model's properties, passing lambda expressions to `LabelFor` and `EditorFor` such as `(model => model.Name)`. I know another way is to instead use `HTML.Label(Resources.LabelName)` instead of 'LabelFor(model => model.Name)` But this changes how the code needs to be maintained by no longer retrieving the name of the property with the lambda expression. Is this the best way if I want the string to be localized?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T22:13:18.877",
"Id": "44712",
"Score": "0",
"body": "I found a good article to supplement your answer about domain models and inheritance: http://nohack.eingenetzt.com/system-architecture/domain-model-and-class-inheritance/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-15T00:23:29.133",
"Id": "44715",
"Score": "1",
"body": "@MattRohde Cheers matt. Good reading."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T08:14:06.717",
"Id": "27467",
"ParentId": "27454",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27467",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T17:19:57.803",
"Id": "27454",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"asp.net"
],
"Title": "What Data Annotations need to be shared/different between my Model & ViewModel to keep seperation of concerns?"
}
|
27454
|
<p>I'm new to hand coding a PHP form/email submission. Are the security checks I've included here good enough? Or is this super vulnerable to attacks? </p>
<p>My main concern is protecting the email login credentials below. Any feedback much appreciated.</p>
<p>Thank you! </p>
<pre><code> // IF WE'VE SUBMITTED A FORM
if(
!empty($_POST) &&
isset( $_POST['moveDate'] ) &&
isset( $_POST['email'] ) && !empty( $_POST['email'] ) &&
isset( $_POST['emailConfirm'] ) && !empty( $_POST['emailConfirm'] ) &&
$_POST['email'] === $_POST['emailConfirm'] &&
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
) {
// Make sure there are no fields posted that are not in the white list
foreach ($_POST as $key=>$item) {
if (!in_array($key, $whitelist)) {
die('<div class="validation-message warning">Please use only the fields in the form</div>');
}
if( $_POST[$key] && is_array($_POST[$key]) ) {
if(count($_POST[$key]) > 5) {
die('<div class="validation-message warning">Please use only the fields in the form</div>');
}
}
}
$form_output = array();
$move_date = $_POST['moveDate'];
$move_type = $_POST['moveType'];
$whered = $_POST['wheredYouFindUs'];
$name = $_POST['moveName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$multistop_type = '';
if( !empty($_POST['multistopType']) ) {
$multistop_type = ' / ' . $_POST['multistopType'];
}
$form_output[] = '<strong style="color: #666 !important">Move Date:</strong> ' . $move_date;
$form_output[] = '<strong style="color: #666 !important">Move Type:</strong> ' . $move_type . $multistop_type;
$form_output[] = '<strong style="color: #666 !important">Name:</strong> ' . $name;
$form_output[] = '<strong style="color: #666 !important">Email:</strong> ' . $email;
$form_output[] = '<strong style="color: #666 !important">Phone:</strong> ' . $phone;
$form_output[] = '<br><hr>';
$pickup1 = '';
$pickup2 = '';
$pickup3 = '';
$dropoff1 = '';
$dropoff2 = '';
$dropoff3 = '';
$pickup1_stairs = '';
$pickup2_stairs = '';
$pickup3_stairs = '';
$dropoff1_stairs = '';
$dropff2_stairs = '';
$dropoff3_stairs = '';
$pickup1_dropoff1Items = '';
$pickup2_dropoff1Items = '';
$pickup3_dropoff1Items = '';
$pickup1_dropoff2Items = '';
$pickup1_dropoff3Items = '';
$pickup1_dropoff1List = '';
$pickup2_dropoff1List = '';
$pickup3_dropoff1List = '';
$pickup1_dropoff2List = '';
$pickup1_dropoff3List = '';
// PICKUP AND DROPOFF ADDRESSESS + STAIRS
include('assets/includes/quote-email-addresses.php');
$form_output[] = '<br><hr>';
// ITEMS
include('assets/includes/quote-email-items.php');
$form_output[] = '<hr>';
// COMMENTS
if(isThere($_POST['comments'])) {
$form_output[] = '<strong style="color: #666 !important">Additional Items/Comments:</strong><br> ' . wordwrap ( stripcleantohtml( strip_tags( $_POST['comments'] ) ), 90, "<br>" ) . '<br>';
}
$form_output[] = '<strong style="color: #666 !important">Inventory:</strong><br>' . implode('<br>', $inventory);
$form_output[] = '<br><strong style="color: #666 !important">Total Quote</strong> = $' . $price . '<br>';
if($whered !== '' && !empty($whered)) {
$form_output[] = '<strong style="color: #666 !important">How did you find us? </strong> ' . $whered;
}
$breaks = array("\r\n", "\n", "\r");
$email_output = strip_tags( implode('<br>', $form_output), '<em><br><hr><strong><table><tr><td>');
$email_output = str_replace($breaks, "", $email_output);
require("class.phpmailer.php");
$a52D22xux = new PHPMailer();
$a52D22xux->IsSMTP();
$a52D22xux->SMTPSecure = "tls";
$a52D22xux->Host = 'smtp.gmail.com';
$a52D22xux->Port = 587;
$a52D22xux->SMTPAuth = true;
$a52D22xux->Username = '***';
$a52D22xux->Password = '***';
$a52D22xux->From = $email;
$a52D22xux->FromName = $name;
$a52D22xux->AddAddress('***');
$a52D22xux->AddReplyTo($email, $name);
$a52D22xux->IsHTML(true);
$a52D22xux->Subject = 'Quote Request ' . date('m/d H:i');
$a52D22xux->Body = sanitize_output( $email_output );
$a52D22xux->Send();
?>
<div class="inner">
<div class="feedback-success feedback pr tac">
<h2 class="futura">Success!</h2>
<p>Good news! Your quote request has been submitted successfully.</p>
</div>
</div>
</div>
</section>
<?php
} else {
// Show the form
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>The whitelist check is giving a false sense of security. Consider its use case: There is no way a normal user will ever submit more parameters than those which are in the form. Therefore, you can safely assume that anyone submitting other parameters is an attacker, who should receive as little information as possible. The fact that you check parameters against a whitelist is information that could conceivably be used by an attacker to focus their efforts. Rather than a check, you could use the <code>$whitelist</code> to assign POSTed values to a \"safe\" dictionary and empty <code>$_POST</code> after that to ensure that the code doesn't ever touch any other values.</li>\n<li>You want to simplify security-related code to the max, to avoid any bugs. For example, make sure you get rid of any variables you are not using (such as <code>pickup1_dropoff2List</code>).</li>\n<li>You should <em>never</em> store credentials in code. Use PKI if you can, and store credentials (or references to them) in configuration files.</li>\n<li>Put warning verbosity to the max, and verify that you don't get any errors or warnings from the code. For example, <code>isset( $_POST['moveDate'] )</code> should probably be changed to <code>array_key_exists('moveDate', $_POST)</code>.</li>\n<li>Any user input must be escaped on output. You should probably use <a href=\"http://php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow\">htmlspecialchars</a> (but check for any caveats) for the form output.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T08:53:11.590",
"Id": "27469",
"ParentId": "27459",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T21:09:59.063",
"Id": "27459",
"Score": "2",
"Tags": [
"php",
"security",
"form"
],
"Title": "Is my form secure? PHP Security checks"
}
|
27459
|
<p>When I wrote this it just felt messy due to the null checks. Any good ideas on how to clean it up would be most appreciated.</p>
<pre><code> def getItemsInStock(self):
itemsInStock = []
items = self.soup.find_all("ul", {'class':re.compile('results.*')})
getItems = [x for x in items if x.find("div", class_="quantity")]
if getItems:
itemsInStock += getItems
pages = self.combThroughPages()
if pages:
for each in pages:
self.uri = each
soup = self.createSoup()
items = soup.find_all("ul", {'class':re.compile('results.*')})
if items:
inStock = [x for x in items if x.find("div", class_="quantity")]
if inStock:
itemsInStock += inStock
if itemsInStock:
return self.__returnItemDetailAsDictionary(itemsInStock)
else:
return None
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-22T07:39:25.587",
"Id": "379609",
"Score": "0",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what your code does](//codereview.meta.codereview.stackexchange.com/q/1226) and what the purpose of doing that is, the easier it will be for reviewers to help you. The current title states your concerns about the code; it needs an [edit] to simply *state the task*; see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>As an example,</p>\n\n<pre><code> getItems = [x for x in items if x.find(\"div\", class_=\"quantity\")]\n if getItems:\n itemsInStock += getItems\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code> itemsInStock.extend(x for x in items if x.find(\"div\", class_=\"quantity\")]\n</code></pre>\n\n<p><code>extend</code> (and for that matter, <code>+=</code>) are no-ops on empty lists.</p>\n\n<p>Now, I'm not sure what some of the function you call return, but I don't like that <code>getItemsInStock</code> returns <code>None</code> if no items are in stock -- it makes more sense to return an empty list in that case. If your other functions did the same, you wouldn't need any of your <code>if</code> guards. Another example:</p>\n\n<pre><code> pages = self.combThroughPages()\n if pages:\n for each in pages:\n ...\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code> for page in self.combThroughPages():\n ...\n</code></pre>\n\n<p>but only if <code>combThroughPages</code> returns an empty list when there are no, um, pages, I guess? (It's not clear from your function name.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T00:48:56.523",
"Id": "42715",
"Score": "2",
"body": "And finally, change `__returnItemDetailAsDictionary` to accept an empty list for which it returns an empty dictionary. Now you can drop the `if itemsInStock` block and simply return `self.__returnItemDetailAsDictionary(itemsInStock)` in all cases."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T22:40:25.837",
"Id": "27463",
"ParentId": "27461",
"Score": "4"
}
},
{
"body": "<p>If a function like <code>self.combThroughPages()</code> returns None or a list of items you can wrap such a call in a function <code>listify()</code> that makes None into an empty list:</p>\n\n<pre><code>def listify(l):\n if l is None:\n return []\n</code></pre>\n\n<p>and make the call like:</p>\n\n<pre><code>...\nfor each in listify(self.combThroughPages())\n self.uri = each\n...\n</code></pre>\n\n<p>This works even if you don't have control over the definition of <code>combThroughPages()</code>. </p>\n\n<p>Sometimes you have functions that return None, or a single item or a list.\nI use a slightly more elaborate version of listify() myself to handle that:</p>\n\n<pre><code>def listify(val, none=None):\n \"\"\"return a list if val is only an element.\n if val is None, normally it is returned as is, however if none is set \n and True then [None] is returned as a list, if none is set but not \n True ( listify(val, False) ), then the empty list is returned.\n\n listify(None) == None\n listify(None, 1) == [1]\n listify(None, [2]) == [[2]]\n listify(None, False) == []\n listify(3) == [3]\n listify([4]) == [4]\n listify(5, 6) == [5]\n \"\"\"\n if val is None:\n if none is None:\n return None\n elif none:\n return [None]\n else:\n return []\n if isinstance(val, list):\n return val\n return [val]\n</code></pre>\n\n<p>In your case that version would be called like:</p>\n\n<pre><code>...\nfor each in listify(self.combThroughPages(), False)\n self.uri = each\n...\n</code></pre>\n\n<hr>\n\n<p>Since you are not further using the temporary lists getItems or inStock you can get rid of them and directly append items found to itemsInStock. This would get you (assuming you have the extended version of listify in your scope)</p>\n\n<pre><code>def getItemsInStock(self):\n itemsInStock = []\n for item in self.soup.find_all(\"ul\", {'class':re.compile('results.*')}):\n if item.find(\"div\", class_=\"quantity\"):\n itemsInStock.append(item)\n for self.uri in listify(self.combThroughPages(), False):\n soup = self.createSoup()\n for item in listify(soup.find_all(\"ul\", {'class':re.compile('results.*')}), False):\n if item.find(\"div\", class_=\"quantity\"):\n itemsInStock.append(item)\n if itemsInStock:\n return self.__returnItemDetailAsDictionary(itemsInStock)\n else:\n return None\n</code></pre>\n\n<p>It is of course impossible to test without context, but this should work.</p>\n\n<p>I also removed the variable <code>each</code> directly setting <code>self.uri</code>. I can only assume that self.createSoup is dependent on the value of self.uri, otherwise I am not sure why you would have differences in calling createSoup.</p>\n\n<hr>\n\n<p>Of course you don't need <code>listify()</code> around <code>self.combThroughPages()</code> if you change the latter to return an empty list as @ruds already proposed that would work as well. In that case I would probably also have <code>getItemsInStock()</code> return an empty dictionary ( <code>return {}</code> ) depending on how that function itself is called:</p>\n\n<pre><code> iis = self.getItemsInStock()\n if iis:\n for key, value in iis.iteritems()\n</code></pre>\n\n<p>could then be changed to:</p>\n\n<pre><code> for key, value in iis.iteritems():\n</code></pre>\n\n<p>(or you can write a <code>dictify()</code> function).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T09:34:22.990",
"Id": "27471",
"ParentId": "27461",
"Score": "1"
}
},
{
"body": "<p>One of my favourite Python shorthands is the <code>or</code> operator being used to provide a default value:</p>\n\n<pre><code>x = y or 42\n</code></pre>\n\n<p>This will assign the value of <code>y</code> to <code>x</code>, if <code>y</code> evaluates to <code>True</code> when interpreted as a boolean, or <code>42</code> otherwise. While this may seem odd at first, it is perfectly normal if you consider short-circuit evaluation and how Python can interpret nearly everything as a boolean: If the first operand evaluates to <code>True</code> (e.g., it is not <code>None</code>), return the first operand, otherwise return the second.</p>\n\n<p>In other words, <code>A or B</code> is equivalent to <code>A if A else B</code>, and conversely (but not quite as intuitive, I guess), <code>A and B</code> is equivalent to <code>B if A else A</code>.</p>\n\n<p>This is not only handy for assigning default values to variables, as in the above example, but can also be used to get rid of some of your <code>if</code> checks. For example, instead of </p>\n\n<pre><code>pages = self.combThroughPages()\nif pages:\n for each in pages:\n # do stuff\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>pages = self.combThroughPages() or []\nfor each in pages:\n # do stuff\n</code></pre>\n\n<p>or even shorter, since now you need <code>pages</code> only once:</p>\n\n<pre><code>for each in self.combThroughPages() or []:\n # do stuff\n</code></pre>\n\n<p>Now, if <code>combThroughPages()</code> returns <code>None</code> (which is <code>False</code> when interpreted as a boolean), the <code>or</code> operator will return the second operand: <code>[]</code>.</p>\n\n<p>(Of course, if <code>combThroughPages()</code> returns an empty list instead of <code>None</code>, you don't have to check at all, as pointed out by @ruds; same for your list comprehensions.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T04:31:10.817",
"Id": "43723",
"Score": "0",
"body": "I'm a big fan of None or [] as a way of unifying return values - in the Maya api, which is extremely inconsistent about returning None, single items, or lists it's a lifesaver"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-06T11:35:24.697",
"Id": "351457",
"Score": "0",
"body": "`y = 0` will evaluate in `x = y or 42` to `x = 42`. Is this ok?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-06T16:37:56.780",
"Id": "351515",
"Score": "0",
"body": "@Elmex80s What do you mean with \"is this okay\"? If a function returns `None` or numeric values, including `0`, then yes, that's a very good point where using `or` can lead to unexpected behavior. But in OP's case, that should not be a problem."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T17:48:43.147",
"Id": "28002",
"ParentId": "27461",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27471",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T21:55:30.730",
"Id": "27461",
"Score": "5",
"Tags": [
"python"
],
"Title": "refactor Python code with lots of None type checks"
}
|
27461
|
<p>Previous review of this project:</p>
<p><a href="https://codereview.stackexchange.com/questions/27379/deck-and-card-classes-and-member-accessing-with-one-header">Deck and Card classes and member-accessing with one header</a></p>
<p>I'm nearly finished with my deck of cards project, and this time I made changes to hide the <code>Card</code> class by nesting it in the <code>Deck</code> class. I'm still getting correct results when displaying the deck. However, I do now realize that I can no longer maintain <code>Card</code> objects outside the class. Instead, I have to call <code>Card deal()</code> with a <code>Deck</code> object in order to retrieve a <code>Card</code>, and I cannot store that <code>Card</code> anywhere.</p>
<p>Does this render my design ineffective for this purpose? If so, how else can I maintain <code>Card</code>s outside the class while still preventing the user from directly constructing a <code>Card</code>? Would a <code>private</code> constructor (with <code>Card</code> un-nested from <code>Deck</code>) be a better option?</p>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <iostream>
#include <array>
class Deck
{
private:
class Card
{
private:
char rank;
char suit;
unsigned value;
public:
Card::Card() : value(0), rank(' '), suit(' ') {}
Card::Card(char r, char s, unsigned v) : rank(r), suit(s), value(v) {}
bool operator<(const Card &rhs) const {return (value < rhs.value);}
bool operator>(const Card &rhs) const {return (value > rhs.value);}
bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
friend std::ostream& operator<<(std::ostream &out, const Card &aCard);
friend std::ostream& operator<<(std::ostream &out, const Card &aCard)
{return out << '[' << aCard.rank << aCard.suit << ']';}
};
static const unsigned VALUES[13];
static const char RANKS[13];
static const char SUITS[4];
static const unsigned MAX_SIZE = 52;
std::array<Card, MAX_SIZE> cards;
int topCardPos;
public:
Deck();
void shuffle();
Card deal();
unsigned size() const {return topCardPos+1;}
bool empty() const {return topCardPos == -1;}
friend std::ostream& operator<<(std::ostream &out, const Deck &aDeck);
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include <algorithm>
#include "Deck.h"
const unsigned Deck::VALUES[13] = {1,2,3,4,5,6,7,8,9,10,10,10,10};
const char Deck::RANKS[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
const char Deck::SUITS[4] = {'H','D','C','S'};
Deck::Deck() : topCardPos(-1)
{
for (unsigned rank = 0, value = 0; rank, value < 13; ++rank, ++value)
{
for (unsigned suit = 0; suit < 4; ++suit)
{
topCardPos++;
cards[topCardPos] = Card(RANKS[rank], SUITS[suit], VALUES[value]);
}
}
shuffle();
}
void Deck::shuffle()
{
topCardPos = MAX_SIZE-1;
std::random_shuffle(&cards.front(), &cards.back()+1);
}
Deck::Card Deck::deal()
{
if (empty())
{
std::cerr << "\nDECK IS EMPTY\n";
Card blankCard;
return blankCard;
}
topCardPos--;
return cards[topCardPos+1];
}
std::ostream& operator<<(std::ostream &out, const Deck &aDeck)
{
for (unsigned iter = aDeck.size(); iter--> 0;)
{
out << "\n" << aDeck.cards[iter];
}
return out;
}
</code></pre>
|
[] |
[
{
"body": "<p>The way I understand your question, you want <code>Card</code> to be publicly available, yet only <code>Deck</code> should be able to construct a <code>Card</code>. One way to achieve this is to make the <code>Card()</code> constructor private and a <code>friend</code> of <code>Deck</code>:</p>\n\n<pre><code>class Deck;\n\nclass Card {\n Card() {}\n friend class Deck;\npublic:\n // ...\n};\n\nclass Deck {\n Card card; // ok\npublic:\n Card createCard() { // ok\n return Card();\n }\n};\n\nint main()\n{\n Deck deck;\n Card card = deck.createCard();\n\n Card doesntWork; // error! Attempt to access private member\n}\n</code></pre>\n\n<p>A somewhat cleaner solution would be to have only <code>createCard()</code> as <code>friend</code> of <code>Card</code>. In that case, however, you will have to dynamically allocate the <code>Card</code> (and return a pointer to it), because of mutual dependencies.</p>\n\n<p>(The reason for this is that <code>Card</code> needs the definition, and not just declaration, of <code>Deck</code> to declare one of the <code>Deck</code> functions a friend. At the same time, <code>Deck::createCard()</code> needs the definition of <code>Card</code> to be able to return a <code>Card</code> by value. If you return a pointer, however, you only need the declaration.)</p>\n\n<hr>\n\n<p><strong>Other comments:</strong></p>\n\n<p><strong>1:</strong> Consider giving ranks, suits and values distinct and unique types. For example using <code>enum</code>. Make use of the type system to enlist the compiler's aid -- by doing this you will be notified if you accidentally switch types somewhere.</p>\n\n<p><strong>2:</strong> I would change</p>\n\n<pre><code>for (unsigned iter = aDeck.size(); iter--> 0;)\n</code></pre>\n\n<p>to the more traditional</p>\n\n<pre><code>for (int i = aDeck.size() - 1; i > -1; --i)\n</code></pre>\n\n<p>The latter is more readable and clear about what is going on. The former is vulnerable to be <em>incorrected</em>, i.e. refactored to the (incorrect)</p>\n\n<pre><code>for (unsigned iter = aDeck.size(); iter > 0; --iter)\n</code></pre>\n\n<p><strong>3:</strong> Don't call a variable <code>iter</code> when it's a counter and not an iterator.</p>\n\n<p><strong>4:</strong> Initializer list ordering should be the same as the variables are declared in the class. By doing this, you avoid ever risking dependency problems. (Variables are always initialized in the order they are declared in the class, <em>not</em> the order they appear in initializer lists.)</p>\n\n<p><strong>5:</strong> <a href=\"http://blog.knatten.org/2010/07/01/the-order-of-include-directives-matter/\" rel=\"nofollow\">Reorder your <code>#includes</code> in the implementation file.</a></p>\n\n<p><strong>Update</strong></p>\n\n<p><strong>6:</strong> Your card generation/constructor is error-prone. Apart from introducing type safety, I would recommend generating <code>value</code> based on <code>rank</code>, for example through a function and an <code>std::map</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T01:33:35.683",
"Id": "42716",
"Score": "1",
"body": "Yes! That's my ideal `main()` right there. :-) I'll try to work out these changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T02:11:11.330",
"Id": "42717",
"Score": "0",
"body": "I've made the changes (in addition to using `std::vector` instead of `std::array`), and my results are to my satisfaction. Many thanks! I have kept `deal()` intact, though. In that function, is there a better way to handle an empty deck (internally), or is that good enough? In its current form, I'll have to keep my default constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T02:48:27.190",
"Id": "42718",
"Score": "1",
"body": "@Jamal: Happy to help! You can keep it the way it is, you could reshuffle the deck and deal again or you could throw an exception. What is \"best\" depends on the situation. While considering this, I noticed another issue; see the updated post. By the way, consider accepting the answer if you find it satisfactory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T02:56:45.433",
"Id": "42719",
"Score": "0",
"body": "Since I'm using `std::vector` now, I put in more code to allow the `shuffle()` to work with it. I'm now just trying to figure out how to do the `enum`/`std::map` idea. Since the ranks' values depends on the specific game, I'll need to be able to change them easily. Oh yeah, sorry about that. I considered waiting for any additional answers, but this one did answer my question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T03:10:30.753",
"Id": "42720",
"Score": "1",
"body": "@Jamal: An object-oriented sketch to point you in the right direction: http://codepad.org/YRi4rgLl. If using C++11, you could instead bind the correct assignment function to a `std::function`, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T03:14:45.183",
"Id": "42721",
"Score": "0",
"body": "Okay, I'll take a look at the link since I haven't heard of `std::function` before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T03:47:58.670",
"Id": "42722",
"Score": "0",
"body": "I put that code into a header file, and it doesn't compile. I can't figure out how to use it anyway (I'm barely familiar with OOP), so I'll stay with what I have for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T06:23:03.823",
"Id": "42725",
"Score": "1",
"body": "I got it working with an `std::map`, which I put in a header file. The suits is now in a string, so all of the iterating for both containers is done via the `auto` method."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T01:18:07.257",
"Id": "27464",
"ParentId": "27462",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27464",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T22:32:15.233",
"Id": "27462",
"Score": "4",
"Tags": [
"c++",
"classes",
"playing-cards"
],
"Title": "Nested Deck class design and implementation"
}
|
27462
|
<p>I want to know if what I have coded is good enough or if there is any simpler/faster/better/less size taking substitute.</p>
<p>I am trying to take input from push buttons and I also want to remove repeated input so I coded like it and saved in a variable key. I used internal pullup to eradicated random input from digital pins. I am in pre-graduation in computer applications and a beginner in electronics.</p>
<pre><code>byte key=0;
unsigned int st=millis(),ct=millis(); //st-starttime , ct-currenttime
void setup()
{
delay(5000); //start prog after 5 sec
pinMode(7, INPUT);
pinMode(8, INPUT);
pinMode(9, INPUT);
byte i;
for(i=7;i<=9;i++)
digitalWrite(i, HIGH); //7,8,9 pins HIGH for internal pullup
Serial.begin(9600);
}
void loop()
{
byte i;
for(i=7;i<=9;i++)
if(checkswitch(i)==1) //check which switch was last pressed
{
key=i;
st=millis();
while(st>65000) //controlling limits of unsigned int
st=st-65000;
}
ct=millis();
while(ct>65000)
ct=ct-65000; //controlling limits of unsigned int
if(ct>st+200) //Triggers only if 200 ms passed
{ //to not fill the Serial input
if(key!=0)
{
Serial.println(key);
key=0; //clear saved key
}
}
}
byte checkswitch(byte n) //Check button pressed with internal pullup
{
byte p=0;
if(digitalRead(n)==LOW) p=1; //my best algo for if-else statement
return p;
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't <em>know</em> the Arduino language but I've recently been learning, from what I can gather on the website unsigned ints will \"roll-back\" to zero if they reach their maximum (which will be reached in a huge \"<strong>fifty days</strong>\" so no need to worry about that.</p>\n\n<p>You can clean up your syntax for your statements by putting the braces at the end of the statement (on the same line), also remove the <code>byte i</code> from the function visibility into only the loop by declaring it in the <code>for</code>.</p>\n\n<p>I also noticed that your function <code>checkswitch</code> is only used for boolean operations yet it's returning a byte - this can be fixed by returning the result of the comparison of the <code>if</code> you used directly.</p>\n\n<p>Here is my suggestion:</p>\n\n<pre><code>byte key=0;\nunsigned int st=millis(),ct=millis(); //st-starttime , ct-currenttime\n\nvoid setup() {\n delay(5000); //start prog after 5 sec\n pinMode(7, INPUT);\n pinMode(8, INPUT);\n pinMode(9, INPUT);\n for(byte i=7;i<=9;i++)\n digitalWrite(i, HIGH); //7,8,9 pins HIGH for internal pullup\n Serial.begin(9600);\n}\n\nvoid loop() {\n for(byte i=7;i<=9;i++)\n if(isHigh(i)) { //check which switch was last pressed \n key=i;\n st=millis();\n }\n\n if(ct>st+200) { //triggers only if 200 ms passed to not fill the Serial input\n if(key!=0) {\n Serial.println(key);\n key=0; //clear saved key\n }\n }\n}\n\nboolean isHigh(byte n) { //Check button pressed with internal pullup\n return digitalRead(n)==LOW;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-21T10:52:24.773",
"Id": "45242",
"Score": "0",
"body": "You can combine `if(ct>st+200)` and `if(key!=0)` into one condition like `if(ct > st + 200 && key)`. That will make it even smaller. Other than it this looks good to me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T13:13:05.290",
"Id": "27475",
"ParentId": "27465",
"Score": "2"
}
},
{
"body": "<p>For Arduino there is a nice <a href=\"http://playground.arduino.cc/Code/Button\" rel=\"nofollow\">Button library</a> that is already de-bounced, that is very simple to implement, with desired methods already.</p>\n\n<p>Where it would be argumentative to compare it versus your code against the different aspects of simpler/faster/better/less, in that you have successfully implemented the minimum of what you need. Being there are different criteria to balance ones opinion. Where as I would believe it to be much simpler to implement, read and nearly same size of code as your, but with additional features ready to use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T13:38:07.423",
"Id": "27477",
"ParentId": "27465",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T04:10:56.930",
"Id": "27465",
"Score": "1",
"Tags": [
"optimization",
"arduino"
],
"Title": "Taking input from push buttons"
}
|
27465
|
<p><em>Update: Now that <a href="https://github.com/bionicspirit/scala-atomic" rel="nofollow">https://github.com/bionicspirit/scala-atomic</a> is available, I have less of a need for this.</em></p>
<p>Am I doing anything bad? I wrote this class to allow modifying an atomic reference with the assurance that two threads modifying it will not step on each other's toes. To illustrate:</p>
<pre><code>val x = new AtomicRef(List.empty[String])
def compute(s: String) = { Thread.sleep(1000); s }
def updateX(s: String) = x.transform(strings => compute(s) :: strings)
</code></pre>
<p>The idea is to guarantee that if two threads call <code>updateX</code> many times, all the strings passed to <code>updateX</code> will wind up in <code>x</code>.</p>
<p><code>run</code> is like <code>transform</code> but it lets you return a value to the caller other than the value you're setting into the reference.</p>
<p>Here is the class:</p>
<pre><code>/**
* A subclass of java.util.concurrent.atomic.AtomicReference[A]
* that adds the ability to atomically modify its value relative to itself.
*/
class AtomicRef[A](init: A) extends java.util.concurrent.atomic.AtomicReference[A](init) {
/**
* Update the value atomically by applying a function to it.
* Uses `compareAndSet` and will keep trying until it succeeds.
*/
final def transform(f: A => A): A = run { a =>
val ret = f(a)
(ret, ret)
}
/**
* Update the value atomically by applying a computation to it.
* The computation returns a pair of values, of which the
* `AtomicRef` is updated to the first.
* Uses `compareAndSet` and will keep trying until it succeeds.
* @return the second value of the computation
*/
@annotation.tailrec final def run[B](f: A => (A, B)): B = {
val a = get
val (a2, b) = f(a)
if(compareAndSet(a, a2)) b
else {
Thread.sleep(10)
run(f)
}
}
}
</code></pre>
<p>To put it in different terms, this sort of abstracts over doing something like this (in Java; List here is a fictional immutable list):</p>
<pre><code>AtomicReference<List<String>> ref = new AtomicReference<List<String>>(new List());
void update(String s) {
while(true) {
List<String> a = ref.get;
// now do "f(a)"
Thread.sleep(1000); // pretend it takes a long time to run the computation
List<String> b = a.prepend(s);
if(compareAndSet(a, b)) return b;
else {
Thread.sleep(10);
// loop the while instead of tail recursion
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T07:55:33.440",
"Id": "42729",
"Score": "0",
"body": "This cannot be really called atomic, especially the `run` function; if another thread has a reference to this `AtomicReference` it can modify the value from under your nose. What is the intent of this class exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:59:27.993",
"Id": "42815",
"Score": "0",
"body": "Hi @fge, apologies for not describing the intent before. I added it to the question text. Is it clear?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T09:01:09.203",
"Id": "42816",
"Score": "0",
"body": "@fge It's true another thread can modify the value while the computation is running. But then `compareAndSet` will fail (return false) and we will try again! `compareAndSet` means don't store the result of the computation unless the value still is what the computation thought it was!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T09:02:41.530",
"Id": "42817",
"Score": "0",
"body": "Uh, OK, I don't understand scala well enough to really comment :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T17:08:25.630",
"Id": "42928",
"Score": "0",
"body": "@fge thanks anyway, I added a Java snippet that illustrates the pattern, except now having functions it doesn't abstract over the operation."
}
] |
[
{
"body": "<p>Your approach is definitely valid, I've seen something similar used in GHC's implementation of <a href=\"http://www.haskell.org/ghc/docs/7.6.2/html/libraries/base/Data-IORef.html#v%3aatomicModifyIORef\" rel=\"nofollow\">atomicModifyIORef</a>.</p>\n\n<p>However I have some doubts if such a class is really useful. If the computations are potentially long running, the performance advantage of using <code>AtomicReference</code> instead of some standard synchronization primitive is negligible. Moreover, if there are several updating threads, it will result in repeated recomputation, wasting CPU power on it. So using plain <code>synchronized</code> on some private lock object (so that no other part of code can lock on it) seems simpler, safer and with better performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T02:51:17.997",
"Id": "45579",
"Score": "0",
"body": "Okay, that's a good point. I would say that this class is designed for quick computations, but designed in a reusable way. So the decision whether to use this class would need to be made in each use site."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T13:01:00.060",
"Id": "28876",
"ParentId": "27466",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28876",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T06:33:48.947",
"Id": "27466",
"Score": "1",
"Tags": [
"scala"
],
"Title": "Subclass of AtomicReference with atomic function application"
}
|
27466
|
<p>As a bit of a learning project, I decided to take the concept of proxying objects a bit further and extend it to creating proxy classes which create proxy'd objects. I originally found the idea of proxying objects in python on <a href="http://code.activestate.com/recipes/496741-object-proxying/" rel="nofollow">Activestate</a>. I'm currently using a very odd pattern (creating a class with just staticmethods and abusing <code>__new__</code> to return my classes, instead of using a function (since that would reinstantiate <code>__special_names__</code>, <code>__imethods__</code>, and <code>__other_magic__</code> every time it ran.</p>
<p>Is this a good idea, or should I return to using a function that takes a <code>type</code> and returns a Proxy subclass? On a second note, is there any way to make <code>isinstance</code> and <code>issubclass</code> happy without actually subclassing the given <code>type</code>? I originally wanted to use <code>__call__</code> for the class which would make it at least somewhat readable, since when you call functions, you call their <code>__call__</code> attribute (afaik), but python seems to think I have to use the <code>__new__</code> attribute instead to use a class as a function.</p>
<p>The entire purpose of this <code>class Proxy</code> hack is to create <code>Proxy</code> classes for immutable objects - this way if you do <code>a = b = 10</code> and <code>a += 5</code>, <code>a == b == 15</code> without having to update <code>b</code>.</p>
<p>Shameless self-plugging: This is actually a core piece of code at <a href="https://github.com/pyprogrammer/pyranoid" rel="nofollow">pyranoid</a>, which I work on, since it seems interesting.</p>
<pre><code>import functools
import collections
class Proxy(type):
__special_names__ = {
'__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',
'__contains__', '__delitem__', '__delslice__', '__div__', '__divmod__',
'__eq__', '__float__', '__floordiv__', '__ge__', '__getitem__', '__getslice__',
'__gt__', '__hash__', '__hex__', '__int__', '__iter__', '__le__', '__len__',
'__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__',
'__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__',
'__rdivmod__', '__reduce__', '__reduce_ex__', '__reversed__',
'__rfloorfiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__',
'__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setitem__',
'__setslice__', '__sub__', '__truediv__', '__xor__', '__next__'
}
__imethods__ = {
'__iadd__', '__iand__', '__idiv__', '__idivmod__',
'__ifloordiv__', '__ilshift__', '__imod__', '__imul__',
'__invert__', '__ior__', '__ipow__', '__irshift__',
'__isub__', '__itruediv__', '__ixor__'
}
__other_magic__ = {
'__int__',
'__long__',
'__float__',
'__complex__',
'__oct__',
'__hex__',
'__index__',
'__trunc__',
'__coerce__',
'__str__',
'__repr__',
'__unicode__',
'__format__',
'__hash__',
'__nonzero__',
'__dir__',
'__sizeof__'
}
__overridden__ = __special_names__.union(__imethods__).union(__other_magic__)
@staticmethod
def __imethod_wrapper____(method):
'''makes a wrapper around __i<something>__ methods, such as __iadd__ to act on __subject__'''
@functools.wraps(method)
def wrapper(self,*args,**kwargs):
tmp = self.__subject__
tmp = method(tmp,*args,**kwargs)
self.__subject__ = tmp
return self
return wrapper
@staticmethod
def __method_wrapper__(method):
'''makes a wrapper around methods and cast the result to a proxytype if possible'''
@functools.wraps(method)
def wrapper(self,*args,**kwargs):
res = method(self.__subject__,*args,**kwargs)
try:
return Proxy(type(res),'Proxy<{t}>'.format(t=type(res).__name__))(res)
except TypeError: #if the result's type isn't subclassable, i.e. types.FunctionType would raise a TypeException
return res
return wrapper
@staticmethod
def usable_base_type(Type):
try:
type('',(Type,),{})
return True
except TypeError:
return False
def __new__(cls,parentType,classname=None): #So that Proxy emulates a function
'''parentType is the type you wish to proxy, and classname is the name that appears for the class, <class 'classname'>'''
if not cls.usable_base_type(parentType):
raise TypeError("type '{Type}' is not an acceptable base type".format(Type=parentType.__name__))
if classname is None:
classname = 'Proxy<{name}>'.format(name=parentType.__name__)
class newType(parentType):
def __init__(self,*args,**kwargs):
self.__subject__ = parentType(*args,**kwargs)
def setvalue(self,value):
self.__subject__ = value
def getvalue(self):
return self.__subject__
def __getattr__(self,name):
if name not in cls.__overridden__:
return getattr(self.__subject__,name)
for name,prop in ((k,v) for k,v in parentType.__dict__.items() if k != '__doc__'): #because magic methods are implemented as staticmethods
if name in cls.__special_names__:
setattr(newType,name,cls.__method_wrapper__(prop))
for name in cls.__imethods__: #parentType may not implement all of them
if hasattr(parentType,name):
setattr(newType,name,cls.__imethod_wrapper____(parentType.__dict__[name]))
else:
non_i_name = name[:2]+name[3:]
if hasattr(parentType,non_i_name):
setattr(newType,name,cls.__imethod_wrapper____(getattr(parentType,non_i_name)))
for name in cls.__other_magic__:
if hasattr(parentType,name):
parent_item = getattr(parentType,name)
if isinstance(parent_item,collections.Callable):
setattr(newType,name,lambda self,*args,**kwargs:parent_item(self.__subject__,*args,**kwargs))
else:
setattr(newType,name,parent_item)
newType.__name__ = classname
return newType
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T01:54:55.657",
"Id": "42787",
"Score": "0",
"body": "If it were me, I'd make `Proxy` a function which returns the type. It can still be implemented in terms of the class but you shouldn't make it directly accessible. Keep its definition within the function so people can't go poking around in it. Cleaner (IMHO) if you are making this into a module."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T05:03:04.777",
"Id": "42789",
"Score": "0",
"body": "@JeffMercado but then what if I want to subclass Proxy and modify the wrapper functions, etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T14:29:15.390",
"Id": "43653",
"Score": "0",
"body": "It sounds like the only reason you made `Proxy` a class was so you could easily subclass it. In that case perhaps it would be better to implement it as a metaclass because you can also subclass them and it seems to me that's what you're really doing here."
}
] |
[
{
"body": "<p>Some quick thoughts:</p>\n\n<ol>\n<li><p>I can't tell from reading the code what the purpose is. What is this for? What are the use cases? How am I supposed to use it?</p></li>\n<li><p>There's no docstring for the <code>Proxy</code> class or for the <code>usable_base_type</code> method.</p></li>\n<li><p>What is the role of the <code>Proxy</code> class? You never seem to create any instances of it. (The <code>__new__</code> method returns an instance of the <code>newType</code> that it has just created.) Python is not Java: not everything needs to be a class.</p></li>\n<li><p>Names starting and ending with two underscores <a href=\"http://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers\" rel=\"nofollow\">are reserved</a> for future use by the language and the standard library:</p>\n\n<blockquote>\n <p><code>__*__</code> System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of <code>__*__</code> names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.</p>\n</blockquote>\n\n<p>So I'd recommend avoiding names of this form in your own code.</p></li>\n<li><p>What's the difference between <code>__special_names__</code> and <code>__other_magic__</code>? Why is <code>__slots__</code> not in either of these sets?</p></li>\n<li><p>The docstring for <code>__method_wrapper__</code> says \"cast the result\", but Python doesn't have casting. What does this method really do?</p></li>\n<li><p>Why does <code>__imethod_wrapper____</code> end in four underscores?</p></li>\n<li><p>Instead of</p>\n\n<pre><code>__special_names__.union(__imethods__).union(__other_magic__)\n</code></pre>\n\n<p>you could write</p>\n\n<pre><code>__special_names__ | __imethods__ | __other_magic__\n</code></pre></li>\n<li><p><code>__special_names__</code> is almost in alphabetical order (which is a useful way to order a list like this, because it helps you spot missing and duplicate items), but <code>__next__</code> is out of order. Why is that?</p></li>\n<li><p>What order are the names in <code>__other_magic__</code> in? Why not alphabetical order like the two other lists? And why is this list formatted with one name per line while the others are paragraph-wrapped?</p></li>\n<li><p>The method returned by <code>__method_wrapper__</code> calls <code>Proxy()</code> each time it is called, which will create another <code>newType</code> class. Is this really what you want to happen? Won't this lead to a proliferation of identical classes?</p></li>\n</ol>\n\n<p>But really this is just fumbling in the dark because I don't understand what problem you are trying to solve. I see that you edited the post to add an explanation (you want to be able to proxy immutable objects), but this still leaves me in the dark. <em>Why</em> do you want to proxy immutable objects?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T03:29:38.170",
"Id": "43450",
"Score": "0",
"body": "I think one use of this could be to simulate references that other language have, as illustrated in the example `a = b = 10`, `a += 5`, `a == b == 15` in the OP's question. WRT coding style, I think there should be a single space between items in most comma-separated list, a recommended in PEP-8. Also whitespace related is the fact that a number of lines are extremely long and should have been broken-up into multiple lines for better viewing and readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T09:56:51.780",
"Id": "43639",
"Score": "0",
"body": "@martineau: That's *what* the OP wants to achieve (proxying of immutable objects) but I want to know *why*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T13:56:48.113",
"Id": "43651",
"Score": "0",
"body": "Oh, I don't know, most likely it's one of the several things people use [references](http://en.wikipedia.org/wiki/Reference_%28computer_science%29) to accomplish. What relevance does knowing _why_ have on answering the OP's question about whether a class is a good way to implement a class factory in Python?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-01T14:11:29.250",
"Id": "43652",
"Score": "0",
"body": "@martineau: I'd like to know the purpose in order to try to provide a better answer. An implementation is only good (or bad) in so far as it meets (or fails to meet) someone's goals. If I knew more about the OP's goals (or use cases) then I would be in a better position to evaluate the solution presented in the question, or to propose a better solution."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T12:20:23.610",
"Id": "27511",
"ParentId": "27468",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27511",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T08:28:33.307",
"Id": "27468",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"immutability",
"proxy"
],
"Title": "Creating Proxy classes for immutable objects"
}
|
27468
|
<p>Some time ago I had to make a memory game as a college project. I spent around 6hrs coding this since I was also busy juggling exams. I'm not experienced in C# so there are probably a lot of things I could've done better, and I am also bad at conjuring algorithms. So please let me know on what I did right and what I did wrong here and how to prevent these mistakes in my future projects.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
namespace Memory_Game
{
public partial class MemoryGame : Form
{
private const int CARDS = 8;
private const int DUPLICATE_COUNT = 2;
private const int UNFLIPS = 2;
private const string SCORES_FILENAME = "scores.xml";
private RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); // rng
private int flipCount = 0; // I could've probably used cardsToCheck.Count instead of making another variable but I don't quite trust myself
private List<Card> cardsToCheck = new List<Card>(); // List which takes flipped cards so that only they are checked if they are pairs, instead of traversing the whole board
// also Card class is nothing more than an inherited button class with two boolean properties (Flipped, Paired)
private bool cardsMatch = false; // I have no idea why this is global, it's only used in one place
private int matchCount = 0; // counts the pairs which is then displayed in game
private int gameTime = 0; // counts game time in seconds and is then formatted and displayed in game
private int unflipsLeft = 0; // unflips - bonus "feature" which allows the player to un-flip a flipped card(basically undo), this came about from my lack of knowledge of memory games
private bool paused = false; // pretty self explanatory
private int totalFlipsCounter = 0; // also self explanatory, counts total flips made in the game
private string playerName = "noname";
private Timer gameTimer = new Timer();
// All game images. I had originally planned on having an XML file and allow players to add their own images, but time constraints and
// lack of experience led me to scrap that
#region images
System.Drawing.Bitmap triangle = Properties.Resources.triangle;
System.Drawing.Bitmap circle = Properties.Resources.circle;
System.Drawing.Bitmap square = Properties.Resources.square;
System.Drawing.Bitmap hexagon = Properties.Resources.hexagon;
System.Drawing.Bitmap diamond = Properties.Resources.diamond;
System.Drawing.Bitmap star = Properties.Resources.star;
System.Drawing.Bitmap halfCircle = Properties.Resources.halfCircle;
System.Drawing.Bitmap crescent = Properties.Resources.crescent;
#endregion
public MemoryGame()
{
InitializeComponent();
this.tableLayoutPanel.Visible = false;
this.bttnPause.Enabled = false;
this.menuGamePause.Enabled = false;
this.bttnRestart.Text = "Start";
gameTimer.Tick += new EventHandler(gameTimer_onTick);
gameTimer.Interval = 1000; //ms
}
private void gameTimer_onTick(Object sender, EventArgs e)
{
// I believe I'm doing way too much in this event however I have no idea of any other way I could do all those checks
// checking for game over on click would a lot more mess to already messy on click event method imho
this.lblTimer.Text = formatTime(gameTime);
if (matchCount == CARDS)
{
this.gameTimer.Stop();
this.bttnPause.Enabled = false;
this.menuGamePause.Enabled = false;
int score = calculateScore();
MessageBox.Show("You finished in: " + formatTime(gameTime)
+ "\n With " + totalFlipsCounter + " total flips"
+ "\n Total Score: " + score, "Finished!", MessageBoxButtons.OK);
XmlSerializer serializer = new XmlSerializer(typeof(List<PlayerScore>));
if (File.Exists(SCORES_FILENAME))
{
List<PlayerScore> scoreList = new List<PlayerScore>();
using (FileStream stream = File.OpenRead(SCORES_FILENAME))
{
scoreList = (List<PlayerScore>)serializer.Deserialize(stream);
}
if (scoreList.Count < 10)
{
bool alreadyAdded = false;
for (int i = 0; i < scoreList.Count; i++)
{
if (score > scoreList[i].Score)
{
EnterNameForm dialogEnterName = new EnterNameForm();
dialogEnterName.Owner = this;
dialogEnterName.ShowDialog();
scoreList.Insert(i, new PlayerScore(playerName, score));
alreadyAdded = true;
break;
}
}
if (!alreadyAdded)
{
EnterNameForm dialogEnterName = new EnterNameForm();
dialogEnterName.Owner = this;
dialogEnterName.ShowDialog();
scoreList.Add(new PlayerScore(playerName, score));
}
using (FileStream stream = File.OpenWrite(SCORES_FILENAME))
{
serializer.Serialize(stream, scoreList);
}
}
else
{
for (int i = 0; i < scoreList.Count; i++)
{
if (score > scoreList[i].Score)
{
EnterNameForm dialogEnterName = new EnterNameForm();
dialogEnterName.Owner = this;
dialogEnterName.ShowDialog();
scoreList.RemoveAt(scoreList.Count - 1);
scoreList.Insert(i, new PlayerScore(playerName, score));
break;
}
}
File.Delete(SCORES_FILENAME);
using (FileStream stream = File.Create(SCORES_FILENAME))
{
serializer.Serialize(stream, scoreList);
}
}
}
else
{
using (FileStream stream = File.Create(SCORES_FILENAME))
{
List<PlayerScore> scoreList = new List<PlayerScore>();
EnterNameForm dialogEnterName = new EnterNameForm();
dialogEnterName.Owner = this;
dialogEnterName.ShowDialog();
scoreList.Add(new PlayerScore(playerName, score));
serializer.Serialize(stream, scoreList);
}
}
}
gameTime++;
}
protected internal void getPlayerName(string name)
{
playerName = name;
}
private string formatTime(int timeInSeconds)
{
TimeSpan time = TimeSpan.FromSeconds(timeInSeconds);
return string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
}
private int calculateScore()
{
double timeScore = 100f * (20f/(double)gameTime);
int unflipBonusScore = 20 * unflipsLeft;
double flipScore = 500f * (20f / (double)totalFlipsCounter);
return (int)(timeScore + unflipBonusScore + flipScore);
}
private void Pause()
{
if (!this.tableLayoutPanel.Visible) return;
if (this.gameTimer.Enabled) this.gameTimer.Enabled = false;
foreach (Control card in this.tableLayoutPanel.Controls)
{
if (((Card)card).Enabled) ((Card)card).Enabled = false;
}
this.paused = true;
this.bttnPause.Text = "Continue";
}
private void UnPause()
{
if (!this.tableLayoutPanel.Visible) return;
if (!this.gameTimer.Enabled) this.gameTimer.Enabled = true;
foreach (Control card in this.tableLayoutPanel.Controls)
{
if (!((Card)card).Enabled) ((Card)card).Enabled = true;
}
this.paused = false;
this.bttnPause.Text = "Pause";
}
private void Restart()
{
// Also somewhat messy
// Restart is responsible for randomly generating cards and their positions
// It's done by creating a string list which contains all card names
// That list is then shuffled using Fisher - Yates shuffle, whose code I conveniently stole from http://stackoverflow.com/a/1262619/1182835
// afterwards those names are then added to each cards tags
// there is a glaring problem here in that while I tried making most of my code here extensible this is quite static
// since I've manually typed only 8 cards if I wanted to have more or less I'd have to refactor the code
if (!this.tableLayoutPanel.Visible) this.tableLayoutPanel.Visible = true;
if (!this.bttnPause.Enabled) this.bttnPause.Enabled = true;
if (!this.menuGamePause.Enabled) this.menuGamePause.Enabled = true;
if (this.bttnRestart.Text == "Start") this.bttnRestart.Text = "Restart";
if ((this.matchCount > 0 || this.flipCount > 0) && matchCount != CARDS)
{
Pause();
DialogResult result = MessageBox.Show("Are you sure you want to restart the current game?\n You will lose all progress", "Restart?", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
UnPause();
return;
}
}
gameTime = 0;
matchCount = 0;
unflipsLeft = UNFLIPS;
totalFlipsCounter = 0;
this.lblUnflipIndicator.Text = "Unflips: " + unflipsLeft;
this.lblFlipCounter.Text = "Flips: " + totalFlipsCounter;
List<string> boardTags = new List<string>();
for (int i = 0; i < DUPLICATE_COUNT; i++)
{
boardTags.Add("Triangle");
boardTags.Add("Circle");
boardTags.Add("Square");
boardTags.Add("Hexagon");
boardTags.Add("Diamond");
boardTags.Add("Star");
boardTags.Add("HalfCircle");
boardTags.Add("Crescent");
}
Shuffle(boardTags);
int c = 0;
foreach (Control bttn in this.tableLayoutPanel.Controls)
{
((Card)bttn).Tag = boardTags[c < boardTags.Count - 1 ? c++ : c];
((Card)bttn).Image = global::Memory_Game.Properties.Resources.cardBg;
((Card)bttn).Flipped = false;
((Card)bttn).Paired = false;
flipCount = 0;
}
this.gameTimer.Start();
if (this.paused) UnPause();
}
private void Shuffle<T>(List<T> list)
{
int n = list.Count;
while (n > 1)
{
byte[] box = new byte[1];
do provider.GetBytes(box);
while (!(box[0] < n * (Byte.MaxValue / n)));
int k = (box[0] % n);
n--;
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
private void card_Clicked(object sender, EventArgs e)
{
if (((Card)sender).Paired) return;
// In this method i check if 2 cards are flipped twice!
// This first one is a check when there are two cards flipped and the player is trying to flip a third card
// in that case the previous two flipped cards are reverted granted that they weren't paired before
// cause you will see further down that when two cards are paired they are removed from the check list
if (flipCount == DUPLICATE_COUNT && !((Card)sender).Paired && !((Card)sender).Flipped)
{
flipCount = 0;
foreach (Card card in cardsToCheck)
{
card.Image = global::Memory_Game.Properties.Resources.cardBg;
card.Flipped = false;
card.Paired = false;
}
cardsToCheck.Clear();
}
if (!((Card)sender).Flipped && flipCount < DUPLICATE_COUNT)
{
((Card)sender).Flipped = true;
flipCount++;
totalFlipsCounter++;
switch (((Card)sender).Tag.ToString()) //Here is where the card gets its image according to its tag
{
case "Triangle": ((Card)sender).Image = triangle; break;
case "Circle": ((Card)sender).Image = circle; break;
case "Square": ((Card)sender).Image = square; break;
case "HalfCircle": ((Card)sender).Image = halfCircle; break;
case "Hexagon": ((Card)sender).Image = hexagon; break;
case "Star": ((Card)sender).Image = star; break;
case "Crescent": ((Card)sender).Image = crescent; break;
case "Diamond": ((Card)sender).Image = diamond; break;
// this is missing a default case, if card by any chance didn't get a tag we'd encounter some problems
}
cardsToCheck.Add(((Card)sender));
}
else if (((Card)sender).Flipped && unflipsLeft > 0)
{
((Card)sender).Flipped = false;
((Card)sender).Image = global::Memory_Game.Properties.Resources.cardBg;
flipCount--;
totalFlipsCounter--;
cardsToCheck.Remove(((Card)sender));
unflipsLeft--;
this.lblUnflipIndicator.Text = "Unflips: " + unflipsLeft;
}
if (flipCount == DUPLICATE_COUNT) // I hate having to do this check twice
{
cardsMatch = checkForMatch();
if (cardsMatch)
{
cardsToCheck[0].Paired = true;
cardsToCheck[1].Paired = true;
matchCount++;
cardsToCheck.Clear();
flipCount = 0;
}
}
this.lblFlipCounter.Text = "Flips: " + totalFlipsCounter;
}
private bool checkForMatch()
{
if (cardsToCheck.Count != 2) return false;
if (cardsToCheck[0].Tag == cardsToCheck[1].Tag) return true;
return false;
}
private void bttnRestart_Click(object sender, EventArgs e)
{
Restart();
}
private void bttnPause_Click(object sender, EventArgs e)
{
if (this.paused) UnPause();
else Pause();
}
private void menuGameExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void showHighScoresToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.bttnRestart.Text != "Start" && matchCount != CARDS) Pause();
HighScoresList hsForm = new HighScoresList();
hsForm.Owner = this;
hsForm.ShowDialog();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T11:30:29.527",
"Id": "42736",
"Score": "2",
"body": "“I have no idea why this is global, it's only used in one place” If you know about some issues in your code, I think it would help if you fixed them first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T12:58:30.947",
"Id": "42738",
"Score": "0",
"body": "@svick I added comments right before I posted and didn't feel like changing anything."
}
] |
[
{
"body": "<blockquote>\n <p>how to prevent these mistakes in my future projects.</p>\n</blockquote>\n\n<p><strong>Rewrite your program from scratch</strong></p>\n\n<ul>\n<li>Rewrite, from scratch, several times, as you progress in your skill and knowledge.</li>\n<li>There is no absolutely correct code solution. Your goal in re-writing is not to make it perfect but see how the code evolves - how it's easier to write, understand, change - as you apply good Object Oriented Programming practices and principles.</li>\n<li>I guarantee the before and after picture will be an eye opener.</li>\n<li>It's the journey, not the end.</li>\n</ul>\n\n<p><strong>Let Reality be Your Guide</strong></p>\n\n<ul>\n<li>Build your code to refelct the real world of your problem. It will be more understandable and intuitive.</li>\n<li>If the realities of writing detail code, how you have to write in the language to make things work, obscure what it's doing in <em>reality</em> then hide it in other methods and classes that do a better job of saying things in real terms.</li>\n</ul>\n\n<p><strong>Classes</strong></p>\n\n<ul>\n<li>Go overboard on making classes. Do the opposite of your sample code. The longer term goal is to see how lots of well focused classes makes the program better. Better to build, better to understand, better to modify.</li>\n<li>Possibly making too many classes is fine for now. This is a learning process. Learn to think in terms of objects.</li>\n<li>Work hard on puting things into the proper class. Very hard.</li>\n<li>If it's a noun, make a class.</li>\n<li>If it's a thing with some kind of independent identity, real or conceptual, make a class. </li>\n<li>Seriously, go overboard on making classes. You will find it is not as overboard as you first thought.</li>\n<li>Think of what you do and what you do it to as separate things, generally. </li>\n</ul>\n\n<p><strong>Structure Your Classes</strong></p>\n\n<ul>\n<li>Everything is made of parts and so should your code. </li>\n<li>Use class and data structure to make manipulating things easier.</li>\n<li>Use class and data structure to make things reflect it's reality.</li>\n<li>Knowing classic data structures - Arrays, Collections, trees, etc. is absolutely indespensible.</li>\n<li><em>Composing</em> your \"lots of\" classes in a way that the parts do their individual things yet are a coherent whole is absolutely indespensible. </li>\n<li>The Human Body is Object Oriented. The body (a class) has clearly defined connections (<em>interfaces</em>) inside itself to interact with other internal parts (<em>classes</em>); and <em>interfaces</em> on the outside to interact with the outside world. The parts are specialized and fundamentally independent. And you could say that eyes, ears, mouth, etc. are Application Public Interfaces (APIs).</li>\n</ul>\n\n<p><strong>Get a good overview of C#</strong></p>\n\n<ul>\n<li>You will run across things that give you that \"A-Ha, I can use that\" moments.</li>\n<li>Over time you will be learning how to translate your real world problems into C# code details. </li>\n</ul>\n\n<p><strong>Complexity and Simplicity</strong></p>\n\n<ul>\n<li>We're tackling complex problems with code. OO does not discard complexity, rather it manages complexity.</li>\n<li>Simplicity is complexity broken into understandable parts.</li>\n<li>Classes and their interaction makes the problem space manageable.</li>\n<li>Limiting the number of classes and their interactions for the sake of simplicity misses the point.</li>\n<li>Object oriented guidelines, generally, are fractal; OO principles can apply at the conditional-code, method, class, module, assembly levels.</li>\n</ul>\n\n<p><strong>Sample Application to Your Code</strong></p>\n\n<ul>\n<li>Player, Card, CardDeck could all be classes.</li>\n<li>GetPlayerName() could be in the Player class.</li>\n<li>A Card is not a pile of Cards. A CardDeck is a pile of cards.</li>\n<li>The CardDeck could be a stack. Cards come off the top of the deck. This is a quintessential behavior of a stack data structure.</li>\n<li>A stack of cards does not shuffle, flip, etc. itself. <em>Something</em> or <em>someone</em> has to be doing that however.</li>\n<li><em>Something</em> has to be working the interaction of the card(s) and player(s). </li>\n<li>\"Something\" and \"Someone\" may very well be their own classes.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T20:01:50.717",
"Id": "42773",
"Score": "0",
"body": "Whoa, nice wall of text... I have to admit that I suck at conjuring up meaningful classes. I always try to jam things which don't belong, into a class. Even now, I'm trying to make a simple asteroids game using C++ and SFML, and a simple game object class is turning out to not be as simple as I thought. I really suck at planning things out. Thanks for the advice, I'll try to follow it as best as i can"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T17:26:33.420",
"Id": "27484",
"ParentId": "27472",
"Score": "14"
}
},
{
"body": "<p>What you did right:</p>\n\n<ul>\n<li>Good variable names</li>\n<li>Good use of private members</li>\n<li>Good method names</li>\n<li>Early exits on <code>Pause</code> and <code>UnPause</code></li>\n<li>Reasonably consistent naming style</li>\n<li>Clever inheriting Button for Card</li>\n</ul>\n\n<p>What you did not-so-right:</p>\n\n<ul>\n<li>As you pointed out, some of your event handlers are quite long. Even some simple extract method refactoring would go a long way to making it more readable.</li>\n<li>No real architecture or design here. It's a sample project, so that may be overkill - but it'd be nice to see a few other classes besides <code>Card</code>. It would give you a place to put those decomposed methods into as well.</li>\n<li>Storing state in the UI itself without an abstraction (<code>.Text</code>, <code>.Tag</code>, etc.). This often starts out as the \"simplest possible thing\" - but usually quickly ends up in a tangled mess. You may want to consider abstracting out a <code>ViewModel</code>.</li>\n</ul>\n\n<p>As an example of an extract method refactoring on your <code>gameTimer_Click</code> handler:</p>\n\n<pre><code> private void gameTimer_onTick(Object sender, EventArgs e)\n {\n this.lblTimer.Text = formatTime(gameTime);\n if (matchCount != CARDS) return; // prefer early exit to deeply nested ifs\n\n this.gameTimer.Stop();\n this.bttnPause.Enabled = false;\n this.menuGamePause.Enabled = false;\n\n int score = calculateScore();\n MessageBox.Show(\n string.Format(FINISH_TEXT, totalFlipsCounter, score), // abstract out long text; makes the code cleaner and eases changing it later \n MessageBoxButtons.OK\n );\n\n SaveHighScore(score);\n gameTime++;\n }\n\n // saving the score is long, and a discrete op. Perfect for a method extraction.\n void SaveHighScore(int newScore) \n {\n const int MAX_SCORES = 10;\n\n XmlSerializer serializer = new XmlSerializer(typeof(List<PlayerScore>));\n List<PlayerScore> scoreList; // don't new if you're not going to use it\n if (File.Exists(SCORES_FILENAME)) // make if branches in a method as small as possible and then join back up to your main logic\n {\n using (FileStream stream = File.OpenRead(SCORES_FILENAME))\n {\n scoreList = (List<PlayerScore>)serializer.Deserialize(stream);\n }\n }\n slse \n {\n scoreList = new List<PlayerScore>(); \n }\n\n // It *looks* like this is supposed to add the newScore in order - kind of hard to tell\n // since there's 3 almost-identical blocks.\n // A SortedList would work well for this - but I don't have Intellisense handy and don't\n // use it enough to know it off-hand, so I'll use LINQ (which for 10 scores won't be a problem)\n scoreList.Add(new PlayerScore(GetPlayerName(), score));\n var topScoresList = scoreList.OrderByDescending(p => p.Score).Take(MAX_SCORES).ToList();\n\n using (FileStream stream = File.OpenOrCreate(SCORES_FILENAME)) // don't delete when you can just overwrite...\n {\n serializer.Serialize(stream, topScoresList);\n }\n }\n\n string GetPlayerName() \n {\n using (EnterNameForm dialogEnterName = new EnterNameForm())\n {\n dialogEnterName.Owner = this;\n dialogEnterName.ShowDialog();\n }\n\n // not sure how playerName gets set? Spooky action-at-a-distance from EnterNameForm and Owner or Form?\n // Would be better for this Form to grab it from the dialog...\n return playerName;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:17:15.293",
"Id": "42806",
"Score": "0",
"body": "Thanks for the response. It was quite helpful.\nTo explain a few things. While adding new scores that code was indeed to add scores in order. I was forced to use NET 2.0 framework so I couldn't use LINQ and all the newer useful stuff. Also I chose to delete the file when entering a new score because it's a top 10 list and when a new score would be added after the list already contains 10 scores then if the player name was shorter than the previous one when overwriting there would remain some artefacts in the xml code which didn't get overwritten and that would make the xml code unreadable"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T22:16:26.003",
"Id": "27490",
"ParentId": "27472",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27484",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T10:22:31.917",
"Id": "27472",
"Score": "5",
"Tags": [
"c#",
"beginner",
"game"
],
"Title": "Memory game in C#"
}
|
27472
|
<p>This is probably a really simple question.</p>
<p>An embedded device I'm working with will store the device information in an xml file.</p>
<p>In my code, I want to read this xml file and freely reference to it wherever I need to, so I made a simple helper class:</p>
<pre><code>public class DeviceInformation {
public static final String XML_DIRECTORY_ON_DEVICE = "/xml/";
public static final String ROOT_DEVICE_XML_FILE = "rootdevice.xml";
public static String DEVICE_ID;
public static String DEVICE_TYPE;
public static String HOME_ID;
public DeviceInformation() {
File xmlFile = new File(XML_DIRECTORY_ON_DEVICE + ROOT_DEVICE_XML_FILE);
if (!xmlFile.exists())
return;
RootDeviceXMLReader rootDeviceXMLReader = new RootDeviceXMLReader(xmlFile);
DeviceInfoStruct deviceInfoStruct = rootDeviceXMLReader.getDeviceInfoStruct();
DEVICE_ID = deviceInfoStruct.getDeviceID();
DEVICE_TYPE = deviceInfoStruct.getDeviceType();
HOME_ID = deviceInfoStruct.getHomeID();
}
}
</code></pre>
<p>And then I'd just get my device id by DeviceInformation.DEVICE_ID. Same goes for type and home_id.</p>
<p>But this approach just doesn't seem elegant. Turn the initializer into a static one? Still, I feel like there's something wrong with this whole approach and I just cannot articulate it. How can I improve this class?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T13:24:57.670",
"Id": "42739",
"Score": "0",
"body": "Do you only have one device?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:15:21.070",
"Id": "42741",
"Score": "0",
"body": "Multiple devices, but one configuration per device."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:20:22.680",
"Id": "42743",
"Score": "0",
"body": "Then why are the device's id and type static?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:51:34.353",
"Id": "42750",
"Score": "0",
"body": "Because.. there's a single configuration per device..?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:54:09.123",
"Id": "42751",
"Score": "0",
"body": "So it means you have one class per device type? No functionality is common between any of them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T15:10:07.013",
"Id": "42752",
"Score": "0",
"body": "What? one class per device type? There's only one class period in any given device. I have multiple **physical** devices, but each device will have its own unique device id, type and home id stored in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T15:12:20.900",
"Id": "42753",
"Score": "0",
"body": "Then storing them as static variables is useless, since static variables are visible at the class level -- they cannot be overriden by instances of the class"
}
] |
[
{
"body": "<p>I think you should have :</p>\n\n<ol>\n<li><p>A constructor taking device_id, device_type and home as an argument.</p></li>\n<li><p>a static method doing the file handling and calling the constructor previously defined.</p></li>\n</ol>\n\n<p>This would make your code more modular, easier to test and would put different independent things (device creation and file handling) in different places.</p>\n\n<p>I'd also like to point out that at the moment, your constructor does create a non-properly-initialised device when the file does not exist. It would probably be much better not to create it at all (and return <code>null</code> ?) if we don't have the required information to do so.</p>\n\n<p>Also, and this is not relevant to your question but there's not real need for 2 variables <code>XML_DIRECTORY_ON_DEVICE</code> and <code>ROOT_DEVICE_XML_FILE</code> if you are always going to call them together. It might be just as easy to have \"XML_PATH\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T15:59:54.663",
"Id": "42754",
"Score": "0",
"body": "Thanks. You're probably right on the part that I should return null instead of just returning."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T13:21:29.473",
"Id": "27476",
"ParentId": "27474",
"Score": "1"
}
},
{
"body": "<p>I'm not 100% sure what you mean but if you want to refer to it everywhere then maybe make the class a singleton? You could just call it everywhere this way.</p>\n\n<pre><code>DeviceInformation.getInstance().someMethod(); \n</code></pre>\n\n<p>This means that there is only <strong>one</strong> DeviceInformation in the project instead of many.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-11T13:39:13.467",
"Id": "119632",
"ParentId": "27474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27476",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T13:08:36.203",
"Id": "27474",
"Score": "0",
"Tags": [
"java",
"object-oriented"
],
"Title": "Best way to manage a device information class"
}
|
27474
|
<p>I have just finished my first iteration of conway's game of life as a codeing excercise. I have little experience with coding, so I think my code could use some refactoring. What i am curios about is the drivers for having a more efficient code. My code is based on a cell object:</p>
<pre><code>//Defining the cells --------------------------------------------
function Cell (x,y,id, num) {
this.id = id;
this.num = num;
this.isAlive = false;
this.x = x;
this.y = y;
this.nextIsAlive = false;
this.cellChange = false;
this.cellTop = function() {
if (this.y === 0) {
return false;
}
return getCell(this.x, this.y-OFFS-RECH/2).isAlive;
};
this.cellRight = function() {
if (this.x+RECW >= canvas.width) {
return false;
}
return getCell(this.x+RECW+OFFS+RECW/2, this.y).isAlive;
};
this.cellBottom = function() {
if (this.y+RECH >= canvas.height) {
return false;
}
return getCell(this.x, this.y+RECH+OFFS+RECH/2).isAlive;
};
this.cellLeft = function() {
if (this.x === 0) {
return false;
}
return getCell(this.x-OFFS-RECW/2, this.y).isAlive;
};
this.cellUpperLeft = function() {
if (this.x === 0 || this.y === 0) {
return false;
}
return getCell(this.x-OFFS-RECW/2, this.y-OFFS-RECH/2).isAlive;
};
this.cellUpperRight = function() {
if (this.x+RECW >= canvas.width || this.y === 0) {
return false;
}
return getCell(this.x+RECW+OFFS+RECW/2, this.y-OFFS-RECH/2).isAlive;
};
this.cellBottomLeft = function() {
if (this.x === 0 || this.y+RECH >= canvas.height) {
return false;
}
return getCell(this.x-OFFS-RECW/2, this.y+RECH+OFFS+RECH/2).isAlive;
};
this.cellBottomRight = function() {
if (this.x+RECW >= canvas.width || this.y+RECH >= canvas.height) {
return false;
}
return getCell(this.x+RECW+OFFS+RECW/2, this.y+RECH+OFFS+RECH/2).isAlive;
};
this.numOfLiveNeighbour = function() {
var i = 0;
if (this.cellTop()) {
i++;
}
if (this.cellRight()) {
i++;
}
if (this.cellBottom()) {
i++;
}
if (this.cellLeft()) {
i++;
}
if (this.cellUpperLeft()) {
i++;
}
if (this.cellUpperRight()) {
i++;
}
if (this.cellBottomLeft()) {
i++;
}
if (this.cellBottomRight()) {
i++;
}
return i;
};
}
Cell.prototype = {
constructor: Cell,
//Function where cell draws itself
drawCell: function() {
if (this.isAlive) {
ctx.fillRect(this.x,this.y,RECW,RECH);
} else {
ctx.clearRect(this.x,this.y,RECW,RECH);
}
},
//Function for killing a cell during animation
killCell: function () {
this.nextIsAlive = false;
},
//Function for reviving a cell during animation
reviveCell: function () {
this.nextIsAlive = true;
},
//function for turning on & off a cell when animation is not going.
toggle: function() {
if (this.isAlive) {
this.isAlive = false;
} else {
this.isAlive = true;
}
}
};
// Cell finished -----------------------------------------------
</code></pre>
<p>As you can see i am trying to use a constructor/prototype pattern, but i think i have too many function definitions in the constructor, is that correct to assume? Is it a better way to do this?</p>
<p>I also have a suspicion that my functions for getting cells, determining next steps etc are not optimal:</p>
<pre><code>//Function for finding a cell based on x & y coordinates ------------
function getCell(x,y) {
for (var cell in cells) {
var currCell = cells[cell];
if (x >=currCell.x && x <= currCell.x+RECW && y >=currCell.y && y <= currCell.y+RECH) {
return currCell;
}
}
}
//Function for drawing next step
function cellsNextStep() {
var currCell;
for (var cellNext in cells) {
currCell = cells[cellNext];
determineNextStep(currCell);
}
for (var cellDraw in cells) {
currCell = cells[cellDraw];
if (currCell.cellChange) {
currCell.isAlive = currCell.nextIsAlive;
}
currCell.drawCell();
currCell.cellChange = false;
currCell.nextIsAlive = false;
}
}
//Function for determining next value for each cell
function determineNextStep(cell) {
var neighbours = cell.numOfLiveNeighbour();
if (cell.isAlive) {
if (neighbours < 2 || neighbours > 3) {
cell.killCell();
cell.cellChange = true;
}
} else {
if (neighbours === 3) {
cell.reviveCell();
cell.cellChange = true;
}
}
}
</code></pre>
<p>My main problem is that when i try to increase the canvas size (number of cells are increased) the animation comes to a stand still. It is currently working ok with a canvas ov width 300, height 150 and cellsize of 7 (RECH and RECW) and offset between cells of 1 (OFFS).</p>
<p>I also have three different handlers, one for turning cells on and off before animation, one to start animation and one to stop. I guess I also should use one click handler on the document and make use of the bubble feature to only have one event handler (but i dont think that is my main performance issue here).</p>
<p>Any feedback would be appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T12:34:13.757",
"Id": "42747",
"Score": "3",
"body": "It's a bad idea to use `for ... in` loops on arrays in JavaScript. Use a numeric index and a plain `for` loop. Besides that, your performance problem stems from the fact that you have to **search** to find your cells. Keep track of them with an array of arrays (a 2-dimensional array, in other words) and your \"getCell()\" function will be **much** faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T12:40:46.910",
"Id": "42748",
"Score": "0",
"body": "Yes, you can put all your methods on the prototype since they're using only properties of your objects, not the local variables (parameters) in your constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:36:30.883",
"Id": "42749",
"Score": "0",
"body": "For starters, run this through jslint or jshint."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:06:15.903",
"Id": "42757",
"Score": "0",
"body": "@Pointy: thanks, the `for ... in` change helped alot. I also moved the functions to the prototype, but i didn't quite understand the change of the `getCell()` function. This function is based on the event from a mouseclick (using the x and y coordinates to determine the cell). Maybe it is smart to have one functions for this task and one \"internal\" getCell that keeps track of the cells?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:59:18.073",
"Id": "42765",
"Score": "0",
"body": "@Øyvind well if you kept track of your cells in a data structure that allowed a direct lookup instead of a search, you'd save a huge amount of overhead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T16:44:36.077",
"Id": "61773",
"Score": "0",
"body": "Can you build a jsfiddle for this? I would love to play with this code."
}
] |
[
{
"body": "<p>Your code could indeed probably use some tuning.</p>\n\n<p>The three major points are:</p>\n\n<ul>\n<li><p>A cell should know it's neighbors, you should only <strong>once</strong> determine the neighbors for each cell and place them in an array in that Cell. This will speed up your code tremendously.</p></li>\n<li><p>Only living cells and their neighbors can change, tracking the living cells in a queue ( array ) will speed up your code. You would check the cells in that queue and the neighbors within the cells for changes.</p></li>\n<li><p>Checking all cells for life status changes in status slows the code down, you should have a queue ( array ) where you add all cells that change status. This way you only draw what changes.</p></li>\n</ul>\n\n<p>Then there are some minor things you can consider:</p>\n\n<p>1.</p>\n\n<pre><code>drawCell: function() {\n if (this.isAlive) {\n ctx.fillRect(this.x,this.y,RECW,RECH);\n } else {\n ctx.clearRect(this.x,this.y,RECW,RECH);\n }\n</code></pre>\n\n<p>this could be a little DRYer since the parameters are the same.</p>\n\n<pre><code>drawCell: function() {\n var action = this.isAlive ? ctx.fillRect : ctx.clearRect;\n action(this.x,this.y,RECW,RECH);\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>toggle: function() {\n if (this.isAlive) {\n this.isAlive = false;\n } else {\n this.isAlive = true;\n }\n}\n</code></pre>\n\n<p>could use some Boolean magic:</p>\n\n<pre><code>toggle: function() {\n this.isAlive = !this.isAlive;\n}\n</code></pre>\n\n<p>Finally, <code>determineNextStep</code> should really be part of the <code>prototype</code> of <code>Cell</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T14:51:06.177",
"Id": "38116",
"ParentId": "27481",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38116",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T12:29:39.033",
"Id": "27481",
"Score": "4",
"Tags": [
"javascript",
"performance",
"game-of-life"
],
"Title": "Conway's game of life - Optimizing the code"
}
|
27481
|
<p>I'm building an alarm set to reoccur every 30 days. I was wondering if I could get a few extra sets of eyes to look things over and see if you can notice anything I may have done wrong. Any/all input is greatly appreciated! </p>
<p><strong>SOURCE:</strong></p>
<pre><code>public class WifiMonitor extends Activity {
Button sendButton;
EditText msgTextField;
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView infoView = (TextView) findViewById(R.id.traffic_info);
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.##");
String totalStr = nf.format(totalBytes);
String mobileStr = nf.format(mobileBytes);
String info = String.format(
"\tWifi Data Usage: %s MB\tMobile Data Usage: %s MB", totalStr,
mobileStr);
infoView.setText(info);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("7862611848", null, info, null, null);
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Intent Aintent = new Intent("REFRESH_THIS");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
// reschedule to check again tomorrow
Intent serviceIntent = new Intent(WifiMonitor.this, Alarm.class);
PendingIntent restartServiceIntent = PendingIntent.getService(
WifiMonitor.this, 0, serviceIntent, 0);
AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);
// cancel previous alarm
alarms.cancel(restartServiceIntent);
// schedule alarm for today + 1 day
calendar.add(Calendar.DATE, 1);
// schedule the alarm
alarms.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
restartServiceIntent);
}
}
</code></pre>
<p><strong>ALARM:</strong></p>
<pre><code>public class Alarm extends Service {
// compat to support older devices
@Override
public void onStart(Intent intent, int startId) {
onStartCommand(intent, 0, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// check to ensure everything is functioning
Toast toast = Toast.makeText(this, "WiFi Usage Sent", 2000);
toast.show();
// send SMS
String sms = "";
sms += ("\tWifi Data Usage: "
+ (TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes() - (TrafficStats
.getMobileRxBytes() + TrafficStats.getMobileTxBytes()))
/ 1000000 + " MB");
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("7862611848", null, sms, null, null);
return START_STICKY;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:39:42.867",
"Id": "42768",
"Score": "0",
"body": "Any reason to avoid using cron and a shell script?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:41:54.160",
"Id": "42770",
"Score": "0",
"body": "It's an Android app (which I probably should have mentioned) and I'm looking for the simplest solution. Android doesnt use cron, does it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:42:55.563",
"Id": "42771",
"Score": "0",
"body": "Looks like you do have to use the AlarmManager. http://developer.android.com/reference/android/app/AlarmManager.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T19:46:14.010",
"Id": "42772",
"Score": "0",
"body": "Thought so... \n\nI've started 2 threads regarding the different issues/questions I'm having regarding this (but no working solutions thus far) \n\nhttp://stackoverflow.com/questions/17151775/issues-implementing-monthly-repeating-alarms\n\n\nhttp://stackoverflow.com/questions/17155371/starting-a-future-alarm-based-on-todays-date"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T17:18:00.117",
"Id": "50574",
"Score": "0",
"body": "please notice [this question](http://stackoverflow.com/q/14376470/1056359) of mine regarding this issue"
}
] |
[
{
"body": "<p>I'm not familiar with Android, so just some generic note:</p>\n\n<ol>\n<li><pre><code>calendar.set(Calendar.DAY_OF_WEEK, 0);\n</code></pre>\n\n<p>What is this line supposed to do? <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#DAY_OF_WEEK\" rel=\"nofollow\">Javadoc of <code>DAY_OF_WEEK</code></a> says the following:</p>\n\n<blockquote>\n <p>Field number for get and set indicating the day of the week. This field takes \n values <code>SUNDAY</code>, <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>, <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.</p>\n</blockquote>\n\n<p>Unfortunately, none of the mentioned constants has <code>0</code> as <a href=\"http://docs.oracle.com/javase/7/docs/api/constant-values.html#java.util.Calendar.SUNDAY\" rel=\"nofollow\">value</a>. (<code>SUNDAY</code> = 1, <code>MONDAY</code> = 2. ..., <code>FRIDAY</code> = 6) You should use on the constants above here for better clarity.</p></li>\n<li><p>I'd move the <code>Calendar</code> creation and and modification to a named method where the name explains the purpose of the method. It would be easier just reading the name of the method to figure out what contains the created <code>Calendar</code> instance than reading through the calls of setter methods.</p></li>\n<li><p>The <code>alarm</code> variable is unused. Remove it.</p></li>\n<li><p><code>(AlarmManager) getSystemService(Context.ALARM_SERVICE)</code> is duplicated in the code. You could use the same object and call it twice or create a <code>getAlarmManager()</code> method which does the casting too to remove the duplication.</p></li>\n<li><pre><code>Calendar calendar = Calendar.getInstance();\ncalendar = Calendar.getInstance();\n</code></pre>\n\n<p>Could be simply</p>\n\n<pre><code>Calendar calendar = Calendar.getInstance();\n</code></pre>\n\n<p>It's the same.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T16:41:24.873",
"Id": "42517",
"ParentId": "27482",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T14:40:21.920",
"Id": "27482",
"Score": "5",
"Tags": [
"java",
"android",
"datetime"
],
"Title": "Building 30 day alarm"
}
|
27482
|
<p>I'm a hobbyist Python programmer with not much experience.</p>
<p>I wrote some code for a solution to a Tic Tac Toe AI problem on the internet.</p>
<p>Then yesterday I wrote a simple console Tic Tac Toe game for human vs computer play where the computer plays randomly.</p>
<p>So I thought it would be nice how difficult it would be to combine the code from the AI solution with the console game, so the computer plays intelligently rather than randomly.</p>
<p><strong>Final Product:</strong></p>
<pre><code>import random
class TTTGame(object):
_coords = [(x, y) for y in range(3) for x in range(3)]
_num_to_coord = dict([(n+1, c) for n, c in enumerate(_coords)])
_win_ways = (# Horizontal
set([1, 2, 3]),
set([4, 5, 6]),
set([7, 8, 9]),
# Verticle
set([1, 4, 7]),
set([2, 5, 8]),
set([3, 6, 9]),
# Diagonal
set([1, 5, 9]),
set([3, 5, 7]))
def __init__(self, game=None):
if not game:
self.board = map(list, ['___'] * 3)
self.avail = set(xrange(1, 10))
self.xnums = set()
self.onums = set()
else:
self.board = map(list, game.board)
self.avail = set(game.avail)
self.xnums = set(game.xnums)
self.onums = set(game.onums)
def __str__(self):
rows = [' | '.join(row).replace('_',' ')
for row in self.board[::-1]]
divs = ['\n---+---+---\n', '\n---+---+---\n', '\n']
return ' ' + ' '.join(map(''.join, zip(rows, divs)))
def winner(self):
"""Return 'X' or 'O' or 'T' else False if game not over."""
for way in self._win_ways:
if way.issubset(self.xnums):
return 'X'
if way.issubset(self.onums):
return 'O'
if len(self.xnums) + len(self.onums) == 9:
return 'T'
return False
def play(self, n, piece=None):
"""
Place piece at spot numbered n and ammend attributes.
if piece is None, remove the piece at cell n and ammend attributes.
"""
x, y = self._num_to_coord[n]
if piece:
self.board[y][x] = piece
(self.xnums if piece == 'X' else self.onums).add(n)
self.avail.remove(n)
else:
self.board[y][x] = '_'
self.avail.add(n)
(self.xnums if n in self.xnums else self.onums).remove(n)
def next_move(self, piece):
"""
Return the next best move for piece as cell number.
"""
if all(map(lambda x: len(set(x)) == 1, self.board)):
return random.choice((1, 3, 7, 9)) # Corners are best first play.
scores = []
avail = list(self.avail)
for n in avail:
node = TTTGame(self)
node.play(n, piece)
scores.append(node._evaluate(piece))
best = max(enumerate(scores), key=lambda x: x[1])[0]
return avail[best]
def _evaluate(self, piece):
"""
Return a score for how favourable the current board is towards piece.
"""
state = self.winner()
if state:
return (1 if state == piece else 0 if state == 'T' else -1)
scores = []
apponent = 'OX'.replace(piece, '')
for n in self.avail:
self.play(n, apponent)
scores.append(0-self._evaluate(apponent))
self.play(n) # reverse play
safest = min(scores)
return safest
class CLI(object):
# - Note that game_loop() is not concerned with any of the display
# attributes or refreshing the screen.
# - Each method is responsible for
# handling it's own display characteristics, for now, with the use of
# the message attribute and refresh().
# - Methods which modify the message attribute should assign an empty
# string to message attribute before returning, except in cases like
# coin_toss().
# - Methods may communicate with each other via return values, not
# via message or any other display attribute.
def __init__(self):
# Display variables.
self.wins = 0
self.losses = 0
self.ties = 0
self.message = ''
# Piece assignments.
self.player = ''
self.computer = ''
# TTTGame instance.
self.game = None
# Players turn or not.
self.turn = None
def refresh(self):
screen = '\n' * 100 # Clear screen.
screen += "TicTacToe\n"
screen += ("wins:%s\tlosses:%s\tties:%s\n\n" %
(self.wins, self.losses, self.ties))
screen += str(self.game) if self.game else '\n' * 4 # The game board.
screen += '\n' + self.message + '\n'
print screen
def coin_toss(self):
"""Assigns player a piece at random, Returns None."""
while True: # until user enters valid input
self.refresh()
option = raw_input("Heads or Tails (or just hit enter)? ")
if option.lower() in ['', 'heads', 'h', 'tails', 't']:
self.player = random.choice(['X', 'O'])
self.computer = 'XO'.replace(self.player, '')
break
else:
self.message = "That's not a valid choice!"
self.message = "You go first" if self.player == 'X' else ''
def player_turn(self):
while True: # until user enters valid input
self.refresh()
option = raw_input("cell number: ").strip().lower()
if option == 'hint':
self.message = str(self.game.next_move(self.player))
elif not (option.isdigit() and 1 <= int(option) <= 9):
self.message = "That's not a valid option!"
elif int(option) not in self.game.avail:
self.message = "That cell is already occupied!"
else:
break
self.game.play(int(option), self.player)
self.message = ''
def computer_turn(self):
self.refresh()
best = self.game.next_move(self.computer)
self.game.play(best, self.computer)
self.message = ''
def play_again(self):
"""Gives user the chance to quit the program or continue."""
while True: # until user enters valid input
self.refresh()
option = raw_input("Play again (enter) or n? ").strip().lower()
if not option:
self.message = ''
return
elif option in ["no", 'n']:
import sys
sys.exit()
else:
self.message = "That's not a valid option!"
def game_loop(self):
"""Simple game loop."""
while True:
self.game = TTTGame()
self.coin_toss()
self.turn = (self.player == 'X') # X always goes first.
while not self.game.winner():
if self.turn:
self.player_turn()
else:
self.computer_turn()
self.turn = not self.turn
winner = self.game.winner()
if winner == 'T':
self.message = "You tied."
self.ties += 1
elif winner == self.player:
self.message = "You won!"
self.wins += 1
else:
self.message = "You lost."
self.losses += 1
self.play_again()
if __name__ == '__main__':
print '\n' * 100
print ("Welome to TicTacToe\n\n" +
"Cells are numbered 1 to 9 and correspond directly\n" +
"with keys on your keyboards numpad.\n\n" +
"To make a play, type the relevent number and hit enter\n\n" +
"You can also type hint when it's your turn to play.\n\n" +
"BTW, the computer is unbeatable. Which means your win\n" +
"statistic will never show anything other than 0.\n" +
"Have fun ;)\n\n")
raw_input(".... (hit enter) ...")
user_interface = CLI()
user_interface.game_loop()
</code></pre>
|
[] |
[
{
"body": "<p>From <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> : </p>\n\n<blockquote>\n <p>Comparisons to singletons like None should always be done with is or is not, never the equality operators.</p>\n</blockquote>\n\n<p>,</p>\n\n<blockquote>\n <p>Don't compare boolean values to True or False using ==</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T23:05:33.790",
"Id": "42781",
"Score": "0",
"body": "I changed `if game == None:` to `if not game:`\nAlthough the other cases where I'm using == to compare booleans was because I hadn't thought long enough of the right way to work the return values of TTTGame.winner() function. So I ended up having to do things like `if CLI.game.winner() == None` which means **if game not over** and `if CLI.game.winner() == False` which translates to (kinda) **if game tied**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T23:19:03.323",
"Id": "42783",
"Score": "0",
"body": "Yep, I understand your concern. I was about to comment the fact that the return types were somehow awkward (subtle mix of None, booleans and strings) but I couldn't see any better solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T17:51:26.937",
"Id": "27485",
"ParentId": "27483",
"Score": "1"
}
},
{
"body": "<ul>\n<li>The <code>CLI</code> class uses static methods and class attributes for no\nreason. Use normal instance methods and instance attributes -- it\ngives you more flexibility and you avoid typing <code>@staticmethod</code> all\nover the place.</li>\n<li><code>winner</code> returns 'X' or 'O' if won else False if tie else None. This is unusual as False is normally used as the opposite of True. You could use some other non-empty string to indicate tie.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T23:14:21.013",
"Id": "42782",
"Score": "0",
"body": "Thanks for your input, I really appreciate it. You're right about the winner method and the other poster also picked up on some strange code that was a consequence of the odd nature of winner(). Although I was wondering how instance methods would improve the code. I thought about making an instance class for CLI but it just didn't seem fitting. It doesn't seem like an actual object, but I wanted to encapsulate it all of it incase I needed to import it as a module and working in global just feels messy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T05:57:32.167",
"Id": "42790",
"Score": "0",
"body": "@Russ Class attributes share a major characteristic of global variables: there can be only one instance of them. Using class instances and instance variables allows you to have multiple game sessions going on simultaneously, eg. if you develop this into a web application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T06:31:54.937",
"Id": "42791",
"Score": "0",
"body": "Thanks very much. I completely missed that. I'll start changing it to an instance class today."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T18:11:22.627",
"Id": "27487",
"ParentId": "27483",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T17:15:55.900",
"Id": "27483",
"Score": "1",
"Tags": [
"python",
"design-patterns",
"classes"
],
"Title": "Extending a simple Python console program with external code. Did I handle this correctly?"
}
|
27483
|
<p>I'm currently working on a small chess game written in Java (<a href="https://github.com/Ouzned/JavaChess/tree/f1a88a76c531e98fd46dc08a2fca7073709e60cd" rel="nofollow noreferrer">on GitHub</a>). The board is modeled as a Board object with a 2D array of Piece objects :</p>
<pre><code>public class Board {
private final int ROWS = 8;
private final int COLS = 8;
private Piece[][] board;
private List<Move> moveList;
[...]
}
</code></pre>
<p>At first, I tried to implement all the board's possible states / legal move generation (<code>isCheck</code>, <code>isCheckMate</code>, <code>isStaleMate</code>, <code>legalMoves</code>...) inside the Board class. </p>
<p>For example :</p>
<pre><code>private List<Move> moves(Color color) {
List<Move> allMoves = new ArrayList<Move>();
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
Square src = new Square(row, col);
Piece piece = getPiece(src);
if (piece == null || !piece.isColor(color))
continue;
allMoves.addAll(piece.availableMoves(src, this));
}
}
return allMoves;
}
</code></pre>
<p>However it ended up being about 300 lines and it was not very easy to read (especially because of the duplication of the board iteration loops).</p>
<p>So I decided to try another approach : I removed all the state evaluation code and replaced it with this method :</p>
<pre><code> public void accept(BoardVisitor bv) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
bv.visit(board[row][col], new Square(row, col));
}
}
}
</code></pre>
<p>I then created a set of classes to "evaluate" the different states :</p>
<pre><code>public class CheckEvaluator implements BoardVisitor {
private Square kingSquare;
private Board board;
private Color color;
private boolean isCheck = false;
public CheckEvaluator(Color color, Board board) {
this.board = board;
this.color = color;
}
@Override
public void visit(Piece piece, Square src) {
isCheck = isCheck || piece.canGoTo(src, kingSquare, board);
}
public boolean getResult() {
this.kingSquare = board.findKing(color);
board.accept(this);
return isCheck;
}
}
</code></pre>
<p>I regrouped all these evaluators inside a single class :</p>
<pre><code>public class BoardEvaluator {
private Board board;
public BoardEvaluator(Board board) {
this.board = board;
}
public boolean isCheck(Color color) {
CheckEvaluator ce = new CheckEvaluator(color, board);
return ce.getResult();
}
public boolean isCheckMate(Color color) {
CheckMateEvaluator cme = new CheckMateEvaluator(color, board);
return cme.getResult();
}
public boolean isStaleMate() {
StaleMateEvaluator sme = new StaleMateEvaluator(board);
return sme.getResult();
}
public List<Move> legalMoves(Color color) {
LegalMovesEvaluator lme = new LegalMovesEvaluator(color, board);
return lme.getResult();
}
</code></pre>
<p>This version seems clearer and easier to me but I don't have a lot of experience and I'd be very glad to get some feedback about it:</p>
<ul>
<li>Do you think this is a valid design?</li>
<li>Is my BoardVisitor a good (if simple) implementation of the Visitor pattern?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T06:57:10.390",
"Id": "42793",
"Score": "0",
"body": "at a first glance it looks nice to me. just two things: 1. according to Java naming conventions your static final members should be `COLS` and `ROWS` and 2. `bv.visit(board[row][col], new Square(col, row));` looks confusing to me. You should consider reordering the parameters and always use `row` or `col`as first parameter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:08:04.013",
"Id": "42801",
"Score": "0",
"body": "Thank you very much for your comment! I've edited my post to take your remarks into account. How about the fact that a new evaluator is created each time one of the `BoardEvaluator` method is called? Should I try to implement some kind of singleton pattern? (only one instance for each board/color couple...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:20:17.793",
"Id": "42808",
"Score": "0",
"body": "I wonder if your Evaluators have to be stateful at all. If it would suffice to pass board and color to the evaluation method you could implement them as singletons"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:12:28.653",
"Id": "42839",
"Score": "0",
"body": "Yeah I'll pass the board to `getResult()` and use the Evaluators as singletons. Thanks"
}
] |
[
{
"body": "<p>At the moment it seems your board holds 64 (8*8) Pieces :</p>\n\n<pre><code>private Piece[][] board;\n</code></pre>\n\n<p>It would be more logical to have :</p>\n\n<pre><code>private Square[][] board;\n</code></pre>\n\n<p>Secondly, you can avoid a lot of nested loops by representing the board with a one dimensional array : </p>\n\n<pre><code>private Square[] board;\n</code></pre>\n\n<p>Which is simply putting all rows in one big sequence.\nFor the clients of Board this can be perfectly well hidden by converting coordinates to index behind the scenes : </p>\n\n<pre><code>private Square at(int row, int col) {\n return board[row * COLS + col];\n}\n</code></pre>\n\n<p>This, for instance, greatly simplifies the accept method :</p>\n\n<pre><code>public void accept(BoardVisitor bv) {\n for (Square square : board) {\n bv.visit(square);\n }\n}\n</code></pre>\n\n<p><strong>Edit :</strong> </p>\n\n<p>The responsibility of the Board class is to keep track of the positions of the pieces on the chess board. In essense this would lead me to this interface :</p>\n\n<pre><code>public interface Board {\n Square positionOf(Piece piece);\n Piece at(Square square);\n void make(Move move);\n}\n</code></pre>\n\n<p>Your current implementation (an array that contains Pieces) would make <code>at()</code> faster than <code>positionOf()</code>. Though other data structures would be possible. (I'm thinking of a bidirectional map of <code>Piece</code> and <code>Square</code>).</p>\n\n<p>You worried about a board keeping 64 square instances around, I worried about creating the same <code>Square</code>s over and over. I'd say both worries would amount to premature optimization. At the moment, I would simply ensure we can address it both ways : make a static factory method on <code>Square</code> :</p>\n\n<pre><code>public static Square valueOf(int col, int row) { return new Square(col, row); }\n</code></pre>\n\n<p>This allows the board not to worry about whether it is creating new squares or not, and <em>if need be</em> the factory method can later be changed to do a lookup in a cache (an array of <code>Square</code>), rather than creating a new one every time.</p>\n\n<p>For your current implementation I would suggest you simple rename the <code>Piece</code> array from <code>board</code> to <code>positions</code>, just to take away the suggestion that a <code>Board</code> is 64 <code>Piece</code>s.</p>\n\n<p>I think the visitor pattern is overkill (there is no family of classes we want to add behavior to). Extracting the board evaluators out of the Board class is, however, a very good idea. The Iterator pattern will be more than enough. So maybe :</p>\n\n<pre><code>public interface Board {\n Square positionOf(Piece piece);\n Piece at(Square square);\n void make(Move move);\n Iterator<Square> allSquares(); // traverse all Squares of the board\n Iterator<Piece> allPieces(); // traverse all Pieces still on the board.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T17:03:39.933",
"Id": "42851",
"Score": "0",
"body": "Thanks for your answer! I agree that storing the Piece objects into a flat array simplifies the accept method. However I think the board doesn't really need to generate and keep 68 square objects just for the sake of setting a Piece on a Square. The way I see it, Square objects are only used to communicate position throughout the application instead of using basic integers. Aside from that, I don't see the benefits of changing the Piece[] into a Square[]. (btw, a Piece[][] doesn't mean that the board contains 64 pieces, only that it contains 64 placeholders that may or may not contain one)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T20:24:24.967",
"Id": "42861",
"Score": "0",
"body": "I understand that the name doesn't imply that there are 64 pieces, it just suggests it when you read the code, so readability could be improved there.\nSecondly, while unwilling to have the board keep 64 squares around, you are willing to create 64 new ones whenever a visitor passes through all coordinates..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T20:49:54.187",
"Id": "42862",
"Score": "0",
"body": "Well, I prefer to create Square objects that are quickly discarded rather than keeping them around for the entire duration of the game. Another reason behind this is that putting pieces on Squares would force me to create duplicates when copying the Board. Right now, I only have to clone the array as the Pieces are stateless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:58:11.587",
"Id": "42887",
"Score": "0",
"body": "I never said to make Squares mutable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T23:23:27.863",
"Id": "42890",
"Score": "0",
"body": "Sorry I thought that was what you meant. Would you then create a copy of the square only when a piece is moved on the board?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T05:19:45.310",
"Id": "42900",
"Score": "0",
"body": "Edited answer with new insights."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T22:44:54.647",
"Id": "43167",
"Score": "0",
"body": "I've added a link to my github repo in my original post. Your ideas of bidirectional `Piece` and `Board` and the static `Square` methods really helped me. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T15:05:44.783",
"Id": "27518",
"ParentId": "27488",
"Score": "2"
}
},
{
"body": "<p>Warning! Arm Chair Quarterbacking in progress. Given that I offer this.</p>\n\n<p><strong>Game Class</strong></p>\n\n<p>Why is this <code>Board.moveList</code> in the <code>Board class</code>? You need a \"driver\" for a chess game and that would be a <code>Game</code> class. \"A game consists of (has) moves\" makes more sense.</p>\n\n<p>The <code>Game</code> gives us a conceptual framework for a richer chess game. A <code>Game</code> has players, may have a timer for speed chess, and can keep track of pieces removed from the board; and of course records the moves.</p>\n\n<p><strong>Board Class</strong></p>\n\n<p>The chess board is a data structure. Don't make more of it than it is; nor less.</p>\n\n<p>In the <a href=\"http://www.oodesign.com/visitor-pattern.html\" rel=\"noreferrer\">Visitor Pattern</a> the data structure has-a element that has an <code>accept</code> method. That element seems to be a <code>Square</code>. I'm not certain if it's better than the <code>Board</code> being visited, but certainly the point is that we're evaluating the state at that one square? I don't see a big deal in giving a board reference to each square.</p>\n\n<p>OR .. maybe the <code>Piece</code>s are visited. To test if the piece is \"inCheck\" for example. This perspective makes more sense than a square is in check. Is this why your board is <code>Piece[][]</code> and not <code>Square[][]</code>?</p>\n\n<p>Whether we are visiting the board and iterating the squares; or iterating the board and visiting the squares; or iterating the squares and visiting the pieces may be more than semantics. I vote for whatever best reflects intent, gives me good code expressions, and sensible building blocks.</p>\n\n<p>In any case I agree with @bowmore about refactoring <code>Piece[][]</code> to <code>Square[][]</code>. </p>\n\n<p><strong>Pieces</strong></p>\n\n<p>Even given a rich <code>Piece</code> class, I like the idea of using an enumeration for names. This makes for nicer coding and expressability overall (and my pet peeve - it avoids strings). Maybe two enumerations. As in <code>White.Knight</code> and <code>Black.Queen</code>; or <code>Pieces.WhiteKnight</code>, <code>Pieces.BlackQueen</code> And a value to represent an empty square might be nice <code>Pieces.none</code> or <code>Pieces.undefined</code>. </p>\n\n<p>Maybe <code>Piece</code> has a <code>Square</code> reference so it knows where it is. This may have a nice effect on the <code>visit</code> code.</p>\n\n<p><strong>Visitor Pattern</strong></p>\n\n<p>Nice call.</p>\n\n<p>I agree with @MarcoForgerg, the visitors do not need to keep state. Just pass in the needed parameters and forget-about-it when done. And, instead of Singletons perhaps just static.</p>\n\n<p>Nested visitors? Ok, so the board gets \"visited\" which in turn \"visits\" each square, which in turn, <em>finally</em> gets to <code>Piece.accept(Evaluator xxxx)</code>. Visitors, by definition, understand their visited data structure so I'm thinking board iteration is wrapped in the board visitor, and the square visitor knows to check for an occupying piece and knows what Evaluator(s) to pass to the piece. It <em>feels</em> like nicely layered (code) logic to me. And note how the iteration logic is in the visitors, not the board (data structure). And subsequently all the business logic is in the visitor as well.</p>\n\n<p>SO instead of this</p>\n\n<pre><code>public void accept(BoardVisitor bv) {\n for (Square square : board) {\n bv.visit(square);\n }\n}\n</code></pre>\n\n<p>THIS - Let the Visitor do the walking and talking (decision making). And the decision to evaluate empty squares is delayed as long as possible - <em>push details down</em>. Note that Board, Square, Piece visiting logic is decoupled/layered.</p>\n\n<pre><code>// in Board class\npublic void accept(BoardVisitor bv) { bv.visit(this));}\n\n// BoardVisitor class\npublic void visit (Board board) {\n // \"board level\" logic as needed\n for (Square square in board) {\n square.accept (this.squareVisitor);\n }\n}\n\n// Square class\npublic void accept (SquareVisitor sv) {\n sv.visit(this);\n}\n\n// SquareVisitor class\npublic void visit (Square square) {\n // \"square level\" logic as needed\n if(!square.isEmpty) {\n // maybe we target Evaluators for the particular piece on the square\n\n this.evaluator(square); // square has references to its piece and board.\n // maybe the square.piece has \"visit\"\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T18:27:32.443",
"Id": "42858",
"Score": "0",
"body": "Your points are very interesting! The moveList should indeed belong to the Game object. Concerning the Piece[][], please read my answer to @bowmore above.\nAs for the visitor, I agree that it has a knowledge of the entity it visits (in the sense that it knows the entity exists) but I think it shouldn't understand the entity's internal representation. As a result the visitor can't know how to iterate over the board pieces, hence the iteration inside the Board class. Your nested visitor example is quite interesting but don't you think in this case we only visit the board as a \"whole\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T13:19:48.110",
"Id": "42914",
"Score": "0",
"body": "(1) Ah, I see your rational for `Piece[][]`. If a `Piece` has a position property then maybe no need for `Square` at all? (2) Client code (Board class, Evaluators) manipulating things *in terms of* chess is the holy grail of OO here and as long as higher level code does not obfuscate what's going on then fine. (3)Re: Iterator vs. visitor. Iterator, good idea. But not mutually exclusive. *Iterator* abstracts looping thru a pile of stuff. *Visitor* decouples logic code, allowing you to \"swap out\" different visitor behavior on each iteration."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T17:23:09.463",
"Id": "27524",
"ParentId": "27488",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27524",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T20:25:17.910",
"Id": "27488",
"Score": "5",
"Tags": [
"java",
"chess",
"visitor-pattern"
],
"Title": "Chess board representation in Java"
}
|
27488
|
<pre><code>class ShareModel
constructor: ->
questionaireView = new QuestionnaireView
@previewImages =
shareCurrent: -> ShareModel::getSingle(ModelView::getCurrentImage(),'current',questionaireView.weight(),questionaireView.weightUnits())
shareGoal: -> ShareModel::getSingle(ModelView::getGoalImage(),'goal',questionaireView.goal(),questionaireView.weightUnits())
shareSideBySide: -> ShareModel::getDualImage(questionaireView.weight(),questionaireView.goal(),questionaireView.weightUnits())
getSingle:(image,caption,weight,units) ->
url = "http://..."
url += "?current=#{image}"
url += "&template=single"
url += "&text=#{caption}"
url += "&weight=#{weight+units}"
getDualImage:(current,goal,units) ->
url = "http://..."
url += "?current=#{ModelView::getCurrentImage()}&goal=#{ModelView::getGoalImage()}"
url += "&template=side_by_side"
url += "&current_weight=#{current+units}&goal_weight=#{goal+units}"
</code></pre>
|
[] |
[
{
"body": "<p>Next time, add a brief description of what the code actually does. Sure, we can read it, but it still leaves a lot of questions. For instance, the <code>current</code> parameter: Is that a path to an image, or a number or what?</p>\n\n<p>Anyway, here are some observations, but I don't know enough of the context to fully refactor your code.</p>\n\n<ol>\n<li><p>Build your parameters from an object; don't hand-code them. Use jQuery's <a href=\"http://api.jquery.com/jQuery.param/\" rel=\"nofollow\"><code>$.param</code></a> or something similar to build the query string. It makes everything more explicit and less error-prone.<br>\nHere's how it'd work with jQuery</p>\n\n<pre><code>url = \"http://...?\" + $.param\n { name: \"current\", value: someVar }\n { name: \"text\", value: someVar }\n ...\n</code></pre></li>\n<li><p>Don't add <em>instance</em> methods to your \"class\" and then call them as <em>prototype</em> methods (you seem to be doing the same for <code>ModelView</code>). Either make local functions or IIFEs just to group the code and keep it private, or make them \"static methods\" (i.e. define a method with <code>@foo -></code> on <code>ShareModel</code>, and call it as <code>ShareModel.foo()</code> from anywhere), or keep them as instance methods and just call with <code>@getSingle(...)</code>. Calling a prototype's methods directly is something you <em>can</em> do in javascript, but that doesn't mean it's the <em>right</em> thing to do.<br>\nAlternatively: Why not make the <code>previewImages</code> functionality a separate class? Or create global utility functions?</p></li>\n<li><p>Keep your naming consistent. One method is called <code>getDualImage</code> while the other is called <code>getSingle</code> with no <code>Image</code> suffix. Also, I'd call the former one <code>getSideBySideImage</code> as that's what it's called elsewhere (and \"dual\" could imply getting 2 image URLs, not one) </p></li>\n<li><p>Keep the signatures more consistent too. One method (<code>getSingle</code>) is sent all the variables it needs, while the other accesses some of them itself. The latter seems more appropriate, as most parameters can indeed be accessed from the methods themselves.<br>\nThe same can be said of the parameters; the two URLs end up being very different. Passing parameter arrays might be better, i.e. <code>weight[]=...&weight[]=...</code> for the side-by-side.<br>\nAnd <code>current</code> seems an odd choice for a parameter name, when it might not actually be the current image, but the goal image instead. I'd prefer something more generic like <code>image</code> or whatever is appropriate for the kind of value you're sending.</p></li>\n<li><p>Lastly, it might be easier to use 3 separate base URLs for side-by-side, current, and goal images. Right now, you're passing a hard-coded <code>template</code> parameter, and (sometimes) a hardcoded <code>text</code> parameter; why not have URLs like <code>current.png?param...</code>, <code>goal.png?param...</code> and <code>/side-by-side.png?param...</code> instead?</p></li>\n</ol>\n\n<p>As mentioned, I'd provide more code, but there's a lot that could be done differently, and I don't know enough of the context to know what will work, and what won't.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T17:09:18.040",
"Id": "27523",
"ParentId": "27489",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27523",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T20:48:30.977",
"Id": "27489",
"Score": "-1",
"Tags": [
"coffeescript"
],
"Title": "Coffeescript Review"
}
|
27489
|
<p>Previous review of this project: <a href="https://codereview.stackexchange.com/questions/27462/is-this-nested-class-design-ineffective-for-my-deck-class">Nested Deck class design and implementation</a></p>
<p>My program finally meets all of my expectations to the best of my ability, but I'd still like another review. Please give as many critiques as you can. I will then implement this with future games that I have in mind.</p>
<p><strong>CardValuesMap.h</strong></p>
<pre><code>#ifndef CARDVALUESMAP_H
#define CARDVALUESMAP_H
std::map<char, unsigned> retrieveMap()
{
std::map<char, unsigned> values;
values['A'] = 1;
values['2'] = 2;
values['3'] = 3;
values['4'] = 4;
values['5'] = 5;
values['6'] = 6;
values['7'] = 7;
values['8'] = 8;
values['9'] = 9;
values['T'] = 10;
values['J'] = 11;
values['Q'] = 12;
values['K'] = 13;
return values;
}
#endif
</code></pre>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <iostream>
#include <array>
#include <map>
#include <string>
class Deck;
class Card
{
private:
friend class Deck;
unsigned value;
char rank;
char suit;
Card::Card(unsigned v, char r, char s) : value(v), rank(r), suit(s) {}
public:
Card::Card() : value(0), rank(' '), suit(' ') {}
bool operator<(const Card &rhs) const {return (value < rhs.value);}
bool operator>(const Card &rhs) const {return (value > rhs.value);}
bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
friend std::ostream& operator<<(std::ostream &out, const Card &aCard)
{return out << '[' << aCard.rank << aCard.suit << ']';}
};
class Deck
{
private:
static const unsigned MAX_SIZE = 52;
static const std::map<char, unsigned> values;
static const std::string SUITS;
std::array<Card, MAX_SIZE> cards;
int topCardPos;
public:
Deck();
void shuffle();
Card deal();
unsigned size() const {return topCardPos+1;}
unsigned empty() const {return topCardPos == -1;}
friend std::ostream& operator<<(std::ostream &out, const Deck &aDeck);
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include "Deck.h"
#include "CardValuesMap.h"
#include <algorithm>
const std::map<char, unsigned> Deck::values = retrieveMap();
const std::string Deck::SUITS = "HDCS";
Deck::Deck() : topCardPos(-1)
{
for (auto valueIter = values.cbegin(); valueIter != values.cend(); ++valueIter)
{
for (auto suitIter = SUITS.cbegin(); suitIter != SUITS.cend(); ++suitIter)
{
topCardPos++;
cards[topCardPos] = Card(valueIter->second, valueIter->first, *suitIter);
}
}
shuffle();
}
void Deck::shuffle()
{
topCardPos = MAX_SIZE-1;
std::random_shuffle(&cards.front(), &cards.back()+1);
}
Card Deck::deal()
{
if (empty())
{
std::cerr << "\nDECK IS EMPTY -- RESHUFFLING NOW\n";
shuffle();
}
topCardPos--;
return cards[topCardPos+1];
}
std::ostream& operator<<(std::ostream &out, const Deck &aDeck)
{
for (int i = aDeck.size()-1; i > -1; --i)
{
out << "\n" << aDeck.cards[i];
}
return out;
}
</code></pre>
|
[] |
[
{
"body": "<p>I haven't followed your previous reviews, so a few of these may be things that have already been pointed out.</p>\n\n<p>Anyway, here's my go at it.</p>\n\n<hr>\n\n<p>The <code>Card::</code> is invalid on the following:</p>\n\n<pre><code>Card::Card(unsigned v, char r, char s) : value(v), rank(r), suit(s) {}\nCard::Card() : value(0), rank(' '), suit(' ') {}\n</code></pre>\n\n<hr>\n\n<p>The suit should likely be an enum (in particular, a strongly typed one as you're using C++11).</p>\n\n<hr>\n\n<p>The comparators in Card are non-sensical. Why do you sometimes compare value and sometimes compare suit? How are a Jack of Spades and a 2 of Spades equal just because they're both a Spade?</p>\n\n<hr>\n\n<p>For maintainability, try to define comparators in terms of each other: <code>bool operator!=(const Card &rhs) const {return !(suit == rhs.suit);}</code> and so on.</p>\n\n<hr>\n\n<p>Don't use bare <code>unsigned</code>. Use <code>unsigned int</code>. </p>\n\n<p>(Personal preference really on this one)</p>\n\n<hr>\n\n<p>Even better yet, define the types as public typedefs. Like <code>Deck::size_type</code>, <code>Card:suit_type</code> and so on (standard library-esque).</p>\n\n<hr>\n\n<p>Why make the maximum size be 52? </p>\n\n<p>You could either have the size be templated and default to 52, or you could have it be a constructor parameter (in which case you'd have to use a vector rather than std::array).</p>\n\n<hr>\n\n<p>Is the mapping in <code>retrieveMap</code> ever meant to be used by consuming code? If not, make it static in Deck.cpp.</p>\n\n<hr>\n\n<p><code>Card::deal</code> has no business outputting anything. If dealing can't be done, throw an exception.</p>\n\n<hr>\n\n<p>Rather than having to think in reverse iteration, you could think of the top of the deck as being 0. This would likely simplify a lot of the logic.</p>\n\n<hr>\n\n<p>Are you happy being stuck with a 52 card deck? What if you don't want Jokers? What if you want some completely different kind of card system? A</p>\n\n<p>Basically what I'm saying is that a deck shouldn't be responsible for filling itself up with cards.</p>\n\n<p>In fact, constructing objects in a construct tends to be an anti-pattern: <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"nofollow\">http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/</a>. Note that \"new\" in this context is talking about Java, not C++. Though the terminology is Java centric, what it actually means is is construction in general. Constructing objects in a construct tends to imply that the objects should be provided to the constructor rather than be created in there.</p>\n\n<p>Rather than having the deck populate itself with a traditional set of cards, have a utility method:</p>\n\n<pre><code>Deck classDeck = Deck::makeClassicDeck();\n</code></pre>\n\n<p>This lets you have the convenience that you currently have, but it doesn't hold you to a certain set of cards (you could also go the two constructors route).</p>\n\n<hr>\n\n<p>Why are you trying to hide the Card class? You should probably trust your consuming code to handle cards. How do you know that the code isn't going to be used for some very odd game that involves a deck composed of a normal deck and 6 extra jokers? If you let the consumer of Deck decide what to put it in, it's a lot more flexible.</p>\n\n<hr>\n\n<p>As a person about to make a program that involves card game logic, why should I use your Deck class? What does it offer me over using a simple <code>std::deqeue</code> (or <code>std::stack</code> or <code>std::vector</code>) of <code>Card</code>? The way I see it at the moment, it offers basically nothing over a vector. It just has a more convenient shuffle.</p>\n\n<hr>\n\n<p>MAX_SIZE should be a <code>std::size_t</code></p>\n\n<p><code>empty</code> should return a <code>bool</code></p>\n\n<p><code>size</code> should return a std::size_t</p>\n\n<hr>\n\n<p>I'm not sure if I'd bother defining an ostream<<. Might be more useful to let each application determine how it wants to print a deck rather than tie it to one format.</p>\n\n<hr>\n\n<p>I'd go with a more idiomatic shuffling approach:</p>\n\n<pre><code>std::random_shuffle(cards.begin(), cards.end());\n</code></pre>\n\n<hr>\n\n<p>I don't like <code>SUITS</code>. Why is it the only all caps variable?</p>\n\n<p>I don't like <code>aDeck</code> and <code>aCard</code>. A <code>const Deck&</code> is obviously a Deck. Just call it <code>deck</code> or something. Names beginning with an article seem odd (imagine if <code>Deck::cards</code> were instead <code>theCards</code>).</p>\n\n<hr>\n\n<p>Since it's private, it's not <em>as</em> important, but <code>Card::Card(unsigned v, char r, char s)</code> should still have proper names for the parameters.</p>\n\n<hr>\n\n<p>Crazy paranoid moment: deal() is not exception safe (well, technically it is since Card::Card never throws, but there's no hard gaurantee of that in place). </p>\n\n<p>You could theoretically encounter an exception in the card constructor which would mean the card would properly be removed from the deck, but the consuming code would not be able to have it.</p>\n\n<p>Then again, this is complete paranoia, especially since Card's constructor never throws for the time being.</p>\n\n<p>(Just happened to think of it since the oddity of <code>std::stack</code>'s <code>pop()</code> returning void has always been an interesting little necessity to me.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:11:28.353",
"Id": "42794",
"Score": "0",
"body": "Although it looks like I'm able to use most C++11 features, the compiler doesn't like the syntax for the strongly-typed `enum`s. I'll have to find a different option. I was still unsuccessful with the exception-handling, but I'll keep working on it. It's my preferred option anyway. For now, at least, I may limit my deck to 52 cards. I could still consider a `template` or a different container. Lastly, should I bother with another review after I make sufficient changes? Had I known that there's still a lot of room for improvement, I would've used a better title."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:40:00.077",
"Id": "42795",
"Score": "0",
"body": "In: `The Card:: is superfluous on the following:` You mean it is completely illegal. Only broken compilers allow this (which is MSVS)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:43:34.167",
"Id": "42796",
"Score": "0",
"body": "Be very careful comparing different languages `note that \"new\" in this context is talking about Java, not C++`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:45:23.253",
"Id": "42797",
"Score": "0",
"body": "Everything else looks fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:45:29.900",
"Id": "42814",
"Score": "0",
"body": "@LokiAstari: If I knew of a better compiler with more C++11 support and such (yes, I use MSVS), I'd switch to it. You are right that this compiler has not detected this (among other things). Regarding this program, I cannot use strongly-typed `enum`s (mentioned above). Finding the best way to construct these Cards, with such restrictions, is really frustrating me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T09:54:51.847",
"Id": "42818",
"Score": "0",
"body": "@LokiAstari Have updated accordingly on both counts :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T09:58:20.470",
"Id": "42819",
"Score": "0",
"body": "@Jamal The only complete implementation I know of at the moment is LLVM's clang. g++, which is a lot more accessible on Windows though, is pretty near close with 4.8 and 4.7 is only missing a few things you're likely to come across unless you get into threading or some more corner areas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T17:05:04.053",
"Id": "42852",
"Score": "0",
"body": "@Corbin: Until I can find a solid solution that I can also understand, I'll keep my original deck-construction techniques (but using something other than `std::map`). I need to keep looking into this. I may go for another review at some point, but it won't be a general one like this one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T18:07:53.373",
"Id": "42855",
"Score": "0",
"body": "@Corbin: Also, you're right about the nonsensical Card comparators. Those kinds of comparisons are primary for Texas Hold'Em, but I should instead use functions (or something) else instead of overloads."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T06:20:40.107",
"Id": "27500",
"ParentId": "27491",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T01:58:34.883",
"Id": "27491",
"Score": "4",
"Tags": [
"c++",
"playing-cards"
],
"Title": "Deck of cards program using a card value map"
}
|
27491
|
<p>At the suggestion of @templatetypedef, I am posting the code for my quick sort to see if anyone can offer suggestions as to where to make comparisons. And any tips on improving the code. I am using this in conjunction with a Merge Sort and Heap sort to see how the different comparison algorithms sort an array of random numbers.</p>
<p>I will post my Merge Sort and heap sort in other posts so they stay separate based on tips from @templatetypedef. I actually have them all in a package that runs them together but separating them out for clarity.</p>
<pre><code>package AlgorithmComparison;
import java.util.*;
import java.math.*;
public class AlgCompareApp
{
public static void main(String[] args)
{
int qSortCnt = 0;
int numbersNeeded = 5000; // Number in the array
double total = logb(numbersNeeded, 2);
double logN = numbersNeeded * total;
int loopCount = 50; // Change this for the Loop through each sort
System.out.print("n log(n) for " + numbersNeeded + " is ");
System.out.printf(" %.2f", logN);
System.out.println();
System.out.println("Quick Sort");
for (int l = 0; l < loopCount; l++)
{
Random rng = new Random();
// Create initial Array List of numbers
ArrayList<Integer> arrlist = new ArrayList<Integer>();
// Populate Initial Array List with numbers and no duplicates
for (int i = 0; i < numbersNeeded; i++)
{
while (true)
{
Integer next = rng.nextInt(numbersNeeded * 2);
if (!arrlist.contains(next))
{
arrlist.add(next);
break;
}
}
}
// Create QuickSort Int Array from ArrayList
int[] quickSortArray = new int[arrlist.size()];
for (int i = 0; i < arrlist.size(); i++)
{
quickSortArray[i] = arrlist.get(i);
}
// QUICK SORT RUN
//System.out.print("\n---------------Quick Sort---------------\n");
QuickSortRun qksrt = new QuickSortRun(quickSortArray, numbersNeeded);
qksrt.quickSort();
qSortCnt = qSortCnt + qksrt.getComparisons();
qksrt.displayComparisons();
}
System.out.println("Averages");
System.out.println((qSortCnt / loopCount));
System.out.println("Percentage of n log(n)");
System.out.printf("%.2f", ((qSortCnt / loopCount) / logN));
System.out.println();
}
public static double logb(double a, double b)
{
return Math.log(a) / Math.log(b);
}
}
</code></pre>
<p></p>
<pre><code>package AlgorithmComparison;
import java.util.*;
public class QuickSortRun {
private int[] theArray;
private int nElms;
private int comparisons;
public QuickSortRun(int[] max, int n){
theArray = max;
nElms = n;
}
public void insert(int value){
theArray[nElms++] = value;
}
public void display(){
// for(int i = 0; i < nElms; i++){
// System.out.print(theArray[i] + " ");
// }
// System.out.println(" ");
}
public void displayComparisons(){
System.out.println(comparisons);
}
public void reverseArray(){
int left = 0;
int right = theArray.length - 1;
while(left < right){
int temp = theArray[left];
theArray[left] = theArray[right];
theArray[right] = temp;
left++;
right--;
}
}
private void swap(int dx1, int dx2){
int temp = theArray[dx1];
theArray[dx1] = theArray[dx2];
theArray[dx2] = temp;
comparisons++;
}
private int medianOf3(int left, int right){
int center = (left +right)/2;
if(theArray[left] > theArray[center])
swap(left, center);
if(theArray[left] > theArray[right])
swap(left, right);
if(theArray[center] > theArray[right])
swap(center, right);
swap(center, right);
return theArray[left];
}
public void quickSort(){
comparisons = 0;
recQuickSort(0, nElms-1);
}
private void recQuickSort(int left, int right){
int size = right-left+1;
if(size < 5)
insertionSort(left, right);
else
{
int median = medianOf3(left, right);
int partition = partitionIt(left, right, median);
recQuickSort(left, partition-1);
recQuickSort(partition+1, right);
}
}
private int partitionIt(int left, int right, int pivot){
int leftPtr = left-1;
int rightPtr = right;
while(true){
while(theArray[++leftPtr] < pivot);
while(theArray[--rightPtr] > pivot);
if(leftPtr >= rightPtr)
break;
else
swap(leftPtr,rightPtr);
}
swap(leftPtr, right);
return leftPtr;
}
private void insertionSort(int left, int right){
int in, out;
for(out = left + 1; out <= right; out++){
int temp = theArray[out];
in = out;
while(in > left && theArray[in-1] >= temp){
theArray[in] = theArray[in-1];
in--;
}
theArray[in] = temp;
comparisons++;
}
}
public int getComparisons()
{
return comparisons;
}
}
</code></pre>
<p>My entire Java package is zipped up and can be downloaded from <a href="http://steadmanusa.com/AlgorithmCompare.zip" rel="nofollow">here</a>.</p>
|
[] |
[
{
"body": "<p>I'll review the testing procedure here. The <code>main()</code> function is long enough to be worth breaking up.</p>\n\n<p>If you intend to test several sorting algorithms, then the algorithms should all implement a common interface so that they are interchangeable.</p>\n\n<pre><code>public interface SortingAlgorithm {\n public void sort(int[] array);\n}\n\npublic class QuickSort implements SortingAlgorithm {\n @Override\n public void sort(int[] array) {\n // Quicksort implementation\n }\n}\n\npublic class MergeSort implements SortingAlgorithm {\n @Override\n public void sort(int[] array) {\n // Mergesort implementation\n }\n}\n</code></pre>\n\n<p>Then you would be able to use the same driver to test all of them.</p>\n\n<pre><code>public class AlgCompareApp {\n private SortingAlgorithm[] algorithms;\n private long[] times;\n\n public AlgCompareApp(int arraySize, SortingAlgorithm[] algorithms) {\n this.algorithms = algorithms;\n this.times = new long[algorithms.length];\n }\n\n public void run(int iterations, int arraySize) {\n for (int i = 0; i < iterations; i++) {\n int[] array = generateRandomArray(arraySize);\n for (SortingAlgorithm alg : this.algorithms) {\n this.times[i] += measureSortingAlgorithm(alg, array);\n }\n }\n }\n\n public void displayStatistics() {\n // TODO\n }\n\n private static int[] generateRandomArray(int size) {\n // TODO\n }\n\n private static long measureSortingAlgorithm(SortingAlgorithm alg, int[] array) {\n array = Arrays.copyOf(array, array.length);\n long startTime = System.nanoTime();\n alg.sort(array);\n long finishTime = System.nanoTime();\n return finishTime - startTime;\n }\n\n public static void main(String[] args) {\n SortingAlgorithm[] algorithms = new SortingAlgorithm[] {\n new QuickSort(),\n new MergeSort(),\n new HeapSort()\n };\n AlgCompareApp app = new AlgCompareApp(algorithms);\n app.run(50, 5000);\n app.displayStatistics();\n }\n}\n</code></pre>\n\n<p>Your procedure for generating random arrays of distinct elements is inefficient, both because you attempt to filter out duplicates (towards the end, each number will collide with near 50% probability), and because you search for duplicates by linear traversal of the array (which takes O(<em>n</em><sup>2</sup>) time in total). I'm not sure why you want to weed out duplicates, as the ability of sorting algorithms to handle duplicate entries is important to test too. If you do want all array elements to be distinct, you might as well use consecutive numbers. (Comparison-based sorts shouldn't care how large the gaps are between numbers.) If you really want to achieve your original goal, you could put 2 <em>n</em> consecutive numbers in an array, apply a Fisher-Yates shuffle, then truncate it to <em>n</em> elements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T06:06:26.310",
"Id": "38811",
"ParentId": "27495",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T03:35:41.247",
"Id": "27495",
"Score": "4",
"Tags": [
"java",
"unit-testing",
"sorting",
"quick-sort"
],
"Title": "Help with comparison counters in quick sort algorithm"
}
|
27495
|
<p>I am posting the code for my merge sort to see if I can get folks offer suggestions as to where to make comparisons or if I am making the correctly already. </p>
<p>I will post my heap sort and quick sorts in other posts. I actually have them all in a package that runs them together but separating them out for clarity.</p>
<pre><code>package AlgorithmComparison;
import java.util.*;
import java.math.*;
public class AlgCompareApp
{
public static void main(String[] args)
{
int mSortCnt = 0;
int numbersNeeded = 5000; // Number in the array
double total = logb(numbersNeeded,2);
double logN = numbersNeeded * total;
int loopCount = 50; // Change this for the Loop through each sort
System.out.print("n log(n) for " + numbersNeeded + " is ");
System.out.printf(" %.2f",logN);
System.out.println();
System.out.println("Merge Sort");
for(int l = 0; l < loopCount; l++)
{
Random rng = new Random();
// Create initial Array List of numbers
ArrayList<Integer> arrlist = new ArrayList<Integer>();
// Populate Initial Array List with numbers and no duplicates
for (int i = 0; i < numbersNeeded; i++)
{
while (true)
{
Integer next = rng.nextInt(numbersNeeded * 2);
if (!arrlist.contains(next))
{
arrlist.add(next);
break;
}
}
}
// Create QuickSort Int Array from ArrayList
int[] mergeSortArray = new int[arrlist.size()];
for (int i = 0; i < arrlist.size(); i++)
{
mergeSortArray[i] = arrlist.get(i);
}
//System.out.print("\n---------------Merge Sort---------------\n");
MergeSortRun mgsrt = new MergeSortRun();
mgsrt.MergeSortRun(mergeSortArray, 0, mergeSortArray.length - 1);
mgsrt.displayList();
mSortCnt = mSortCnt +mgsrt.getCounterOne();
}
System.out.println("Averages");
System.out.println((mSortCnt / loopCount));
System.out.println("Percentage of n log(n)");
System.out.printf("%.2f",((mSortCnt / loopCount)/logN));
System.out.println();
}
public static double logb( double a, double b )
{
return Math.log(a) / Math.log(b);
}
}
</code></pre>
<hr>
<pre><code>package AlgorithmComparison;
import java.util.*;
public class MergeSortRun
{
private int counterOne = 0;
int[] displayList;
public void MergeSortRun(int array[], int lo, int n)
{
int low = lo;
int high = n;
if (low >= high)
{
return;
}
int middle = (low + high) / 2;
MergeSortRun(array, low, middle);
MergeSortRun(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((lo <= end_low) && (start_high <= high))
{
if (array[low] < array[start_high])
{
low++;
} else
{
int Temp = array[start_high];
for (int k = start_high - 1; k >= low; k--)
{
array[k + 1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
//counterOne++;
}
counterOne++;
}
// counterOne++;
displayList = Arrays.copyOf(array, n + 1);
}
public void displayList()
{
// for (int i = 0; i < displayList.length; i++)
// {
// System.out.print(displayList[i] + " ");
// }
System.out.println(counterOne);
}
public int getCounterOne()
{
return counterOne;
}
}
</code></pre>
<p>My entire java package is zipped up and can be downloaded from <a href="http://steadmanusa.com/AlgorithmCompare.zip" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T04:59:01.307",
"Id": "43149",
"Score": "0",
"body": "You seem to be asking us to find bugs in your code. That's not the purpose of this site. The best (and certainly a quicker) way to find bugs is to write unit tests yourself, and use a Java debugger yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T14:09:50.113",
"Id": "43159",
"Score": "0",
"body": "I am sorry if you thought I was asking for the code to be debugged, my intent was really to get folks who had more experience to look at where I was making comparisons and see if they thought I was counting the comparisons correctly. Or better yet, how they might do it versus how I did it in my code."
}
] |
[
{
"body": "<p>Here's some suggestions on what you can do differently to get a better result (both performance counters and code style).</p>\n\n<p>The <code>MergeSortRun</code> class breaks many rules for naming conventions in Java.... well, actually the class name is OK (<code>MergeSortRun</code>), but the method (also called <code>MergeSortRun</code>) is very confusing, because only the constructor (which you don't have coded up) is supposed to have that name.</p>\n\n<p>Rename the <code>MergeSortRun</code> method to something simple like 'sort'.</p>\n\n<p>Additionally, the variables 'counterOne' and 'displaylist' are not necessary... if it were me, I would have 'counterOne' returned from the <code>sort</code> method, and the <code>displaylist</code> variable is completely dead anyway. Doing this will allow you to make the <code>sort</code> method static, of the form:</p>\n\n<pre><code>public static final int sort(int array[], int lo, int n) {...}\n</code></pre>\n\n<p>The 'int' return value is the number of comparisons you want to count.</p>\n\n<p>Now, you have to question what your counter should be. There are two key items that tend to impact performance of sorts. The one is comparisons, and the other is data-moves (or swaps).</p>\n\n<p>Since your input data is an <code>int[]</code> array, the comparisons between values are just as expensive as any other <code>int</code> based comparison. Thus, I think you should potentially be counting much more. The easiest way to do it is to show you what I think it should look like:</p>\n\n<pre><code>public int sort(int array[], int lo, int n) {\n int low = lo;\n int high = n;\n int compares = 1;\n if (low >= high) {\n return compares; // NOTE - 1 comparison (low >= high)\n }\n int middle = (low + high) / 2; // technically should be: (low + high) >>> 1\n compares += sort(array, low, middle);\n compares += sort(array, middle + 1, high);\n int end_low = middle;\n int start_high = middle + 1;\n while ((lo <= end_low) && (start_high <= high)) {\n compares += 3; // two in 'while' loop above, and one in 'if' below.\n if (array[low] < array[start_high]) {\n low++;\n } else {\n int Temp = array[start_high];\n compares++; // entry in to the for loop\n for (int k = start_high - 1; k >= low; k--) {\n array[k + 1] = array[k];\n compares++; // exit from the for loop\n }\n array[low] = Temp;\n low++;\n end_low++;\n start_high++;\n }\n }\n return compares;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T03:24:46.717",
"Id": "36103",
"ParentId": "27497",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T03:49:51.390",
"Id": "27497",
"Score": "1",
"Tags": [
"java",
"sorting",
"mergesort"
],
"Title": "Debug merge sort and validate comparison counters"
}
|
27497
|
<p>Is there a smarter way to do the following without the <code>$result</code> variable and without the if-statements?</p>
<pre><code> ...
$description = BIG ARRAY
$result = array('error' => '', 'amounts' => array(5, 10, 25, 50));
if (isset($description['error'])) $result['error'] = $description['error'];
if (isset($description['amounts'])) $result['amounts'] = $description['amounts'];
return $result;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T06:44:46.737",
"Id": "42792",
"Score": "1",
"body": "Can you explain a bit more what you're trying to do? $result has defaults that you're trying to overwrite with values from $description if they exist and are non-null? Are error and amounts the only fields?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:53:07.013",
"Id": "42798",
"Score": "0",
"body": "@Corbin: yes, exactly."
}
] |
[
{
"body": "<p>To see if an array has a specific index you should use <a href=\"http://php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow\"><code>array_key_exists</code></a> rather than <code>isset</code>.</p>\n\n<p>In case you want default values, how about just assigning all the defaults at the same time:</p>\n\n<pre><code>$foo = function_call();\n$result = array('error' => (array_key_exists('error', $description) ? $description['error'] : ''), ...);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:58:50.893",
"Id": "42799",
"Score": "0",
"body": "Thanks for the tip with the in_array. I thought thats internally the same as isset(). But the function_call() call does not work this way. Where do I put the in_array/isset check? It returned bool, not the element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:08:56.617",
"Id": "42802",
"Score": "0",
"body": "$a = false || 7; echo $a; gives me \"true\". I think, the boolean operators here are handled the wrong way. I use PHP 5.4.16"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:10:29.960",
"Id": "42803",
"Score": "0",
"body": "What do you mean by \"does not work this way\"? And the point of the code was to avoid the check completely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:11:26.433",
"Id": "42804",
"Score": "0",
"body": "Fixed [syntax](http://php.net/manual/en/language.operators.logical.php)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:21:05.703",
"Id": "42810",
"Score": "0",
"body": "You removed the boolean operator and now Its the same as above with a tenary operator :( I hoped there are a solution (like the |= in other languages) to avoid the if condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:24:56.247",
"Id": "42811",
"Score": "0",
"body": "Looks like there isn't, according to the link above. But this at least removes some duplication."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T09:59:24.630",
"Id": "42820",
"Score": "1",
"body": "`in_array` does not do what you think it does. You're thinking of `array_key_exists`. `in_array` searches for a value, not a key. Also, `array_key_exists` and `isset` are not equivalent. (`isset($arr[$key]) === array_key_exists($key, $arr) && $arr[$key] !== null`)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:35:02.900",
"Id": "27502",
"ParentId": "27501",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T06:21:24.693",
"Id": "27501",
"Score": "0",
"Tags": [
"php",
"array"
],
"Title": "Check for existence and assign"
}
|
27501
|
<p>I'm receiving a certain string value over the network and I need to call a function based on that value.</p>
<p>So this is more or less what I have at the moment:</p>
<pre><code>String methodName = soapObj.getMethodName();
switch(methodName) {
case "getTemperature":
getDeviceTemp();
break;
case "getBrightness":
getScreenBrightness();
break;
...
}
</code></pre>
<p>And.. there are about 60 to 70 methods supported like that.</p>
<p>What's the most elegant way of handling above situation without using reflection? (The app is moderately constrained performance-wise).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T22:47:18.070",
"Id": "43235",
"Score": "0",
"body": "Do you mind me asking for more details about your use case or the domain? Just curious to know more about the situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T01:28:58.997",
"Id": "43240",
"Score": "0",
"body": "@DavidJohnSmith Communication with a device known as Direct Digital Control that runs on embedded linux. (Building Management Solution, controlling lights, electricity, water valves etc)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:43:59.770",
"Id": "43282",
"Score": "0",
"body": "Why are you getting the device temperature, screen brightness, etc., but not returning it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-25T17:34:05.193",
"Id": "254573",
"Score": "0",
"body": "My impression is that SOAP is not a lightweight, high-performance protocol to begin with. Reflection might not be such a bad choice."
}
] |
[
{
"body": "<p>The easiest way is to create an interface for your function, for instance:</p>\n\n<pre><code>public interface ParameterGetter\n{\n int getValue()\n}\n</code></pre>\n\n<p>Then have a <code>Map<String, ParameterGetter></code> in which you would pair keys with implementations of <code>ParameterGetter</code>. If no entry exists, of course, the method call is wrong.</p>\n\n<p>While this is easy, however, it is not practical. Many frameworks, including light ones, include annotation systems which will do the job automatically for you -- you should try and find one, and use it.</p>\n\n<p>There is also another solution -- since this is JDK 7 you are using, you'll have it: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html\"><code>ServiceLoader</code></a>.</p>\n\n<p>It also requires that you implement an interface, but using this, you can load your method implementations easily. This is what I use in one of my projects, and it works quite well; the only trouble with it is you need to create a file in <code>META-INF/services</code>, but it's a trouble you only have to do once for each method you create; or if you use Maven, there is a plugin to generate it for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:08:01.013",
"Id": "42800",
"Score": "0",
"body": "Sounds like a good idea. Can you give me an example of a framework that does such job for me in Java?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:14:20.667",
"Id": "42805",
"Score": "0",
"body": "The \"lightest\" one I know of is [reflections](https://code.google.com/p/reflections), but I would be surprised if there didn't exist something even lighter. Using reflections require that you write some code to handle that... But as you seem to be doing SOAP (which I have never done), there probably exists much better solutions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:19:57.790",
"Id": "42807",
"Score": "0",
"body": "BTW, an example of such a standardized framework (but not SOAP dedicated) is JAX-RS, an implementation of which is Jersey"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:27:09.267",
"Id": "42813",
"Score": "0",
"body": "There is another solution too, see my edit"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:05:25.313",
"Id": "27504",
"ParentId": "27503",
"Score": "6"
}
},
{
"body": "<p>I would suggest to:</p>\n\n<ul>\n<li><p>Define an interface with a method that will be called inside every <code>case</code>, e.g.</p>\n\n<pre><code>public interface ServiceMethod {\n public void execute();\n}\n</code></pre></li>\n<li><p>Create a map that will contain contain instances of <code>ServiceMethod</code> findable by the a <code>String</code> key, e.g.:</p>\n\n<pre><code>Map<String, ServiceMethod> serviceMethodMap = new HashMap<>();\n</code></pre></li>\n<li><p>Fill up the <code>serviceMethodMap</code> map with <code>ServiceMethod</code> instances (this is to avoid the <code>switch</code>), e.g.:</p>\n\n<pre><code>serviceMethodMap.put(\"getTemperature\", new ServiceMethod() {\n public void execute() {\n getDeviceTemp();\n });\nserviceMethodMap.put(\"getBrightness\", new ServiceMethod() {\n public void execute() {\n getBrightness();\n }); \n</code></pre></li>\n<li><p>Finally replace the <code>switch</code> with:</p>\n\n<pre><code>final ServiceMethod serviceMethod = serviceMethodMap.get(methodName);\nif(serviceMethod != null) {\n serviceMethod.execute();\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>Update 2/18/2015, added Java 8 support</p>\n\n<ul>\n<li><p>Define an interface with a method that will be called inside every <code>case</code>, e.g.</p>\n\n<pre><code>@FunctionalInterface\npublic interface ServiceMethod {\n public void execute();\n}\n</code></pre></li>\n<li><p>Create a map that will contain contain instances of <code>ServiceMethod</code> findable by the a <code>String</code> key, e.g.:</p>\n\n<pre><code>Map<String, ServiceMethod> serviceMethodMap = new HashMap<>();\n</code></pre></li>\n<li><p>Fill up the <code>serviceMethodMap</code> map with <code>ServiceMethod</code> instances (this is to avoid the <code>switch</code>), e.g.:</p>\n\n<pre><code>serviceMethodMap.put(\"getTemperature\", () -> getDeviceTemp());\nserviceMethodMap.put(\"getBrightness\", () -> getBrightness());\n</code></pre></li>\n<li><p>Finally replace the <code>switch</code> with:</p>\n\n<pre><code>final ServiceMethod serviceMethod = serviceMethodMap.get(methodName);\nif(serviceMethod != null) {\n serviceMethod.execute();\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:20:51.467",
"Id": "42809",
"Score": "1",
"body": "Uh, there is `java.util.concurrent.Executor`... Naming your interface like a JDK-provided class is not a very good idea ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:24:57.120",
"Id": "42812",
"Score": "0",
"body": "@fge Good spot, renamed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T17:18:37.143",
"Id": "42853",
"Score": "0",
"body": "You can also use `Runnable`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T20:20:30.563",
"Id": "42860",
"Score": "1",
"body": "@tcb Yes, you are right, I have suggested a new interface to allow having a different return type then `void` and allowing to have arguments passed to the `execute` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T11:58:37.637",
"Id": "42912",
"Score": "0",
"body": "or use reflection?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T13:58:50.197",
"Id": "42918",
"Score": "0",
"body": "@user1737909 Yes, it is possible, however not recommended, because: 1) compile time rather runtime checks 2) worse performance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-18T06:30:38.333",
"Id": "147221",
"Score": "0",
"body": "Thank you so much for this answer, I've read many answers regarding passing a func as a param using reflection or invocation but this is clearest and most concise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-18T09:11:01.637",
"Id": "147241",
"Score": "0",
"body": "@Amalgovinus with Java 8 and lambdas it is even simpler, updated the answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T19:30:58.180",
"Id": "233346",
"Score": "0",
"body": "How do we pass parameters and set return type"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-01T23:05:34.793",
"Id": "243098",
"Score": "0",
"body": "just what I was looking for with java8, thanks a ton!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-05T12:08:50.353",
"Id": "268776",
"Score": "0",
"body": "I do not see what the advantage is of using this approach to the approach with the ugly `switch-case`, could you explain this further? Because this seems longer and more complex, altough different versions of this solution are mentioned everywhere when it comes to removing `switch-cases`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-05T13:53:57.370",
"Id": "268801",
"Score": "0",
"body": "@hamena314 you can look up \"open closed principle\""
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T08:19:22.300",
"Id": "27505",
"ParentId": "27503",
"Score": "18"
}
},
{
"body": "<p>Why don't you use <a href=\"http://docs.oracle.com/javase/tutorial/reflect/\" rel=\"nofollow\">reflection</a> (<strong>I know the drawbacks</strong>) but there is trade of, rename all your methods to exact same as the service would return String and execute the method with 2 lines of code.</p>\n\n<pre><code>Method m = Class.forName(MyClass.class.getName()).getDeclaredMethod(methodName);\nm.invoke(null);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T11:52:14.910",
"Id": "27546",
"ParentId": "27503",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27505",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T07:54:28.320",
"Id": "27503",
"Score": "8",
"Tags": [
"java",
"soap"
],
"Title": "Dispatching SOAP function calls"
}
|
27503
|
<p>All,
I barely have a week of angular behind me and I am still struggling with some of the concepts. Below is a piece of code I came up with. The idea is to let the user add/delete entries in a model (in practice, the model is read from a json and is more complex than what is presented). While this code seems to work, I'm wondering whether it's "proper" angular:</p>
<ul>
<li>Is it OK to leave the <code>add_item</code> function in the controller ? I understand that any DOM manipulation should be put in a directive, but it's only manipulating the model, right?</li>
<li>Shouldn't the <code>del_item</code> be in the controller too, then?</li>
<li>Using the index to control which item to delete look a bit dangerous, what would be a better alternative?</li>
</ul>
<p>Thanks for any input.</p>
<pre><code><html ng-app="main">
<head >
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<div ng-controller="BaseController">
{{items}}
<div>
<button type="button" ng-click="add_item()">
New item
</button>
</div>
<ul>
<li ng-repeat="i in items">
<display-item idx={{$index}}></display-item>
</li>
</ul>
</div>
<script>
angular.module("main", [])
.controller("BaseController",
function($scope){
$scope.items = [{key:1, a:'A'},{key:2, a:'B'},{key:3, a:'C'}];
$scope.last = $scope.items.length;
$scope.add_item = function() {
var item={key: $scope.last + 1, a:'?'};
$scope.items.push(item);
$scope.last += 1;
};
}
)
.directive('displayItem',
function() {
return {
restrict: 'E',
transclude: true,
scope: {idx: '@'},
template: '<strong>{{idx}}:</strong>'+
'{{$parent.items[idx].key}}={{$parent.items[idx].a}}'+
'<button ng-click="del_item(idx)">X</button>',
link: function(scope, element, attrs) {
scope.del_item=function(i){
scope.$parent.items.splice(i,1)}
}
}
}
);
</script>
</code></pre>
<p>
</p>
|
[] |
[
{
"body": "<ul>\n<li><p>Right, you're only manipulating the model, updating the model about a change (thus) updating it in the controller is perfectly fine, and it's what the controller does.</p></li>\n<li><p><code>del_item</code> should be in the controller too, you are correct. That's where it belongs.</p></li>\n<li><p>Using the index to deleting the item <em>is</em> dangerous, what I'd do is pass <code>this</code> as a function and then use an <code>indexOf</code> to locate the element you're deleting and delete that.</p></li>\n</ul>\n\n<p>If I may ask, why are your display items in a directive in the first place and not in the DOM? You could use an <code>ng-repeat</code> in the DOM to repeat the items instead and drop the directive altogether.</p>\n\n<p>Directives are useful for code reuse, are you reusing this spefici component in a lot of other places through out your code? Behaviors affecting your models and not just your presentation logic should probably not be in the directive to begin with (like <code>del_item</code> in your example), a directive should encompass presentational behavior and not business logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T14:36:56.577",
"Id": "43417",
"Score": "0",
"body": "Thanks a lot for the feedback. As I had mentioned, I'm still very new to Angular, but the concepts are slowly sinking in..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T08:15:56.463",
"Id": "27718",
"ParentId": "27506",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27718",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T10:58:21.253",
"Id": "27506",
"Score": "3",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Manipulating model elements in angular"
}
|
27506
|
<pre><code>class Connection
{
private string param1;
private string param2;
private static readonly ConcurrentDictionary<Tuple<string, string>, Connection>
connections = new ConcurrentDictionary<Tuple<string, string>, Connection>();
private Connection()
{
//Prevent instantiation
}
private Connection(string param1, string param2)
{
this.param1 = param1;
this.param2 = param2;
}
public static Connection getInstance(string param1, string param2)
{
Connection conn = activeConnections.GetOrAdd(new Tuple<string, string>
param1,param2), new Connection (param1, param2));
return conn;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:21:55.813",
"Id": "42826",
"Score": "0",
"body": "Are you saying that if two threads ask for a connection with the same parameters, they should get the same `Connection`? That means the actual code of `Connection` (the one that uses the parameters and that you didn't show) has to be thread-safe too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:25:40.330",
"Id": "42827",
"Score": "0",
"body": "Also, it's okay to create duplicate `Connection` objects as long as nobody ever sees them, right? (Because that's what you do.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T11:56:07.977",
"Id": "42911",
"Score": "0",
"body": "@svick \nOk so here is what I intended to do:\n1. If two threads ask for a connection with the same parameters, only one connection object has to be created & used by them.\n2. Never create two connection objects with the same parameters. If one exists, use it. Else create a new one.\nIs this what I am doing or not?\nIf this is a bad idea, do elaborate."
}
] |
[
{
"body": "<p>yes. But it's ugly. You won't remember what those parameters means when you come back in a couple of months and have to maintain the code.</p>\n\n<p>I really hate convenience classes like <code>Tuple</code> and <code>Action<T></code> (the latter is OK some times but is usually abused).</p>\n\n<p>It's much better to create small classes which actually describes what the values represent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T11:49:45.353",
"Id": "42822",
"Score": "0",
"body": "Ok so create a class called ParamDetails with the values and use that as the Key?\nKeys do not have to be primitive datatypes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T11:53:07.270",
"Id": "42823",
"Score": "0",
"body": "`Tuple` is not a primitive either. But you have to implement `GetHashCode()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:26:48.290",
"Id": "42828",
"Score": "0",
"body": "In this specific case, I disagree. I think `Tuple` as an implementation detail is okay, when it's clear from the surrounding code that `Item1` and `Item2` actually mean `param1` and `param2` (assuming those actually have meaningful names in real code)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T11:22:13.697",
"Id": "27508",
"ParentId": "27507",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>Never create two connection objects with the same parameters. If one exists, use it.</p>\n</blockquote>\n\n<p>If you really need to guarantee this, then I think you will need to use locking instead of <code>ConcurrentDictionary</code>.</p>\n\n<p>If it's okay to create duplicate <code>Connection</code>s (that will never be used) in rare circumstances, then you can use an overload of <code>GetOrAdd()</code> that takes a lambda that creates the <code>Connection</code>:</p>\n\n<pre><code>return activeConnections.GetOrAdd(\n Tuple.Create(param1,param2), _ => new Connection (param1, param2));\n</code></pre>\n\n<p>With your current code, every time you call <code>getInstance()</code>, a new <code>Connection</code> is created and then most of the time thrown away.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T13:42:31.893",
"Id": "42916",
"Score": "0",
"body": "Ok, I checked if that happens in a crude way, I used a class member - Guid which instantiated every time I created a class.\nWhen I created two objects with same params, the Guids were the same >> SO I assumed they were referencing the same (single) object.\nIf 2 objects are being created, then they must have different GUID right?\nCan you explain that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T13:59:18.720",
"Id": "42919",
"Score": "0",
"body": "@rtindru Two objects are being *created*, but both calls to `GetOrAdd()` will *return* the same object. Basically, call 2 creates new `Connection`, realizes the dictionary already contains one, so it throws the one it created away and returns the one from the dictionary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T05:20:47.273",
"Id": "42971",
"Score": "0",
"body": "Oh, that seems like a waste of time and effort. Are you sure about this?\nTHis is what the msdn website says: \nAdds a key/value pair to the `ConcurrentDictionary<TKey,Value>` if the key does not already exist.\n[link]http://msdn.microsoft.com/en-us/library/ee378676.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T06:47:40.617",
"Id": "42976",
"Score": "0",
"body": "@rtindru `ConcurrentDictionary` doesn't change how C# works. And method parameters are always evaluated before the method is invoked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T07:39:25.710",
"Id": "42979",
"Score": "0",
"body": "hmm... Alright, then what is the alternative that you suggest. Because clearly this is a vain effort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T08:19:58.430",
"Id": "42981",
"Score": "0",
"body": "@rtindru First, it may sound like a waste, but creating a small object for a very short time should have really negligible performance penalty. If you're okay with creating a duplicate in rare cases, use the delegate overload of `GetOrAdd()` I suggested. If you need to ensure there are no duplicates ever, use normal `Dictionary` and locking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T13:47:50.613",
"Id": "131632",
"Score": "0",
"body": "@svick shouldn't the 2nd argument be: `_ => new Connection (param1, param2)` instead? Actually, I am not sure if it should be `x => new Connection (x.Item1, x.Item2)` hence no closure is needed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T13:50:46.417",
"Id": "131633",
"Score": "0",
"body": "@svick And if possible, could you please elaborate a little more on your first \"locking\" version in http://stackoverflow.com/questions/27358761/how-to-improve-this-objects-dictionary-caching-lock-in-multi-thread please"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T13:52:18.273",
"Id": "131634",
"Score": "0",
"body": "@colinfang You're right, thanks, fixed. And avoiding that closure would make the code less readable, so I would use the more readable version by default."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T12:12:12.460",
"Id": "27548",
"ParentId": "27507",
"Score": "2"
}
},
{
"body": "<p>If you are on V4 or later, <code>Lazy<T></code> might help:</p>\n\n<pre><code>private static readonly ConcurrentDictionary<Tuple<string, string>, Lazy<Connection>> \n connections = new ConcurrentDictionary<Tuple<string, string>, Lazy<Connection>>();\n\npublic static Connection getInstance(string param1, string param2)\n{ \n var connLazy = activeConnections.GetOrAdd(\n Tuple.Create(param1,param2), \n new Lazy<Connection>(\n () => new Connection (param1, param2),\n LazyThreadSafetyMode.ExecutionAndPublication\n );\n return conn.Value;\n}\n</code></pre>\n\n<p><code>GetOrAdd</code> ensures that every threads will get same object, and extra <code>Lazy<Connection></code> will be discarded. <code>LazyThreadSafetyMode.ExecutionAndPublication</code> mode ensures that the instance will be initiated only once and no more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T17:47:30.227",
"Id": "72046",
"ParentId": "27507",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27548",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T11:14:17.047",
"Id": "27507",
"Score": "2",
"Tags": [
"c#",
"thread-safety",
"singleton"
],
"Title": "Is this code thread-safe - Singleton Implementation using Concurrent Dictionary"
}
|
27507
|
<p>This is my most recent login system I have been developing. It is working with Sessions. I want to know if I am doing well, if my code contains any serious exploits, and if my logic is correct.</p>
<p>This is the login class, handling everything related to users:</p>
<pre><code>/**
* UserHandler.class
*
* Handling login/logout and others
*
* @Author Jony <artemkller@gmail.com> <www.driptone.com>
**/
Class UserHandler
{
/**
* Properties
**/
protected $pdo;
private $query;
private $fetch;
private $delete;
private $update;
private $check;
private $insert;
private $get;
/**
* Constructor
*
* Creating MySQL connection using PDO
**/
public function __construct($pdo)
{
$this->pdo = $pdo;
}
/**
* Method login
*
* Logs the user in, securly.
*
* @param username The entered username
* @param password The entered password
* @param ip The computer's IP
**/
public function login($username, $password, $ip)
{
/* Checking if there are any attempts with that ip*/
$this->check = $this->pdo->prepare("SELECT * FROM login_attempts WHERE ip = :ip");
$this->check->execute(array("ip" => $ip));
/* Checking if there are any attempt histories with that ip */
$this->get = $this->pdo->prepare("SELECT * FROM login_attempts_history WHERE ip = :ip");
$this->get->execute(array("ip" => $ip));
/* Fetching from login_attempts */
$this->fetch = $this->check->fetch(PDO::FETCH_ASSOC);
/* Fetching from login_attempts_history */
$this->query = $this->get->fetch(PDO::FETCH_ASSOC);
// If history attempts is more than 20, block user for 1 day.
if ($this->query['attempts'] > 20)
{
$this->update = $this->pdo->prepare("UPDATE login_attempts_history SET blocked = 1 WHERE ip = :ip");
$this->update->execute(array("ip" => $ip));
}
// If not blocked, process..
if ($this->query['blocked'] != 1)
{
// If attempts is less than 6, continue login.
if ($this->fetch['attempts'] < 6)
{
// checking if details are correct.
$this->check = $this->pdo->prepare("SELECT * FROM users WHERE username = :user AND password = :pass");
$this->check->execute(array
(
":user" => $username,
":pass" => $password
));
//Details are correct, login user.
if ($this->check->rowCount())
{
$this->delete = $this->pdo->prepare("DELETE FROM login_attempts WHERE ip = :ip");
$this->delete->execute(array("ip" => $ip));
return true;
}
// Login failed, storing attempts.
else
{
// Checking if there are any attempts again.
$this->check = $this->pdo->prepare("SELECT * FROM login_attempts WHERE ip = :ip");
$this->check->execute(array("ip" => $ip));
// If attempts found, update attempts count.
if ($this->check->rowCount())
{
$this->update = $this->pdo->prepare("UPDATE login_attempts SET attempts = attempts + 1 WHERE ip = :ip");
$this->update->execute(array("ip" => $ip));
}
// No attempts found, create row.
else
{
$this->insert = $this->pdo->prepare
("
INSERT INTO login_attempts
(attempts, ip)
VALUES
('1', :ip)
");
$this->insert->execute(array
(
":ip" => $ip
));
}
// Checking if there are any histories again
$this->check = $this->pdo->prepare("SELECT * FROM login_attempts_history WHERE ip = :ip");
$this->check->execute(array("ip" => $ip));
// If yes, update row.
if ($this->check->rowCount())
{
$this->update = $this->pdo->prepare("UPDATE login_attempts_history SET attempts = attempts + 1 WHERE ip = :ip");
$this->update->execute(array("ip" => $ip));
}
else
{
// Not found, create row.
$this->insert = $this->pdo->prepare
("
INSERT INTO login_attempts_history
(attempts, ip, blocked)
VALUES
('1', :ip, 0)
");
$this->insert->execute(array
(
":ip" => $ip
));
}
// Details incorrect error.
throw new exception ("Details are incorrect!");
}
}
else
{
// Ran out of login attempts error
throw new exception ("You have ran out of login attempts, please wait 5 minutes.");
}
}
else
{
// Blocked from system error
throw new exception ("You have been blocked from our system for 1 day.");
}
//Clear limits.
$this->clearLimits();
//Clear history.
$this->clearLoginHistory();
}
/**
* Method clearLimits
*
* Clears all limits older than 5 minutes
**/
private function clearLimits()
{
$this->delete = $this->pdo->prepare("DELETE FROM login_attempts WHERE date < DATE_SUB(NOW(), INTERVAL 5 MINUTE) AND blocked != 1");
$this->delete->execute();
}
/**
* Method clearLoginHistory
*
* Clears all histories older than 1 day.
**/
private function clearLoginHistory()
{
$this->delete = $this->pdo->prepare("DELETE FROM login_attempts_history WHERE date < DATE_SUB(NOW(), INTERVAL 1 DAY)");
$this->delete->execute();
}
/**
* Method logOut
*
* Logs the user out.
*
* @param name The username.
**/
public function logOut($name)
{
//Checking if that user exists.
$this->check = $this->pdo->prepare("SELECT * FROM users WHERE username = :name");
$this->check->execute(array(":name" => $name));
//If yes, process.
if ($this->check->rowCount())
{
//Update last login date.
$this->update = $this->pdo->prepare("UPDATE users SET lastLogin = NOW() WHERE username = :name");
$this->update->execute(array(":name" => $name));
}
//Else throw error.
else
{
throw new excpetion ("An error has occurred!");
}
}
/**
* Method getLastLoginDate
*
* Gets the last login date.
*
* @param name The username.
**/
public function getLastLoginDate($name)
{
//Checking if user exists
$this->check = $this->pdo->prepare("SELECT * FROM users WHERE username = :name");
$this->check->execute(array(":name" => $name));
//If yes, process..
if ($this->check->rowCount())
{
$this->fetch = $this->check->fetch(PDO::FETCH_ASSOC);
return $this->fetch['lastLogin'];
}
else
{
// Else, throw error..
throw new exception ("An error has occurred!");
}
}
}
</code></pre>
<p>And this is login.php page that lets the user login:</p>
<pre><code><?php
/**
* Index.php
*
* Recovery System v2.0
*
* Password recovery for java games
* are made easy with this script!
*
* @Author Jony <artemkller@gmail.com> <www.driptone.com>
**/
session_start();
require("includes/db.inc.php");
include("includes/config.inc.php");
/* Creating our object */
$user = new UserHandler($pdo);
if (isset($_COOKIE['remember_me']))
{
$_SESSION['user'] = $_COOKIE['remember_me'];
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Recovery System</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<header>
<?php
if (!isset($_SESSION['user']))
{
?>
<div class="container">
<div class="voting_box">
<?php
if (isset($_POST['submit']) && isset($_POST['user']) && isset($_POST['pass']) && !empty($_POST['user']) && !empty ($_POST['pass']))
{
try
{
$user->login($_POST['user'], $_POST['pass'], $_SERVER['REMOTE_ADDR']);
$_SESSION['user'] = $_POST['user'];
if (isset($_POST['remember']))
{
setCookie('remember_me', $_POST['user'], time() + 604800000);
}
header ("location: index.php");
}
catch (exception $e)
{
echo '<div class="alert alert-error">'.$e->getMessage().'</div>';
}
}
else if (isset($_POST['submit']))
{
echo '<div class="alert alert-error">Your fields are empty!</div>';
}
?>
<form action="login.php" method="post" id="form">
Username:<br />
<input type="text" name="user" class="fieldd1" id="user"><br /><br />
Password:<br />
<input type="password" name="pass" class="fieldd1" id="pass"><br /><br />
Remember me?:<br />
<input type="checkbox" name="remember"><br /><br />
<input type="submit" name="submit" value="login" class="btnn">
</form>
</div>
</div>
<?php
}
else
{
header ("Location: index.php");
}
?>
</html>
</code></pre>
<p>Many people been telling me that I am using **exceptions for the wrong reason. I really find using sessions the best thing, and easiest to handle errors like password and username is incorrect, and more.</p>
<p>Is that fine to do? Are there any exploits in my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T12:20:01.913",
"Id": "42824",
"Score": "0",
"body": "Hi and welcome to Code Review! This question involves a *lot* of code and is very open ended, and as such is likely to be closed or go unanswered. I suggest you trim the code down to some specific snippets and ask about those in separate questions."
}
] |
[
{
"body": "<p>If I manually set a cookie in my browser with the name 'remember_me', then I am logged in because you are not doing any validation on the cookie to make sure it is a valid cookie and not a forged cookie. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T13:41:14.567",
"Id": "42832",
"Score": "0",
"body": "I see, any suggestions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T15:01:35.770",
"Id": "42834",
"Score": "0",
"body": "you do a good thing using PDO and prepared statements mistrusting everything that comes from the user. That part of the code should do.\n\nBut once the coockie is there, you trust that person. But a Coockie is just content send by the browser and is thus easily edited.\n\nyou should create a hash large enough that it is hard to guess and send that as coockie content. Then when the coockie is send, check wether the hash in the coocke is actually a valid hash. Then proceed.\n\nThe hash in the coockie acts as a replacement for the username/password combination."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T12:43:04.500",
"Id": "27513",
"ParentId": "27510",
"Score": "5"
}
},
{
"body": "<p>Couple of remarks:</p>\n\n<ul>\n<li>It looks like the \"Remember Me\" checkbox is always considered checked by your program. Use empty, not isset. See <a href=\"https://stackoverflow.com/questions/7066066/php-isset-not-working-with-checkbox\">this.</a></li>\n<li>If somebody notices that remember_me contains their username, they'll try changing it to log into another person's account. What you should do instead: Have two variables in $_SESSION \n\n<ol>\n<li><code>last_seen</code> The last <code>time()</code> that the user was seen.</li>\n<li><code>time_to_expire</code> Set at login based on the <code>remember</code> checkbox. If they check it, set it to 2 weeks. If they don't, set it to an hour.<br>\nIf <code>last_seen + time_to_expire < time()</code>, reject the login.</li>\n</ol></li>\n<li>Instead of writing two statements, use the <code>INSERT ... ON DUPLICATE KEY</code> syntax. <a href=\"https://stackoverflow.com/questions/12136711/update-if-exists-insert-if-not-exists-multiple-rows-in-single-query-in-php-mys/12137154#12137154\">https://stackoverflow.com/questions/12136711/update-if-exists-insert-if-not-exists-multiple-rows-in-single-query-in-php-mys/12137154#12137154</a></li>\n<li>Don't use a separate table to keep track of who's blocked. Just count how many attempts they have. Granted, this means that sometimes bans will be less than 24 hours, but that doesn't seem like it reduces your security.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T01:26:06.607",
"Id": "42893",
"Score": "0",
"body": "isset is fine. If a checkbox is not checked, it is not sent with the data (as per the HTML specifications -- http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3). Browsers typically destroy session cookies when they are closed, thus rendering your second point useless. Also, sessions don't stay alive for 2 weeks on the PHP side (unless you set the session keep alive period to be 2 weeks of course). INSERT ... ON DUPLICATE key is great for MySQL, but why couple yourself to MySQL unnecessarily?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T05:43:52.340",
"Id": "42901",
"Score": "0",
"body": "`isset is fine.` Huh, didn't know that. `Browsers typically destroy session cookies when they are closed` Besides Tor Browser Bundle, I can't think of any that are configured like that out of the box. `sessions don't stay alive for 2 weeks` True. Use session.gc_maxlifetime for more than one day. `why couple yourself to MySQL` To avoid repeating yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T06:02:30.353",
"Id": "42902",
"Score": "0",
"body": "`Browsers typically destroy session cookies when they are closed` Make a page: `<?php session_start(); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } echo ++$_SESSION['count'];`. Refresh it a few times. Close your browser and go back to it. Notice how it resets? http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T00:39:31.883",
"Id": "27533",
"ParentId": "27510",
"Score": "1"
}
},
{
"body": "<p>This review will be entirely focused on your <code>UserHandler</code> class.</p>\n\n<p>There's quite a lot to improve.</p>\n\n<p>Let's analize by method:</p>\n\n<p><strong>__construct()</strong></p>\n\n<p>Lets check the first victim:</p>\n\n<pre><code>public function __construct($pdo)\n</code></pre>\n\n<p>You don't need the <code>public</code> there, since all methods are <code>public</code> by default (since, at least, PHP5.3).</p>\n\n<p>You should use type hinting. This basically limits the received value to a certain type/class.</p>\n\n<p>This is how you should've done it:</p>\n\n<pre><code>function __construct(PDO $pdo)\n</code></pre>\n\n<hr>\n\n<p><strong>login()</strong></p>\n\n<ul>\n<li><p>You are using <code>$this->check</code> and <code>$this->get</code>.</p>\n\n<p>Since you are using them as local variables, please, <strong>remove them</strong>. They only slow down your code. Just create a local variable.</p></li>\n<li><p>Your whole model is quite sketchy...</p>\n\n<p>You have a table where you check login attempts and then you have <strong>another one</strong> to record attempts!</p>\n\n<p>Allow me to simplify your whole scheme:</p>\n\n<ul>\n<li>Create a table with the following fields:\n\n<ul>\n<li><code>ip</code> (<code>VARCHAR(15) PRIMARY KEY</code>)</li>\n<li><code>last_attempt</code> (<code>DATETIME</code>)</li>\n<li><code>last_failed_attempt</code> (<code>DATETIME</code>)</li>\n<li><code>fails</code> (<code>TINYINT(2)</code>)</li>\n</ul></li>\n<li>Everytime there is an attempt:\n\n<ul>\n<li>Fetch from the database the record for that IP</li>\n<li>Verify the number of failed attempts (<code>fails</code>)\n\n<ul>\n<li>If there's 6 fails, don't allow any logins for 5 minutes</li>\n<li>If there's 20 or more fails, wait 24 hours or until the next day</li>\n<li>Else, let it proceed</li>\n</ul></li>\n<li>Verify if the user exists\n\n<ul>\n<li>If it exists, clear the attempts (by setting the fields <code>fails</code> and <code>last_failed_attempt</code> to nothing)</li>\n<li>If it doesn't exist add or increment the <code>fails</code> fields</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>So much easier to reason and change!</p></li>\n<li><p>Why are you calling <code>clearLimits()</code> and <code>clearLoginHistory()</code> after you returned <code>true</code> after a successful authentication?</p></li>\n</ul>\n\n<hr>\n\n<p><strong>clearLimits() and clearLoginHistory()</strong></p>\n\n<p>Why do you use <code>$this->delete</code>? Again, create a local variable! <code>$stmt</code> is the 'default' name for query results, since it returns a <code>PDOStatement</code>.</p>\n\n<hr>\n\n<p><strong>logOut()</strong></p>\n\n<p>Oh, so, it requires that you run this function to store the last login date?</p>\n\n<p>What if I close my tab/browser and walk away, like how <strong>many</strong> users do since ever?</p>\n\n<p>This will be storing defective information.</p>\n\n<p>To combat this, you can create a field with the old value of the login, before you login. This way, the value will be always present. And that is the value you use to display.</p>\n\n<p>And please, <strong>use local variables</strong>!</p>\n\n<hr>\n\n<p><strong>getLastLoginDate()</strong></p>\n\n<p>Seriously, <strong>USE LOCAL VARIABLES</strong>!</p>\n\n<p>And why in the love of God are you fetching the information <strong>again</strong> from the database, when you could store it all in a session or similar?</p>\n\n<hr>\n\n<p><strong>General considerations:</strong></p>\n\n<ul>\n<li><p>Please, don't switch between single-quote and double-quote.</p>\n\n<p>Pick one and stick with it!</p>\n\n<p>My preference is single-quotes, since it doesn't need any expantion/interpolation of the variables within it, and doesn't have to interpret escape sequences (except <code>\\'</code>), which results in a <strong>VERY TINY</strong> speed improvement (less OP codes per string).</p></li>\n<li><p>Don't use multi-line comments for a single line.</p>\n\n<p>Really, just use single-line comments (<code>//</code>). To me, it is a little confusing.</p></li>\n<li><p>Some comments are completelly useless!</p>\n\n<p>Some examples:</p>\n\n<pre><code>// If not blocked, process..\nif ($this->query['blocked'] != 1)\n\n[...]\n\n/* Fetching from login_attempts */\n$this->fetch = $this->check->fetch(PDO::FETCH_ASSOC);\n/* Fetching from login_attempts_history */\n$this->query = $this->get->fetch(PDO::FETCH_ASSOC);\n</code></pre>\n\n<p>If the variable names were clear, and the whole process wasn't so obscure and over-complicated, you wouldn't need comments.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-27T23:59:38.093",
"Id": "105864",
"ParentId": "27510",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T12:06:42.533",
"Id": "27510",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"security",
"validation"
],
"Title": "Exploitable holes in login script"
}
|
27510
|
<p>I have a main form for adding and deleting records and a button that opens a child form that displays records from an access database. Child form will have buttons for moving though the rows like first, last, next, previous and search. When user selects a record the child form will close and the selected record will be displayed in the main form, from which it can be changed, deleted, etc. This is the logic behind what I’m doing. So far I have written a class for accessing the data and is called from the child form to display the records. Before I move on, I want to get advice on what I have done so far and if it follows best practices. Any advice would be greatly appreciated.</p>
<p>Main Form:</p>
<pre><code>namespace Test
{
public partial class frmTest : Form
{
public frmTest()
{
InitializeComponent();
}
public class myClass
{
private static OleDbConnection myConn = new OleDbConnection();
private static DataSet myDS;
private static DataRow myDR;
public static int MaxRows = 0;
public static int increment = 0;
public static string name;
public static void GetConnection()
{
myClass.myConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Testing\TestDatabase.accdb";
try
{
myConn.Open();
myDS = new DataSet();
string SQL = "SELECT * From Test";
OleDbDataAdapter myDA = new OleDbDataAdapter(SQL, myConn);
myDA.Fill(myDS, "People");
NavigateRecords();
MaxRows = myDS.Tables["People"].Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myConn.Close();
}
}
public static void NavigateRecords()
{
myDR = myDS.Tables["People"].Rows[increment];
name = myDR.ItemArray.GetValue(1).ToString();
}
}
private void frmNewForm_Click(object sender, EventArgs e)
{
frmNewForm fNew = new frmNewForm();
fNew.ShowDialog();
}
}
}
</code></pre>
<p>Child form:</p>
<pre><code>namespace Test
{
public partial class frmNewForm : Form
{
public frmNewForm()
{
InitializeComponent();
}
private void frmNewForm_Load(object sender, EventArgs e)
{
MyAlias.GetConnection();
txtName.Text = MyAlias.name;
}
private void FillTextBox()
{
txtName.Text = MyAlias.name;
}
private void btnNext_Click(object sender, EventArgs e)
{
if (MyAlias.increment != MyAlias.MaxRows - 1)
{
MyAlias.increment++;
MyAlias.NavigateRecords();
FillTextBox();
}
else
{
MessageBox.Show("No more rows");
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Learn about Data Binding</strong></p>\n\n<p><a href=\"http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial\" rel=\"nofollow noreferrer\">Here is one tutorial</a>. My main point is that with the Visual Studio designer linking back end data and the UI is pretty straight forward. And you can get navigation automagically; and along with \"master / detail\" synchronization it is so \"thank goodness I didn't have to write this.\"</p>\n\n<p><strong>Separate UI from Data Fetching</strong></p>\n\n<p>I would pass in a <code>MyClass</code> object to the <code>Form</code>. This <em>dependency injection</em> is generally superior to \"newing up\" objects internally; making the design far more flexible and <em>testable</em>. I.E. we can <em>inject</em> <a href=\"https://stackoverflow.com/questions/2665812/what-is-mocking\">mock (fake) stuff for the sake of testing</a>.</p>\n\n<p><strong>One Form</strong></p>\n\n<p>Once the data fetching is factored out of <code>frmTest</code> then it becomes clear that a second <code>Form</code> is not needed. However, if you want that child form look/feel/behavior, then the data binding above makes it easy peasy.</p>\n\n<p><strong>Code Convention for Data Fetching</strong></p>\n\n<ul>\n<li>Don't leave open / unused connections lying about</li>\n<li>Always wrap DB calls in try/catch. There's so much that can go wrong.</li>\n</ul>\n\n<p>Here is a generally accepted good way of writing the code, <a href=\"http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">taken right out of MSDN</a>.</p>\n\n<pre><code>public void GetPeopleData() {\n // I put these outside of \"using\" because they are class variables.\n myClass.myConn.ConnectionString = @\"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Temp\\Testing\\TestDatabase.accdb\"; \n myDS = new DataSet();\n\n // everything created in \"using\" gets destroyed/goes out of scope at end\n // of \"using\" block. And in particular \"myConn\" gets disposed / destroyed \n // at the end because it is the \"using\" parameter. We really want to make\n // sure all the resources - and in particular the OleDbConnection - go \n // away. \n using (OleDbConnection myConn= new OleDbConnection(connectionString))\n {\n string SQL = \"SELECT * From Test\";\n OleDbDataAdapter myDA = new OleDbDataAdapter(SQL, myConn);\n\n // Open the connection and execute the insert command.\n try\n {\n connection.Open();\n myDA.Fill(myDS, \"People\");\n NavigateRecords();\n MaxRows = myDS.Tables[\"People\"].Rows.Count;\n } catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n } //using\n\n // The connection is automatically closed when the\n // code exits the using block.\n} //GetPeopleData()\n</code></pre>\n\n<p><strong>Rename GetConnection()</strong></p>\n\n<p>This method gets the data. \"Getting the connection\" is merely a detail in that process.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Changed the general example to be specific to the question code.</p>\n\n<p>Renamed <code>GetConnection()</code> to <code>GetPeopleData()</code></p>\n\n<p><strong>Refactor GetPeopleData()</strong></p>\n\n<p><code>GetPeopleData()</code> should do that and only that. I do not understand <code>NavigateRecords()</code> in there. I should think navigating records is done in the child form ... or does <code>NavigateRecoreds()</code> even navigate the records?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:27:12.057",
"Id": "42845",
"Score": "0",
"body": "Thanks, I will definitely read up on Data Binding. \"I would pass in a MyClass object to the Form\", I thought that creating the myClass was giving the ability to pass the methods and properties to the forms? I'm not following you on that point. Also, are you saying to insert the bulk of my GetConnection under the Try after connection.Open() of the above example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T13:34:54.850",
"Id": "42915",
"Score": "0",
"body": "Your connection string and SQL query are hard coded in `frmTest` because `MyClass` is an inner class. What if you want a different SQL query? What if you want a different connection string? What if you want to unit test (always a very good idea) and need to pass in bogus stuff just for that test? Take `MyClass` out of `frmTest`. Have your main program instantiate a `MyClass` object and give it to a `frmTest` as you create that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T18:31:23.300",
"Id": "42932",
"Score": "0",
"body": "In your example, taken from MSDN, you use connectionString which isn't passign into the GetPeopleData method. In the MSDN example, the method takes in that parameter, but in mine I'm not passing it in. I'm setting it up inside the method itself. So, I'm not sure how to use the 'using' in this situation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:19:03.977",
"Id": "43020",
"Score": "0",
"body": "How `connectionString` gets set is not relevant to the big picture of `using`. The point is `using(<create connection object here>)`. The next salient point is that, inside `try`, that connection object is opened and the DB call/fill is done."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T15:26:05.450",
"Id": "27519",
"ParentId": "27512",
"Score": "1"
}
},
{
"body": "<p>Pull your MyClass out, and don't make it static. For the most part, you should avoid static variables and methods unless you really understand what you're doing.</p>\n\n<p>MyClass is trying to do 2 different things - data access and keeping state of the current row. I'd suggest splitting those responsibilities out, and making MyClass only responsible for filling the dataset and returning it. Currently, your navigation is simple enough that your child form can track the state without too much complexity, so I would move that there. If it becomes more complex, you may want to introduce a new class to handle it.</p>\n\n<p>Don't try to handle exceptions at the source unless you can recover from it automatically. Usually, you can't recover from it so it's best to let it go back to the form - the form can show a message box if it wants to.</p>\n\n<p>Pay attention to naming - even at this early stage. Naming is not just for readability, but it'll help you keep the concepts and responsibilities clear in your head as you design. MyClass is meaningless, and doesn't tell you anything about what that class does - you may as well name it Class1.</p>\n\n<p>You'll want to figure out how to get data from one form to another. Currently, it looks like you plan to use static variables for that - that's not a good idea. You should either use events, pass forms along or create a custom class to pass along to hold state. Passing the form along is simple and probably the easiest option to start with.</p>\n\n<p>At the end, you'll have something like:</p>\n\n<pre><code> class ParentForm {\n DataRow SelectedRow { get; Set; }\n\n void GetSelectedRow() { \n Var f = new ChildForm();\n F.ShowDialog();\n this.SelectedRow = f.SelectedRow;\n }\n }\n\n class DataAccess {\n Dataset GetAllPeople();\n }\n\n class ChildForm {\n int selectedRecordIndex;\n int maxRows;\n DataRow SelectedRow { get { return AllPeople.Rows[selectedRecordIndex]; } }\n Dataset allPeople;\n\n ChildForm_Load() {\n Var da = new DataAccess();\n try {\n this.allPeople = da.GetAllPeople();\n } catch (Exception ex) {\n MessageBox.Show(ex.Message);\n // nothing for this form to do anymore\n this. Close();\n }\n this.maxRows = this.allPeople.Rows.Count;\n this.selectedRecordIndex = 0;\n this.FillTextBox();\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T18:17:45.870",
"Id": "27562",
"ParentId": "27512",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27519",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T12:28:48.087",
"Id": "27512",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "Multiple forms for accessing records in database"
}
|
27512
|
<p>In my app development, I need to fetch data from backed, and it needs to implement it into an HTML page.</p>
<p>I've written the below code for this, but I think it's very lengthy. Can anyone give me suggestions on making this better?</p>
<p><strong>Function:</strong></p>
<pre><code>var JsonHandler = function(url) {
return $.getJSON(url)
};
(function ($) {
var manupulate = function(data){
var header = {}, locales = {}, userLocales = {};
$.each(data, function(key,val){
if(key === "name"){
header[key] = val;
}else if (key === "username"){
header[key] = val;
}else if (key === "allLocales"){
locales = val;
}else if (key === "userLocales"){
userLocales[key] = val;
}
})
var headerHtml = Handlebars.compile($("#header-template").html());
$("header").html(headerHtml(header));
var formHtml = Handlebars.compile($("#locale-template").html());
$("form").append(formHtml(locales));
$.each(userLocales["userLocales"], function(key,val){
$(":checkbox", "form").each(function(i,e){
if($(e).val() === val.name){
$(this).prop("checked", true);
}
})
})
var status = [];
var checkBox = $("form").find(":checkbox");
$(checkBox).each(function(i,el){
status.push($(el).prop("checked"));
$(el).click(function(){
var clickedIndex = checkBox.index($(this));
var prevStatus = status[clickedIndex];
if(prevStatus !== $(this).prop("checked")){
console.log("You made the change on " + $(this).val());
}
})
})
}
Handlebars.registerHelper("showHr", function(index_count,block) {
if(parseInt(index_count) % 20 === 0){
return block.fn(this)}
});
var path = "js/data.json";
new JsonHandler(path).done(function(data){
manupulate(data);
})
})(jQuery);
</code></pre>
<p><strong>JSON data:</strong></p>
<pre><code>{
"username": "lgangula",
"name": "Lavanya Gangula",
"allLocales": [{
"name": "Afrikaans"
}, {
"name": "Albanian"
}, {
"name": "Arabic"
}, {
"name": "Arabic (Argentina)"
}, {
"name": "Arabic (Bahrain)"
}, {
"name": "Arabic (Egypt)"
}, {
"name": "Arabic (Jordan)"
}, {
"name": "Arabic (Oman)"
}, {
"name": "Arabic (Qatar)"
}, {
"name": "Arabic (Saudi Arabia)"
}, {
"name": "Arabic (U.A.E.)"
}, {
"name": "Bengali"
}, {
"name": "Bulgarian"
}, {
"name": "Catalan"
}, {
"name": "Chinese"
}, {
"name": "Chinese (Hong Kong)"
}, {
"name": "Chinese (Macau)"
}, {
"name": "Chinese (Simplified)"
}, {
"name": "Chinese (Traditional)"
}, {
"name": "Croatian"
}, {
"name": "Czech"
}, {
"name": "Danish"
}, {
"name": "Dutch"
}, {
"name": "Dutch (Belgium)"
}, {
"name": "Dutch (Netherlands)"
}, {
"name": "English (Armenia)"
}, {
"name": "English (Australia)"
}, {
"name": "English (Bahrain)"
}, {
"name": "English (Botswana)"
}, {
"name": "English (Canada)"
}, {
"name": "English (Egypt)"
}, {
"name": "English (Guinea-Bissau)"
}, {
"name": "English (Hong Kong)"
}, {
"name": "English (India)"
}, {
"name": "English (Indonesia)"
}, {
"name": "English (Ireland)"
}, {
"name": "English (Israel)"
}, {
"name": "English (Jordan)"
}, {
"name": "English (Kenya)"
}, {
"name": "English (Kuwait)"
}, {
"name": "English (Latin America)"
}, {
"name": "English (Macau)"
}, {
"name": "English (Macedonia)"
}, {
"name": "English (Malaysia)"
}, {
"name": "English (Malta)"
}, {
"name": "English (Moldova)"
}, {
"name": "English (Montenegro)"
}, {
"name": "English (Mozambique)"
}, {
"name": "English (New Zealand)"
}, {
"name": "English (Nigeria)"
}, {
"name": "English (Oman)"
}, {
"name": "English (Other Asia)"
}, {
"name": "English (Philippines)"
}, {
"name": "English (Qatar)"
}, {
"name": "English (Saudi Arabia)"
}, {
"name": "English (Singapore)"
}, {
"name": "English (South Africa)"
}, {
"name": "English (Thailand)"
}, {
"name": "English (US)"
}, {
"name": "English (Uganda)"
}, {
"name": "English (United Arab Emirates)"
}, {
"name": "English (United Kingdom)"
}, {
"name": "English (Vietnam)"
}, {
"name": "Estonian"
}, {
"name": "Finnish"
}, {
"name": "French"
}, {
"name": "French (Africa)"
}, {
"name": "French (Belgium)"
}, {
"name": "French (Cameroon)"
}, {
"name": "French (Canada)"
}, {
"name": "French (Central African Republic)"
}, {
"name": "French (Cote d'Ivoire)"
}, {
"name": "French (Equatorial Guinea)"
}, {
"name": "French (France)"
}, {
"name": "French (Guinea)"
}, {
"name": "French (Luxembourg)"
}, {
"name": "French (Madagascar)"
}, {
"name": "French (Mali)"
}, {
"name": "French (Mauritius)"
}, {
"name": "French (Morocco)"
}, {
"name": "French (Niger)"
}, {
"name": "French (Senegal)"
}, {
"name": "French (Switzerland)"
}, {
"name": "French (Tunisia)"
}, {
"name": "German"
}, {
"name": "German (Austria)"
}, {
"name": "German (Germany)"
}, {
"name": "German (Liechtenstein)"
}, {
"name": "German (Luxembourg)"
}, {
"name": "German (Switzerland)"
}, {
"name": "Greek"
}, {
"name": "Greek (Cyprus)"
}, {
"name": "Hebrew"
}, {
"name": "Hindi"
}, {
"name": "Hungarian"
}, {
"name": "Icelandic"
}, {
"name": "Indonesian"
}, {
"name": "Italian"
}, {
"name": "Italian (Italy)"
}, {
"name": "Italian (Switzerland)"
}, {
"name": "Japanese"
}, {
"name": "Korean"
}, {
"name": "Latvian"
}, {
"name": "Lithuanian"
}, {
"name": "Macedonian"
}, {
"name": "Malay (Malaysia)"
}, {
"name": "Maltese"
}, {
"name": "Montenegrin"
}, {
"name": "Norwegian"
}, {
"name": "Pashto"
}, {
"name": "Polish"
}, {
"name": "Portuguese (Brazil)"
}, {
"name": "Portuguese (Portugal)"
}, {
"name": "Romanian"
}, {
"name": "Russian"
}, {
"name": "Serbian (Cyrillic)"
}, {
"name": "Serbian (Latin)"
}, {
"name": "Slovak"
}, {
"name": "Slovenian"
}, {
"name": "Spanish (Latin America)"
}, {
"name": "Spanish (Mexico)"
}, {
"name": "Spanish (Spain)"
}, {
"name": "Spanish (US)"
}, {
"name": "Swedish"
}, {
"name": "Tajik"
}, {
"name": "Thai"
}, {
"name": "Turkish"
}, {
"name": "Ukrainian"
}, {
"name": "Vietnamese"
}],
"userLocales": [{
"name": "English (US)"
}, {
"name": "Swedish"
}
],
"message": ""
}
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>IT White Admin</title>
<link rel="stylesheet" href="styles/reset.min.css">
<link rel="stylesheet" href="styles/admin.css">
</head>
<body>
<!-- wrapper starts -->
<section id="wrapper">
<header>
</header>
<!-- main contents goes here -->
<section>
<div class="locales">
<form>
<legend>Select Locales</legend>
</form>
</div>
</section>
<!-- end of main contents -->
</section>
<!-- wrapper ends -->
<script id="header-template" type="text/x-handlebars-template">
<span>Welcome {{name}}</span>
<div class="loginInfo"> <a href="#">{{username}}</a> | <a href="#">Logout</a> </div>
</script>
<script id="locale-template" type="text/x-handlebars-template">
{{#each this}}
{{#showHr @index}}
<hr/>
{{/showHr}}
<label><input value="{{name}}" type="checkbox" /> {{name}} </label>
{{/each}}
</script>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/handlebars.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
</body>
</html>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T14:59:35.040",
"Id": "27517",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"json",
"template"
],
"Title": "Data with Handlebars templating function"
}
|
27517
|
<p>I'm trying to find an elegant and secure way to track the currently reported site. I originally just used a cookie but realized this was not very secure. I have since switched to combine the session and the cookie. It still feels a bit clumsy. Am I missing something here as far as best practices? Can this be improved on?</p>
<pre><code>public static int SiteID
{
get
{
if (HttpContext.Current.Session[SITE_ID_KEY] == null)
{
if (Web.CookieUtil.CookieExists(SITE_ID_KEY))
{
Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
int siteId = Convert.ToInt32(Web.CookieUtil.GetCookieValue(SITE_ID_KEY));
if (Sites.ValidateSite(StateManager.AccountID.Value, siteId, userId))
{
HttpContext.Current.Session[SITE_ID_KEY] = siteId;
}
else
{
Web.CookieUtil.DeleteCookie(SITE_ID_KEY);
return -1;
}
}
else
{
return -1;
}
}
return (int)HttpContext.Current.Session[SITE_ID_KEY];
}
set
{
HttpContext.Current.Session[SITE_ID_KEY] = value;
Web.CookieUtil.CreateCookie(SITE_ID_KEY, value.ToString(), null);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:06:00.520",
"Id": "42836",
"Score": "0",
"body": "I don't understand, what does “currently reported site” mean? How are you going to use the value? How do you set it in the first place?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:06:47.617",
"Id": "42837",
"Score": "0",
"body": "Also, I don't think your question belongs here, since you're not actually asking for code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:12:58.170",
"Id": "42840",
"Score": "0",
"body": "I am asking for a code review. I have a working solution here and I'm asking for it to be critiqued. The title had to somewhat describe what I'm asking about or trying to accomplish."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:14:13.597",
"Id": "42841",
"Score": "0",
"body": "By current site I mean i need to track the current user's website that I am reporting on. I use a site id to track it. I didn't want the user trying to change the cookie and getting some else's data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:19:42.333",
"Id": "42843",
"Score": "0",
"body": "I'm still not sure I understand what you mean. Are you saying that each user has some websites, can select “current” website from among them and you want to track this selection? Keep in mind you didn't tell us anything about what your application does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:21:44.373",
"Id": "42844",
"Score": "0",
"body": "Yes, that is correct. The user can select from among their sites. That site id is what is used to look up their data in the database."
}
] |
[
{
"body": "<p>As you pointed out, relying on cookies means that the user can choose someone else's site. That means you should not use cookies at all, not even in addition to the session. If you choose to use cookies anyway, you have to validate that the current user actually has access to the selected site before returning any data (or even worse, before performing some action), which your code already does. You also have to be very careful that there isn't any code path that doesn't perform the validation.</p>\n\n<p>Because of this, I think you should store the data in session only. If you need more persistent storage, use your database, not cookies.</p>\n\n<hr>\n\n<p>Some points about your code:</p>\n\n<pre><code>return -1;\n</code></pre>\n\n<p>You shouldn't use “magic” values like -1 to indicate “no value”. Instead, change the return type to <code>int?</code> and return <code>null</code> of no site is selected.</p>\n\n<pre><code>Convert.ToInt32(…)\nvalue.ToString()\n</code></pre>\n\n<p>This may not work well unless you're 100 % sure that all servers running this code will be on the same culture. You should probably use <code>InvariantCulture</code> here.</p>\n\n<p>Also, if the cookie contains garbage, I think your code should return “no value” not throw an exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:51:43.840",
"Id": "42850",
"Score": "0",
"body": "Yeah I thought about switching it to nullable int when I saw it and need to do that I guess. I'll look into the culture thing. I was unaware of that. Not sure how I could eliminate the cookies altogether because the cookie is set from the main website before the app loads but I will give it some thought. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T16:40:13.217",
"Id": "27522",
"ParentId": "27520",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T15:31:46.970",
"Id": "27520",
"Score": "0",
"Tags": [
"c#",
"asp.net",
"session"
],
"Title": "Is this a good way to track current site being reported on?"
}
|
27520
|
<p>This is my code which implements Nd vectors. I chose valarray as a base of the class. Is this a good idea or I simply need to make a typedef std::valarray gvector instead of writing a class?
Please review this code.</p>
<pre><code>//gvector.h
#ifndef GVECTOR_H_
#define GVECTOR_H_
#include <cmath>
#include <fstream>
#include <iostream>
#include <valarray>
double sqr(const double &); //square
typedef std::valarray < double > coordinates;
std::ifstream & operator >> (std::ifstream &, coordinates &);
std::ostream & operator << (std::ostream &, const coordinates &);
class gvector;
std::ifstream & operator >> (std::ifstream &, gvector &);
std::ostream & operator << (std::ostream &, const gvector &);
class gvector {
friend std::ifstream & operator >> (std::ifstream &, gvector &);
friend std::ostream & operator << (std::ostream &, const gvector &);
coordinates crds;
public:
gvector(): crds() {};
gvector(const size_t & d): crds(d) {}; //set dimension
gvector(const coordinates & c): crds(c) {};
gvector(const gvector & v): crds(v.coords()) {};
//Initialize gvector by its start-point and end-point:
gvector(
const coordinates & start,
const coordinates & end
): crds(end - start) {};
size_t dim() const; //show dimension
coordinates coords() const; //show
double len() const; //show length
void set_dim(const size_t &);
void set_coords(const coordinates &);
void set_coords(const coordinates &, const coordinates &); //Change start-point and end-point of gvector
double & operator [] (const size_t &);
double const & operator [] (const size_t &) const;
//Opposite vector
gvector operator - () const;
gvector & operator = (const gvector &);
gvector & operator += (const gvector &);
gvector & operator -= (const gvector &);
gvector & operator *= (const double &);
};
inline size_t gvector::dim() const { return crds.size(); }
inline coordinates gvector::coords() const { return crds; }
inline double gvector::len() const {
return sqrt(crds.apply(sqr).sum());
}
inline void gvector::set_dim(const size_t & d) {
if (crds.size() != d) crds.resize(d);
}
inline void gvector::set_coords(const coordinates & c) {
size_t csz = c.size();
if (crds.size() != csz) crds.resize(csz);
crds = c;
}
inline void gvector::set_coords(const coordinates & start, const coordinates & end) {
size_t ssz = start.size(),
esz = end.size();
if (ssz == esz && ssz == crds.size()) crds = end - start;
}
inline double & gvector::operator [] (const size_t & idx) {
return crds[idx];
}
inline double const & gvector::operator [] (const size_t & idx) const {
return crds[idx];
}
inline gvector gvector::operator - () const { return gvector(-crds); }
inline gvector & gvector::operator = (const gvector & v) {
size_t vdim = v.dim();
if (crds.size() != vdim) crds.resize(vdim);
crds = v.coords();
return *this;
}
inline gvector & gvector::operator += (const gvector & v) {
if (crds.size() == v.dim()) crds += v.coords();
return *this;
}
inline gvector & gvector::operator -= (const gvector & v) {
if (crds.size() == v.dim()) crds -= v.coords();
return *this;
}
inline gvector & gvector::operator *= (const double & scalar) {
crds *= scalar;
return *this;
}
gvector operator + (gvector, const gvector &);
gvector operator - (gvector, const gvector &);
gvector operator * (gvector, const double &);
gvector operator * (const double &, gvector);
#endif /* GVECTOR_H_ */
</code></pre>
<p>//gvector.cpp</p>
<pre><code>#include "gvector.h"
#include <iostream>
#include <fstream>
double sqr(const double & x) { return x * x; }
std::ostream & operator << (std::ostream & os, const coordinates & c) {
if (c.size()) {
os << '(' << c[0];
for (size_t i = 1; i < c.size(); ++i) {
os << ", " << c[i];
}
os << ')';
}
return os;
}
std::ifstream & operator >> (std::ifstream & ifs, coordinates & c) {
for (size_t i = 0; i < c.size(); ++i) {
ifs >> c[i];
}
return ifs;
}
std::ostream & operator << (std::ostream & os, const gvector & v) {
os << v.crds;
return os;
}
std::ifstream & operator >> (std::ifstream & ifs, gvector & v) {
ifs >> v.crds;
return ifs;
}
gvector operator + (gvector lft, const gvector & rht) {
return lft += rht;
}
gvector operator - (gvector lft, const gvector & rht) {
return lft -= rht;
}
gvector operator * (gvector v, const double & scalar) {
return v *= scalar;
}
gvector operator * (const double & scalar, gvector v) {
return v *= scalar;
}
</code></pre>
|
[] |
[
{
"body": "<p><code>std::valarray</code> by itself only acts like a 1D array. The <code><valarray></code> <em>header</em> includes a few ancillary classes to do this though. More importantly, <code>valarray</code> itself includes direct support for those classes.</p>\n\n<p>For your purposes, the most important of these are probably <code>std::slice</code> and <code>std::gslice</code>. <code>std::slice</code> allows you to address a slice of the array and address it (about) like you'd index along a dimension of a multi-dimensional array.</p>\n\n<p>For example, let's assume we have an array of 28 items that we want to treat as a 2D array (with dimensions 4x7). While it's probably not entirely obvious from the standard<sup>1</sup> <code>std::slice</code> makes it <em>fairly</em> easy to do this. Let's say we want to walk across it, and look at one \"column\" of the 2D array at a time. So, we're going to create 7 columns (one at a time) each containing 4 items.</p>\n\n<p>Now, the trick to this: the slices you create this way act as objects in themselves. You <em>don't</em> get access to the individual elements in the slice; you get access to the slice as a whole. To assign one value to all the elements in the slice, you do <em>not</em> walk through the slice with a <code>for</code> loop and assign to each element individually. Rather, you assign to the entire slice at once (which will assign that value to all the elements in the slice).</p>\n\n<p>If you want to assign separate/unrelated values to the items in the slice, you can do that--but you need to use some other slice or valarray as the source. For example, let's create a valarray of 28 items, which we'll treat as a 2D array of 4x7 (4 rows of 7 columns each). For the sake of argument, we'll start with a valarray of 4 items holding 1, 2, 3, 4. We'll then assign that to the columns in the matrix. To keep things from getting too boring, we'll multiply that by the column number before assigning it, so the first row should count across by 1's, the second row by 2's, the third row by 3's and the fourth row by 4's.</p>\n\n<pre><code>std::valarray<int> data(rows * cols);\nstd::valarray<int> filler = { 1, 2, 3, 4 };\n\nfor (int i = 0; i < cols; i++)\n data[std::slice(i, rows, cols)] = filler * i;\n\n // show the data:\n for (int i = 1; i <= t.size(); i++) {\n std::cout << t[i-1] << \"\\t\";\n if (i % cols == 0)\n std::cout << \"\\n\";\n }\n</code></pre>\n\n<p>The result should look like this:</p>\n\n<pre><code>0 1 2 3 4 5 6\n0 2 4 6 8 10 12\n0 3 6 9 12 15 18\n0 4 8 12 16 20 24\n</code></pre>\n\n<p>As we can see, this fits the expected results, indicating that our <code>slice</code> has allowed us to address columns of the array, exactly as intended.</p>\n\n<p>So, the bottom line: no, you can't (quite) <em>just</em> use <code>std::valarray</code> to do N-dimensional array access--but you can do it with <code>valarray</code> + the other classes included in it header. As such, I'm not sure your <code>gvector</code> class really adds any capability that isn't already present.</p>\n\n<hr>\n\n<p><sup>\n1. Okay, almost nothing in the C++ standard is really obvious, but this is probably even harder to figure out than most things.\n</sup></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T05:48:27.657",
"Id": "45465",
"ParentId": "27527",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "45465",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T20:54:25.837",
"Id": "27527",
"Score": "7",
"Tags": [
"c++"
],
"Title": "Implementation of Nd vectors using valarray"
}
|
27527
|
<p>I've been getting help with this script seen below. It allows one input box to be used to put values into a text area and also display a list of the items. The items can be deleted once inserted:</p>
<p><a href="http://jsfiddle.net/ZTuDJ/50/" rel="nofollow">http://jsfiddle.net/ZTuDJ/50/</a></p>
<pre><code>// If JS enabled, disable main input
$("#responsibilities").prop('disabled', true);
// $("#responsibilities").addClass("hidden");
// If JS enabled then add fields
$("#resp").append('<input placeholder="Add responsibility" id="resp_input" ></input><input type="button" value="Add" id="add"> ');
// Add items to input field
var eachline='';
$("#add").click(function(){
var lines = $('#resp_input').val().split('\n');
var lines2 = $('#responsibilities').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += lines[i] + '\n';
}
}
$('#responsibilities').text($("<div>" + eachline + "</div>").text()).before("<li>"+$("<p>"+lines+"</p>").text()+"<span class='right'><a href='#'>Remove</a></span></li>");
$('#resp_input').val('');
});
$(document).on('click', '.right a', function(){
var el = $(this).closest('li')
var index = $('li').index(el);
var text = eachline.split('\n');
text.splice(index, 1);
eachline = text.join('\n')
$('#responsibilities').text(eachline)
el.remove()
})
</code></pre>
<p>I was wondering if it would be possible to tag links in the list with the following information:</p>
<pre><code><span refid="1">Remove</span>
</code></pre>
<p>By tagging the links in this way I was thinking I could easily point to them with jquery if I wanted to delete it or later edit it.</p>
<p>Is there room to simplify this script in this way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:21:38.163",
"Id": "42866",
"Score": "0",
"body": "May I suggest a solution that uses another library in place of jQuery, or just adds another library? There are very good tools that make this very easy to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:22:49.800",
"Id": "42867",
"Score": "0",
"body": "I really don't want to use any other frameworks other than jQuery I'm afraid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:23:08.293",
"Id": "42869",
"Score": "0",
"body": "What about dropping the jQuery dependency?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:23:26.117",
"Id": "42870",
"Score": "0",
"body": "Straight javascript?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:27:41.027",
"Id": "42872",
"Score": "0",
"body": "Yes. This is what I mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:28:48.400",
"Id": "42873",
"Score": "0",
"body": "If it would make the code more efficient then im all ears. I think my current code is quite bloated and hacky"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:32:14.473",
"Id": "42874",
"Score": "1",
"body": "Yes, it's _very_ hacky :) I'm working on something"
}
] |
[
{
"body": "<p>What's good here:</p>\n\n<ul>\n<li>It's fairly simple</li>\n<li>Using <code>prop</code> over <code>attr</code></li>\n</ul>\n\n<p>What I did not like</p>\n\n<ul>\n<li><strong>Using HTML strings</strong> in code makes code <em>very</em> hard to modify later on. It's hard to debug and might cause potential issues (like making XSS easy for example).</li>\n<li><strong>No separation of concerns.</strong> You're treating your HTML like your source of knowledge instead of backing up your data with a model in the background. This is <em>very</em> harmful and I personally consider it a big design flaw. Your business logic (in this case the list items) and your presentational layer (the DOM nodes) is the same here. Every time you want to operate on the list you have to query the DOM. This is not only slow, but it becomes <em>very</em> nasty <em>very</em> fast as your code logic begins to expand.</li>\n</ul>\n\n<p>There are frameworks like KnockoutJS that do data binding making this trivial to accomplish in just a few lines of code. However since you wanted a solution that has no 'magic' (Which I totally appreciate by the way) let's see what would be a simple JavaScript solution would look like.</p>\n\n<p>Short note, I'm doing JavaScript with function constructors here since a lot of people find it easier, personally I'd use object initializers.</p>\n\n<p><a href=\"http://jsfiddle.net/x5M7q/\" rel=\"nofollow\">Here is a working fiddle</a></p>\n\n<p>First, we'll have a data model for a responsibility.</p>\n\n<pre><code>//This is our element in the view model.\nfunction Responsibility(text){\n this.text=text;\n}\n</code></pre>\n\n<p>Next, we'll need to store all our responsibilities. We'll use an array:</p>\n\n<pre><code>// a list of our responsibilities, an actual view model to back our data\nvar responsibilities = []; \n</code></pre>\n\n<p>Now, we'll want a <code>render</code> function, that'll take our elements, and turn them into actual DOM objects. We'll spit it into two. First, we'll render the list item:</p>\n\n<pre><code>function renderResponsibility(rep,deleteClick){\n var el = document.createElement(\"li\");\n var rem = document.createElement(\"a\");\n rem.textContent = \" Remove\";\n rem.onclick = deleteClick;\n var cont = document.createElement(\"span\");\n cont.textContent = rep.text;\n el.appendChild(cont);\n el.appendChild(rem);\n return el;\n}\n</code></pre>\n\n<p>On <code>renderResponsibility</code> another alternative would be to use a templating engine, but you said no extra libraries so I'm keeping my word :)</p>\n\n<p>Now, our general <code>render</code>:</p>\n\n<pre><code>//render our actual elements\nfunction render(){\n respList.innerHTML = \"\";\n // note, foreach needs a modern browser but can easily be shimmed\n responsibilities.forEach(function(responsibility,i){\n var el = renderResponsibility(responsibility,function(){\n responsibilities.splice(i,1);//remove the element\n render();//re-render\n });\n respList.appendChild(el);\n });\n //update the text area;\n respTextArea.textContent = responsibilities.map(function(elem){\n return elem.text;//get the text. \n }).join(\"\\n\");\n}\n</code></pre>\n\n<p>Finally, let's add the functionality to the <code>Add</code> button:</p>\n\n<pre><code>//events \naddButton.onclick = function(e){\n var text = newResp.value;\n var resp = new Responsibility(text);\n responsibilities.push(resp);\n render();\n newResp.value = \"\";\n}\n</code></pre>\n\n<p>And we're done :)</p>\n\n<p>Just to tease:</p>\n\n<ul>\n<li><a href=\"http://jsfiddle.net/sGjq8/\" rel=\"nofollow\">Here is a solution in KnockoutJS</a></li>\n<li><a href=\"http://jsfiddle.net/AwvAK/\" rel=\"nofollow\">Here is a shorter solution in KnockoutJS</a> without using an object for responsibility</li>\n<li><a href=\"http://jsfiddle.net/HFF7p/\" rel=\"nofollow\">Here is a solution in AngularJS</a></li>\n</ul>\n\n<p>Also <a href=\"http://jsfiddle.net/dhhJS/\" rel=\"nofollow\">here is a more 'jQuery'</a> version of the vanilla solution. As you can see a DOM manipulation library isn't very useful when building an application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:02:21.380",
"Id": "42876",
"Score": "0",
"body": "Thank you Benjamin, that was extremely informative. I will read through this and make sure I understand each line. Thank you again for your help, I really appreciate it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:07:48.413",
"Id": "42877",
"Score": "1",
"body": "@JamesWillson I'm glad I could help, if you'd like to discuss this further (I really can not express how important separation of concerns is) you're welcome to the [javascript chat](http://chat.stackoverflow.com/rooms/17/javascript) in SO, it's how I got to this question in the first place.\nHere is the KnockoutJS solution, http://jsfiddle.net/sGjq8/ I think it's _much_ cleaner and much nicer than the alternatives. Frameworks like KnockoutJS, EmberJS and AngularJS are much better suited at building web applications than libraries like jQuery."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:43:29.727",
"Id": "42883",
"Score": "0",
"body": "Can you please tell me your aversion to using jQuery please? I am forced to have jquery on my site due to google maps and certain other services so I'd like to keep everything in jquery but not at the expense of making the code horrible..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:54:32.733",
"Id": "42885",
"Score": "1",
"body": "I have no problem with jQuery itself (did I say that?). I use jQuery myself a lot, especially for legacy browser support and animations. Query selectors are practically useless (you created the elements, why would you ask for them? You own them). Creating elements with text seems counter productive. Working with the DOM api is usually a lot cleaner than doing string appends in jQuery. Basically in your use case it offers no real advantage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:57:47.367",
"Id": "42886",
"Score": "0",
"body": "Ok, I didn't mean to put words in your mouth, but it did sound like you didnt think jquery was the ticket, and I am just trying to understand why. I'd be really interested to see how the jquery version compared it something like the knockoutjs solution. I'll be doing some more reading on all of this thanks to you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T23:14:15.583",
"Id": "42888",
"Score": "0",
"body": "@JamesWillson This is a more jQuery solution. It's basically like the vanilla one, I used whatever jQuery gave me in the scenario but a DOM manipulation library's worth isn't very high when building an application. http://jsfiddle.net/dhhJS/"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:50:33.947",
"Id": "27530",
"ParentId": "27528",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27530",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:17:32.503",
"Id": "27528",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Jquery improvement of this script - Adding and removing items from list"
}
|
27528
|
<p>I'm trying to develop my own math library to use on a Voxel engine, but I'm worried about Matrices multiplication. Everywhere I saw people using 4x4 Matrices on a 2D Float Array but I'm using a 1D Float Array because of performance needs.</p>
<pre><code> public float[] multiplicate(float[] factor){
float[] result = new float[factor.length];
for (int i = 0, a = 0, b = 0; i < factor.length; i++){
a = (i/4)*4;
b = (i%4);
result[i] = (mat4f[a] * factor[b]) + (mat4f[a+1] * factor[b+4]) + (mat4f[a+2] * factor[b+8]) + (mat4f[a+3] * factor[b+12]);
}
return result;
}
</code></pre>
<p><strong>EDIT:</strong> I'm using a 1D array to store the 4x4 Vector. If I use 16 <code>float</code> variables instead, should I gain in performance or memory usage? The code should be like that:</p>
<pre><code> r00 = a00*b00+a01*b10+a02*b20+a03*b30;
r01 = a00*b01+a01*b11+a02*b21+a03*b31;
r02 = a00*b02+a01*b12+a02*b22+a03*b32;
r03 = a00*b03+a01*b13+a02*b23+a03*b33;
r10 = a10*b00+a11*b10+a12*b20+a13*b30;
r11 = a10*b01+a11*b11+a12*b21+a13*b31;
r12 = a10*b02+a11*b12+a12*b22+a13*b32;
r13 = a10*b03+a11*b13+a12*b23+a13*b33;
r20 = a20*b00+a21*b10+a22*b20+a23*b30;
r21 = a20*b01+a21*b11+a22*b21+a23*b31;
r22 = a20*b02+a21*b12+a22*b22+a23*b32;
r23 = a20*b03+a21*b13+a22*b23+a23*b33;
r30 = a30*b00+a31*b10+a32*b20+a33*b30;
r31 = a30*b01+a31*b11+a32*b21+a33*b31;
r32 = a30*b02+a31*b12+a32*b22+a33*b32;
r33 = a30*b03+a31*b13+a32*b23+a33*b33;
</code></pre>
<p>Where r00~r33 are 16 float variables where I store the result and later set to my 16 float main fields...The variables a00~a33 and b00~b33 are the factors variables.</p>
<p>So if I use fixed fields instead of a float array, should I gain in performance or memory usage? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:10:21.223",
"Id": "42879",
"Score": "0",
"body": "in the init part of your loop: `a= 0, b=0` is superfluous since you assign values right at the beginning of the loop body"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:40:35.417",
"Id": "42881",
"Score": "0",
"body": "This is the same as if I declared the variables int a, b; before the loop...no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T01:45:42.283",
"Id": "42894",
"Score": "0",
"body": "@AfonsoLage but it makes it harder to read your for loop. We get the idea that a and b affect the loop some how, but instead they are just local variables. There by making it harder to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T01:48:12.370",
"Id": "42895",
"Score": "0",
"body": "To answer your question about performance gains you could use a simple test to time how long it takes to do your multiplication. You'd want to have it perform the task a few thousand times to check for performance. In terms of memory though there is no difference (usually) since it will allocate the same amount of memory if it was a 1d array or a 16d array. In the end it is how many elements you have."
}
] |
[
{
"body": "<p>My final code is:</p>\n\n<pre><code>public float[] multiplicate(float[] factor){\n int a = 0;\n int b = 0;\n float[] result = new float[factor.length];\n for (int i = 0; i < factor.length; i++){\n a = (i/4)*4;\n b = (i%4);\n result[i] = (mat4f[a] * factor[b]) + (mat4f[a+1] * factor[b+4]) + (mat4f[a+2] * factor[b+8]) + (mat4f[a+3] * factor[b+12]);\n }\n return result;\n}\n</code></pre>\n\n<p>I'll keeping using 1D float array because I'll need to use a <code>FloatBuffer</code> to send it to OpenGL (using LWJGL). So i'll get less overhead by calling one <code>FloatBuffer.put(myArrFloatVar)</code> then <code>FloatBuffer.put(new float[]{r00, r01...r33}</code> or event calling F<code>loatBuffer.put(r00)</code> 16 times.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T15:02:33.133",
"Id": "27550",
"ParentId": "27529",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27550",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T21:48:28.680",
"Id": "27529",
"Score": "1",
"Tags": [
"java",
"performance",
"mathematics",
"matrix",
"floating-point"
],
"Title": "Is my 4x4 matrix multiplication on a 1D float array correct?"
}
|
27529
|
<p>I've never put together a plugin before but I thought this would be useful to push technology forward. It's basically a browser sniffer, but if the user has a modern browser it will reward them for keeping it up to date.</p>
<p>Unfortunately, the code is a little heavier than I expected (6kb minified).</p>
<p>I just wondered if anyone could give some advice on how to make it more clean and compressed.</p>
<pre><code>function abiejs(d) {
"use strict";
/*
abiejs.d === defaults
abiejs.b === document body
abiejs.c === abie container
abiejs.e === abie experience
*/
abiejs.d = (function() {
var def = d;
if(!def.position){def.position = 'tr';}
if(!def.merit){def.merit = 'http://browsehappy.com/';}
if(!def.demerit){def.demerit = 'http://browsehappy.com/';}
if(!def.showTime){def.showTime = 5000;}
if(!def.content){def.content = '';}
if(!def.meritColor){def.meritColor = 'green';}
if(!def.demeritColor){def.demeritColor = 'red';}
if(def.cookie){def.cookie = true;} else {def.cookie = false;}
if(!def.cookieShowLimit){def.cookieShowLimit = 'none';}
if(!def.cookieExperiation){def.cookieExperiation = 10000;}
if(def.flag){def.flag = true;} else {def.flag = false;}
return def;
})(d);
navigator.sayswho = (function() {
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M &&(tem= ua.match(/version\/([\.\d]+)/i)) !== null){M[2] = tem[1];}
M= M? [M[1], M[2]]: [N, navigator.appVersion, '-?'];
return M;
})();
/*
* navigator.sayswho[0] === browser name
* navigator.sayswho[1] === browser version
*/
function createAbie(p) {
//Get position and set it to lowercase characters
var pos = p.toLowerCase();
//Create the abie container div
abiejs.c = document.createElement('div');
//Decalre id
abiejs.c.id = 'abie';
//Declare position
abiejs.c.style.position = 'fixed';
//Declare display
abiejs.c.style.display = 'block';
//Set element in document
document.getElementsByTagName('body')[0].appendChild(abiejs.c);
//Create Abie Experience Element (This will animate)
abiejs.e = document.createElement('div');
//Declare id
abiejs.e.id = 'abieExp';
//Declare position
abiejs.e.style.position = 'absolute';
abiejs.e.style.cursor = 'pointer';
//Set the merit here (this will need to be a condition) !!!!!!!!!!!
abiejs.e.innerHTML = abiejs.d.content;
//Append element to container
abiejs.c.appendChild(abiejs.e);
//Define the height and width of the merit property
abiejs.e.height = abiejs.d.height || abiejs.e.offsetHeight;
abiejs.e.width = abiejs.d.width || abiejs.e.offsetWidth;
//Set the height and width values
abiejs.c.style.height = abiejs.e.height + 'px';
abiejs.c.style.width = abiejs.e.width + 'px';
abiejs.e.style.height = abiejs.e.height + 'px';
abiejs.e.style.width = abiejs.e.width + 'px';
//Run condition to ensure where abie should be
if(pos.indexOf('t') !== -1){
abiejs.c.style.top = '0';
abiejs.e.style.top = (abiejs.e.height * -1) + 'px';
} else if(pos.indexOf('b') !== -1) {
abiejs.c.style.bottom = '0';
abiejs.e.style.bottom = (abiejs.e.height * -1) + 'px';
} else {
abiejs.c.style.top = '0';
abiejs.e.style.top = (abiejs.e.height * -1) + 'px';
}
if(pos.indexOf('r') !== -1) {
abiejs.c.style.right = '0';
abiejs.e.style.right = '0';
abiejs.e.style.textAlign = 'right';
} else if(pos.indexOf('l') !== -1){
abiejs.c.style.left = '0';
abiejs.e.style.left = '0';
abiejs.e.style.textAlign = 'left';
} else {
abiejs.c.style.right = '0';
abiejs.e.style.textAlign = 'right';
}
abiejs.e.style.background = ((judgeAbie() === true) ? abiejs.d.meritColor : abiejs.d.demeritColor);
}
//Create Cookie
function createCookie(name,value,days) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
//Read Cookie
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {c = c.substring(1,c.length);}
if (c.indexOf(nameEQ) == 0) {return c.substring(nameEQ.length,c.length);}
}
return null;
}
//Erase Cookie
function eraseCookie(name) {
createCookie(name,"",-1);
}
//Set property for first loop so danceInAbie.inc can be set
danceInAbie.firstStep = false;
function danceInAbie(pos, h) {
if(bindAbie.first === true) {return false;}
//Check if it is first iteration
if(danceInAbie.firstStep === false) {
//Update property so danceInAbie.inc isn't updated over and over again
danceInAbie.firstStep = true;
//Set danceInAbie.inc to the height of element so it starts animating from current position
danceInAbie.inc = (h * -1);
}
//If abie's height is less than -1 increment the value
if(danceInAbie.inc < -1) {
setTimeout(function(){
if(pos === 't') {
abiejs.e.style.top = danceInAbie.inc + 'px';
} else {
abiejs.e.style.bottom = danceInAbie.inc + 'px';
}
danceInAbie.inc++;
//danceInAbie.inc = danceInAbie.inc + 2;
danceInAbie(pos, h);
}, 20);
return true;
} else {
danceOutAbie.firstStep = false;
return true;
}
}
danceOutAbie.firstStep = false;
function danceOutAbie(pos, h) {
if(bindAbie.first === true) {return false;}
//Check if it is first iteration
if(danceOutAbie.firstStep === false) {
//Update property so danceInAbie.inc isn't updated over and over again
danceOutAbie.firstStep = true;
//Set danceInAbie.dec to the height of element so it starts animating from current position
danceOutAbie.dec = 0;
}
//If abie's height is less than 0 increment the value
if(danceOutAbie.dec < h) {
setTimeout(function(){
if(pos === 't') {
abiejs.e.style.top = '-' + danceOutAbie.dec + 'px';
} else {
abiejs.e.style.bottom = '-' + danceOutAbie.dec + 'px';
}
danceOutAbie.dec++;
//danceOutAbie.dec = danceOutAbie.dec + 2;
danceOutAbie(pos, h);
}, 10);
} else {
danceInAbie.firstStep = false;
return true;
}
}
//Add Events
function addEvent(elem, event, fn) {
// avoid memory overhead of new anonymous functions for every event handler that's installed
// by using local functions
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// set the this pointer same as addEventListener when fn is called
// and make sure the event is passed to the fn also so that works the same too
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
function judgeAbie() {
var v = parseInt(navigator.sayswho[1], 10);
if(navigator.sayswho[0] === 'Chrome'){
if(v < 27) {
return false;
} else {
return true;
}
} else if(navigator.sayswho[0] === 'Firefox') {
if(v < 21) {
return false;
} else {
return true;
}
} else if(navigator.sayswho[0] === 'MSIE') {
if(v < 9) {
return false;
} else {
return true;
}
} else if(navigator.sayswho[0] === 'Safari') {
if(v < 6) {
return false;
} else {
return true;
}
} else if(navigator.sayswho[0] === 'Opera') {
if(v < 12) {
return false;
} else {
return true;
}
} else {
//I don't know what you have
return false;
}
}
//Merit or Demerit
function meriter() {window.location = abiejs.d.mer;}
function demeriter() {window.location = abiejs.d.dmer;}
function abieMeritDemerit() {
//Get abies judgement
abieMeritDemerit.judgement = judgeAbie();
//Decide to merit or demerit
if(abieMeritDemerit.judgement === true) {
//If string send user to page
if(typeof abiejs.d.merit === 'string') {
return meriter();
//Else try to run as function
} else {
return abiejs.d.merit();
}
} else if(abieMeritDemerit.judgement === false) {
//If string send user to page
if(typeof abiejs.d.demerit === 'string') {
return demeriter();
//Else try to run as function
} else {
return abiejs.d.demerit();
}
} else {
return abiejs.d.dmer();
}
}
function abieRun(pos) {
abieRun.cookie = readCookie('abiejs');
if(abieRun.cookie < abiejs.d.cookieShowLimit || abiejs.d.cookie === false) {
if(pos.indexOf('t') !== -1) {
//If danceInAbie is complete and returns true then run danceOutAbie
danceInAbie('t', abiejs.e.height);
setTimeout(function() {danceOutAbie('t', abiejs.e.height);}, abiejs.d.showTime);
} else {
//If danceOutAbie is complete and returns true then run danceInAbie
danceInAbie('b', abiejs.e.height);
setTimeout(function() {danceOutAbie('b', abiejs.e.height);}, abiejs.d.showTime);
}
}
}
//bind mouseover and onclick events
//Check if mouse is already over element
bindAbie.first = false;
function bindAbie(pos) {
addEvent(abiejs.c, 'mouseover', function() {
bindAbie.first = true;
if(pos.indexOf('t') !== -1) {
abiejs.e.style.top = 0;
} else {
abiejs.e.style.bottom = 0;
}
});
addEvent(abiejs.c, 'mouseout', function() {
bindAbie.first = true;
if(pos.indexOf('t') !== -1) {
abiejs.e.style.top = '-' + abiejs.e.height + 'px';
} else {
abiejs.e.style.bottom = '-' + abiejs.e.height + 'px';
}
});
addEvent(abiejs.e, 'click', function() {
abieMeritDemerit();
});
}
function abiesFlag(pos) {
if(abiejs.d.flag === true) {
if(pos.indexOf('t') !== -1) {
if(pos.indexOf('r') !== -1) {
abiejs.e.style.WebkitBorderRadius = '0 0 0 100%';
abiejs.e.style.MozBorderRadius = '0 0 0 100%';
abiejs.e.style.borderRadius = '0 0 0 100%';
} else {
abiejs.e.style.WebkitBorderRadius = '0 0 100% 0';
abiejs.e.style.MozBorderRadius = '0 0 100% 0';
abiejs.e.style.borderRadius = '0 0 100% 0';
}
} else {
if(pos.indexOf('r') !== -1) {
abiejs.e.style.WebkitBorderRadius = '100% 0 0 0';
abiejs.e.style.MozBorderRadius = '100% 0 0 0';
abiejs.e.style.borderRadius = '100% 0 0 0';
} else {
abiejs.e.style.WebkitBorderRadius = '0 100% 0 0';
abiejs.e.style.MozBorderRadius = '0 100% 0 0';
abiejs.e.style.borderRadius = '0 100% 0 0';
}
}
}
}
//Make Cookie
function abieMakeCookies() {
//Check if user wants cookie
if(abiejs.d.cookie === true) {
var cookieVal = readCookie('abiejs');
//Create Cookie Expiration
abieMakeCookies.expry = (abiejs.d.cookieExperiation === 'none' ? 1000 : abiejs.d.cookieExperiation);
//Check if no cookie exists yet
if(cookieVal === null) {
//If there is no cookie then create the first iteration
createCookie('abiejs',0,abieMakeCookies.expry);
//If there is a cookie begin incrementing iteration
} else {
//If the cookie has no limit then set it a huge number
if(abiejs.d.cookieShowLimit === 'none') {
createCookie('abiejs',0,abieMakeCookies.expry);
} else {
cookieVal++;
createCookie('abiejs',cookieVal,abieMakeCookies.expry);
}
}
}
}
createAbie(abiejs.d.position);
bindAbie(abiejs.d.position);
abiesFlag(abiejs.d.position);
abieMakeCookies();
abieRun(abiejs.d.position);
</code></pre>
<p>}</p>
<p>This is the initiation:</p>
<pre><code>abiejs({
merit : function() {
cornify();
},
demerit : 'http://browsehappy.com/'
</code></pre>
<p>});</p>
<p>Also, I'm curious if I'm using the proper terminology in the comments. If you look <a href="https://github.com/justinboyd/abie.js" rel="nofollow">here</a> you can see more of it's documentation. I would love it if someone could help me out and give me pointers on ways to optimize a pure javascript plugin.</p>
|
[] |
[
{
"body": "<p>\"d\", \"b\", \"c\", \"e\" are not good variable names. Use other ones. If you're afraid about the size (and I'll tackle that later), this is gzip's task.\nCreate local variables instead of accessing \"abiejs\" every time.</p>\n\n<pre><code>// for example, from\nabiejs.d...\nabiejs.d.style.color = 'red';\nabiejs.d...\n// to\nvar d = abiejs.d;\nd...\nd.style.color = 'red';\nd...\n</code></pre>\n\n<p>You're trying to do really too much in there. There's code to add events in all browsers, code to create cookies, etc. I suggest you to take a look at <a href=\"http://modernizr.com/\" rel=\"nofollow\">Modernizr</a>, it uses feature detection instead of just trying to poll the browser.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T12:06:01.060",
"Id": "27547",
"ParentId": "27531",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T22:17:07.993",
"Id": "27531",
"Score": "2",
"Tags": [
"javascript",
"plugin"
],
"Title": "Review my browser reward plugin"
}
|
27531
|
<p>Previous review of this project:</p>
<p><a href="https://codereview.stackexchange.com/questions/27491/deck-of-cards-program-using-a-card-value-map">Deck of cards program using a card value map</a></p>
<p>Based on the previous feedback I've received, my program could become more flexible (it formerly created a standard 52-card deck by itself). Now, the user can add <code>Card</code>s to a <code>Deck</code>, and <code>Card</code> is no longer hidden. I like this approach better (also easier to work with), but I'm sure it can still be improved. Regarding its use, I have a few questions:</p>
<ol>
<li><p>Although accessors aren't always recommended, would they still be necessary for allowing the driver to know each <code>Card</code> value/rank/suit (unless they're maintained elsewhere)? For instance, Blackjack requires card numerical values for determining a bust.</p></li>
<li><p>Is the exception-handling in <code>deal()</code> effective (when called on an empty <code>Deck</code>), although it'll still need to return a <code>Card</code>? This is assuming that the user will not always call <code>empty()</code> before calling <code>deal()</code>.</p></li>
<li><p>Is this particular approach <em>too</em> flexible? If so, what could be done instead?</p></li>
</ol>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <iostream>
#include <cstdint>
#include <vector>
class Card
{
private:
unsigned value;
char rank;
char suit;
public:
Card(unsigned v, char r, char s) : value(v), rank(r), suit(s) {}
friend std::ostream& operator<<(std::ostream &out, const Card &card)
{return out << '[' << card.rank << card.suit << ']';}
};
class Deck
{
private:
std::vector<Card> cards;
int topCardPos;
public:
Deck();
void addCard(unsigned value, char rank, char suit);
void shuffle();
Card deal();
std::size_t size() const {return topCardPos+1;}
bool empty() const {return topCardPos == -1;}
friend std::ostream& operator<<(std::ostream &out, const Deck &deck);
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include "Deck.h"
#include <algorithm>
#include <stdexcept>
Deck::Deck() : topCardPos(-1) {}
void Deck::shuffle()
{
topCardPos = cards.size()-1;
std::random_shuffle(cards.begin(), cards.end());
}
void Deck::addCard(unsigned value, char rank, char suit)
{
cards.push_back(Card(value, rank, suit));
topCardPos++;
}
Card Deck::deal()
{
try
{
topCardPos--;
return cards.at(topCardPos+1);
}
catch (const std::out_of_range &oor)
{
std::cerr << "\nDECK DEAL ERROR: " << oor.what() << "\n";
Card blankCard(0, '*', '*');
return blankCard;
}
}
std::ostream& operator<<(std::ostream &out, const Deck &deck)
{
for (unsigned i = 0; i < deck.size(); ++i)
{
out << "\n" << deck.cards[i];
}
return out;
}
</code></pre>
<p><strong>(<em>Possible driver</em>)</strong></p>
<pre><code>Deck deck;
std::array<char, 13> RANKS = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
std::array<char, 4> SUITS = {'H','D','C','S'};
for (unsigned rank = 0; rank < RANKS.size(); ++rank)
{
unsigned value = (rank < 10) ? rank+1 : 10;
for (unsigned suit = 0; suit < SUITS.size(); ++suit)
{
deck.addCard(value, RANKS[rank], SUITS[suit]);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T04:23:11.097",
"Id": "42896",
"Score": "2",
"body": "value seems redundant. it could just be rank<10?rank:10"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T04:29:43.070",
"Id": "42897",
"Score": "0",
"body": "Ah, a ternary statement. Haven't thought of that. Thanks!"
}
] |
[
{
"body": "<p><strong>1: Yes,</strong> your <code>Card</code> class should expose its <code>rank</code> and <code>suit</code> through a public interface. (See the previous thread and @user225770's answer for <code>value</code>.) It should at least give read-only access, but write access may not be necessary. (It is probably better to create a copy than to alter a card.)</p>\n\n<p>The simplest indication of this is your output stream operator overload. The fact that it needs access to these members is a good indication that other client code (i.e. code using this class) will need access as well.</p>\n\n<p><strong>2: It depends,</strong> <em>but in either case it should be modified a bit.</em> Exceptions are used for exceptional circumstances, scenarios that you don't expect to run into a lot. If it's rare that your deck runs out of cards, then throwing an exception is fine. However, you shouldn't throw an exception for your own function. Let the exception propagate to the calling code, and let them decide how to handle the exception.</p>\n\n<p><em>However</em>, if it's a common occurrence that your deck runs out of cards, you should use another approach. What immediately comes to mind is to simply reduce the chance of this happening by checking <code>empty()</code> before calling <code>deal()</code>. You can verify this behavior by adding an <code>assert</code> at the beginning of the function.</p>\n\n<p>(What you are technically doing is defining a <em>precondition</em> for your function. In short, this means that your function requires and assumes that the deck is not empty when <code>deal()</code> is called.)</p>\n\n<p><strong>3: No,</strong> I don't think this solution is over-engineered. However, a more interesting question is \"How can I tell if I have over-engineered my solution?\". Why, thank you for asking! This leads me to my next, and perhaps most important point:</p>\n\n<p><strong>Start doing unit tests.</strong> You are writing good code. The best way for you to improve now is by doing test-driven development. By writing unit tests, several of your questions will answer itself. For example: <em>Should my class expose this member through its interface?</em> Unit tests will answer this question for you by letting you know what you need access to to test and use your code in unit tests.</p>\n\n<p>Test-driven development will let you know if your code is over-engineered. You write a test that works as a requirement to your code. Do you need to do <em>X</em> to make the test pass? Then implement it. Don't you? Then <a href=\"http://en.wikipedia.org/wiki/YAGNI\">You Ain't Gonna Need It (yet)</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T17:23:43.877",
"Id": "42930",
"Score": "0",
"body": "The chances of my deck running out of cards should be unlikely, but I also want to properly handle such a situation anyway. I can still do some other kind of check within the function, and I **know** I will always call `empty()` in my own program (unless of course I'm testing the class). I also forgot to mention, regarding the previous review, that I could also create a function that creates a classic 52-card deck. However, I'll be back at square one with this approach since I still haven't been able to do it free of underlying problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T23:21:27.937",
"Id": "42956",
"Score": "0",
"body": "In that case, your `deal()` function should throw an exception when used incorrectly. `std::vector::at()` will already do this for you, so `deal()` can simply be `return cards.at(topCardPos--);`. Then, depending on your error handling strategy, you could either handle the exception in client code, or you can let it propagate to `main()` and terminate the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T23:28:38.717",
"Id": "42957",
"Score": "0",
"body": "For some reason, Visual C++ can't catch my exception. I have to install Eclipse for my class anyway, so I'll try it on there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T23:43:22.890",
"Id": "42958",
"Score": "0",
"body": "What do you mean? If the exception is propagates out of `main()`, the program should be terminated. A somewhat better approach would be to have a try/catch in `main()` or another entry-level function where you catch the exception and terminate gracefully."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T02:21:45.790",
"Id": "42965",
"Score": "0",
"body": "I really don't know exactly what's going on with my exception-handling. I'm just going to leave it out for now."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T11:22:29.757",
"Id": "27544",
"ParentId": "27534",
"Score": "7"
}
},
{
"body": "<p>I would personnally not associate a card to its rank. I know a number of card games, and rank of card is a very variable thing.</p>\n\n<p>As so, I think the rank of a card is not a property of the Card class, but should be elsewhere, associated to a Game kind of class.</p>\n\n<p>Else, I think that Lstor answer is really good. <strong>Unit tests</strong> are a fundamatenal piece of code, go for it :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T12:58:19.737",
"Id": "42913",
"Score": "1",
"body": "+1, and welcome to CodeReview.StackExchange! I fully agree regarding rank (as I pointed out in the previous thread)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T18:00:14.297",
"Id": "42931",
"Score": "0",
"body": "I'm not sure I quite understand (I don't know a whole lot of card games anyway). If `rank` shouldn't be a member of `Card`, then how would it be able to know what to output for `rank`? Please show me some example code if it will help explain it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T23:17:30.323",
"Id": "42955",
"Score": "1",
"body": "I have confused `rank` and `value`. I think that *value* should not be part of the class, whereas *rank* should. Create a `map`, function mapping or something else in order to achieve this. The most natural choice would be to have a `Game` class with a member function along the lines of `Value valueToRank(Card const&);`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T02:24:09.287",
"Id": "42966",
"Score": "0",
"body": "Ah, okay. That makes more sense. :-) I'll take out the `value` data member and put such an `std::map` in my driver for now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T12:38:29.227",
"Id": "27549",
"ParentId": "27534",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27544",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T04:17:11.517",
"Id": "27534",
"Score": "6",
"Tags": [
"c++",
"playing-cards"
],
"Title": "Usage flexibility of Deck class"
}
|
27534
|
<p>I'm trying to construct something which would work a bit like <code>Zip</code> for two tasks, but I'm a bit worried about race conditions in this code. </p>
<pre><code>public static Task<R> ContinueWhenBoth<T1, T2, R>(this TaskFactory<R> factory, Task<T1> t1,
Task<T2> t2, Func<T1, T2, R> f)
{
var result = new TaskCompletionSource<R>();
t1.ContinueWith(t => { if(t2.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });
t2.ContinueWith(t => { if(t1.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });
return result.Task;
}
</code></pre>
<p>Is this a good way to go?</p>
<pre><code>public static Task<R> ContinueWhenBoth<T1, T2, R>(this TaskFactory<R> factory, Task<T1> t1,
Task<T2> t2, Func<T1, T2, R> f)
{
var result = new TaskCompletionSource<R>();
int tasksLeft = 2;
t1.ContinueWith(t =>
{
if(Interlocked.Decrement(ref tasksLeft) == 0 && t2.IsCompleted)
result.TrySetResult(f(t1.Result, t2.Result));
});
t2.ContinueWith(t =>
{
if(Interlocked.Decrement(ref tasksLeft) == 0 && t1.IsCompleted)
result.TrySetResult(f(t1.Result, t2.Result));
});
return result.Task;
}
</code></pre>
|
[] |
[
{
"body": "<p>Any chance you are using .NET 4.5? It contains the method that does exactly what you need: <a href=\"http://msdn.microsoft.com/en-us/library/hh160374.aspx\" rel=\"nofollow\">Task.WhenAll</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T07:09:41.100",
"Id": "42903",
"Score": "0",
"body": "No quite (I think), because my tasks have different types"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T06:32:11.320",
"Id": "27537",
"ParentId": "27536",
"Score": "0"
}
},
{
"body": "<p>You don't need to write this code yourself, there is already a method that does something very similar: <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.continuewhenall.aspx\" rel=\"nofollow\"><code>Task.Factory.ContinueWhenAll()</code></a>.</p>\n\n<p><code>ContinueWhenAll()</code> doesn't directly support working with <code>Task</code>s that return different types, but you can create a helper method that does:</p>\n\n<pre><code>public static Task<R> ContinueWhenBoth<T1, T2, R>(\n this TaskFactory<R> factory, Task<T1> t1, Task<T2> t2, Func<T1, T2, R> f)\n{\n return factory.ContinueWhenAll(new Task[] { t1, t2 }, _ => f(t1.Result, t2.Result));\n}\n</code></pre>\n\n<p>If you didn't want to use closure for performance reasons, you could use the array of <code>Task</code>s and casting:</p>\n\n<pre><code>return factory.ContinueWhenAll(\n new Task[] { t1, t2 }, tasks => f(((Task<T1>)tasks[0]).Result, ((Task<T2>)t2).Result));\n</code></pre>\n\n<hr>\n\n<pre><code>t1.ContinueWith(t => { if(t2.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });\nt2.ContinueWith(t => { if(t1.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });\n</code></pre>\n\n<p>This code has a race condition: if <code>t1</code> and <code>t2</code> complete at the same time, then <code>f</code> might be executed twice. I don't think that's a good idea, since <code>f</code> might take a long time, or, worse, it might have side-effects.</p>\n\n<pre><code>if(Interlocked.Decrement(ref tasksLeft) == 0 && t2.IsCompleted) \n</code></pre>\n\n<p>The <code>Decrement()</code> here avoids the race condition from the previous code. But it also means that the check of <code>t2.IsCompleted</code> will always succeed, so you should remove it.</p>\n\n<hr>\n\n<p>But your code also has a significant issue: if <code>t1</code> or <code>t2</code> fail with an exception, your resulting <code>Task</code> will never complete. (And on .Net 4.0, it will also crash the process some time in the future, because there is an uncaught exception in a <code>Task</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T08:06:53.050",
"Id": "42904",
"Score": "0",
"body": "Can it combine input tasks of different types?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T08:15:15.220",
"Id": "42905",
"Score": "0",
"body": "@Benjol See edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T08:37:25.533",
"Id": "42906",
"Score": "0",
"body": "OK, I see. I'll try that. One thing I don't understand is you say that `t2.IsCompleted` will always succeed: surely only if t2 completes first?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T09:15:48.823",
"Id": "42909",
"Score": "0",
"body": "@Benjol I mean, if the first condition succeeds, the second one will too, so there is no reason to check it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T08:00:58.320",
"Id": "27539",
"ParentId": "27536",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T05:46:06.183",
"Id": "27536",
"Score": "1",
"Tags": [
"c#",
"task-parallel-library"
],
"Title": "TaskFactory.CompleteWhenBoth"
}
|
27536
|
<p>My implementation in Progress 4GL of the Luhn Algorithm. Any suggestions on improving it?</p>
<pre><code>FUNCTION fnLuhnAlgorithm RETURNS LOGICAL
(INPUT pcNumber AS CHARACTER):
/*------------------------------------------------------------------------------
Purpose: Applies Luhn Algorithm to check a Number
Notes: Returns True/False Validation based on check digit
From the rightmost digit, which is the check digit, moving left, double the value
of every second digit;
if product of this doubling operation is greater than 9 (e.g., 7 * 2 = 14).
Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together
Compute the sum of the digits.
Multiply by 9.
The last digit, is the check digit.
------------------------------------------------------------------------------*/
DEFINE VARIABLE cNum AS CHARACTER NO-UNDO.
DEFINE VARIABLE iCheck AS INTEGER NO-UNDO.
DEFINE VARIABLE iLength AS INTEGER NO-UNDO.
DEFINE VARIABLE iLoopCnt AS INTEGER NO-UNDO.
DEFINE VARIABLE iNum AS INTEGER NO-UNDO.
DEFINE VARIABLE iNum1 AS INTEGER NO-UNDO.
DEFINE VARIABLE iNum2 AS INTEGER NO-UNDO.
DEFINE VARIABLE iTestLength AS INTEGER NO-UNDO.
ASSIGN
iLength = LENGTH(pcNumber)
iTestLength = iLength - 1
iCheck = 1. /* 1 for the check digit we skip */
DO iLoopCnt = iTestLength TO 1 BY -1:
ASSIGN
iNum = INTEGER(SUBSTR(pcNumber,iLoopCnt,1))
iCheck = iCheck + 1.
IF iCheck MODULO 2 = 1 THEN
ASSIGN iNum1 = iNum1 + iNum.
ELSE
DO:
ASSIGN iNum2 = iNum * 2.
IF iNum2 < 10 THEN
ASSIGN iNum1 = iNum1 + iNum2.
ELSE
ASSIGN
cNum = STRING(iNum2)
iNum1 = iNum1 + INTEGER(SUBSTR(cNum,1,1)) + INTEGER(SUBSTR(cNum,2,1)).
END.
END.
ASSIGN
iNum2 = iNum1 * 9
iNum = iNum2 MODULO 10.
IF iNum = INTEGER(SUBSTR(pcNumber,iLength,1)) THEN
RETURN TRUE.
ELSE
RETURN FALSE.
END FUNCTION. /* fnLuhnAlgorithm */
</code></pre>
|
[] |
[
{
"body": "<p>You are kind of overdoing it a little in my opinion, there are too many variables that don't really add much value, also I would change the parameter to be DECIMAL, to avoid calls using not numbers that would cause run time errors.</p>\n\n<p>My implementation would look like this:</p>\n\n<pre><code>FUNCTION fnLuhnAlgorithm RETURNS LOGICAL\n (INPUT pcNumber AS DECIMAL):\n/*------------------------------------------------------------------------------\n Purpose: Applies Luhn Algorithm to check a Number \n Notes: Returns True/False Validation based on check digit\n\n From the rightmost digit, which is the check digit, moving left, double the value\n of every second digit; \n if product of this doubling operation is greater than 9 (e.g., 7 * 2 = 14).\n Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together \n Compute the sum of the digits.\n Multiply by 9.\n The last digit, is the check digit.\n------------------------------------------------------------------------------*/\n DEFINE VARIABLE cNumber AS CHARACTER NO-UNDO INITIAL \"\".\n DEFINE VARIABLE iDigit AS INTEGER NO-UNDO INITIAL 0.\n DEFINE VARIABLE iSum AS INTEGER NO-UNDO INITIAL 0.\n DEFINE VARIABLE iLoopCnt AS INTEGER NO-UNDO INITIAL 0.\n\n cNumber = STRING(pcNumber).\n\n DO iLoopCnt = LENGTH(cNumber) - 1 TO 1 BY -1:\n\n iDigit = INTEGER(SUBSTR(cNumber,iLoopCnt,1)).\n\n IF iLoopCnt MODULO 2 = LENGTH(cNumber) MODULO 2 THEN\n iSum = iSum + iDigit.\n ELSE\n iSum = iSum + INTEGER(SUBSTR(STRING(iDigit * 2,\"99\"),1,1)) \n + INTEGER(SUBSTR(STRING(iDigit * 2,\"99\"),2,1)). \n\n END.\n\n IF ((iSum * 9) MODULO 10) = INTEGER(SUBSTR(cNumber,LENGTH(cNumber),1)) THEN\n RETURN TRUE.\n ELSE\n RETURN FALSE.\n\nEND FUNCTION. /* fnLuhnAlgorithm */\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:23:34.277",
"Id": "43070",
"Score": "0",
"body": "Looks good, I would just either keep the input parm as character or make it integer instead of decimal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T11:52:26.517",
"Id": "43073",
"Score": "0",
"body": "if input parm is character you can also get rid of the variable cNumber"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T20:46:49.733",
"Id": "43094",
"Score": "0",
"body": "I have defined as DECIMAL because it would be able to hold a much higher maximum value than an INTEGER, and if you are dealing with account numbers or similar you'll reach it easily.\nAbout the CHARACTER input parameter, if that is the case then you'll need to first check the value is a valid number to be able to check it, also, seems much more clear if the function is to validate numbers that the parameter you pass is a number itself to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T10:40:02.123",
"Id": "43334",
"Score": "0",
"body": "Agree will need a check to make sure it is number, but same if input is decimal you still need to check to make sure it is not a decimal value. I use the LUHN Algorithm to test ID number, but before I call the algorithm i first do a lot of tests to make sure the ID number is a number and contains valid values in certain positions, etc. So by the time I call the function I know I have a valid number I just need to make sure the check digit is correct, so the Luhn Algorithm does not have to worry if value is a number."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:05:56.567",
"Id": "27593",
"ParentId": "27540",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27593",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T08:38:11.557",
"Id": "27540",
"Score": "1",
"Tags": [
"algorithm",
"performance",
"progress-4gl"
],
"Title": "Progress 4GL - Luhn algorithm"
}
|
27540
|
<p>I've been spending lot of time reading through this site and found plenty of resources that shaped up my code.</p>
<p>I am working on an open source project known as Quizz. It is in a primitive stage as I work only during my spare time I cannot concentrate much. For this JavaScript to work, I have a huge objects and array's of topics and questions in a variable called <code>qbank</code> (read question bank).</p>
<pre><code>var qbank = {};
qbank['js'] = [];
qbank['html'] = [];
qbank['js'].push({
level: 'basic',
questions: [
{
title: 'One JS BASIC A question statement?',
type: 'single',
anss: [
'Answer 1',
'Answer 2',
'Answer 3'
],
ans: [1],
comments: 'If there is a wrong answer, a justification is needed'
},
]
});
</code></pre>
<p>I guess from the above code it is understandable that the topics may be JavaScript/HTML/PHP or Java, and each JavaScript array holds set of questions based on levels (basic, intermediate,... advanced).</p>
<p>The idea is to iterate over array and hold each levels and topics in a separate array variable. </p>
<p>Do you think this approach is good? I really feel there is something wrong with this.</p>
<pre><code>var digest = function() {
for( var q in qbank ) {
// q is js/html/php/..... topic names
var
topic,
t,
qns = 0,
i = 0,
questions,
question,
level
;
topic = qbank[q];
// Initializing instance topics
_instance.topics[q]= [];
for(
var
l = levels.length
; i < l; i++ ) {
if( typeof _instance.topics[q][i] === 'undefined' ) {
_instance.topics[q][i] = {
'level': levels[i],
'questions': []
};
}
}
for( t in topic ) {
questions = topic[t].questions;
level = topic[t].level;
for( qns in questions ) {
for( var
inst = 0,
l = _instance.topics[q].length; inst < l; inst++ ) {
if( _instance.topics[q][inst].level === level ) {
_instance.topics[q][inst].questions.push( questions[qns] );
}
}
}
}
}
};
</code></pre>
<p>Secondly, I have this digest function where it will pull out and merge all the questions based on levels and topics. I really hate to see my code with plenty of <code>for</code> loops. Please help in suggesting a good practice or approach I need to take.</p>
|
[] |
[
{
"body": "<p>I can understand your frustration of nested for loops.</p>\n\n<p>However, your data structure is full of nested arrays. How else can you handle them?</p>\n\n<p>One way to have pretty code is to separate each loop in its own function, with clear names.</p>\n\n<p>This way, the main logic remains readable. And if you want to go in detail, the only scope you have to care about is a small function.</p>\n\n<p>You can refactor more than in the example given above, it's all up to you.</p>\n\n<p>Example:</p>\n\n<pre><code>var digest = function() { \n for( var q in qbank ) {\n // q is js/html/php/..... topic names \n var\n topic,\n t,\n qns = 0,\n i = 0,\n questions,\n question,\n level\n ;\n\n topic = qbank[q];\n\n initInstance( _instance, q );\n\n for( t in topic ) {\n initTopics( _instance, t, q );\n\n }\n }\n\n // Initializing instance topics\n function initInstance( _instance, q ) {\n _instance.topics[q]= [];\n\n for( \n var \n l = levels.length\n ; i < l; i++ ) {\n\n if( typeof _instance.topics[q][i] === 'undefined' ) {\n _instance.topics[q][i] = {\n 'level': levels[i],\n 'questions': []\n };\n }\n }\n }\n\n function initTopics( _instance, t, q ) {\n var\n questions = topic[t].questions,\n level = topic[t].level\n ;\n\n for( qns in questions ) { \n for( var \n inst = 0, \n l = _instance.topics[q].length; inst < l; inst++ ) {\n\n if( _instance.topics[q][inst].level === level ) {\n _instance.topics[q][inst].questions.push( questions[qns] );\n }\n }\n }\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T10:02:36.107",
"Id": "42910",
"Score": "0",
"body": "+1 for this suggestion, my bad it didn't hit me in the first place about using functions. Now I can break down topics and levels based on your suggestion. TY!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T09:57:33.770",
"Id": "27542",
"ParentId": "27541",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T09:31:58.010",
"Id": "27541",
"Score": "3",
"Tags": [
"javascript",
"quiz"
],
"Title": "JavaScript-based quiz application called Quizz"
}
|
27541
|
<p>I have a switch case statement containing enum values as cases. These enum values are time units. Now I want to generate a timespan by using an enum value and a long value so like this:</p>
<blockquote>
<p>2 (long) Minutes (Enum value)</p>
<p>1 (long) Year (Enum value)</p>
</blockquote>
<p>... and so on.</p>
<p>This is the switch-case statement:</p>
<pre><code>private const double yearValue = 365.2425;
public TimeSpan ResetTimeSpan
{
get
{
switch (ResetTimeUnitEnumValue)
{
case TimeUnit.Seconds:
return new TimeSpan(0,0,0, (int)ResetTime);
case TimeUnit.Minutes:
return new TimeSpan(0, 0, (int)ResetTime, 0);
case TimeUnit.Hours:
return new TimeSpan(0, (int)ResetTime, 0);
case TimeUnit.Days:
return new TimeSpan((int)ResetTime, 0, 0, 0);
case TimeUnit.Months:
return new TimeSpan((int)(ResetTime * (yearValue / 12)), 0, 0, 0);
case TimeUnit.Years:
return new TimeSpan((int)(ResetTime * yearValue), 0, 0, 0);
default:
throw new ArgumentOutOfRangeException();
}
}
}
</code></pre>
<p>But I don't like it and it feels very double. Could anyone review this and refactor it, since I'm not able to see it.</p>
|
[] |
[
{
"body": "<pre><code>private const double yearMultiplier = 365.2425;\n\nprivate Dictionary<TimeUnit, Func<double, TimeSpan>> timespanConverters = new Dictionary<TimeUnit, Func<double, TimeSpan>>\n{\n { TimeUnit.Seconds, TimeSpan.FromSeconds },\n { TimeUnit.Minutes, TimeSpan.FromMinutes },\n { TimeUnit.Hours, TimeSpan.FromHours },\n { TimeUnit.Days, TimeSpan.FromDays },\n { TimeUnit.Months, t => TimeSpan.FromDays((int)t * (yearMultiplier / 12))) },\n { TimeUnit.Years, t => TimeSpan.FromDays((int)t * yearMultiplier)) }\n}\n\n// ....\n\npublic TimeSpan ResetTimeSpan\n{\n get\n {\n return timespanConverters[ResetTimeUnitEnumValue](ResetTime);\n }\n}\n</code></pre>\n\n<p>Bit of a shame that <code>System.TimeSpan</code> doesn't have <code>FromMonths</code> or <code>FromYears</code> methods otherwise this would look really neat :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T16:39:41.023",
"Id": "42925",
"Score": "2",
"body": "`TimeSpan` always represents a specific duration, e.g. x seconds. How many seconds are there in a month or year? Keep in mind that expressions like `date + TimeSpan.FromMonths(x)` should behave reasonably."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T16:41:24.437",
"Id": "42926",
"Score": "0",
"body": "@svick good point, months and years are not consistent so it's not possible to measure without approximating them, like in the OP's sample."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:40:26.483",
"Id": "42937",
"Score": "0",
"body": "It does not need to be precise so its perfect this way!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T08:17:34.583",
"Id": "42980",
"Score": "0",
"body": "As an easy optimisation, you could also think about memoizing the functions in the dictionary :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T16:34:53.003",
"Id": "27557",
"ParentId": "27552",
"Score": "7"
}
},
{
"body": "<p>I don't think you're going to get too much cleaner, but I'll offer up a few alternatives and thoughts.</p>\n\n<p>First, you could use the <a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx\" rel=\"nofollow\">TimeSpan convenience methods</a> (<code>TimeSpan.FromSeconds</code>, <code>FromMinutes</code>, <code>FromHours</code>, and <code>FromDays</code>) to at least get up to days. FWIW, I think that's more readable than using the constructor parameters. Alternatively, using named arguments to the constructor would help readability.</p>\n\n<p>You could abstract out the calculation to a map:</p>\n\n<pre><code>private const double yearValue = 365.2425;\n\nstatic readonly timeUnitInSeconds = new Dictonary<TimeUnit, double>() {\n { TimeUnit.Seconds, 1 },\n { TimeUnit.Minutes, 60 },\n { TimeUnit.Hours, 60 * 60 },\n { TimeUnit.Days, 60 * 60 * 24 },\n { TimeUnit.Months, 60 * 60 * 24 * (yearValue / 12) }, \n { TimeUnit.Years, 60 * 60 * 24 * yearValue }\n};\n\nget { \n return TimeSpan.FromSeconds(timeUnitInSeconds[ResetTimeUnitEnumValue] * (int)ResetTime);\n}\n</code></pre>\n\n<p>which is a little cleaner, and makes the calcs easier to read.</p>\n\n<p>Or, you could go for the whole shebang, and make the <code>TimeUnit</code> enum itself the value in seconds:</p>\n\n<pre><code>private const double yearValue = 365.2425;\n\nenum TimeUnit {\n // in seconds\n Seconds = 1,\n Minutes = 60,\n Hours = 60 * 60,\n Days = 60 * 60 * 24,\n Months = (int)(60 * 60 * 24 * (yearValue / 12))),\n Years = (int)(60 * 60 * 24 * yearValue)\n}\n\nget {\n return TimeSpan.FromSeconds((int)ResetTimeUnitEnumValue * (int)ResetTime);\n}\n</code></pre>\n\n<p>That's probably bit too clever by half, though. Also note the int conversion is done first there, which could lead to slightly different results if you don't have a whole # of seconds. Your month value is a bit odd (it should be closer to 30.5 if it's intended to be the average month length in days) so you may want to double check that one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T16:48:40.523",
"Id": "27558",
"ParentId": "27552",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27557",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T15:11:27.063",
"Id": "27552",
"Score": "4",
"Tags": [
"c#",
"datetime"
],
"Title": "A switch case statement that returns a timespan"
}
|
27552
|
<p>Is there any ways I can write redundant-less code without this infinite loop? I have also tried putting the conditions and the generating number, but since it has two conditions, the output number will be different.</p>
<pre><code>private static final int PERCENT_97 = 3;
/**
* Returns returns a pseudo-random Gaussium number. Forumla:
* {@code (RanGassium * 3) + mean }
*
* @param mean
* mean of returning value
* @param min
* min bound
* @param max
* max bound
* @return a pseduo-random Gaussium that is close to the mean.
*/
public static double getRandomGaussium(double mean, double min, double max) {
double returningNumber = 0;
double rangeMean=(max-min)/2;
while (true) {
returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;
if (returningNumber > min && returningNumber < max) {
break;
}
}
return returningNumber;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T15:53:33.230",
"Id": "42924",
"Score": "0",
"body": "It's not infinite if you provide a way to escape the loop. That is, if the escape can be reached although."
}
] |
[
{
"body": "<p>A do while would be an equivalent construct. I don't really think either is more or less preferable, but is an alternative that avoids the <em>appearance</em> of an infinite loop:</p>\n\n<pre><code>do {\n returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;\n} while (returningNumber < min || returningNumber > max);\nreturn returningNumber;\n</code></pre>\n\n<p>That still leaves open a possibility of an eternal loop, though. You should probably at least validate your params to guard against that (eg., a min of 1 and max of 1 would run forever). You may also want to put an iteration counter to give up and throw an exception after so many iterations. At that point, a for loop with an early return if one is found may be a better choice than stuffing it all into the where or if conditionals:</p>\n\n<pre><code>for (int i = 0; i < MAX_TRIES; i++) {\n returningNumber = (generator.nextGaussian() * rangeMean/PERCENT_97) + mean;\n if (returningNumber > min && returningNumber < max) {\n return returningNumber;\n }\n}\nthrow new IGiveUpException();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T16:11:59.227",
"Id": "27556",
"ParentId": "27554",
"Score": "5"
}
},
{
"body": "<p>Firstly, I'm not convinced that the javadoc of you method matches what the code actually does. Certainly, the formula <code>(RanGassium * 3) + mean</code> needs some explanation ... because it does not match what the code is literally doing.</p>\n\n<p>Second, you are missing some critical validation on the input parameters. For instance if you call the method with <code>min</code> greater than <code>max</code> you will get a <em>real</em> infinite loop.</p>\n\n<p>Third, I'm not sure of your methodology for using <code>min</code>, <code>max</code> and <code>PERCENT_97</code> to generate the multiplier.</p>\n\n<hr>\n\n<p>Anyway, the away to avoid the loop is to take a look at the various methods listed in Wikipedia for <a href=\"https://en.wikipedia.org/wiki/Normal_distribution#Generating_values_from_normal_distribution\" rel=\"nofollow\">generating Gaussian random numbers</a> and picking one that allows you set the bounds on the input side of the uniform -> Gaussian mapping. The first bullet looks promising, though you'd need to understand the mathematics. A general approach based on this for generating Gaussian distributed PRNs in a range would be:</p>\n\n<ul>\n<li><p>map <code>min</code> and <code>max</code> (in Gaussian space) to uniform space; i.e. calculate \"phi(min)\" and \"phi(max)\" (I think ...)</p></li>\n<li><p>generate a single uniform number in the range \"phi(min) < N < phi(max)\"</p></li>\n<li><p>calculate \"phi<sup>-1</sup>(N)\"</p></li>\n</ul>\n\n<p>From a performance perspective, this is probably only worthwhile if <code>min</code> and <code>max</code> are very close together, and you would need to do a large number of iterations of your \"potentially infinite\" loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T02:02:30.830",
"Id": "27684",
"ParentId": "27554",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27556",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T15:39:21.347",
"Id": "27554",
"Score": "2",
"Tags": [
"java",
"random"
],
"Title": "Returning a pseudo-random Gaussian number"
}
|
27554
|
<p>First of all, I'm trying to learn OOP PHP, so any advise will be great.</p>
<p>My idea is to create some kind of MVC Framework CMS kind of thing, just to learn OOP PHP and MVC well.</p>
<p>Let's say that I've got this code (note: I will separate the code pieces in different files, but this was just for testing):</p>
<pre><code><?php
function printExtender($var) {
$returnVal = '<pre>';
$returnVal .= print_r($var, TRUE);
$returnVal .= '</pre>';
return $returnVal;
}
class Main_Controller {
protected $_vars = array();
protected static $_instance;
private function __construct() {
}
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function & __get($name) {
return $this -> _vars[$name];
}
public function __set($name, $value) {
$this -> _vars[$name] = $value;
}
public function loadDefaultClasses(){
$main = Main_Controller::getInstance();
$main -> config = Config::getInstance();
$main -> sql = SQL::getInstance();
}
}
class Config {
protected $_vars = array();
protected static $_instance;
private function __construct() {
$this-> db = array("localhost");
}
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function & __get($name) {
return $this -> _vars[$name];
}
public function __set($name, $value) {
$this -> _vars[$name] = $value;
}
}
class SQL{
protected static $_instance;
private function __construct() {
$main = Main_Controller::getInstance();
echo printExtender($main -> config -> db);
}
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
}
$main = Main_Controller::getInstance();
$main -> loadDefaultClasses();
</code></pre>
<p>The idea was to get the <code>$main -> config -> ....</code> thing working so I can use that later on. Am I doing this right, or is it awful? And do you have any tips?</p>
|
[] |
[
{
"body": "<h1>Overview</h1>\n<p>This isn't OOP. To me, <em>object</em>-oriented programming requires thinking about your programs in terms of classes, their responsibilities, their attributes, and behaviours. This means:</p>\n<ul>\n<li>Information hiding</li>\n<li>Encapsulation</li>\n<li>Polymorphism</li>\n<li>Collaboration</li>\n</ul>\n<h1>Config Class</h1>\n<p>Dearth of source code comments aside, let's look at the <code>Config</code> class. Here are some questions about the configuration options:</p>\n<ul>\n<li>What are the options?</li>\n<li>What do each of the options do?</li>\n<li>How do the options affect the application?</li>\n<li>How are the options communicated to the end user?</li>\n</ul>\n<p>In this case, the <code>Config</code> "class" as written is nothing more than a functional structure (i.e., it is a dynamic array) wrapped in the syntax of a PHP class. A class, <a href=\"http://en.wikipedia.org/wiki/Class_%28computer_science%29\" rel=\"nofollow noreferrer\">by definition</a>, allows instances to have <em>state</em> and <em>behaviour</em>. The <code>Config</code> class has no discernible behaviour. To give it behaviour, we'd have to contemplate the purpose of the class: its <a href=\"http://en.wiktionary.org/wiki/raison_d%27%C3%AAtre\" rel=\"nofollow noreferrer\">raison d'être</a>.</p>\n<p>The name "Config" indicates that the class is <em>responsible</em> for some kind of <em>configuration</em>. (Note: I absolutely abhor abbreviations.) I would further imagine that the configuration is specifically for the CMS application. So I would have named the class <code>CMSConfiguration</code>, which inherits from a more generic <code>Configuration</code> class. Let's look at that generic class.</p>\n<p>What can an application configuration class do? I imagine a general configuration class can do the following:</p>\n<ul>\n<li>Load options (from a stream, a file, command line switches)</li>\n<li>Save options (to maintain current state, or save preferences)</li>\n<li>Answer whether an option is set</li>\n<li>Answer whether an option is equal to a given value</li>\n<li>Export help for the options in an display-device-neutral markup language</li>\n</ul>\n<p>That's its behaviour. The single responsibility is clear: the <code>Configuration</code> class loads and queries the state of configuration options. The implementation might resemble:</p>\n<pre><code><?php\n/**\n * Responsible for loading and saving configuraiton options.\n */\nclass Configuration {\n /**\n * Loads the configuration options from application's database connection.\n */\n public function load() {\n Database database = Database::getInstance();\n $result = database->call( "get_configuration_options" );\n\n // Set the configuration options using the result set.\n }\n\n /** Saves the current state of the configuration options. */\n public function save() {\n }\n\n /**\n * Returns true to indicate that the option with the given name is set.\n *\n * @param $option The name of the option to check.\n * @return true The option has a value that is not false.\n */\n public function isOptionSet( $option ) {\n return $this->getOption( $option );\n }\n\n /** ... */\n public function isOptionEqual( $option, $value ) {\n return $this->getOption( $option ) === $value;\n }\n\n /** Writes the help for all the options as an XML document. */\n public function exportHelp() {\n foreach( $this->getOptions() as $option ) {\n // ...\n }\n }\n}\n?>\n</code></pre>\n<p>There seems to be a trend of not declaring attributes, but using magical <code>__set</code> and <code>__get</code> functions combined with dynamic arrays. This will lead to unmaintainable code. If the variables that are used by a class are not defined in a single location, how do you expect anyone else to understand how the code works?</p>\n<p>You could, for example, have <code>ClassA</code> and <code>ClassB</code>. What is stopping <code>ClassB</code> from using <code>ClassA</code> as its container for attribute values? Nothing. And that's a terrible, terrible thing, as it completely violates both information hiding <em>and</em> encapsulation.</p>\n<h1>SQL Class</h1>\n<p>Judging by its name, the SQL Class seems to be some kind of holder for SQL statements? This will directly violate encapsulation again, as the class that needs to use the SQL will have to call the SQL class to get it. The SQL class should know nothing about the SQL that other classes need to perform.</p>\n<p>I actually go a bit further than this. I don't like exposing SQL in my applications at all. SQL changes a lot over the lifetime of a project. When you have many different fingers all creating their own SQL statements, you wind up with a mess: duplicate code, inefficient queries, a burdened query cache, brittle code that will break anytime a table changes, and no clean way to unit test the queries.</p>\n<p>The problem, in my mind, is that there is no contract prototype between a CRUD (Create, Read, Update, or Delete) statement and the calling code. This means that the two cannot easily vary independently.</p>\n<p>To resolve this, I move the SQL code into stored procedures and stored functions (collectively <em>stored routines</em>). Some people will despise this approach, others will laud it. I prefer it because it means I can create a contract between the stored routine and the underlying code. (It also means that if I wanted to switch from PHP to another language, there's less code to change.)</p>\n<p>Once all the SQL code is written in stored routines, it becomes trivial to write a generic database class that can call those routines with arbitrary parameters.</p>\n<pre><code><?php\nuse PDO;\nuse PDOException;\n\n/**\n * Used for interacting with the database. Usage:\n * <pre>\n * $db = Database::get();\n * $db->call( ... );\n * </pre>\n */\nclass Database {\n private static $instance;\n private $dataStore;\n\n /**\n * Sets the connection that this class uses for database transactions.\n */\n public function __construct() {\n global $dbhost;\n global $dbname;\n global $dbuser;\n global $dbpass;\n\n try {\n $this->setDataStore(\n new PDO( "pgsql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass ) );\n }\n catch( PDOException $ex ) {\n $this->log( $ex->getMessage() );\n }\n }\n\n /**\n * Returns the singleton database instance.\n */\n public function get() {\n if( self::$instance === null ) {\n self::$instance = new Database();\n }\n\n return self::$instance;\n }\n\n /**\n * Call a database function and return the results. If there are\n * multiple columns to return, then the value for $params must contain\n * a comma; otherwise, without a comma, the value for $params is used\n * as the return column name. For example:\n *\n *- SELECT $params FROM $proc( ?, ? ); -- with comma\n *- SELECT $proc( ?, ? ) AS $params; -- without comma\n *- SELECT $proc( ?, ? ); -- empty\n *\n * @param $proc Name of the function or stored procedure to call.\n * @param $params Name of parameters to use as return columns.\n */\n public function call( $proc, $params = "" ) {\n $args = array();\n $count = 0;\n $placeholders = "";\n\n // Key is zero-based (e.g., $proc = 0, $params = 1).\n foreach( func_get_args() as $key => $parameter ) {\n // Skip the $proc and $params arguments to this method.\n if( $key < 2 ) continue;\n\n $count++;\n $placeholders = empty( $placeholders ) ? "?" : "$placeholders,?";\n array_push( $args, $parameter );\n }\n\n $sql = "";\n\n if( empty( $params ) ) {\n // If there are no parameters, then just make a call.\n $sql = "SELECT $proc( $placeholders )";\n }\n else if( strpos( $params, "," ) !== false ) {\n // If there is a comma, select the column names.\n $sql = "SELECT $params FROM $proc( $placeholders )";\n }\n else {\n // Otherwise, select the result into the given column name.\n $sql = "SELECT $proc( $placeholders ) AS $params";\n }\n\n $db = $this->getDataStore();\n $statement = $db->prepare( $sql );\n\n for( $i = 1; $i <= $count; $i++ ) {\n $statement->bindParam( $i, $args[$i - 1] );\n }\n\n try {\n $result = null;\n\n if( $statement->execute() === true ) {\n $result = $statement->fetchAll( PDO::FETCH_ASSOC );\n $this->decodeArray( $result );\n }\n else {\n // \\todo Send an e-mail.\n $info = $statement->errorInfo();\n $this->log( "SQL failed: $sql" );\n $this->log( "Error: ". $info[2] );\n }\n }\n catch( PDOException $ex ) {\n // \\todo Send an e-mail.\n $this->log( $ex->getMessage() );\n }\n\n return $result;\n }\n\n /**\n * Converts an array of numbers into an array suitable for usage with\n * PostgreSQL.\n *\n * @param $array An array of integers.\n */\n public function arrayToString( $array ) {\n return "{" . implode( ",", $array ) . "}";\n }\n\n /**\n * Recursive method to decode a UTF8-encoded array.\n *\n * @param $array - The array to decode.\n * @param $key - Name of the function to call.\n */\n private function decodeArray( &$array ) {\n if( is_array( $array ) ) {\n array_map( array( $this, "decodeArray" ), $array );\n }\n else {\n $array = utf8_decode( $array );\n }\n }\n\n private function getDataStore() {\n return $this->dataStore;\n }\n\n private function setDataStore( $dataStore ) {\n $dataStore->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );\n $this->dataStore = $dataStore;\n }\n}\n</code></pre>\n<p>The code is used in one of three ways:</p>\n<pre><code>// Returns a boolean value\n$result = $db->call( "is_existing_cookie", "existing", $cookie_value );\n\n// Calls a stored procedure\n$this->call( "procedure_insert", "", $this->getId(), $action_name_id );\n\n// Returns a tuple pair of ids and labels\nreturn $this->call( "get_list", "id, label", $this->getId() );\n</code></pre>\n<p>The <code>Database</code> class has behaviours (make a database call) and attributes (the singleton instance). There is certainly room for improvement, but this should give you more ideas to ponder.</p>\n<p>All of the text is great, but the example code... That database class violates just about every OOP principle there is. Importing global variables? Constructing a PDO instance in the constructor? A singleton? What? Why? Globals have no place in modern PHP, nor do singletons. Dependency injection is the way to go here. And suppressing exceptions? Nooooo. The consuming code needs to know something exceptional happened. Logging is not enough (and I would argue that either an extension, wrapper or consumer of the class should be responsible for logging).</p>\n<h1>Response to Corbin</h1>\n<blockquote>\n<p>That database class violates just about every OOP principle there is.</p>\n</blockquote>\n<p>The Database class violates neither encapsulation nor information hiding. This is apparent from its intended usage:</p>\n<pre><code>return $this->call( "get_list", "id, label", $this->getId() );\n</code></pre>\n<p>The underlying implementation (of the <code>call</code> method) can change without any impact to the client code. No information about the internal workings of the Database class is being exposed.</p>\n<blockquote>\n<p>Importing global variables?</p>\n</blockquote>\n<p>True, this is poor form. However, it can be mitigated by using a configuration file, or dependency injection. Again, the calling classes will not need to change.</p>\n<blockquote>\n<p>Constructing a PDO instance in the constructor? A singleton? What? Why?\nGlobals have no place in modern PHP, nor do singletons.</p>\n</blockquote>\n<p>True, globals are poor form. The Singleton pattern was employed for its simplicity. In my application, every single class uses the Database, but most of the subclasses do not use it directly.</p>\n<p>This code is also fairly temporary, as the application will be rewritten using <a href=\"http://haxe.org/\" rel=\"nofollow noreferrer\">Haxe</a>.</p>\n<blockquote>\n<p>And suppressing exceptions? Nooooo.</p>\n</blockquote>\n<p>Depends on if the calling code needs them. In my case, the calling code never needs to care about the error. Users don't care if there was a database error. There is no point bubbling an error message to the user, as they'll never understand "ORA-10168: INSERT violates duplicate key" or whatever. Ergo, the message is suppressed and the application must handle an empty result set.</p>\n<p>In this particular case, all empty result sets yield a relatively empty XML document, which is rendered using XSLT, to produce a web page for the user. There is little difference between the following:</p>\n<pre><code>try {\n $result = $this->call( ... );\n}\ncatch( Exception $e ) {\n $result = $this->getErrorXML();\n}\n</code></pre>\n<p>And this:</p>\n<pre><code>$result = $this->call( ... );\n\nif( !isset( $result ) ) {\n $result = $this->getErrorXML();\n}\n</code></pre>\n<p>They are functionally equivalent, although the exception handling allows slightly more flexibility for eliminating duplicate code (by allowing the exception to bubble naturally and get handled in a single location).</p>\n<p>As I mentioned, there are a number of minor issues with the Database class, however it does not violate either encapsulation or information hiding.</p>\n<p>From a big picture perspective, I'd rather see:</p>\n<pre><code>return $this->call( "get_list", "id, label", $this->getId() );\n</code></pre>\n<p>Sprinkled throughout the codebase, than hundreds of <code>SELECT</code> statements married to <code>PDO</code> calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T05:23:27.723",
"Id": "42973",
"Score": "0",
"body": "Thank you verry much for taking so much time to answer. As i first menthoid, am i beginning in OOP, so any help that i could get is nice. But i didn't suspect such an nice and long but still understanding answer. Thank you. I'll leave the question a little longer open, so that mayby others can shine there knowledge about this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T06:30:24.940",
"Id": "42975",
"Score": "1",
"body": "All of the text is great, but the example code... That database class violates just about every OOP principle there is. Importing global variables? Constructing a PDO instance in the constructor? A singleton? What? Why? Globals have no place in modern PHP, nor do singletons. Dependency injection is the way to go here. And suppressing exceptions? Nooooo. The consuming code needs to know something exceptional happened. Logging is not enough (and I would argue that either an extension, wrapper or consumer of the class should be responsible for logging)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T08:40:22.503",
"Id": "42983",
"Score": "0",
"body": "@Corbin, how would you do it than? ( please make an answer of it, so i can see and understand it beter )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:47:59.670",
"Id": "43032",
"Score": "1",
"body": "@Mathlight I will consider writing an answer later. Dave Jarvis and Paul (though he said it indirectly) are both right though: \"This isn't OOP.\" Until the basic principles are there, there's not really much I can add. Your best bet for the time being is to look into the links that Paul provided along with all of the other major. Object oriented programming requires a certain way of thinking, and getting to that can take a while. I quite like http://ircmaxell.github.io/DontBeStupid-Presentation/ as a quick, simple little explanation of SOLID along with some anti-patterns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:54:53.367",
"Id": "43033",
"Score": "0",
"body": "@Corbin, thanks for the link and push in the right direction. I agree that it will take time to fully understand and think like the OOP principles and what's come with that... Thanks anywhay for taking the time :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T02:34:42.977",
"Id": "43304",
"Score": "0",
"body": "Fighting against Corbin's suggestions doesn't help your code. The example code you have written is very difficult to unit test as it depends on global state and the creation of other objects. `__call` hides the way to interact with objects of your class, a consumer realy needs to know the implementation details of it to use this class. The public interface of the class does not convey enough information to allow it to be used easily."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T02:37:48.940",
"Id": "43305",
"Score": "0",
"body": "@Paul: Too true! There should be `callFunc` and `callProc` routines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-26T02:53:57.283",
"Id": "43306",
"Score": "0",
"body": "I disagree, I am often in the [PHP chat](http://chat.stackoverflow.com/rooms/11/php) if you want to talk about it."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-19T23:03:10.510",
"Id": "27575",
"ParentId": "27564",
"Score": "6"
}
},
{
"body": "<p>I have just a few quick tips.</p>\n\n<p><strong>Tips for OO</strong></p>\n\n<ul>\n<li>Read and understand <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\">SOLID</a>.</li>\n<li><code>$main->$config->...</code> is a violation of the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\">Law Of Demeter</a>.</li>\n<li>Dependencies should be injected. e.g <code>$object = new Object($db);</code> rather than: <code>function __construct() { $this->db = new DB; }</code></li>\n<li>Singleton is a form of global state (see <a href=\"http://googletesting.blogspot.com.au/2008/11/clean-code-talks-global-state-and.html\">here</a>). I consider it an anti-pattern which should be avoided for PHP.</li>\n</ul>\n\n<p><a href=\"http://ircmaxell.github.io/DontBeStupid-Presentation/\">Here</a> are some more good principles of object oriented design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T08:39:11.653",
"Id": "42982",
"Score": "0",
"body": "Hy, Thank you for the tips. I will read al the articels when i've got the time, and i'll be back if i've got another question. Thanks for taking the time :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T06:22:26.583",
"Id": "27580",
"ParentId": "27564",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T18:54:26.150",
"Id": "27564",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"classes",
"inheritance"
],
"Title": "Classes and variables in PHP"
}
|
27564
|
<p>I have wrote few function that grab the values from a form page and pass them to PHP
is there a way to write it better</p>
<pre><code>function resultstype(form) {
var prod_dev=form.results_type.options[form.results_type.options.selectedIndex].value;
self.location='dd.php?pd=' + prod_dev;
}
function stype(form)
{
var prod_dev=form.results_type.options[form.results_type.options.selectedIndex].value;
var stand_type=form.std_type.options[form.std_type.options.selectedIndex].value;
//alert("Stand Type : " + stdtype);
self.location='dd.php?pd='+ prod_dev + '&stdt=' + stand_type ;
}
function stand_name(form)
{
var prod_dev=form.results_type.options[form.results_type.options.selectedIndex].value;
var stand_type=form.std_type.options[form.std_type.options.selectedIndex].value;
var stand_name=form.std_name.options[form.std_name.options.selectedIndex].value;
//alert('dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name) ;
self.location='dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name ;
}
function benchmark_type(form)
{
var prod_dev=form.results_type.options[form.results_type.options.selectedIndex].value;
var stand_type=form.std_type.options[form.std_type.options.selectedIndex].value;
var stand_name=form.std_name.options[form.std_name.options.selectedIndex].value;
var bench_type=form.bench_type.options[form.bench_type.options.selectedIndex].value;
self.location='dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name + '&bt=' + bench_type;}
function racemq(form) {
var prod_dev=form.results_type.options[form.results_type.options.selectedIndex].value;
var stand_type=form.std_type.options[form.std_type.options.selectedIndex].value;
var stand_name=form.std_name.options[form.std_name.options.selectedIndex].value;
var bench_type=form.bench_type.options[form.bench_type.options.selectedIndex].value;
var racemq_ver=form.racemq_version.options[form.racemq_version.options.selectedIndex].value;
}
</code></pre>
<p>The last function will tage mutli select options.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T19:34:46.290",
"Id": "42934",
"Score": "1",
"body": "Don't. Why do you need to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T19:35:32.627",
"Id": "42935",
"Score": "2",
"body": "The code is already written, and converting it to use jQuery will not only take time, but will slow down the code. Is there a sound reasoning to do so? I can see improvements on the code that you have provided, but am still wondering the drive to make it jQuery?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:13:10.590",
"Id": "42936",
"Score": "0",
"body": "Thanks for that fast answer,\nIf the jQuery will slow the procedure then no,\nQ: is there a way to add multi select to the function ?"
}
] |
[
{
"body": "<p>I know this is out of scope, but I think there is a lot of redudant code here that can easilly be made shorter. Much shorter. Look:</p>\n\n<pre><code>function stand_name(form)\n{\n var prod_dev=form.results_type.options[form.results_type.options.selectedIndex].value; \n var stand_type=form.std_type.options[form.std_type.options.selectedIndex].value; \n var stand_name=form.std_name.options[form.std_name.options.selectedIndex].value; \n\n //alert('dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name) ;\n self.location='dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name ;\n}\n</code></pre>\n\n<p>Can be replaced by this:</p>\n\n<pre><code>function get_opt(form, type) {\n return form[type].options[form[type].options.selectedIndex].value;\n}\n\nfunction stand_name(form)\n{\n var prod_dev = get_opt(form, 'results_type');\n var stand_type = get_opt(form, 'std_type');\n var stand_name = get_opt(form, 'std_name');\n\n //alert('dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name) ;\n self.location='dd.php?pd='+ prod_dev + '&stdt=' + stand_type + '&stdn=' + stand_name ;\n}\n</code></pre>\n\n<p>...or even...</p>\n\n<pre><code>function get_opt(form, type) {\n return form[type].options[form[type].options.selectedIndex].value;\n}\n\nfunction stand_name(form)\n{\n self.location = \n 'dd.php?pd=' + get_opt(form, 'results_type')\n + '&stdt=' + get_opt(form, 'std_type')\n + '&stdn=' + get_opt(form, 'std_name');\n}\n</code></pre>\n\n<p>The same change can be applied to the other functions. It makes the code much more readable and maintaining it will be less error prone.</p>\n\n<p>Cutting down the size of your code should always be a high priority because the number of bugs increase as the size of the code goes up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T11:44:04.630",
"Id": "43105",
"Score": "0",
"body": "Hi Michael,\n\nThank you very much for your help,\n\nI will test it to see if its working ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:56:09.497",
"Id": "27607",
"ParentId": "27566",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T19:18:40.017",
"Id": "27566",
"Score": "-1",
"Tags": [
"javascript",
"php",
"mysql"
],
"Title": "How to change my code to jquery"
}
|
27566
|
<p>In my application I am attempting to queue outgoing messages by the following rules</p>
<ul>
<li>By default they should be sent no less than <code>messageDelay</code> apart</li>
<li>Some messages can be sent immediately, completely bypassing all queued messages</li>
<li>Additionally, some immediately sent messages can reset the waiting time of queued messages</li>
</ul>
<p>If this is confusing, this is what it would look like on the wire</p>
<pre><code>| Normal |Immediate |Immediate-reset|
M----------M---M------M----M----------M ....
</code></pre>
<p>This was originally handled by a dedicated OutputThread and queue but for various reasons outside of the scope of this question I am attempting to implement this with ReentrantLock and Condition so when any of the methods finally returns, the message is known to of been sent (or an Exception is thrown meaning it didn't)</p>
<p>However this is my first time using ReentrantLock and while I think I've implemented it correctly I'm needing someone to verify that its correct since this is an extremely difficult thing to test</p>
<pre><code>protected final ReentrantLock writeLock = new ReentrantLock(true);
protected final Condition writeNowCondition = writeLock.newCondition();
public void sendRawLine(String line) {
//[Verify state code]
writeLock.lock();
try {
sendRawLineToServer(line);
//Block for messageDelay. If rawLineNow is called with resetDelay
//the condition is tripped and we wait again
while (writeNowCondition.await(getMessageDelay(), TimeUnit.MILLISECONDS)) {
}
} catch (Exception e) {
throw new RuntimeException("Couldn't pause thread for message delay", e);
} finally {
writeLock.unlock();
}
}
public void rawLineNow(String line, boolean resetDelay) {
//[Verify state code]
writeLock.lock();
try {
sendRawLineToServer(line);
if (resetDelay)
//Reset the
writeNowCondition.signalAll();
} finally {
writeLock.unlock();
}
}
</code></pre>
<p>Is this the correct way to implement ReentrantLock based on my requirements above? Is there a better way (NOT USING THREADS) to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:53:56.683",
"Id": "42940",
"Score": "0",
"body": "Your code extracts only show the write side locking; how many readers are there? (otherwise, +1 for the recommended use of try/finally!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T01:48:46.627",
"Id": "42963",
"Score": "0",
"body": "@fge There is really only one single threaded reader. It just creates events and executes the listeners in a thread pool, some of which may have output"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T04:43:43.507",
"Id": "42970",
"Score": "0",
"body": "In the first method, I wouldn't catch `Exception`... It is very broad, and do not forget that it also captures all `RuntimeException`s (therefore including NPE, etc)"
}
] |
[
{
"body": "<p>I can see some problems with the code:</p>\n\n<ul>\n<li><p>As @fge mentions, catching <code>Exception</code> is problematic. You should catch the exceptions that you are expecting to occur, and let any other unchecked exceptions propagate.</p></li>\n<li><p>Wrapping the exceptions in <code>RuntimeException</code> is a bad idea <em>unless it is really necessary.</em> It is better to either let them propagate, or wrap them in a <em>custom</em> checked or unchecked exception.</p></li>\n<li><p>The behaviour of the code doesn't match your description in one respect. You talk about queuing messages. In fact, messages are being sent immediately <em>in all cases</em>, and you are delaying <em>after</em> sending the message in the <code>sendRawLine</code> case.</p></li>\n<li><p>In reality, you are blocking client threads rather using a queue data structure and a separate output thread. This might be the right things to do ... but it might be the wrong thing. It depends whether the client threads <em>should</em> be blocked until the their respective messages are sent. Either way, your characterization this as a \"message queuing\" problem is a bit misleading.</p></li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>Re: #3) The idea was to delay the next message from sending. Otherwise all calls to sendRawLine would have a weird pause before doing anything. I'm looking into using the current time though to determine if waiting is even necessary.</p>\n</blockquote>\n\n<p>First, that is NOT what your description of \"message queuing\" implies ... to me. And consider me as an examplar of <em>someone else reading your code</em>.</p>\n\n<p>Second, (if I understand you correctly) using the current time to decide to whether to wait <em>before</em> a send would require that <em>something</em> keeps track of when each thread last sent a message.</p>\n\n<p>Third, there is actually a good reason to not wait <em>before</em> sending a message. If you do wait <em>before</em> then, by the time the wait period has finished, the message could be rather out of date ... especially if there were a number of resets.</p>\n\n<p>Finally, it strikes me that you may be over-using threads here and/or that it might be better for the entity (thread or FSM) responsible for generating messages should check whether a message needs to be sent before generating it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T02:05:09.707",
"Id": "43148",
"Score": "0",
"body": "#1 and #2) I will work on the exceptions. #3) The idea was to delay the next message from sending. Otherwise all calls to sendRawLine would have a weird pause before doing anything. I'm looking into using the current time though to determine if waiting is even necessary. #4) This was intentional."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T01:10:35.113",
"Id": "27683",
"ParentId": "27567",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27683",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T19:53:41.540",
"Id": "27567",
"Score": "4",
"Tags": [
"java",
"multithreading",
"locking"
],
"Title": "Is this the best message delay algorithm?"
}
|
27567
|
<p>As an extension to <a href="https://codereview.stackexchange.com/questions/27375/pages-system-php-sql">this post</a>, I've created this class/script to handle multi-dimensional <code>Menu</code>s whose data is stored in a DB. I need some feedback and new ideas.</p>
<p><a href="http://pastebin.com/ariBn3pE" rel="nofollow noreferrer">Pastebin</a></p>
<pre><code><?php
/*
* Author: Carlos Arturo Alaniz
* Last Modified Date: 06/19/2013
* Languages: PHP/HTML/HTML
*
* Description:
* This class and script creates a multi dimentional menu
* using a SQL database and hierarchical structure
*/
class menu {
/* Constructor */
function __construct($content, $label = NULL) {
$this->ul = array('<ul>', '</ul>');
$this->li = array('<li>', '</li>');
$this->content = $content;
$this->label = $label;
}
/* Private */
private $label;
private $ul;
private $li;
private $menu_str;
/* Public */
public $content;
public function add_level($content, $id) {
$lenght = count($this->content);
for ($i = 0; $i < $lenght; $i++) {
if ($this->content[$i][1] == $id) {
$pos = $i;
break;
}
}
if (isset($pos)) {
$label = $this->content[$pos][0];
unset($this->content[$pos][0]);
$this->content[$pos][0] = $content;
$this->content[$pos][0]->label = $label;
}
}
public function print_con() {
print_r($this->content);
}
public function generateMenu() {
$this->menu_str = NULL;
$this->menu_str.= $this->ul[0];
$size = count($this->content);
for ($i = 0; $i < $size; $i++) {
$this->menu_str.= $this->li[0];
if (!is_object($this->content[$i][0]))
$this->menu_str.= $this->content[$i][0];
else {
$this->menu_str.= $this->content[$i][0]->label;
$this->menu_str.= $this->content[$i][0]->generateMenu();
}
$this->menu_str .= $this->li[1];
}
$this->menu_str .= $this->ul[1];
return $this->menu_str;
}
public function writeMenu($filepath) {
file_put_contents($filepath, $this->menu_str);
}
}
/*Connection info*/
$db_host = "localhost";
$db_user = "root";
$db_password = "EHA";
$db_database = "page_system";
$pdo = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_password);
/*Connection info*/
$qry = "SELECT MAX(parent) FROM menu";
$max_parent = $pdo->query($qry)->fetch();
$content = NULL; //Variable used to store the results of the qery
$menus_objs = array(); //Array to hold the menus and its parent id.
$obj_count = 0;
$level = NULL; // this variable its going to hold
//the last level in the tree
$parent = NULL; //This variable its going to be modified
//in each loop cycle to be later stord in the menu_objs
//array at index 1 as the parent id for that group
$level_element_count = array(); //This array uses the
//$level variable as an index and store how many objects
//exists in each level
//
//Traverse array $max_parent times and group each elements
//in menu objects according to its parent
//
for ($i = 0; $i <= $max_parent[0]; $i++) {
$qry = "SELECT * FROM menu WHERE parent = $i ORDER BY 'order' ASC";
$stmt = $pdo->query($qry);
$content_index = 0; //index for array of elements to be ineserted into a
//Create elements array to later create a menu obj
//Clear existing array before continuing
if (isset($content)) {
unset($content);
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (!isset($content)) {
$level = $row['level'];
$parent = $row['parent'];
}
$content[$content_index] = array($row['label'], $row['id']);
$content_index++;
}
//if content exists Create a menu object using the content array
if (isset($content)) {
//if the level index array is not created yet initiazlize first
//value to one otherwise increse that value this array counts
//how many objects exist in each level.
if (!isset($level_element_count[$level])) {
$level_element_count[$level] = 1;
} else {
$level_element_count[$level]++;
}
//store the object in the correct index and pair it with its
//corresponding parent id and increment the objs count by one
$menus_objs[$obj_count][0] = new menu($content);
$menus_objs[$obj_count][1] = $parent;
$obj_count++;
}
}
//add a zero and the end of level element count
$level_element_count[] = 0;
$i = $obj_count;
//Goinf backwards through the levels of the
//array of objects
for ($l = $level; $l > 0; $l--) {
$c = 0; //counter variable
for ($q = 0; $q < $level_element_count[$l]; $q++) {
$i--;
for ($upl = 0; $upl < $level_element_count[$l - 1]; $upl++) {
$k = $i + $c - $upl - $level_element_count[$l];
//
// $k is index of the corresponding upper level object
// index of object - qty of objets per level - qty of elements
// in upper level
//
echo $k;
$menus_objs[$k][0]->add_level($menus_objs[$i][0], $menus_objs[$i][1]);
}
$c++;
}
}
//At the end we should have all the data from the DB organized
//as a multi-dimentional menu we just have to call the generate menu
//method on the last level object witch its always one, obj [0][0]
$menus_objs[0][0]->generateMenu();
$menus_objs[0][0]->writeMenu("../menu.html");
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T06:51:34.623",
"Id": "42977",
"Score": "0",
"body": "`lenght` should be `length`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T11:36:17.633",
"Id": "116264",
"Score": "0",
"body": "The word in square brackets is the alt text, which gets displayed if the browser can't show the image. Be sure to include meaningful alt text for screen-reading software."
}
] |
[
{
"body": "<p>This code is too complex. It is going to be difficult to maintain or reuse.</p>\n\n<h1>Current Issues</h1>\n\n<p>I see the following problems with the code as it is:</p>\n\n<ul>\n<li>Method names are not consistent: <code>lower_pascal_case</code> is mixed with <code>lowerCamelCase</code></li>\n<li>Hard-coded values of 0 and 1 make the code difficult to read.</li>\n<li>Public property <code>$content</code> takes away from the <a href=\"http://en.wikipedia.org/wiki/Information_hiding\" rel=\"nofollow\">information hiding</a>.</li>\n<li>One letter variables take away from readability. In a few lines of code I see <code>$k$i$c$q</code> (it looks like \"Kick You\" to me).</li>\n<li>Not reusable. You are going to have to copy and paste to reuse this.</li>\n<li>Mixed paradigms. Object Oriented for the view, Procedural for the Model/Persistence. Why not use the same paradigm for both?</li>\n</ul>\n\n<h1>Suggestions</h1>\n\n<p>I can't actually understand your implementation. If it <em>works</em> then I guess it is doing what you want already.</p>\n\n<p>There are a few ways of storing hierarchical data in a flat structure. Read <a href=\"http://www.sitepoint.com/hierarchical-data-database/\" rel=\"nofollow\">hierarchical data in a database</a> especially page 2 and 3 which talk about Modified Preorder Tree Traversal (MPTT). Using MPTT provides you with interesting ways of accessing the menu tree or subtree.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T15:10:38.307",
"Id": "43013",
"Score": "0",
"body": "Thanks for the suggestions, After reading that I think I had the correct idea (Kind of) so Im going to try to re write the code in a cleaner way.. thanks for that warning for the $content variable.\n\nAnd my basic idea was group the elements by their parent id and create menu objs out of them, using the 'level' column in my db I know where each opbj goes (level wise) after that I just traverse the array of objs backwards trying to add each obj to a upper level obj creating at the end a menu obj that contains everything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T03:44:05.460",
"Id": "27578",
"ParentId": "27569",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27578",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:38:43.643",
"Id": "27569",
"Score": "2",
"Tags": [
"php",
"sql",
"array"
],
"Title": "Storing hierarchical data in a database"
}
|
27569
|
<p>I'm currently developing a music website using OOP PHP and I'm trying to correctly implement the Model View Controller pattern.</p>
<p>I am creating this website from scratch so I would like to avoid answers suggesting I use frameworks such CakePHP etc please.</p>
<p>Here are simplified snippets of the files I'm using to generate a page on my site that displays an album release.</p>
<p><strong>albumView.php (VIEW)</strong></p>
<pre><code><?php
include_once($_SERVER['DOCUMENT_ROOT'].'/../app/config.php');
include('commonHead.php'); //shared site head
include('htmlHeader.php'); //shared website header
$album = new AlbumController(); //instantiate controller
?>
<div id="main">
<article>
<header>
<h1><?php $album->echoArtist(); ?></h1>
</header>
<?php if($album->isTracklisting()) : ?>
<section id="tracklisting">
<header>
<h1>TRACK LISTING</h1>
</header>
<ol>
<?php $album->echoTracklisting() ?>
</ol>
</section>
<?php endif ?>
...etc...
<?php
include('htmlFooter.php');
include('commonFoot.php');
?>
</code></pre>
<p><strong>AlbumController.php (CONTROLLER)</strong></p>
<pre><code>//Inherits shared page display fields and functions
class AlbumController extends PageController
{
private $albumModel;
public function __construct()
{
parent::__construct();
//Instantiate new album model
$this->albumModel = new AlbumModel($this->getDate, $this->getRelease);
}
public function echoArtist()
{
echo $albumModel->artist;
}
public function isTracklisting()
{
if(!$this->strEmpty($albumModel->tracklisting)) return true;
}
public function echoTracklisting()
{
$songArray = explode(',', $albumModel->tracklisting);
foreach($songArray as $song) {
...various logic...
$html = '<li class="'.$class.'" '.$mp3Data.'>'.$song.'</li>';
echo $html;
}
}
...etc...
</code></pre>
<p><strong>PageController.php (CONTROLLER SUPER CLASS)</strong></p>
<pre><code>abstract class PageController
{
protected $getDate;
protected $getRelease;
function __construct()
{
if(isset($_GET['date'])) $this->getDate = $_GET['date'];
if(isset($_GET['release'])) $this->getRelease = $_GET['release'];
}
...etc...
</code></pre>
<p><strong>AlbumModel.php (MODEL)</strong></p>
<pre><code>class AlbumModel
{
//Album data variables
public $artist;
public $album;
public $genre;
public $releaseDate;
public $tracklisting;
private $db;
private $getDate;
private $getRelease;
public function __construct($getDate, $getRelease)
{
$this->getDate = $getDate;
$this->getRelease = $getRelease;
//Create new db object
$this->db = new Database();
//Get album array from db
$albumArray = $this->getAlbumArrayFromDB();
//Assign variables
$this->artist = $albumArray['artist'];
$this->album = $albumArray['album'];
$this->genre = $albumArray['genre'];
$this->releaseDate = $albumArray['date'];
$this->tracklisting = $albumArray['tracklisting'];
}
private function getAlbumArrayFromDB()
{
//Query DB
$sql = 'SELECT * FROM releases WHERE date = '.$this->getDate.' AND release_number = '.$this->getRelease;
$qId = $this->db->query($sql);
$albumArray = $this->db->fetch_array_assoc($qId);
return $albumArray;
}
...etc...
</code></pre>
<p>And my config.php defines constants and imports all my classes</p>
<p><strong>config.php</strong></p>
<pre><code>//Paths
define('ABS_PATH', dirname(__FILE__));
//Database
define('DB_NAME', 'myname');
define('DB_USER', 'myuser');
define('DB_PASSWORD', 'mypass');
define('DB_HOST', 'myhost');
...etc...
//Import all classes
foreach(glob(dirname(__FILE__).'/classes/*.php') as $classPath) {
require_once($classPath);
}
</code></pre>
<p>Am I understanding and implementing the MVC design pattern correctly?</p>
<p>I know strictly speaking it's not best practice to access instance variables directly (e.g. $albumModel->artist) but with dozens of additional variables it seems overkill/unnecessary to create getter functions for each one and then redefine them all again in the controller. I put these here because as I understand it the model defines the data, but I could just return an array to the controller and define these variables there?</p>
<p>Anything I'm missing or best practices I'm not adhering to?</p>
<p>Any advice greatly appreciated.</p>
<p>Many thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:07:45.173",
"Id": "42942",
"Score": "0",
"body": "Mostly you are missing MVC. Also adhering to few OOP practice and principles would be preferable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:08:12.137",
"Id": "42943",
"Score": "0",
"body": "Even if you don't want to use an existing framework it would be a good idea to look at some of them (FuelPHP, Laravel, CodeIgniter, Zend, etc.) to see how they do things and why. I would not include files (like header/footer/etc.) the way you are in your view. If you ever decide to have a \"header2\" you'll have to change every one of your views..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:10:53.360",
"Id": "42944",
"Score": "0",
"body": "In your example controller, you are generating HTML and just echoing it, then letting your view call that function. Ideally, a controller generates data (from the model) and returns it to the view and the view is responsible for the HTML-rendering work. In your code, they are more coupled than a controller and view should be.\n\nI agree with @BennyHill. Why do you not want to use an existing framework? Nobody says you have to use an existing one, but don't try to reinvent the wheel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:11:11.750",
"Id": "42945",
"Score": "0",
"body": "Not using a framework for this is just wasted time trying to reinvent the wheel. Use Yii that is easy to learn, try to make some pages and then you will have knowledge about MVC."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:11:55.423",
"Id": "42946",
"Score": "0",
"body": "@Jorge .. only sad that Yii is complete nightmare that does not even implement MVC. It's a bad clone of Django."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:12:16.253",
"Id": "42947",
"Score": "0",
"body": "There are probably more MVC interpretations, then developers at all, so you can't misunderstand it. You can just do it your way. ;) But building your own app architecture doesn't mean you shouldn't look into some frameworks so you could see how it CAN BE done. You would learn a lot. Referring to your code, I think you should learn a lot about OOP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:19:50.810",
"Id": "42948",
"Score": "0",
"body": "[SOLID is a good place to start with regards to OOP](http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29). Follow the links in the design and development principles section too."
}
] |
[
{
"body": "<h3>albumView.php</h3>\n<p>Views are not glorified templates. They should be instances that acquire data from model layer and, based on that information, produce a response for the user.</p>\n<p>Views <strong>do not</strong>:</p>\n<ul>\n<li>initialize controllers</li>\n<li>load configuration</li>\n</ul>\n<p>What you currently have is not a view. It looks more like some variation on newbie's index.php file, that include everything ad outputs HTML.</p>\n<h3>AlbumController.php</h3>\n<p>The responsibility of controller in MVC design pattern is to alter the state of model layer and (sometimes) the current view instance, based on user's request.</p>\n<p>Controllers <strong>do not</strong>:</p>\n<ul>\n<li>create instances from model layer</li>\n<li>route the request</li>\n<li>generate HTML</li>\n<li>extract data from model layer</li>\n</ul>\n<h3>AlbumModel.php</h3>\n<p>Model in MVC design pattern is a layer. <strong>Not</strong> a class or object. There are no "models". It is a singular layer that contains application, domain and storage logic.</p>\n<blockquote>\n<p><sub><strong>P.S.:</strong> You obviously have no (or almost no) experience with OOP paradigm. You could start by watching/reading material that are listed <a href=\"https://stackoverflow.com/a/16356866/727208\"><strong>here</strong></a>. This might provide you with a better grasp on the underlaying concepts.</sub></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T19:27:25.627",
"Id": "61058",
"Score": "0",
"body": "@teresko You stated \"Controllers do not extract data from model layer\", surely they do if view requires data which needs to be processed? This would then be view->controller->model->controller->view ? ie view requests, controller grabs data from model (DB), controller checks it (whatever reason, makes sure it matches user input or perform some calculations based on view's request) then controller hands to view as an object (or array or variable) for view to output? (great answer, just trying to fine tune my understanding of it)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T20:00:57.857",
"Id": "61067",
"Score": "0",
"body": "First of all, model layer is not synonymous with \"DB\". And you seem to assumes that \"view\" is a just a different name for template. It's a common form of misinformation, spread by Rails and Rails-like frameworks. I would suggest you to start with reading [quick overview](https://en.wikipedia.org/wiki/Model_view_controller) about the pattern (yes, it's wikipedia, deal with it). Pay special attention to the **diagram** on the side and \"component interactions\" section. When you re do with it, head over to [this article](http://martinfowler.com/eaaDev/uiArchs.html). That should explain the basics."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:28:23.307",
"Id": "27571",
"ParentId": "27570",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27571",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T20:00:12.330",
"Id": "27570",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"mvc"
],
"Title": "Is this correct implementation of MVC pattern for PHP website?"
}
|
27570
|
<p>I have built a 3D matrix class in C++, mainly for data I/O, for a project I am working on. The code works ok, but I would like you to help me improve it.</p>
<ol>
<li>Are there any bad programming practices I am doing?</li>
<li>Is there any code that could be simplified?</li>
<li>Is there something that would give me fastest access to the data stored in the object? 4. Is there something that could lead me to error in the future?</li>
</ol>
<p>Grid3d.h:</p>
<pre><code>#ifndef _GRID3D_
#define _GRID3D_
#include <iostream>
#include <cmath>
#include <iomanip> // setprecision()
#include <cassert> // assert()
using namespace std;
class Grid3d
{
private:
int L;
int M;
int N;
double *** G;
public:
//Constructors
Grid3d(int,int,int);
Grid3d();
Grid3d(const Grid3d &);
~Grid3d();
//Operators
double & operator()(int,int,int);
Grid3d & operator=(Grid3d);
//Access
int get_L();
int get_M();
int get_N();
double get(int,int,int);
void clean();
void swap(Grid3d &);
friend std::ostream & operator<< (std::ostream &,Grid3d &);
};
#endif
</code></pre>
<p>Grid3d.cc:</p>
<pre><code>#include "Grid3d.h"
//Constructor
Grid3d::Grid3d(int L,int M,int N)
:L(L), M(M), N(N)
{
int i,j,k;
G = new double ** [L];
for (i=0;i<L;i++){
G[i] = new double * [M];
for (j=0;j<M;j++){
G[i][j] = new double [N];
for (k=0;k<N;k++){
G[i][j][k] = NAN;
}
}
}
}
//Empty constructor
Grid3d::Grid3d()
:L(0), M(0), N(0)
{
G = NULL;
}
//Copy constructor
Grid3d::Grid3d(const Grid3d &A)
:L(A.L), M(A.M), N(A.N)
{
G = new double ** [L];
int i,j,k;
for (i=0;i<L;i++){
G[i] = new double * [M];
for (j=0;j<M;j++){
G[i][j] = new double [N];
for (k=0;k<N;k++){
G[i][j][k] = A.G[i][j][k];
}
}
}
}
//Destructor
Grid3d::~Grid3d()
{
// Free memory
for (int i=0;i<L;i++){
for (int j=0;j<M;j++){
delete [] G[i][j];
G[i][j] = NULL;
}
delete [] G[i];
G[i] = NULL;
}
delete G;
G = NULL;
}
//------------------------------------------------------------------
// Operators
//------------------------------------------------------------------
//Access operator ():
double& Grid3d::operator()(int i,int j,int k)
{
assert(i >= 0 && i < L);
assert(j >= 0 && j < M);
assert(k >= 0 && k < N);
return G[i][j][k];
}
//Assignment operator
Grid3d& Grid3d::operator = (Grid3d A)
{
swap(A);
return *this;
}
//------------------------------------------------------------------
// Access
//------------------------------------------------------------------
int Grid3d::get_L()
{
return L;
}
int Grid3d::get_M()
{
return M;
}
int Grid3d::get_N()
{
return N;
}
double Grid3d::get(int i,int j,int k)
{
return G[i][j][k];
}
void Grid3d::clean()
{
int i,j,k;
for (i=0;i<L;i++){
for (j=0;j<M;j++){
for (k=0;k<N;k++){
G[i][j][k] = NAN;
}
}
}
}
//------------------------------------------------------------------
// Others
//------------------------------------------------------------------
//Swap
void Grid3d::swap(Grid3d & A)
{
std::swap(L, A.L);
std::swap(M, A.M);
std::swap(N, A.N);
std::swap(G, A.G);
}
//cout
std::ostream & operator << (std::ostream & os , Grid3d & g)
{
int L = g.get_L();
int M = g.get_M();
int N = g.get_N();
for (int k=0;k<N;k++){
cout << "k = " << k << endl;
for (int i=0;i<L;i++){
for (int j=0;j<M;j++){
cout.width(10);
os << setprecision(3) << g.G[i][j][k] << " ";
}
os << endl;
}
os << endl;
}
return os;
}
</code></pre>
<p>This is a sample function in which I am using these objects to evaluate the curl of a vector field in a point:</p>
<pre><code>double System::curl_r(Grid3d &Ath,Grid3d &Aph,int i,int j,int k)
{
double curl_rA = ( (SIN[j+1]*Aph(i,j+1,k)-SIN[j-1]*Aph(i,j-1,k))/dth - (Ath(i,j,k+1)-Ath(i,j,k-1))/dph )/(2.0e0*R[i]*SIN[j]);
return curl_rA;
}
</code></pre>
<p>For example:</p>
<pre><code>Grid3d Er = Grid3d(Nr,Nth,Nph);
Grid3d Eth = Grid3d(Nr,Nth,Nph);
Grid3d Eph = Grid3d(Nr,Nth,Nph);
Grid3d curlE_r = Grid3d(Nr,Nth,Nph);
...
curlE_r(i,j,k) = curl_r(Eth,Eph,i,j,k);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:29:27.563",
"Id": "43039",
"Score": "1",
"body": "I just noticed something, and as you're unlikely to read through a giant answer answer again, I figured I'd make a comment. Your `delete G`; should be `delete[] G;` since you allocated the contents of `G` with `new[]`."
}
] |
[
{
"body": "<p>We can improve this code.</p>\n\n<p><strong>1:</strong> First of all, I urge you to <strong>change your underlying data structure.</strong> <code>double *** G;</code> hurts my eyes. Consider using for example <code>std::vector<std::vector<std::vector<double> > ></code> instead. (If you are using C++11, you can drop the spaces. Yay!) Using <code>std::vector</code> has a plethora of advantages. The two most important are that it will be easier to get the code to work correctly, the other is readability.</p>\n\n<p>If for some masochistic reason you don't want to use <code>std::vector</code> or a similar type, at least use arrays instead of raw pointers.</p>\n\n<p><strong>2:</strong> <code>L</code>, <code>M</code>, <code>N</code> and <code>G</code> are horrific variable names. Consider using for example <code>width</code>, <code>length</code>, <code>depth</code> and <code>matrix</code> -- or something along those lines -- instead. The same goes for your getter functions.</p>\n\n<p><strong>3:</strong> Your output stream operator (<code>operator<<</code>) doesn't use any private members of <code>Grid3d</code> (which is good!), so it should not be declared as a <code>friend</code> of the class.</p>\n\n<p><strong>4:</strong> You can safely use <code>std::swap()</code> directly on your object.</p>\n\n<p><strong>5: Your class is using <em>destructive assignment</em>.</strong> This <em>could</em> be okay if it's a well thought-out design decision. In almost all cases, however, it is better to make a (deep) copy of your object.</p>\n\n<p><strong>6: Your class is <em>not</em> exception-safe.</strong> Much of the reason for this is that it fiddles with raw pointers. In C++, we try to avoid pointers to owned resources whenever we can. Putting your <code>double</code>s into a <code>std::vector</code> will take care of a lot of this.</p>\n\n<p><strong>7: Use more whitespace.</strong> <code>for (i=0;i<L;i++){</code> is not very easy on the eye. <code>for (i = 0; i < L; i++) {</code> is much better.</p>\n\n<p><strong>8:</strong> <strike>You probably want to <strong>use</strong> <code>operator[]</code> <strong>instead of</strong> <code>operator()</code> <strong>for indexing operations.</strong> When in doubt, do as the built-ins do, and arrays use <code>foo[42]</code> for indexing.</strike> Update: For multiple indices, it's perfectly okay to use <code>operator()</code>.</p>\n\n<p><strong>9: Use as few <code>#include</code>s as possible in your header file.</strong> Move what you can into your implementation file. After removing the <code>friend</code> declaration (as discussed in point 3), you can move <em>all</em> your <code>#include</code>s to your implementation file.</p>\n\n<p><strong>10: Don't ever have <code>using</code> statements or <code>using</code> directives in a header file.</strong> Any file <code>#include</code>ing your header will have its global namespace polluted. You don't want that. Use full namespace specifiers in header files. You are already doing this, so the <code>using</code> directive can safely be removed.</p>\n\n<p>There are some other issues, but these are the most important ones. They should give you something to work on. I suggest you create a new thread with your improved code after incorporating these changes, for further feedback.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T01:03:01.067",
"Id": "42960",
"Score": "1",
"body": "Agreed, except for **8**. It's fairly common practice to overload `operator()` when you need to index something with multiple indices."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T01:05:03.643",
"Id": "42961",
"Score": "0",
"body": "@Yuushi Oh, right, multiple indices. You are completely correct, I'll edit my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T18:19:11.103",
"Id": "43123",
"Score": "0",
"body": "There can be efficiency considerations with a contiguous memory block. So potentially std::vector<double> to do the memory management and then do the appropriate calculations in `operator()` or `operator[]`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T00:13:41.683",
"Id": "27576",
"ParentId": "27573",
"Score": "9"
}
},
{
"body": "<p>I have a few things to add to Lstor's review (and a few things to repeat).</p>\n\n<hr>\n\n<p><code>double***</code> makes me cry. That's just waiting for some weird exception safety problem or a memory leak. As Lstor said, use a vector (thoug technically <code>std::vector< std::vector< std::vector<double> > ></code>, not <code>std::vector<std::vector<double> ></code> as he said).</p>\n\n<p>Or, if you really want to use raw allocation, at least use <code>std::unique_ptr</code> so you have exception safety.</p>\n\n<p>Fun bonus: if you use vectors, you actually won't need your swap (which you don't need now), destructor or <code>operator=</code> as the default ones will work.</p>\n\n<hr>\n\n<p>Your dimensions should be <code>std::size_t</code>s rather than <code>int</code>s.</p>\n\n<hr>\n\n<p>It doesn't apply quite as much here since meaningful names are rather hard to come up with, but in general, you should always use named parameters in your class declarations.</p>\n\n<p><code>Grid3d(int,int,int);</code> doesn't exactly tell me much about what I'm passing to the constructor. <code>Grid3d(int L, int M, int N);</code> tells me more. <code>Grid3d(int width, int height, int depth);</code> tells me a lot more (though it brings up a rather difficult problem of what you would name a fourth dimension if you were to have one)</p>\n\n<hr>\n\n<p><code>clean</code> is a bad name. I wouldn't expect clean to mean set everything to <code>NAN</code>. I would name it <code>reset</code> or <code>nullify</code> or something. Or, better yet, have a method called <code>setAll(double val)</code> that sets the entire matrix. That way the ambiguity of what you're setting it to is gone (and you don't have to duplicate your constructor loop and your clear loops).</p>\n\n<hr>\n\n<p>Declare variables as tightly scoped as possible.</p>\n\n<pre><code>void Grid3d::clean()\n{\n for (int i=0; i < L; i++){\n for (int j=0; j < M; j++){\n for (int k=0; k < N; k++){\n G[i][j][k] = NAN;\n } \n }\n }\n}\n</code></pre>\n\n<p>(And once again, those ints should be <code>std::size_t</code>.)</p>\n\n<hr>\n\n<p>You should have a const getter too. Not having one destroys all possibilities of const correctness with usage of your class. For example, it would be nice if <code>operator<<</code> took a const <code>Grid3d</code> instead of a mutable one. Or what about <code>curl_r</code>? If I saw the declaration of that, I would wonder why in the world calculating the curl changes the vectors.</p>\n\n<hr>\n\n<pre><code>T v = ...;\nreturn v;\n</code></pre>\n\n<p>Should usually just be <code>return ...;</code></p>\n\n<p>But in this case, your statement should probably be broken into more digestable pieces:</p>\n\n<pre><code>const double part1 = ...; //With a better name than part1, ideally\nconst double part2 = ...;\nconst double part2 = ...;\nreturn (part1 * part2) + part3;\n</code></pre>\n\n<p>(This in no way resembles your formula, but I have depressingly little memory of what the different parts mean, so I have no idea how to meaningfully break it apart).</p>\n\n<hr>\n\n<p>I like to declare variables that I don't plan on changing as <code>const</code>. That way, 4 lines later, when I decide I want to reuse <code>width</code> (or whatever), I get an error instead of then having the wrong value 2 more lines down when I think I'm using the original width again. Then again, there is definitely a potential to over do it :).</p>\n\n<hr>\n\n<p>This one is mostly personal preference, but I find spaced out arithmetic operators a million times easier to read. <code>4+3*2</code> vs <code>4 + 3 * 2</code> (though I would also parenthesize that).</p>\n\n<hr>\n\n<p>(This one is 80% personal preference.)</p>\n\n<p>I find middle-reference style awkward. I like either <code>T& t</code> or <code>T &t</code> (personally, I hugely prefer <code>T& t</code> as I see the reference being part of the type, not part of the variable).</p>\n\n<p><code>std::ostream & operator << (std::ostream & os , Grid3d & g)</code> Is weird to read for me. I would use: <code>std::ostream& operator<<(std::ostream& os , Grid3d& g)</code>.</p>\n\n<p>(And I would actually use <code>std::ostream& operator<<(std::ostream& os , const Grid3d& g)</code>.</p>\n\n<hr>\n\n<p>Being a bit pedantic, <code>clean</code> could use the class' getter rather than direct access to G. That way if you change something about G, you only have to alter it in one place.</p>\n\n<p>(If you're worried about performance, <code>get</code> will likely be inlined anyway meaning it will have no overhead. You would of course want to profile though if performance is an issue.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T10:48:40.417",
"Id": "42995",
"Score": "3",
"body": "`inline` is basically a compiler suggestion. The compiler is free to do its own cost/benefit analysis and completely ignore it. For something as simple as a getter/setter, however, on any kind of reasonable optimization level, it's almost 100% guaranteed to be inlined automatically anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T18:05:56.323",
"Id": "43022",
"Score": "1",
"body": "+1. Good points! Also, like @Yuushi points out, `inline` is just a hint to the compiler, which is free to do what it wants. Defining a function in the class definition is the same as declaring it `inline`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:24:53.667",
"Id": "43026",
"Score": "0",
"body": "Ah, seems I need to do some reading on inline. I've been procrastinating it for years now :)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T08:41:04.097",
"Id": "27583",
"ParentId": "27573",
"Score": "6"
}
},
{
"body": "<p><strong>Quickie style issues</strong></p>\n\n<p>Several of these were mentioned in the other answers and some of them weren't.</p>\n\n<ul>\n<li><p>You should generally not write code in the global namespace. There are a number of good reasons for this, but this margin is too small to contain them. <a href=\"https://softwareengineering.stackexchange.com/questions/50120/best-practices-for-using-namespaces-in-c\">The programmers stackexchange has some of them</a>.</p></li>\n<li><p>You usually shouldn't call <code>std::swap</code> directly, though here it is harmless. You should get in the habit of swapping like this: <code>using std::swap; swap(foo, bar);</code> It won't cause a different <code>swap</code> to be used here, but you shouldn't try to keep in your head which namespace <code>swap</code> comes from for each type you use (see <a href=\"https://stackoverflow.com/questions/6380862/how-to-provide-a-swap-function-for-my-class\">this stackoverflow question</a> for more discussion on <code>swap</code> and argument-dependent lookup). I discuss <code>swap</code> a bit more later.</p></li>\n<li><p>Dimensions should generally be passed as <code>size_t</code>, not <code>int</code>.</p></li>\n<li><p>You should not put <code>using</code> statements in a header unless inside a function (or sometimes class) definition. You should <em>especially</em> not put <code>using</code> statements in the global namespace in a header (and usually not in a source file -- put <code>using</code> statements in a namespace to prevent symbol clashes and ODR violations during linking).</p></li>\n<li><p>You should name the arguments in your header file. Names are the primary form of API documentation and you've got none of that at all in this header file. As LStor mentioned, the names you do have are not great, especially <code>L</code>, <code>get_L</code>, etc.</p></li>\n<li><p>What is <code>clean</code> supposed to be doing? Are you trying to pollute your surrounding data with NANs in order to detect use of an uninitialized grid? Consider <code>clear</code> instead with 0s instead of NANs, or maybe <code>setAll</code> as Corbin suggests.</p></li>\n</ul>\n\n<p><strong>Underlying data structure</strong></p>\n\n<p>I (mostly) disagree with the other answers about <code>double***</code>. This is exactly the sort of class that should use a contiguous array as its underlying data structure. You get exception safety by deleting the memory in your destructor (that, after all, is all that smart pointers do!). However, you're losing any efficiency gain of using the raw data structure by creating an array for each row. Instead, use a <code>double*</code> as your underlying memory like so:</p>\n\n<pre><code>class Grid3d {\n private:\n size_t L, M, N;\n double* buffer;\n public:\n Grid3d(size_t L, size_t M, size_t N)\n : L(L), M(M), N(N), buffer(new double[L * M * N]) {}\n ~Grid3d() { delete [] buffer; }\n /* ... */\n};\n</code></pre>\n\n<p>This has the following advantages over your <code>double***</code> approach and over the <code>vector</code>-based approaches suggested in the other answers.</p>\n\n<ul>\n<li><p>The buffer is allocated with a single allocation, which:</p>\n\n<ul>\n<li>reduces heap fragmentation</li>\n<li>reduces the number of system calls (so is faster)</li>\n<li>eliminates the possibility of partial allocation, which genuinely was an exception-safety issue with the previous implementation.</li>\n</ul></li>\n<li><p>Element accesses will require only one memory lookup, instead of 3.</p></li>\n</ul>\n\n<p>This approach is in line with <a href=\"http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/\" rel=\"nofollow noreferrer\">Herb Sutter's excellent guideline</a>:</p>\n\n<blockquote>\n <p>Don’t use explicit new, delete, and owning * pointers, except in rare cases encapsulated inside the implementation of a low-level data structure.</p>\n</blockquote>\n\n<p>This is one of those low-level data structures.</p>\n\n<p><strong>Allow your class to be used correctly when const.</strong></p>\n\n<p>It is a good general guideline to declare variables const whenever possible. If you didn't wish to make your class assignable and swappable, I'd suggest making its dimensions const. As it is, your users have no way to access the data in the grid when the <code>Grid3d</code> is passed to functions by constant reference, for example (as the <code>Grid3d</code> arguments should be passed to <code>System::curl_r</code> in your example). Here's a solution:</p>\n\n<p>Add a private function to share the index calculation logic:</p>\n\n<pre><code>size_t compute_index(size_t i, size_t j, size_t k) const {\n return i * (M * N) + j * N + k; // untested\n}\n</code></pre>\n\n<p>Replace <code>get(int, int, int)</code> by <code>get(int, int, int) const</code>:</p>\n\n<pre><code>double Grid3d::get(size_t i, size_t j, size_t k) const {\n /* add bounds checking */\n return buffer[compute_index(i, j, k)];\n}\n</code></pre>\n\n<p>Add <code>const</code> and non-<code>const</code> versions of <code>operator()</code>:</p>\n\n<pre><code>double& Grid3d::operator()(size_t i, size_t j, size_t k) {\n return buffer[compute_index(i, j, k)];\n}\ndouble Grid3d::operator()(size_t i, size_t j, size_t k) const {\n return buffer[compute_index(i, j, k)];\n}\n</code></pre>\n\n<p><strong>Swap correctness</strong></p>\n\n<p><code>std::swap</code> actually correctly swaps your type (as LStor points out) because its member variables are all built-in types (this is sufficient but not necessary). You needn't provide a <code>swap</code> method at all, but if you do you can write it as</p>\n\n<pre><code>void Grid3d::swap(Grid3d& other) {\n using std::swap;\n swap(*this, other);\n}\n</code></pre>\n\n<p>Using the <code>using std::swap;</code> construction as I have is unnecessary because you know that you actually will be using <code>std::swap</code>, not doing ADL. However, as mentioned above, it's good to get in the habit of doing this because it's absolutely necessary when the arguments to <code>swap</code> are of unknown type, as when writing a template (<code>begin</code> and <code>end</code> are the other two functions which merit this treatment).</p>\n\n<p><strong>The assignment operator</strong></p>\n\n<p>You'll want to provide two assignment operators:</p>\n\n<pre><code>Grid3d& Grid3d::operator=(Grid3d&& other) {\n swap(other);\n return *this;\n}\nGrid3d& Grid3d::operator=(Grid3d other) {\n swap(other);\n return *this;\n}\n</code></pre>\n\n<p>The move-assignment operator prevents an unnecessary copy in expressions like <code>grid1 = std::move(grid2)</code>.</p>\n\n<p>There are, of course, other areas of improvement, but this should be enough to get you started.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T18:26:29.630",
"Id": "43023",
"Score": "0",
"body": "Many good points. However, except if writing an industrial-strength library for numeric computations, your suggestion about a `double*` is simply premature optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:28:46.447",
"Id": "43027",
"Score": "2",
"body": "You're right that a `double*` would have much better performance than a `double***`. One of us probably should have said that sooner. 3 levels of indirection is going to murder the cache, not to mention all the load/store. It could still easily be a std::vector<double> instead of double* though. And, this is *not* a low level data structure. Using a single dimensional vector is going to offer the same performance as a single dimensional array on all but the worst compilers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:37:40.213",
"Id": "43031",
"Score": "0",
"body": "His assignment operator is fine by the way. It's just the classic copy and swap idiom (which is typically done as a simple method of getting a strong exception guarantee -- something your operator= does not offer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T19:57:19.340",
"Id": "43035",
"Score": "0",
"body": "@Corbin With a double*** that gets deleted by the constructor, it is absolutely not fine. It goes like this. Start with the code Grid3d a(10, 10, 10); Grid3d b; b = a; When b = a is computed, a is copied (and in particular, a.G is copied). Now the copy and b are swapped. b.G == a.G. When a and b go out of scope, they'll both delete G. However, if Grid3d were implemented with a vector, you'd be right; copy and swap would be fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:01:14.013",
"Id": "43037",
"Score": "0",
"body": "@Lstor It's really not a premature optimization. You should not sacrifice code clarity in return for unnecessary optimization, that is true. But a vector<vector<vector<double>>> is actually far less clear than a double*, and insisting on it is premature pessimization. Whether you use a vector or a double* here is a matter of taste, I suppose, but it's not completely clear either way. After all, this buffer is not logically a vector."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T20:22:26.913",
"Id": "43038",
"Score": "0",
"body": "@ruds G is deeply copied though. Consider: `Grid3d a(10, 10, 10); Grid3d b(a);`. You've assumed that `a.G == b.G`, but this is not the case. The copy of A and A will not point to the same G, thus there's no double deletion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T22:23:51.800",
"Id": "43042",
"Score": "0",
"body": "@Corbin My mistake. I didn't notice the copy constructor and based my comment on the default copy constructor."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T15:07:48.883",
"Id": "27599",
"ParentId": "27573",
"Score": "3"
}
},
{
"body": "<p>A few points mostly regarding efficiency:</p>\n\n<ul>\n<li>As @ruds said, use a contiguous array. I would use a <code>vector<double></code> instead of the <code>double *</code> he suggests, as this simplifies many member functions, at a trivial extra overhead.</li>\n<li>Try to decouple the <em>size</em> of the leading dimension of your array (i.e. the one whose elements you store contiguously) from its <em>allocation</em>. This allows you to e.g. store 35*10*10 array in a structure with 36*10*10 elements. If you want to make use of the vector processing units (SSE3, Velocity Engine, etc.) that many modern processors have, having structures aligned to 2- or 4-element boundaries can bring tremendous performance benefits. For this reason, numeric libraries like BLAS and LAPACK tend to have separate parameters for the size and allocation of the leading dimension.</li>\n<li>If your problem is suitable for <code>float</code> instead of <code>double</code>, that is also a tremendous performance win.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T17:58:31.563",
"Id": "27605",
"ParentId": "27573",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T21:47:19.347",
"Id": "27573",
"Score": "3",
"Tags": [
"c++",
"matrix"
],
"Title": "Simple matrix class"
}
|
27573
|
<p>We have orange rounded buttons as a standard on our site. For our purposes, we switched everything over to use an anchor tag, instead of input type=button. The exception to this was the File Upload Control. For security reasons, you can't write your own, and since buttons in IE can't be rounded with pure CSS, I decided to use a combination of other people's solutions. I set the Opacity to 0, for the real File Input, and the z-index to 999. For the fake anchor and textbox, which are styled properly, I moved them to the same space that the File Input takes up, but they're underneath it in the layers. So, the File Input doesn't show up, but when people think they're clicking the anchor tag, they're really getting the File Input.</p>
<p>I've tested this in the browsers that we require support for, and it's definitely functional and looks good. I'm curious as to whether this has any glaring holes that I've missed.</p>
<pre><code><div class="editor-field" style="white-space: nowrap;">
<input type="file" name="file" id="file" class="hide-file-input" />
<input type="text" id="file-fake" class="k-textbox fileinput-textbox" />
<span class="file-button-wrapper"><a class="button" id="fileButton">Browse</a></span>
</div>
</code></pre>
<p>Here is the associated script:</p>
<pre><code><script type="text/javascript">
$(document).ready(function () {
$('#file').change(function (e) {
$('#file-fake').val($('#file').val());
});
});
</script>
</code></pre>
<p>And finally, here is the relevant CSS for positioning and hiding these elements:</p>
<pre><code>input.fileinput-textbox {
float: left;
position: absolute;
width: 158px !important;
left: 117px;
display: inline-block;
}
.file-button-wrapper {
float: left;
background-color: #ffffff;
position:absolute;
margin: 0;
padding: 5px;
width: 70px;
height: 20px;
left: 273px;
display: inline-block;
}
.hide-file-input {
opacity: 0;
filter: alpha(opacity = 0);
-ms-filter: "alpha(opacity=0)";
z-index: 999;
line-height: 0;
position: relative;
overflow:hidden;
width: 240px;
}
</code></pre>
<p>The only drawback I've found is that the script only shows the file name, not the path, like the real File Input would. This isn't a problem for our business unit, though, so I haven't even checked to see if I could show the full path. (I think it's a benefit, personally). Other solutions seem to want to throw the File Input off the screen altogether, but I couldn't see a reason not to do it this way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:09:01.707",
"Id": "43517",
"Score": "2",
"body": "FYI: revealing the path to the file to JavaScript is considered a security vulnerability, which is why only the native form control has access to it. Some older browsers (particularly older IE) grant you access to the full file path."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T11:19:10.153",
"Id": "67351",
"Score": "0",
"body": "May I ask why you can't just use buttons and style them with CSS? Rounded corners are possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T16:23:00.960",
"Id": "67517",
"Score": "0",
"body": "As I said in the original question \"buttons in IE can't be rounded with pure CSS\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T21:20:09.463",
"Id": "68794",
"Score": "0",
"body": "@kleinfreund I'm quite well aware of that, and yes I was talking about IE8. Not sure why you're pressing this issue, at this point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:08:33.847",
"Id": "70941",
"Score": "0",
"body": "Try this http://www.quirksmode.org/dom/inputfile.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T01:25:02.017",
"Id": "76391",
"Score": "0",
"body": "To answer your question, 'are there any big holes', in short, no. What you've done is a pretty typical way of handling it. Just make sure your control is clickable anywhere in your styled element in all browsers (or clickable where you want it clickable). For some reason my brain is itching about making sure it's sized to the full size of the re-styled element in some browser. But my brain itches aren't always correct."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T22:26:06.960",
"Id": "27574",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"user-interface"
],
"Title": "File input control with rounded buttons and styled textbox"
}
|
27574
|
<p>I often need to loop through a list of items and need both the index position, and the item itself:</p>
<pre><code>set names {John Paul George Ringo}
set i 0
foreach name $names {
puts "$i - $name"
incr i
}
</code></pre>
<p>Output:</p>
<blockquote>
<pre><code>0 - John
1 - Paul
2 - George
3 - Ringo
</code></pre>
</blockquote>
<p>Since I frequently do this, I decided to implement my own loop and call it <code>for_item_index</code> for lack of creativity. Here is my loop and a short code segment to test it:</p>
<pre><code>proc for_index_item {index item iterable body } {
uplevel 1 set $index 0
foreach x $iterable {
uplevel 1 set $item $x
uplevel 1 $body
uplevel 1 incr $index
}
}
# Test it
set names {John Paul George Ringo}
for_index_item i name $names {
puts "$i - $name"
}
</code></pre>
<p>I have tested it with <code>break</code>, and <code>continue</code> and found my new loop performs as expected. My concern is the excessive use of <code>uplevel</code> command in the code. I am seeking reviewers to give me tips for improving it.</p>
<p>Here are my own review of my code:</p>
<ul>
<li>Excessive use of <code>uplevel</code></li>
<li>The index always starts at zero. There are times when I want it to start at 1 or some other values. To add that feature, I will probably introduce another parameter, <code>startValue</code></li>
<li>Likewise, the index always get incremented by 1. The user might want to increment it by a different values such as 2, or -1 to count backward. Again, introducing another parameter, <code>step</code> might help, but at this point, the loop is getting complicated.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T02:40:59.370",
"Id": "43051",
"Score": "0",
"body": "Here's a bit more concise way to \"Break down indexexpr\": `lassign $indexexpr idxvar start step; if {$start == \"\"} {set start 0}; if {$step == \"\"} {set step 1}` (shame about comment code formatting)"
}
] |
[
{
"body": "<p>I would base something like this on <code>for</code> rather than <code>foreach</code></p>\n\n<pre><code>proc foreach_with_index {idxvar elemvar list body args} {\n array set opts {-start 0 -inc 1}\n if {[llength $args] > 0 && [llength $args]%2 == 0} {array set opts $args}\n upvar 1 $idxvar idx\n upvar 1 $elemvar elem\n for {set idx $opts(-start)} {$idx < [llength $list]} {incr idx $opts(-inc)} {\n set elem [lindex $list $idx]\n uplevel 1 $body\n }\n}\n</code></pre>\n\n<p>So you get</p>\n\n<pre><code>% foreach_with_index i e {a b c d e} {puts \"$i - $e\"}\n0 - a\n1 - b\n2 - c\n3 - d\n4 - e\n% foreach_with_index i e {a b c d e} {puts \"$i - $e\"} -start 1 -inc 2\n1 - b\n3 - d\n</code></pre>\n\n<p>Some thoughts:</p>\n\n<ul>\n<li>don't forget about <code>upvar</code> to link a variable up the call stack. </li>\n<li>I chose to use Tk style <code>-options</code> for some reason. It looks a bit awkward, but it's not exactly pretty to have to jam arguments at the end. You might choose to arguments with default values for <code>start</code> and <code>inc</code>. Or you might decide to put optional arguments in the middle of the list somewhere (like the way <code>puts</code> has an optional filehandle as the 1st arg), but that's more work to parse the arguments.</li>\n<li>in hindsight, using <code>for</code> vs <code>foreach</code> is a pretty arbitrary decision. Here, with <code>for</code>, you need to extract the element from the array. With <code>foreach</code> you need to increment the index. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T11:36:50.343",
"Id": "27590",
"ParentId": "27579",
"Score": "3"
}
},
{
"body": "<p>\"Stealing from python\" one could do the following:</p>\n\n<pre><code># enumerate --\n#\n# Returns an indexed series: \n# $startIDX [lindex $inList 0] $startIDX+1 [lindex $inList 1] ...\n#\n# Arguments:\n# inList list that should be enumerated\n# startIDX (optional) where the numbering should start (default=0)\n\nproc enumerate {inList {startIDX 0}} {\n set outList {}\n set i $startIDX\n foreach l $inList {\n lappend outList $i $l\n incr i\n }\n return $outList\n}\n\nset names {John Paul George Ringo}\nforeach {i n} [enumerate $names] {puts \"$i $n\"}\n</code></pre>\n\n<p>This avoids <code>uplevel</code> and <code>upvar</code> completely ...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-18T15:54:19.357",
"Id": "114382",
"ParentId": "27579",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27590",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T04:24:48.897",
"Id": "27579",
"Score": "4",
"Tags": [
"tcl"
],
"Title": "Tcl loop idea: for_index_item"
}
|
27579
|
<p>After a long search of simple php-jquery script from which i can pick the concept from,i gave up.The scripts i found were not very clear so i decided to make my own.This is the repo <a href="https://github.com/thiswolf/php-jquery-pagination" rel="nofollow">https://github.com/thiswolf/php-jquery-pagination</a></p>
<p>My code is only three file, index.php,my html file and ajax code,my dbconnection file to get connected to the data and finally the getdata.php file to retrieve the pagination data.</p>
<p>index.php</p>
<pre><code><!Doctype html>
<head>
<meta charset="utf-8" />
<title>Ajax Pagination</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get("getdata.php", function(data){
$('.pt').append(data);
});
$(document).on('click','.npl',function(e){
e.preventDefault();
var stuff = $(this).attr('id');
//alert(stuff);
$.post("getdata.php", {page:stuff}, function(data){
$('.pt').replaceWith(data);
});
});
$(document).on('click','.ppl',function(e){
e.preventDefault();
var stuff = $(this).attr('id') ;
//alert(stuff);
$.post("getdata.php", {page:stuff}, function(data){
$('.pt').replaceWith(data);
});
});
$(document).on('click','.lpl',function(e){
e.preventDefault();
var stuff = $(this).attr('id') ;
//alert(stuff);
$.post("getdata.php", {page:stuff}, function(data){
$('.pt').replaceWith(data);
});
});
$(document).on('click','.fpl',function(e){
e.preventDefault();
var stuff = $(this).attr('id') ;
//alert(stuff);
$.post("getdata.php", {page:stuff}, function(data){
$('.pt').replaceWith(data);
});
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div class="pt">
</div>
</body>
</html>
</code></pre>
<p>dbconnection.php</p>
<pre><code><?php
$host = "localhost";
$user = "root";
$password = "";
$database = "world";
$db = mysql_connect($host, $user, $password);
if($db)
{
$select_db = mysql_select_db($database);
if(!$select_db)
{
echo 'Database Error:'. mysql_error();
}
}else
{
echo 'Connection Error:'. mysql_error();
}
?>
</code></pre>
<p>getdata.php</p>
<pre><code><style>td,tr{border:1px solid orange;}</style>
<?php
include_once "dbconnection.php";
$rowsPerPage = 15;
// if $_GET['page'] defined, use it as page number
if (!isset($_POST['page'])){
$pageNum = 1;
}else {
$pageNum = $_POST['page'];
}
// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;
$query = "select * from city" .
" LIMIT $offset, $rowsPerPage";
//print $query;
$resulting=mysql_query($query);
//Part 1 - Fetch Results and Create Links
$result = mysql_query("select count(1) FROM city");
$row = mysql_fetch_array($result);
$total = $row[0];
//echo "Total rows: " . $total;
$maxPage = ceil($total/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a id='$page' class='ppl' href='#'> [Prev]</a> ";
//This line
$first = " <a id='1' class='fpl' href='#'>[First Page]</a> ";
//was approved by the Supreme Leader with the blessing of Gandalf.
}
else
{
$page = $pageNum + 1;
$prev = "<a href=\"$self?page=$page\"></a>"; // we're on page one, don't print previous link
$first = ' '; // nor the first page link
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a id='$page' class='npl' href='#'>[Next]</a> ";
$last = " <a id='$maxPage' class='lpl' href='#'>[Last Page]</a> ";
}
else
{
$next = ' '; // we're on the last page, don't print next link
$last = ' '; // nor the last page link
}
// print the navigation link
?>
<table class="pt">
<th>
<tr>
<td>ID</td><td>District</td><td>Population</td>
</tr>
</th>
<?php
while($rowd=mysql_fetch_array($resulting))
{
?>
<tbody>
<tr>
<td><?php echo $rowd['ID'];?></td><td><?php echo $rowd['District'];?></td><td><?php echo $rowd['Population'];?></td>
</tr>
</tbody>
<?php
}
?>
<tfoot><tr><td><?php
echo $first . $prev .
" Showing page $pageNum of <B>$maxPage</B> pages " . $next . $last;
?></td></tr></tfoot>
</table>
</code></pre>
<p>This script works but i would like to know if i would have done it better.
Thanks.</p>
|
[] |
[
{
"body": "<p>Well, first of. This code is not at all secure. you don't check wether the $_GET['page'] var is actually an int. But I don't think that was the point here.</p>\n\n<p>Second: sometimes you put the page numer in the id, this is a number and is thus invalid HTML, and sometimes you simply put it in the href. Why not always that last thing?</p>\n\n<p>Third: read the specs about mysql_* functions. There is a big red box that tells you not to use it anymore. Use PDO or mysqli_* instead.</p>\n\n<p>And last: If you walk away now and come back in 2 month, you will have no idea what you have written, Gandalf will not answer his phone and variable names as 'stuff' won't help much.</p>\n\n<p>So to sum up: good job writing this. But this could be written better in about everything.</p>\n\n<p>1) Instead of returning HTML, return XML of JSON or atleast make a better sepperation between getting and preparing the data and actually rendering the HTML. If you go for the first part the same script can easily be used in so much more applications (e.g. a smartphone app that needs XML data instead of HTML)</p>\n\n<p>2) Make it more secure, use prepared statements. Both mysqli_* and PDO support that.</p>\n\n<p>3) Use better variable names, if you can't think of a good name for the variable, you probably shouldn't be using it in the first place (there are exceptions ofcourse).</p>\n\n<p>4) create a javascript function that fetches the page and swaps out the HTML. This way when you change the way the php scripts works you only have to edit javascript in one place instead of 4or5 places (you are simply writing the same code over and over again in your Javascript).</p>\n\n<p>As promised, some code examples:</p>\n\n<p>At this point I hav eonly written the page-load part. This meaning you can load pages using Ajax, you will have to write the part that shows the pagination yourself, but I don't think that will be any problem.</p>\n\n<p>I hope you understand what goes on, I did my best writing clean code but I don't have a lot of time at the moment. Hope it is helpfull for you</p>\n\n<p>The files:\nindex.html</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\">\n <title>Ajax Pagination</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"page.css\" />\n\n </head>\n <body>\n\n <div id=\"page-content\"></div>\n <a href=\"2\" id=\"test\">test</a>\n\n <script type=\"text/javascript\" src=\"jquery.js\"></script>\n <script type=\"text/javascript\" src=\"ajax.page.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function() {\n var myAjaxPage = new AjaxPage('#page-content');\n myAjaxPage.loadPage(1); //load the first page\n\n //add a click handler to load a page\n jQuery('#test').click(function(event) {\n event.preventDefault();//prevent the default action\n //load the page\n myAjaxPage.loadPage(\n jQuery(this).attr('href')\n );\n })\n });\n </script>\n </body>\n</html>\n</code></pre>\n\n<p>getpage.php</p>\n\n<pre><code><?php\n#get the database Object\ninclude_once 'connection.php';\n\n$rowsPerPage = 3;\n$page = isset($_GET['page']) ? (int)$_GET['page'] - 1 : 0;\n$offset = $page * $rowsPerPage;\n\n$sql = 'SELECT * FROM city LIMIT ' . $offset . ',' . $rowsPerPage;\n\n$statement = $Database->query($sql);\n\n$result = $statement->fetchAll(PDO::FETCH_ASSOC);\n\n#render the page\ninclude_once 'page.html.php';\n</code></pre>\n\n<p>connection.php</p>\n\n<pre><code><?php\n\n//create a PDO DatabaseHandler\n$Database = new PDO(\n 'mysql:host=localhost;dbname=world',\n 'root', #username\n '' #password\n);\n</code></pre>\n\n<p>page.html.php</p>\n\n<pre><code><table class=\"pt\">\n <th>\n <tr>\n <td>ID</td><td>District</td><td>Population</td>\n </tr>\n </th>\n\n<?php foreach ( $result as $row ) {\n echo '<tr><td>' . $row['ID'] . '</td><td>' . $row['District'] . '</td><td>' . $row['Population'] . '</td></tr>';\n} ?>\n</table>\n</code></pre>\n\n<p>ajax.page.js</p>\n\n<pre><code>function AjaxPage(contentDomId) {\n\n this.contentObject = jQuery(contentDomId);\n\n this.renderPage = function(htmlContent) {\n this.contentObject.html(htmlContent);\n };\n\n this.loadPage = function(pageNumber) {\n jQuery.ajax({\n url : 'getpage.php',\n data : { page : pageNumber },\n datatype : 'html',\n success : this.renderPage.bind(this)\n });\n };\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T06:31:23.060",
"Id": "43099",
"Score": "0",
"body": "I am rewriting it with all recommendations taken into account.One question though.I want to return my main pagination data separate from my next,previous data.To do this,i am returning html but the json data wrapped in section html5 tags.Like this `echo '<section id='mainPaginationData'>'; echo json_encode($jsonData); echo '</section>';` The buttons data follow the same pattern.Is this a good pattern of separating the data from the views?.In my jquery i am returning `dataType: 'html',`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T16:06:44.270",
"Id": "43111",
"Score": "0",
"body": "Dont combine JSON and HTML. either return html and simply paste it into the DOM. Or return JSON and set datatype: 'json' in jquery."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T16:11:32.057",
"Id": "43112",
"Score": "0",
"body": "I wish i could toe the line on that one but they is no other way i know of.Been looking around for other solutions but none so far none."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T16:13:11.423",
"Id": "43113",
"Score": "0",
"body": "@Logan I'll have time in a few hours to write you up some code you can use.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T16:20:10.523",
"Id": "43114",
"Score": "0",
"body": "That'll be great.I shall stay tuned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-22T18:48:49.443",
"Id": "43126",
"Score": "0",
"body": "@Logan I edited my post with some example code"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T21:16:00.300",
"Id": "27610",
"ParentId": "27581",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T08:37:08.967",
"Id": "27581",
"Score": "2",
"Tags": [
"php",
"jquery",
"pagination"
],
"Title": "My method of php ajax pagination"
}
|
27581
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.